Location: PHPKode > projects > DDL CMS > Upload these files to your webspace/admin/tsadmin/main.php
<?php
	define('TSADMINDIR', dirname(__FILE__) . '/');
	define('WWWROOT', substr(TSADMINDIR, 0, -14));
	define('ADMINDIR', WWWROOT . 'admin/');
	define('TSDIR', WWWROOT . 'topsites/');
	require(TSDIR . 'tsphp.php');
	require(TSDIR . 'http.php');
	## Remove slashes from input if magic_quotes is enabled
	if(get_magic_quotes_gpc() != 0)
	{
		ArrayStripSlashes($_POST);
		ArrayStripSlashes($_GET);
		ArrayStripSlashes($_COOKIE);
		ArrayStripSlashes($_REQUEST);
	}
	## If this is the first visit to the control panel, force the user
	## to the edit options interface
	if(!isset($GLOBALS['ADMIN_EMAIL']) && !isset($_POST['ADMIN_EMAIL']))
	{
		require("{$GLOBALS['TDIR']}/admin_options.tpl");
		exit();
	}
if( isset($_REQUEST['T']) && !IsEmptyString($_REQUEST['T']) )
{
    FileTaint("{$GLOBALS['TDIR']}/admin_{$_REQUEST['T']}.tpl");
    require("{$GLOBALS['TDIR']}/admin_{$_REQUEST['T']}.tpl");
}
else if( isset($_REQUEST['Run']) && function_exists($_REQUEST['Run']) )
{
    call_user_func($_REQUEST['Run']);
}
else
{
    require("{$GLOBALS['TDIR']}/admin_main.tpl");
	require("{$GLOBALS['TDIR']}/admin_statistics.tpl");
}



// Backup SQL database and data files
function BackupDatabase()
{
    if( file_exists("{$GLOBALS['DDIR']}/{$_POST['Data_File']}") && !is_writable("{$GLOBALS['DDIR']}/{$_POST['Data_File']}") )
    {
        AdminError("The file {$_POST['Data_File']} is not writable.  Please delete or change permissions to 666");
    }

    if( file_exists("{$GLOBALS['DDIR']}/{$_POST['SQL_File']}") && !is_writable("{$GLOBALS['DDIR']}/{$_POST['SQL_File']}") )
    {
        AdminError("The file {$_POST['SQL_File']} is not writable.  Please delete or change permissions to 666");
    }

    FileTaint($_POST['Data_File']);
    FileTaint($_POST['SQL_File']);

    DoDataBackup($_POST['Data_File']);
    DoSQLBackup($_POST['SQL_File']);

    $times =& IniParse("{$GLOBALS['DDIR']}/times");

    $times['Backup'] = time();

    IniWrite("{$GLOBALS['DDIR']}/times", $times);

    $message = "Database backup has been completed.  Files are located in the data directory.";

    require("{$GLOBALS['TDIR']}/admin_backup.tpl");
}



// Restore SQL datbase and data files
function RestoreDatabase()
{
    if( !file_exists("{$GLOBALS['DDIR']}/{$_POST['Data_File']}") || !is_readable("{$GLOBALS['DDIR']}/{$_POST['Data_File']}") )
    {
        AdminError("The file {$_POST['Data_File']} does not exist or could not be read from");
    }

    if( !file_exists("{$GLOBALS['DDIR']}/{$_POST['SQL_File']}") || !is_readable("{$GLOBALS['DDIR']}/{$_POST['SQL_File']}") )
    {
        AdminError("The file {$_POST['SQL_File']} does not exist or could not be read from");
    }

    DoDataRestore($_POST['Data_File']);
    DoSQLRestore($_POST['SQL_File']);

    $message = "Database restore has been completed.";

    require("{$GLOBALS['TDIR']}/admin_backup.tpl");
}



// Send an e-mail message to one or more members
function EmailMember()
{
    global $DB;

    // Generate the e-mail message
    $message = "=>[Subject]\n" .
               "{$_POST['Subject']}\n" .
               "=>[Text]\n" .
               "{$_POST['Text']}\n" .
               "=>[HTML]\n" .
               "{$_POST['HTML']}\n";

    if( is_array($_POST['Username']) )
    {
        $DB->Connect();

        foreach($_POST['Username'] as $username)
        {
            $username = $DB->Escape($username);

            $account = $DB->Row("SELECT * FROM topsites_Accounts WHERE Username='$username'");

            $account['Script_URL'] = $GLOBALS['SCRIPT_URL'];
            $account['Tracking_URL'] = "{$GLOBALS['IN_URL']}?id={$account['Username']}";

            Email($account['Email'], $GLOBALS['ADMIN_EMAIL'], $message, $account);
        }

        $message = "Selected accounts have been e-mailed";

        require("{$GLOBALS['TDIR']}/admin_accounts.tpl");
    }
    else
    {
        FileWrite("{$GLOBALS['DDIR']}/bulkmessage", $message);
        $bulk = 1;
        require("{$GLOBALS['TDIR']}/admin_emailmember.tpl");
    }
}



## Start sending of bulk e-mail messages
function StartBulkEmail()
{
    $top = "main.php?Run=SendEmailBatch";

    require("{$GLOBALS['TDIR']}/admin_progress.tpl");
}



## Send a batch of e-mail messages
function SendEmailBatch()
{
    global $DB;

    $per_batch = 50;

    if( !isset($_GET['Start']) )
    {
        $_GET['Start'] = 0;
        $percent = 0;
        $message = "Preparing to send e-mail messages";
        $location = "main.php?Run=SendEmailBatch&Start=0";
        usleep(250000); // Allow time for the progress bar frame to load so javascript calls work
    }
    else
    {
        $DB->Connect();

        $total = $_GET['Total'];

        if( !isset($_GET['Total']) )
        {
            $total = $DB->Count("SELECT COUNT(*) FROM topsites_Accounts");
        }

        $result = $DB->Query("SELECT * FROM topsites_Accounts ORDER BY Username LIMIT {$_GET['Start']},$per_batch");

        while($account = $DB->NextRow($result))
        {
            $account['Script_URL'] = $GLOBALS['SCRIPT_URL'];
            $account['Tracking_URL'] = "{$GLOBALS['IN_URL']}?id={$account['Username']}";

            Email($account['Email'], $GLOBALS['ADMIN_EMAIL'], "{$GLOBALS['DDIR']}/bulkmessage", $account);
        }

        $DB->Free($result);

        $this_batch = $_GET['Start'] + $per_batch;
        $message = "E-mails " . ($_GET['Start'] + 1) . " through " . $this_batch  . " of $total have been sent...";

        if( $this_batch > $total )
        {
            $this_batch = $total;
            $done = TRUE;
            $message = "All e-mail messages have been sent";
        }

        $percent = $done ? 100 : ($this_batch/$total) * 100;
        $location = "main.php?Run=SendEmailBatch&Start=" . ($_GET['Start'] + $per_batch) . "&Total=$total";
    }
    
    require("{$GLOBALS['TDIR']}/admin_progresstop.tpl");
}



## Display the account e-mail interface
function DisplayEmailAccount()
{
    require("{$GLOBALS['TDIR']}/admin_emailmember.tpl");
}



## Clear historical administrative stats
function ClearAdminStats()
{
    global $DB;

    $DB->Connect();

    $DB->Update("DELETE FROM topsites_AdminStats");

    $message = "Historical stats have been cleared";

    require("{$GLOBALS['TDIR']}/admin_statistics.tpl");
}



## Generate the action string for a trigger
function GenerateTriggerAction(&$input)
{
    if( $input['Operator'] == '=' )
    {
        return "{$input['Field']}='{$input['Operand']}'";
    }
    else
    {
        return "{$input['Field']}={$input['Field']}{$input['Operator']}{$input['Operand']}";
    }
}



## Add a new trigger
function AddTrigger()
{
    global $DB, $types, $fields, $operators;

    $DB->Connect();

    $DB->EscapeHash($_POST);

    $action = GenerateTriggerAction($_POST);

    $DB->Insert("INSERT INTO topsites_Triggers VALUES ( " .
                "NULL, " .
                "'{$_POST['Type']}', " .
                "'{$_POST['Username']}', " .
                "'$action')");

    $message = "New trigger has been added successfully";

    require("{$GLOBALS['TDIR']}/admin_triggers.tpl");
}



## Remove one or more triggers
function DeleteTrigger()
{
    global $DB, $types, $fields, $operators;

    $DB->Connect();

    $DB->EscapeHash($_REQUEST);

    if( is_array($_REQUEST['ID']) )
    {
        foreach($_REQUEST['ID'] as $id)
        {
            $DB->Update("DELETE FROM topsites_Triggers WHERE Unique_ID='$id'");
        }
    }

    $message = "Selected triggers have been deleted";

    require("{$GLOBALS['TDIR']}/admin_triggers.tpl");
}

## Approve an account edit
function ApproveEdit()
{
    global $DB;

    $DB->Connect();

    if( is_array($_REQUEST['Username']) )
    {
        foreach($_REQUEST['Username'] as $username)
        {
            $username = $DB->Escape($username);
            $edit = $DB->Row("SELECT * FROM topsites_AccountEdits WHERE Username='$username'");

            $DB->EscapeHash($edit);

            $DB->Update("UPDATE topsites_Accounts SET " .
                        "Email='{$edit['Email']}', " .
                        "Site_URL='{$edit['Site_URL']}', " .
                        "Title='{$edit['Title']}', " .
                        "Password='{$edit['Password']}' " .
                        "WHERE Username='$username'");

            $DB->Update("DELETE FROM topsites_AccountEdits WHERE Username='$username'");
        }
    }

    $message = "The selected account edits have been approved";

    require("{$GLOBALS['TDIR']}/admin_reviewedits.tpl");
}



## Reject an account edit
function RejectEdit()
{
    global $DB;

    $DB->Connect();

    if( is_array($_REQUEST['Username']) )
    {
        foreach($_REQUEST['Username'] as $username)
        {
            $username = $DB->Escape($username);
            $DB->Update("DELETE FROM topsites_AccountEdits WHERE Username='$username'");
        }
    }

    $message = "The selected account edits have been rejected";

    require("{$GLOBALS['TDIR']}/admin_reviewedits.tpl");
}

## Re-sort member accounts
function Rerank()
{
    RerankAccounts('Control Panel');

    $message = 'Member accounts have been reranked';

    require("{$GLOBALS['TDIR']}/admin_popup.tpl");
}

## List member e-mail addresses
function ListEmails()
{
    global $DB;

    $DB->Connect();

    eval("\$char = \"{$_POST['Char']}\";"); 

    if( isset($_POST['To_File']) )
    {
        FileWrite("{$GLOBALS['DDIR']}/emails.txt", "");

        $result = $DB->Query("SELECT Email FROM topsites_Accounts");

        while($email = $DB->NextRow($result) )
        {
            FileAppend("{$GLOBALS['DDIR']}/emails.txt", "{$email['Email']}$char");
        }

        $DB->Free($result);

        $message = 'Emails have been written to the emails.txt file in the data directory';
    }

    #require("{$GLOBALS['TDIR']}/admin_listemails.tpl");
}

# Edit Gateway

function EditGateway()
{
	$message = 'Gateway file has been edited.';
	file_put_contents($GLOBALS['TDIR'] . '/in_gateway.tpl', $_POST['gateway']);
	require($GLOBALS['TDIR'] . '/admin_in_gateway.tpl');
}


## Create a new account
function CreateAccount()
{
    global $DB;

    $time = time();

    $DB->Connect();

    ## Remove extra whitespace from account data
    TrimHash($_POST);

    ## Disable HTML in account data
    StripHTMLNoAmp($_POST);

    $_SAFE = $_POST;

    $DB->EscapeHash($_SAFE);


    // Make sure an account with this username doesn't already exist
    if( $DB->Count("SELECT COUNT(*) FROM topsites_Accounts WHERE Username='{$_SAFE['Username']}'") > 0 )
    {
        AdminError('The username you have selected is already taken');
    }


    // Verify username length
    $un_length = strlen($_POST['Username']);
    if( $un_length < 4 || $un_length > 8 )
    {
        AdminError('The account username must be between 4 and 8 characters');
    }


    // Verify password length
    if( strlen($_POST['Password']) < 4 )
    {
        AdminError('The account password must be at least 4 characters');
    }


    // Verify username contains only letters and numbers
    if( preg_match('/[^a-zA-Z0-9]/', $_POST['Username']) )
    {
        AdminError('The account username may only contain English letters and numbers');
    }

    // Add information to the database
    $DB->Insert("INSERT INTO topsites_Cheats VALUES ( " .
                "'{$_SAFE['Username']}', " .
                "0, " .
                "0, " .
                "0, " .
                "0, " .
                "0, " .
                "0, " .
                "0, " .
                "0, " .
                "0, " .
                "0, " .
                "0, " .
                "0, " .
                "0, " .
                "0, " .
                "0, " .
                "0)");


    $DB->Insert("INSERT INTO topsites_Accounts VALUES ( " .
                "'{$_SAFE['Username']}', " .
                "'{$_SAFE['Email']}', " .
                "'{$_SAFE['Site_URL']}', " .
                "'{$_SAFE['Title']}', " .
                "'$time', " .
                "'{$_SAFE['Password']}', " .
                "'', " .
                "'Approved', " .
                "'0', " .
                "'0', " .
                "'$time', " .
                "'{$_SAFE['Notes']}', " .
                "'{$_SAFE['In_Weight']}', " .
                "'{$_SAFE['Out_Weight']}', " .
                "'0', " .
                "'0', " .
                "'0', " .
                "'0', " .
                "'0', " .
                "'0', " .
                "'0', " .
                "'0', " .
                "'0', " .
                "'0', " .
                "'0', " .
                "'0', " .
                "'0', " .
                "'0', " .
                "'0', " .
                "'0', " .
                "'0')");


    $message = "Account with username '{$_POST['Username']}' has been created<br />" .
               "Hit Tracking Link: {$GLOBALS['IN_URL']}?id={$_POST['Username']}";


    require("{$GLOBALS['TDIR']}/admin_createaccount.tpl");
}
	## Remove a banned IP from the list
	function DeleteBannedIP()
	{
		global $DB;
		$DB->Connect();
		$ip = $DB->Escape($_GET['IP_Address']);
		if(strpos($ip, '%'))
		{
			$DB->Update("DELETE FROM topsites_BannedIPs WHERE IP_Address LIKE '$ip';");
		}
		else
		{
			$DB->Update("DELETE FROM topsites_BannedIPs WHERE IP_Address = '$ip';");
		}
		$DB->Disconnect();
		$message = 'Specified IP has been removed from the ban list';
		require("{$GLOBALS['TDIR']}/admin_bannedips.tpl");
	}
## Add a new IP address to the ban list
function AddBannedIP()
{
    global $DB;

    UnixFormat($_POST['IP_Addresses']);

    $DB->Connect();
    
    foreach( explode("\n", $_POST['IP_Addresses']) as $ip )
    {
        $ips = MakeIPArray($ip);

        foreach( $ips as $ip )
        {
            if( $DB->Count("SELECT COUNT(*) FROM topsites_BannedIPs WHERE IP_Address='$ip'") < 1 )
            {
                $DB->Insert("INSERT INTO topsites_BannedIPs VALUES ('$ip')");
            }
        }
    }

    $DB->Disconnect();

    $message = 'Specified IPs have been added to the ban list';

    require("{$GLOBALS['TDIR']}/admin_bannedips.tpl");
}



## Make an array out of the supplied IP range
function MakeIPArray($ip)
{
    global $DB;

    if( strpos($ip, '-') )
    {
        $array = array();

        $range = explode('-', $ip);

        $start = explode('.', trim($range[0]));
        $end = explode('.', trim($range[1]));

        foreach( range($start[0], $end[0]) as $a )
        {
            foreach( range($start[1], $end[1]) as $b )
            {
                foreach( range($start[2], $end[2]) as $c )
                {
                    foreach( range($start[3], $end[3]) as $d )
                    {
                        $array[] = $DB->Escape("$a.$b.$c.$d");
                    }
                }
            }
        }
        
        return $array;
    }
    else
    {
        return array($DB->Escape($ip));
    }
}



## Add item to the blacklist
function AddBlacklist()
{
    global $DB;

    UnixFormat($_POST['Items']);

    $DB->Connect();

    $type = $DB->Escape($_POST['Type']);
    $regex = $DB->Escape($_POST['IsRegex']);

    foreach( explode("\n", $_POST['Items']) as $item )
    {
        $item = $DB->Escape($item);

        if( $DB->Count("SELECT COUNT(*) FROM topsites_Blacklist WHERE Type='$type' AND Value='$item'") < 1 )
        {
            $DB->Insert("INSERT INTO topsites_Blacklist VALUES ('$type', '$item', '$regex')");
        }
    }

    $DB->Disconnect();

    $message = 'Specified items have been added to the blacklist';
    $view = $_POST['Type'];

    require("{$GLOBALS['TDIR']}/admin_blacklist.tpl");
}



## Remove item from the blacklist
function DeleteBlacklist()
{
    global $DB;

    UnixFormat($_REQUEST['Items']);

    $DB->Connect();

    $type = $DB->Escape($_REQUEST['Type']);

    foreach( explode("\n", $_REQUEST['Items']) as $item )
    {
        $item = $DB->Escape($item);

        $DB->Update("DELETE FROM topsites_Blacklist WHERE Type='$type' AND Value='$item'");
    }

    $DB->Disconnect();

    $message = 'Specified items have been removed from the blacklist';
    $view = $_REQUEST['Type'];

    require("{$GLOBALS['TDIR']}/admin_blacklist.tpl");
}

# Delete an account
function DeleteAccount()
{
    global $DB;

    $usernames = $_REQUEST['Username'];

    if( !is_array($_REQUEST['Username']) )
    {
        $usernames = array($_REQUEST['Username']);
    }

    foreach($usernames as $username)
    {
        DoAccountDeletion($username);
    }

    
    if( $_SERVER['REQUEST_METHOD'] == 'GET' )
    {
        $message = "Account '{$_GET['Username']}' has been deleted";
        $reload = 1;
        require("{$GLOBALS['TDIR']}/admin_popup.tpl");
    }
    else
    {
        $message = "Selected accounts have been deleted";
        require("{$GLOBALS['TDIR']}/admin_accounts.tpl");
    }
}



## Confirm a new account
function ConfirmAccount()
{
    global $DB;

    $usernames = $_REQUEST['Username'];

    if( !is_array($_REQUEST['Username']) )
    {
        $usernames = array($_REQUEST['Username']);
    }

    $DB->Connect();

    foreach($usernames as $username)
    {
        $username = $DB->Escape($username);

        $account = $DB->Row("SELECT * FROM topsites_Accounts WHERE Username='$username'");

        if( $account['Status'] == 'Unconfirmed' )
        {
            $DB->Update("UPDATE topsites_Accounts SET Status='Approved' WHERE Username='$username'");

            $account['Tracking_URL'] = "{$GLOBALS['IN_URL']}?id=$username";
            $account['Script_URL'] = $GLOBALS['SCRIPT_URL'];

            Email($account['Email'], $GLOBALS['ADMIN_EMAIL'], "{$GLOBALS['TDIR']}/email_added.tpl", $account);
        }
    }

    if( $_SERVER['REQUEST_METHOD'] == 'GET' )
    {
        $message = "Account '{$_GET['Username']}' has been confirmed";
        $reload = 1;
        require("{$GLOBALS['TDIR']}/admin_popup.tpl");
    }
    else
    {
        $message = "Selected accounts have been confirmed";
        require("{$GLOBALS['TDIR']}/admin_accounts.tpl");
    }
}



## Reject a new account
function RejectAccount()
{
    global $DB;

    $usernames = $_REQUEST['Username'];

    if( !is_array($_REQUEST['Username']) )
    {
        $usernames = array($_REQUEST['Username']);
    }

    $DB->Connect();

    foreach($usernames as $username)
    {
        $username = $DB->Escape($username);

        $account = $DB->Row("SELECT * FROM topsites_Accounts WHERE Username='$username'");

        if( $account['Status'] == 'Unconfirmed' || $account['Status'] == 'Pending' )
        {
            DoAccountDeletion($username);

            ## Send rejection e-mail
            $rejection = $_REQUEST["Reject_$username"];
            if( !IsEmptyString($rejection) )
            {
                $account['Script_URL'] = $GLOBALS['SCRIPT_URL'];

                Email($account['Email'], $GLOBALS['ADMIN_EMAIL'], "{$GLOBALS['DDIR']}/reject/$rejection", $account);
            }
        }
    }
    
    if( $_SERVER['REQUEST_METHOD'] == 'GET' )
    {
        $message = "Account '{$_GET['Username']}' has been rejected";
        $reload = 1;
        require("{$GLOBALS['TDIR']}/admin_popup.tpl");
    }
    else
    {
        $message = "Selected accounts have been rejected";
        require("{$GLOBALS['TDIR']}/admin_accounts.tpl");
    }
}



## Approve a new account
function ApproveAccount()
{
    global $DB;

    $usernames = $_REQUEST['Username'];

    if( !is_array($_REQUEST['Username']) )
    {
        $usernames = array($_REQUEST['Username']);
    }

    $DB->Connect();

    foreach($usernames as $username)
    {
        $username = $DB->Escape($username);

        $account = $DB->Row("SELECT * FROM topsites_Accounts WHERE Username='$username'");

        if( $account['Status'] == 'Pending' )
        {
            $DB->Update("UPDATE topsites_Accounts SET Status='Approved' WHERE Username='$username'");

            $account['Tracking_URL'] = "{$GLOBALS['IN_URL']}?id=$username";
            $account['Script_URL'] = $GLOBALS['SCRIPT_URL'];

            Email($account['Email'], $GLOBALS['ADMIN_EMAIL'], "{$GLOBALS['TDIR']}/email_added.tpl", $account);
        }
    }

    if( $_SERVER['REQUEST_METHOD'] == 'GET' )
    {
        $message = "Account '{$_GET['Username']}' has been approved";
        $reload = 1;
        require("{$GLOBALS['TDIR']}/admin_popup.tpl");
    }
    else
    {
        $message = "Selected accounts have been approved";
        require("{$GLOBALS['TDIR']}/admin_accounts.tpl");
    }
}

## Display accounts in the database
function DisplayAccounts()
{
    global $DB;
    require("{$GLOBALS['TDIR']}/admin_accounts.tpl");
}

## Generate the MySQL queries to use for searching the account database
function GenerateSearchQuery()
{
    global $DB;

    $_SAFE = $_POST;

    $DB->EscapeHash($_SAFE);
   
    $qualifier = "Status IN (" . MakeList($_SAFE['Status']) . ") " .
                 GetSearchString($_SAFE);

    $_POST['Total'] = $DB->Count("SELECT COUNT(*) FROM topsites_Accounts WHERE $qualifier");

    CalculatePositions();

    $order_field = GetOrderString($GLOBALS['SORTINGS'][$_POST['Order_Field']]);

	if($_POST['Per_Page'] <= 0)
	{
		$_POST['Per_Page'] = 20;
	}

    $query = "SELECT *,UNIX_TIMESTAMP(Signup) AS theDate, $order_field AS Sort_Value FROM topsites_Accounts WHERE $qualifier ORDER BY $order_field {$_SAFE['Direction']} LIMIT {$_POST['Limit']},{$_POST['Per_Page']}";

    return $query;
}



## Generate a search string
function GetSearchString(&$hash)
{
    global $DB;

    if( IsEmptyString($hash['Search_Value']) )
    {
        return '';
    }
    else
    {
        $hash['Search_Type'] = stripslashes($hash['Search_Type']);

        StringParse($hash['Search_Type'], $hash);

        return "AND {$hash['Search_Type']}";
    }
}



## Figure the start, end, page, and limit values for pagination
function CalculatePositions()
{
    if( $_POST['Page'] < 0 )
    {
        $_POST['Page'] = 0;
    }

    $_POST['Limit'] = $_POST['Page'] * $_POST['Per_Page'];


    while( $_POST['Limit'] >= $_POST['Total'] && $_POST['Page'] > 0 )
    {
        $_POST['Page']--;
        $_POST['Limit'] = $_POST['Page'] * $_POST['Per_Page'];
    }

    $_POST['Start'] = $_POST['Page'] * $_POST['Per_Page'] + 1;
    $_POST['End']   = ($_POST['Page'] + 1) * $_POST['Per_Page'];

    if( $_POST['Total'] < $_POST['End'] )
    {
        $_POST['End'] = $_POST['Total'];
    }

    if( $_POST['Start'] < 1 )
    {
        $_POST['Start'] = 1;
    }
}

## Save the variables and settings
function SaveOptions()
{
    global $DB;

    $time = time();

    unset($_POST['Run']);

    ## Clear out current option settings
    foreach($GLOBALS as $key => $value)
    {
        if( preg_match('/^O_/', $key) )
        {
            unset($GLOBALS[$key]);
        }
    }

    ## Remove trailing slash from the document root
    $_POST['DOCUMENT_ROOT'] = preg_replace('|/$|', '', $_POST['DOCUMENT_ROOT']);


    ## Get directories that correspond with the provided URLs
    $_POST['BANNER_DIR'] = GetDirectory($_POST['BANNER_URL'], $_POST['DOCUMENT_ROOT']);


    ## Record SUEXEC settings
    $_POST['SUEXEC'] = IsSuexecServer() ? 1 : 0;


    ## Create files if they don't exist
    FileWriteNew("{$GLOBALS['DDIR']}/cheatlog", '');
    FileWriteNew("{$GLOBALS['DDIR']}/rrlock", '');
    FileWriteNew("{$GLOBALS['DDIR']}/rslock", '');
    FileWriteNew("{$GLOBALS['DDIR']}/reset", $time);
    FileWriteNew("{$GLOBALS['DDIR']}/rerank", $time);
    FileWriteNew("{$GLOBALS['DDIR']}/times", "=>[Rerank]\n$time\n=>[Rerank_By]\nNA\n=>[Reset]\n$time\n" .
                                             "=>[Reset_By]\nNA\n=>[Backup]\n$time\n=>[IP_Clean]\n$time\n" .
                                             "=>[HitIPs]\n$time\n=>[RateIPs]\n$time\n" .
                                             "=>[Start]\n$time\n=>[Total_Reset]\n$time\n");


    ## Update the fulltext search indexes
    $_POST['SEARCH_FIELDS'] = UpdateFulltextSearch();


    ## Update the variables file
    FileWrite("{$GLOBALS['DDIR']}/variables", "<?PHP\n");

    foreach($_POST as $key => $value)
    {
        SafeAddSlashes($value);

        FileAppend("{$GLOBALS['DDIR']}/variables", "\$$key = '$value';\n");

        $GLOBALS[$key] = $value;
    }

    FileAppend("{$GLOBALS['DDIR']}/variables", "\$HOSTNAME = '{$GLOBALS['HOSTNAME']}';\n" .
                                               "\$USERNAME = '{$GLOBALS['USERNAME']}';\n" .
                                               "\$PASSWORD = '{$GLOBALS['PASSWORD']}';\n" .
                                               "\$DATABASE = '{$GLOBALS['DATABASE']}';\n" . "?".">");

    $message = "Topsites Settings update was successful.<br><br><< Click on <b>Rerank Accounts</b> to see the changes in your toplist.";
    
	// require("{$GLOBALS['TDIR']}/admin_options.tpl");

	// so we are consistent with DDL Save Options:
	echo $message;
	echo "</td>
	</tr>
	</table>
	
	</td>";
	require("{$GLOBALS['DOCUMENT_ROOT']}/admin/adminfooter.php");
	die;

}



## Update the fulltext search indexes
function UpdateFulltextSearch()
{
    global $DB;

    $current = explode(',', $GLOBALS['SEARCH_FIELDS']);
    $fields = array('Title', 'Description');

    foreach( range(1,3) as $index )
    {
        $key = "O_SEARCH_FIELD_$index";

        if( isset($_POST[$key]) )
        {
            $fields[] = "Field_$index";
        }
    }

    if( !AreArraysIdentical($current, $fields) )
    {
        $DB->Connect();
        $DB->Update("DROP INDEX FTSearch ON topsites_Accounts");
        $DB->Update("CREATE FULLTEXT INDEX FTSearch ON topsites_Accounts (" . join(',', $fields)  . ")");
        $DB->Update("OPTIMIZE TABLE topsites_Accounts");
        $DB->Disconnect();
    }

    return join(',', $fields);
}

## Load one of the software's defined e-mail templates
function LoadEmail()
{
    $email =& IniParse("{$GLOBALS['TDIR']}/{$_POST['Load']}");

    $message = "E-mail template '{$_POST['Load']}' has been loaded for editing";

}



## Save one of the software defined e-mail templates
function SaveEmail()
{
    $email = array();

    $email['Subject'] = $_POST['Subject'];
    $email['Text'] = $_POST['Text'];
    $email['HTML'] = $_POST['HTML'];

    IniWrite("{$GLOBALS['TDIR']}/{$_POST['Template']}", $email);

    $message = "E-mail template '{$_POST['Template']}' has been saved";

    $_POST['Load'] = $_POST['Template'];

    require("{$GLOBALS['TDIR']}/admin_emailtemplates.tpl");
}

## Update the .htpasswd file with a new username and password
function ChangeLogin()
{
    if( IsEmptyString($_POST['Username']) || IsEmptyString($_POST['Password']) )
    {
        AdminError("Both a username and password must be supplied");
    }

    FileWrite("{$GLOBALS['ADIR']}/.htpasswd", "{$_POST['Username']}:" . crypt($_POST['Password']));

    $message = "Your login information has been updated";

    require("{$GLOBALS['TDIR']}/admin_changelogin.tpl");
}



## Clear the cheat tally
function ClearCheatTallyPT()
{
    ClearCheatTally();

    $message = "Cheat tally has been cleared for all member accounts";

    require("{$GLOBALS['TDIR']}/admin_popup.tpl");
}



## Clear the cheat log
function ClearCheatLogPT()
{
    ClearCheatLog();

    $message = "Cheat log has been cleared";

    require("{$GLOBALS['TDIR']}/admin_cheatlog.tpl");
}



## Clear the IP logs for both hits and ratings
function ClearIPLogsPT()
{
    ClearIPLogs();

    $message = "IP logs have been cleared";

    require("{$GLOBALS['TDIR']}/admin_popup.tpl");
}



## Clear the historical account stats from the database
function ClearAccountStatsPT()
{
    ClearAccountStats();

    $message = "Account stats have been cleared";

    require("{$GLOBALS['TDIR']}/admin_popup.tpl");
}



## Reset the current in and out hit counts to zero
function ResetCurrentHitsPT()
{
    ResetCurrentHits('Control Panel');

    $message = "Current in and out hit counts have been reset";

    require("{$GLOBALS['TDIR']}/admin_popup.tpl");
}



## Reset the total in and out hit counts to zero
function ResetTotalHitsPT()
{
    ResetTotalHits();

    $message = "Total hit counts have been reset";

    require("{$GLOBALS['TDIR']}/admin_popup.tpl");
}

## Display error messages generated by control panel functions
function AdminError($message) 
{
    require("{$GLOBALS['TDIR']}/admin_error.tpl");
    exit;
}


## Get a directory path based on the document root and a URL
function GetDirectory($url, $documentRoot)
{
    if( preg_match('|http://[^/]+/(.+)|', $url, $matches) )
    {
        return "$documentRoot/$matches[1]";
    }
    else
    {
        return $documentRoot;
    }
}

?>
Return current item: DDL CMS