Location: PHPKode > projects > DDL CMS > Upload these files to your webspace/topsites/tsphp.php
<?php
	require(WWWROOT . 'topsites/common.php');
	require(WWWROOT . 'topsites/compiler.php');
	## Sorting methods
	$SORTINGS = array('Overall Rank' => 'IF(Overall_Rank > 0, Overall_Rank, NULL)',
                  'Hits In (Raw)' => 'Current_In',
                  'Hits In (Weighted)' => 'ROUND(Current_In * In_Weight + {$GLOBALS[\'FUZZ\']})',
                  'Hits In (Productivity)' => 'ROUND((ROUND(Current_In * In_Weight + {$GLOBALS[\'FUZZ\']})) + (Current_Prod * {$GLOBALS[\'PROD_BONUS\']}) + {$GLOBALS[\'FUZZ\']})',
                  'Hits Out (Raw)' => 'Current_Out',
                  'Hits Out (Weighted)' => 'ROUND(Current_Out * Out_Weight + {$GLOBALS[\'FUZZ\']})',
                  'Total Hits In (Raw)' => 'Total_In',
                  'Total Hits In (Weighted)' => 'ROUND(Total_In * In_Weight + {$GLOBALS[\'FUZZ\']})',
                  'Total Hits In (Productivity)' => 'ROUND(ROUND(Total_In * In_Weight + {$GLOBALS[\'FUZZ\']}) + (Total_Prod * {$GLOBALS[\'PROD_BONUS\']}) + {$GLOBALS[\'FUZZ\']})',
                  'Total Hits Out (Raw)' => 'Total_Out',
                  'Total Hits Out (Weighted)' => 'ROUND(Total_Out * Out_Weight + {$GLOBALS[\'FUZZ\']})',
                  'Average Hits In Per Day (Raw)' => 'IF(({$GLOBALS[\'NOW\']} - Last_Reset) > {$GLOBALS[\'DAY\']}, (Total_In / (({$GLOBALS[\'NOW\']} - Last_Reset) / {$GLOBALS[\'DAY\']})), Total_In)',
                  'Average Hits In Per Day (Weighted)' => 'IF(({$GLOBALS[\'NOW\']} - Last_Reset) > {$GLOBALS[\'DAY\']}, (ROUND(Total_In * In_Weight + {$GLOBALS[\'FUZZ\']}) / (({$GLOBALS[\'NOW\']} - Last_Reset) / {$GLOBALS[\'DAY\']})), ROUND(Total_In * In_Weight + {$GLOBALS[\'FUZZ\']}))',
                  'Average Hits In Per Day (Productivity)' => 'IF(({$GLOBALS[\'NOW\']} - Last_Reset) > {$GLOBALS[\'DAY\']}, (ROUND(ROUND(Total_In * In_Weight + {$GLOBALS[\'FUZZ\']}) + (Total_Prod * {$GLOBALS[\'PROD_BONUS\']}) + {$GLOBALS[\'FUZZ\']}) / (({$GLOBALS[\'NOW\']} - Last_Reset) / {$GLOBALS[\'DAY\']})), ROUND(ROUND(Total_In * In_Weight + {$GLOBALS[\'FUZZ\']}) + (Total_Prod * {$GLOBALS[\'PROD_BONUS\']}) + {$GLOBALS[\'FUZZ\']}))',
                  'Average Hits In Per Week (Raw)' => 'IF(({$GLOBALS[\'NOW\']} - Last_Reset) > {$GLOBALS[\'WEEK\']}, (Total_In / (({$GLOBALS[\'NOW\']} - Last_Reset) / {$GLOBALS[\'WEEK\']})), Total_In)',
                  'Average Hits In Per Week (Weighted)' => 'IF(({$GLOBALS[\'NOW\']} - Last_Reset) > {$GLOBALS[\'WEEK\']}, (ROUND(Total_In * In_Weight + {$GLOBALS[\'FUZZ\']}) / (({$GLOBALS[\'NOW\']} - Last_Reset) / {$GLOBALS[\'WEEK\']})), ROUND(Total_In * In_Weight + {$GLOBALS[\'FUZZ\']}))',
                  'Average Hits In Per Week (Productivity)' => 'IF(({$GLOBALS[\'NOW\']} - Last_Reset) > {$GLOBALS[\'WEEK\']}, (ROUND(ROUND(Total_In * In_Weight + {$GLOBALS[\'FUZZ\']}) + (Total_Prod * {$GLOBALS[\'PROD_BONUS\']}) + {$GLOBALS[\'FUZZ\']}) / (({$GLOBALS[\'NOW\']} - Last_Reset) / {$GLOBALS[\'WEEK\']})), ROUND(ROUND(Total_In * In_Weight + {$GLOBALS[\'FUZZ\']}) + (Total_Prod * {$GLOBALS[\'PROD_BONUS\']}) + {$GLOBALS[\'FUZZ\']}))',
                  'Average Hits In Per Month (Raw)' => 'IF(({$GLOBALS[\'NOW\']} - Last_Reset) > {$GLOBALS[\'MONTH\']}, (Total_In / (({$GLOBALS[\'NOW\']} - Last_Reset) / {$GLOBALS[\'MONTH\']})), Total_In)',
                  'Average Hits In Per Month (Weighted)' => 'IF(({$GLOBALS[\'NOW\']} - Last_Reset) > {$GLOBALS[\'MONTH\']}, (ROUND(Total_In * In_Weight + {$GLOBALS[\'FUZZ\']}) / (({$GLOBALS[\'NOW\']} - Last_Reset) / {$GLOBALS[\'MONTH\']})), ROUND(Total_In * In_Weight + {$GLOBALS[\'FUZZ\']}))',
                  'Average Hits In Per Month (Productivity)' => 'IF(({$GLOBALS[\'NOW\']} - Last_Reset) > {$GLOBALS[\'MONTH\']}, (ROUND(ROUND(Total_In * In_Weight + {$GLOBALS[\'FUZZ\']}) + (Total_Prod * {$GLOBALS[\'PROD_BONUS\']}) + {$GLOBALS[\'FUZZ\']}) / (({$GLOBALS[\'NOW\']} - Last_Reset) / {$GLOBALS[\'MONTH\']})), ROUND(ROUND(Total_In * In_Weight + {$GLOBALS[\'FUZZ\']}) + (Total_Prod * {$GLOBALS[\'PROD_BONUS\']}) + {$GLOBALS[\'FUZZ\']}))',
                  'Average Hits Out Per Day (Raw)' => 'IF(({$GLOBALS[\'NOW\']} - Last_Reset) > {$GLOBALS[\'DAY\']}, (Total_Out / (({$GLOBALS[\'NOW\']} - Last_Reset) / {$GLOBALS[\'DAY\']})), Total_Out)',
                  'Average Hits Out Per Day (Weighted)' => 'IF(({$GLOBALS[\'NOW\']} - Last_Reset) > {$GLOBALS[\'DAY\']}, (ROUND(Total_Out * Out_Weight + {$GLOBALS[\'FUZZ\']}) / (({$GLOBALS[\'NOW\']} - Last_Reset) / {$GLOBALS[\'DAY\']})), ROUND(Total_Out * Out_Weight + {$GLOBALS[\'FUZZ\']}))',
                  'Average Hits Out Per Week (Raw)' => 'IF(({$GLOBALS[\'NOW\']} - Last_Reset) > {$GLOBALS[\'WEEK\']}, (Total_Out / (({$GLOBALS[\'NOW\']} - Last_Reset) / {$GLOBALS[\'WEEK\']})), Total_Out)',
                  'Average Hits Out Per Week (Weighted)' => 'IF(({$GLOBALS[\'NOW\']} - Last_Reset) > {$GLOBALS[\'WEEK\']}, (ROUND(Total_Out * Out_Weight + {$GLOBALS[\'FUZZ\']}) / (({$GLOBALS[\'NOW\']} - Last_Reset) / {$GLOBALS[\'WEEK\']})), ROUND(Total_Out * Out_Weight + {$GLOBALS[\'FUZZ\']}))',
                  'Average Hits Out Per Month (Raw)' => 'IF(({$GLOBALS[\'NOW\']} - Last_Reset) > {$GLOBALS[\'MONTH\']}, (Total_Out / (({$GLOBALS[\'NOW\']} - Last_Reset) / {$GLOBALS[\'MONTH\']})), Total_Out)',
                  'Average Hits Out Per Month (Weighted)' => 'IF(({$GLOBALS[\'NOW\']} - Last_Reset) > {$GLOBALS[\'MONTH\']}, (ROUND(Total_Out * Out_Weight + {$GLOBALS[\'FUZZ\']}) / (({$GLOBALS[\'NOW\']} - Last_Reset) / {$GLOBALS[\'MONTH\']})), ROUND(Total_Out * Out_Weight + {$GLOBALS[\'FUZZ\']}))',
                  'Number of Ratings' => 'Num_Ratings',
                  'Average Rating' => 'IF(Num_Ratings > 0, (Rating_Total/Num_Ratings), 0)',
                  'Signup Date' => 'Signup',
                  'Username' => 'Username',
                  'Inactivity' => 'Inactive');
	## Get the order string for use when reranking members
function GetOrderString($raw_order_string)
{
    global $DB;

    eval("\$order_string = \$DB->Escape(stripslashes(\"$raw_order_string\"));");

    return $order_string;
}



## Format account data
function AccountData(&$account, &$lang)
{
    global $DAY, $WEEK, $MONTH;

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

    $account['In_Weight']          = sprintf("%.3f", $account['In_Weight']);
    $account['Out_Weight']         = sprintf("%.3f", $account['Out_Weight']);
    $account['Weighted_In']        = round($account['Current_In'] * $account['In_Weight']);
    $account['Weighted_Out']       = round($account['Current_Out'] * $account['Out_Weight']);
    $account['Weighted_Total_In']  = round($account['Total_In'] * $account['In_Weight']);
    $account['Weighted_Total_Out'] = round($account['Total_Out'] * $account['Out_Weight']);
    $account['Prod_In']            = round($account['Weighted_In'] + ($account['Current_Prod'] * $GLOBALS['PROD_BONUS']));
    $account['Prod_Total_In']      = round($account['Weighted_Total_In'] + ($account['Total_Prod'] * $GLOBALS['PROD_BONUS']));
    $account['Signup_Date']        = date($date_format, $account['Signup']);
    $account['Signup_Time']        = date($date_format, $account['Signup']);
    $account['In_Per_Day']         = FormatNumber(GetAverage($account['Total_In'], $account['Last_Reset'], $DAY));
    $account['In_Per_Week']        = FormatNumber(GetAverage($account['Total_In'], $account['Last_Reset'], $WEEK));
    $account['In_Per_Month']       = FormatNumber(GetAverage($account['Total_In'], $account['Last_Reset'], $MONTH));
    $account['Weighted_In_Per_Day'] = FormatNumber(GetAverage($account['Weighted_Total_In'], $account['Last_Reset'], $DAY));
    $account['Weighted_In_Per_Week'] = FormatNumber(GetAverage($account['Weighted_Total_In'], $account['Last_Reset'], $WEEK));
    $account['Weighted_In_Per_Month'] = FormatNumber(GetAverage($account['Weighted_Total_In'], $account['Last_Reset'], $MONTH));
    $account['Prod_In_Per_Day']    = FormatNumber(GetAverage($account['Prod_Total_In'], $account['Last_Reset'], $DAY));
    $account['Prod_In_Per_Week']   = FormatNumber(GetAverage($account['Prod_Total_In'], $account['Last_Reset'], $WEEK));
    $account['Prod_In_Per_Month']  = FormatNumber(GetAverage($account['Prod_Total_In'], $account['Last_Reset'], $MONTH));
    $account['Out_Per_Day']        = FormatNumber(GetAverage($account['Total_Out'], $account['Last_Reset'], $DAY));
    $account['Out_Per_Week']       = FormatNumber(GetAverage($account['Total_Out'], $account['Last_Reset'], $WEEK));
    $account['Out_Per_Month']      = FormatNumber(GetAverage($account['Total_Out'], $account['Last_Reset'], $MONTH));
    $account['Weighted_Out_Per_Day'] = FormatNumber(GetAverage($account['Weighted_Total_Out'], $account['Last_Reset'], $DAY));
    $account['Weighted_Out_Per_Week'] = FormatNumber(GetAverage($account['Weighted_Total_Out'], $account['Last_Reset'], $WEEK));
    $account['Weighted_Out_Per_Month'] = FormatNumber(GetAverage($account['Weighted_Total_Out'], $account['Last_Reset'], $MONTH));
    $account['Current_In']         = FormatNumber($account['Current_In']);
    $account['Current_Out']        = FormatNumber($account['Current_Out']);
    $account['Current_Prod']       = FormatNumber($account['Current_Prod']);
    $account['Total_In']           = FormatNumber($account['Total_In']);
    $account['Total_Out']          = FormatNumber($account['Total_Out']);
    $account['Total_Prod']         = FormatNumber($account['Total_Prod']);
    $account['Weighted_In']        = FormatNumber($account['Weighted_In']);
    $account['Weighted_Out']       = FormatNumber($account['Weighted_Out']);
    $account['Weighted_Total_In']  = FormatNumber($account['Weighted_Total_In']);
    $account['Weighted_Total_Out'] = FormatNumber($account['Weighted_Total_Out']);
    $account['Prod_In']            = FormatNumber($account['Prod_In']);
    $account['Prod_Total_In']      = FormatNumber($account['Prod_Total_In']);
    $account['Last_Prod_In']       = round(round($account['Last_In'] * $account['In_Weight']) + ($account['Last_Prod'] * $GLOBALS['PROD_BONUS']));
    $account['Last_Out']           = FormatNumber($account['Last_Out']);
    $account['Last_In']            = FormatNumber($account['Last_In']);
    $account['Last_Sort']          = FormatNumber($account['Last_Sort']); 
    $account['Out_URL']            = "{$GLOBALS['OUT_URL']}?id={$account['Username']}";
    $account['Is_New']             = ($GLOBALS['NOW'] - $account['Signup'] <= $GLOBALS['NEW_SITE']);
    $account['Movement_Overall']   = $account['Last_Overall'] > 0 ? NumCompare($account['Last_Overall'], $account['Overall_Rank']) : 0;

    if( $account['Num_Ratings'] > 0 )
    {
        $account['Average_Rating'] = FormatNumber($account['Rating_Total'] / $account['Num_Ratings'], $GLOBALS['DECIMALS']);
        $account['Percentage_Rating'] = round((($account['Rating_Total'] / $account['Num_Ratings']) / $GLOBALS['MAX_RATING']) * 100);
        $account['Half_Rating'] = GetNearestHalf($account['Rating_Total'] / $account['Num_Ratings']);
    }
    else
    {
        $account['Average_Rating'] = $lang['NOT_RATED'];
        $account['Percentage_Rating'] = $lang['NOT_RATED'];
        $account['Half_Rating'] = $lang['NOT_RATED'];
    }
}

function GetNearestHalf($value)
{
    return round(($value * 2), 0) / 2;
}



function GetAverage($hits, $last_reset, $period)
{
    $age = $GLOBALS['NOW'] - $last_reset;

    if( $age >= $period )
    {
        return ($hits / ($age / $period));
    }
    else
    {
        return $hits;
    }
}



function FormatNumber($value, $decimals = 0)
{
    return number_format($value, $decimals, $GLOBALS['DECIMAL_SEP'], $GLOBALS['THOUSANDS_SEP']);
}



## Check for Internet Explorer or a Mozilla based browser; all others are bad
function IsBadBrowser() 
{
    $agent = $_SERVER['HTTP_USER_AGENT'];
    
    return (stristr($agent, 'Opera') !== FALSE || (stristr($agent, 'MSIE 6.0') === FALSE && stristr($agent, 'Gecko') === FALSE));  
}



## Determine if we should recommend that it is time for a database backup
function IsBackupRecommended(&$times)
{
    return (time() - $times['Backup']) >= 259200;
}



## Clear the cheat tallies for all accounts
function ClearCheatTally()
{
    global $DB;

    $DB->Connect();

    $DB->Update("UPDATE topsites_Cheats SET " .
                "Hit_IP_Address=0, " .
                "Hit_Cookie=0, " .
                "Hit_Exp_Session=0, " .
                "Hit_Proxy=0, " .
                "Hit_Referrer=0, " .
                "Hit_Browser=0, " .
                "Hit_Banned_IP=0, " .
                "Hit_No_Cookies=0, " .
                "Rate_IP_Address=0, " .
                "Rate_Cookie=0, " .
                "Rate_Exp_Session=0, " .
                "Rate_Proxy=0, " .
                "Rate_Referrer=0, " .
                "Rate_Browser=0, " .
                "Rate_No_Cookies=0, " .
                "Rate_Banned_IP=0");

    $DB->Disconnect();
}



## Empty the cheat log
function ClearCheatLog()
{
    FileWrite("{$GLOBALS['DDIR']}/cheatlog", '');
}



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

    $DB->Connect();

    $DB->Update("DELETE FROM topsites_HitIPs");
    $DB->Update("DELETE FROM topsites_RateIPs");

    $DB->Disconnect();
}



## Clear the historical account stats from the database
function ClearAccountStats()
{
    global $DB;

    $DB->Connect();

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

    $DB->Disconnect();
}



## Re-sort the accounts based on selected ranking method
function RerankAccounts($from)
{
    global $DB;

    $time = time();

    $fd = fopen("{$GLOBALS['DDIR']}/rrlock", "a");
    $lock = flock($fd, LOCK_EX | LOCK_NB);

    // One at a time please
    if( $lock === TRUE )
    {
        $times =& IniParse("{$GLOBALS['DDIR']}/times");

        $DB->Connect();

        if( $time - $times['RateIPs'] >= $GLOBALS['IP_EXPIRE_R'])
        {
            $DB->Update("DELETE FROM topsites_RateIPs");
            $times['RateIPs'] = $time;
        }
        
        
        if( $time - $times['HitIPs'] >= $GLOBALS['IP_EXPIRE'])
        {
            $DB->Update("DELETE FROM topsites_HitIPs");
            $times['HitIPs'] = $time;
        }


        ProcessTriggers('PreRerank');


        // Setup the sorting method
        $order_string = GetOrderString($GLOBALS['SORTINGS'][$GLOBALS['RANK_BY']]);


        // Setup the snapshot table
        $table = $DB->Row("SHOW CREATE TABLE topsites_Accounts");
        $DB->Update("DROP TABLE IF EXISTS topsites_Snapshot");
        $table['Create Table'] = str_replace('topsites_Accounts', 'topsites_Snapshot', $table['Create Table']);
        $DB->Update($table['Create Table']);


        // Reset all ranks to zero
        $DB->Update("UPDATE topsites_Accounts SET Overall_Rank=0");


        // Initialize the ranking counter
        $DB->Update("SET @rank=0");


        // Process overall ranks
        $user_sort = !IsEmptyString($GLOBALS['CUSTOM_SORT']) ? ", {$GLOBALS['CUSTOM_SORT']}" : '';
        $DB->Update("UPDATE topsites_Accounts SET Overall_Rank=@rank:=@rank+1 WHERE Suspended=0 AND Status='Approved' ORDER BY $order_string DESC $user_sort");

        // Create snapshot
        $DB->Insert("INSERT INTO topsites_Snapshot SELECT * FROM topsites_Accounts WHERE Suspended=0 AND Status='Approved'");

        
        ProcessTriggers('PostRerank');


        // Update the last rerank time
        $times['Rerank'] = time();
        $times['Rerank_By'] = $from;

        IniWrite("{$GLOBALS['DDIR']}/times", $times);
        FileWrite("{$GLOBALS['DDIR']}/rerank", $time);
        RemoveCacheTimeFiles();
    }
    
    flock($fd, LOCK_UN);
    fclose($fd);

    return $lock;
}



## Remove the files to indicate that the pages need to be updated
function RemoveCacheTimeFiles()
{
    $files =& DirRead("{$GLOBALS['CDIR']}", '\.time$');

    foreach($files as $file)
    {
        FileRemove("{$GLOBALS['CDIR']}/$file");
    }
}



## Reset the current in and out hit counts to zero
function ResetCurrentHits($from)
{
    global $DB;

    // Rerank members immediately before the reset
    $reranked = RerankAccounts($from);


    if( $reranked === TRUE )
    {
        $fd = fopen("{$GLOBALS['DDIR']}/rslock", "a");
        $lock = flock($fd, LOCK_EX | LOCK_NB);

        // One at a time please
        if( $lock === TRUE )
        {
            $time = time();
            $date = date($date_format, time());
            $times =& IniParse("{$GLOBALS['DDIR']}/times");


            ProcessTriggers('PreReset');

            
            // Setup the sorting method
            $order_string = GetOrderString($GLOBALS['SORTINGS'][$GLOBALS['RANK_BY']]);


            // Update the previous values and inactive counts
            $DB->Update("UPDATE topsites_Accounts SET " .
                        "Last_Prod=Current_Prod, " .
                        "Last_Hits_In=Current_In, " . 
                        "Last_Hits_Out=Current_Out, " .
                        "Last_Sort=$order_string, " .
                        "Last_Overall=Overall_Rank, " .
                        "Inactive=IF(Current_In < 1, Inactive+1, 0)");


            // Update member stats
            $DB->Insert("INSERT INTO topsites_MemStats SELECT " .
                        "Username, " .
                        "'$date', " .
                        "Current_Prod, " .
                        "Current_In, " .
                        "Current_Out, " .
                        "Total_Prod, " .
                        "Total_In, " .
                        "Total_Out, " .
                        "Overall_Rank " .
                        "FROM topsites_Snapshot");


            // Update admin stats
            $active = $DB->Count("SELECT COUNT(*) FROM topsites_Snapshot WHERE Current_In > 0");
            $top_ranked = $DB->Count("SELECT Username FROM topsites_Snapshot WHERE Overall_Rank=1");
            $DB->Insert("INSERT INTO topsites_AdminStats SELECT " .
                        "'$date', " .
                        "SUM(Current_Prod), " .
                        "SUM(Current_In), " .
                        "SUM(Current_Out), " .
                        "'$active', " .
                        "'$top_ranked' " .
                        "FROM topsites_Snapshot");


            // Reset all hit counts to zero
            $DB->Update("UPDATE topsites_Accounts SET Current_Prod=0, Current_In=0, Current_Out=0");


            ProcessTriggers('PostReset');


            $times['Reset_By'] = $from;
            $times['Reset'] = $time;

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

        flock($fd, LOCK_UN);
        fclose($fd);
    }

    return $lock;
}



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

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

    $DB->Connect();

    ProcessTriggers('PreTotalReset');

    $DB->Update("UPDATE topsites_Accounts SET Total_Prod=0, Total_In=0, Total_Out=0, Last_Reset='$time'");

    ProcessTriggers('PostTotalReset');

    $times['Total_Reset'] = $time;

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



## Reset the ratings for all accounts to zero
/*function ResetRatings()
{
    global $DB;

    $DB->Connect();

    ProcessTriggers('PreRatingReset');

    $DB->Update("UPDATE topsites_Accounts SET Num_Ratings=0, Rating_Total=0");

    ProcessTriggers('PostRatingReset');
}*/



## Process defined triggers
function ProcessTriggers($type)
{
    global $DB;

    $type = $DB->Escape($type);

    $result = $DB->Query("SELECT * FROM topsites_Triggers WHERE Type='$type'");

    while($trigger = $DB->NextRow($result))
    {
        $username = '';

        $trigger['Action'] = preg_replace("/rand\((\d+),\s*(\d+)\)/ie", "rand($1, $2)", $trigger['Action']);

        if( $trigger['Username'] != 'ALL' )
        {
            $username = "WHERE Username='{$trigger['Username']}'";
        }

        $DB->Update("UPDATE topsites_Accounts SET {$trigger['Action']} $username");
    }

    $DB->Free($result);
}



## Update a ranking page cache file
function BuildPage($page)
{
    global $DB, $T;

    if( !file_exists("{$GLOBALS['DDIR']}/pages/$page") )
    {
        return;
    }

    $DB->Connect();
    
    $L_MINIMUM = $GLOBALS['MINIMUM_HITS'];    

    // Load ini files into global namespace
    LoadGlobalIni("{$GLOBALS['DDIR']}/language", 'LANGUAGE');
    LoadGlobalIni("{$GLOBALS['DDIR']}/times", 'TIMES');
 

    // Get the string that will be used to sort members
    $GLOBALS['ORDER_STRING'] = GetOrderString($GLOBALS['SORTINGS'][$GLOBALS['RANK_BY']]);

    // Minimum hits qualifier string
    $L_MIN_HITS_QUALIFIER = "{$GLOBALS['ORDER_STRING']} >= {$GLOBALS['MINIMUM_HITS']} AND";

    // Determine how many sites are eligible for ranking
    if( $GLOBALS['MINIMUM_HITS'] > 0 && !isset($GLOBALS['RANKABLE_SITES']) )
    {
        $GLOBALS['RANKABLE_SITES'] = $DB->Count("SELECT COUNT(*) FROM topsites_Snapshot WHERE {$GLOBALS['ORDER_STRING']} >= {$GLOBALS['MINIMUM_HITS']}");
    }


    // Adjust the minimum hits requirement if there are not enough sites to list
    if( $GLOBALS['RANKABLE_SITES'] < $GLOBALS['MINIMUM_SITES'] )
    {
        $L_MINIMUM = 0;
    }

    if( $L_MINIMUM == 0 )
    {
        $L_MIN_HITS_QUALIFIER = '';
    }


    // Setup template values
    $T['Total_Members'] = $DB->Count("SELECT COUNT(*) FROM topsites_Accounts WHERE Status='Approved'");
    $T['Last_Rerank'] = date($date_format, $GLOBALS['TIMES']['Rerank']);
    $T['Next_Rerank'] = date($date_format, $GLOBALS['TIMES']['Rerank'] + $GLOBALS['RERANK']);
    $T['Last_Reset'] = date($date_format, $GLOBALS['TIMES']['Reset']);
    $T['Next_Reset'] = date($date_format, $GLOBALS['TIMES']['Reset']  + $GLOBALS['RESET']);
    $T['Script_URL'] = $GLOBALS['SCRIPT_URL'];    

    ob_start();
    require_once("{$GLOBALS['DDIR']}/pages/$page.comp");
    $page_code = ob_get_contents();
    ob_end_clean();

    FileWrite("{$GLOBALS['CDIR']}/$page", $page_code);
    FileWrite("{$GLOBALS['CDIR']}/$page.time", $GLOBALS['NOW']);
}



// See if account information is blacklisted
function IsBlacklisted(&$data)
{
    global $DB;

    $blacklisted = FALSE;
    $item = '';
    $siteinfo = "{$_POST['Title']} {$_POST['Description']}";
    $domainip = GetIPFromUrl($data['Site_URL']);

    $check = array('domain' => $data['Site_URL'],
                   'domainip' => $domainip,
                   'word' => $siteinfo,
                   'ipaddress' => $_SERVER['REMOTE_ADDR'],
                   'email' => $data['Email']);

    $result = $DB->Query("SELECT * FROM topsites_Blacklist ORDER BY Type");
    
    while( $ban = $DB->NextRow($result) )
    {
        if( !$ban['IsRegex'] )
        {
            $ban['Value'] = preg_quote($ban['Value']);
        }

        if( preg_match("|({$ban['Value']})|i", $check[$ban['Type']], $matches) )
        {
            $blacklisted = TRUE;
            $item = $matches[1];
            break;
        }
    }

    $DB->Free($result);

    return array($blacklisted, $item);
}



// Remove unconfirmed accounts older than 4 days
function RemoveUnconfirmed()
{
    global $DB;

    $too_old = time() - 345600;

    $DB->Connect();

    $result = $DB->Query("SELECT Username FROM topsites_Accounts WHERE Status='Unconfirmed' AND Signup <= $too_old");
    $removed = $DB->NumRows($result);

    while( $account = $DB->NextRow($result) )
    {
        DoAccountDeletion($account['Username']);
    }

    $DB->Free($result);
    $DB->Disconnect();

    return $removed;
}

// Handle the actual account deletion
function DoAccountDeletion($username)
{
    global $DB;

    $DB->Connect();

    $username = $DB->Escape($username);

    // Remove all account information from the database
    $DB->Update("DELETE FROM topsites_Accounts WHERE Username='$username'");
    $DB->Update("DELETE FROM topsites_AccountEdits WHERE Username='$username'");
    $DB->Update("DELETE FROM topsites_HitIPs WHERE Username='$username'");
    $DB->Update("DELETE FROM topsites_RateIPs WHERE Username='$username'");
    $DB->Update("DELETE FROM topsites_Cheats WHERE Username='$username'");
    $DB->Update("DELETE FROM topsites_MemStats WHERE Username='$username'");
}



// Load data from an ini file into the global namespace
function LoadGlobalIni($filename, $name)
{
    if( !isset($GLOBALS[$name]) )
    {
        $GLOBALS[$name] =& IniParse($filename);
    }
}

// Backup SQL information to a text file
function DoSQLBackup($backup_file)
{
    global $DB;

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

    $tables = array_keys($tables);

    $DB->Connect();

    $DB->BackupTables($tables, "{$GLOBALS['DDIR']}/$backup_file");

    $DB->Disconnect();
}



// Restore SQL information from a text file
function DoSQLRestore($backup_file)
{
    global $DB;

    $DB->Connect();

    $DB->RestoreTables("{$GLOBALS['DDIR']}/$backup_file");

    $DB->Disconnect();
}



// Backup data files to a single binary file
function DoDataBackup($backup_file)
{
    $files = array('rerank', 'reset', 'times');
    $directories = array('pages', 'reject');


    $fd = fopen("{$GLOBALS['DDIR']}/$backup_file", "w");

    foreach( $files as $file )
    {
        $data = file_get_contents("{$GLOBALS['DDIR']}/$file");

        UnixFormat($data);

        fwrite($fd, pack("i", strlen("$file")));
        fwrite($fd, "$file");
        fwrite($fd, pack("i", strlen($data)));
        fwrite($fd, $data);
    }

    foreach( $directories as $dir )
    {
        $dir_contents =& DirRead("{$GLOBALS['DDIR']}/$dir", '^[^.]');

        foreach( $dir_contents as $file )
        {
            if( is_file("{$GLOBALS['DDIR']}/$dir/$file") )
            {
                $data = file_get_contents("{$GLOBALS['DDIR']}/$dir/$file");

                UnixFormat($data);

                fwrite($fd, pack("i", strlen("$dir/$file")));
                fwrite($fd, "$dir/$file");
                fwrite($fd, pack("i", strlen($data)));
                fwrite($fd, $data);
            }
        }
    }

    fclose($fd);

    Mode($GLOBALS['PERMISSIONS_FILE'], "{$GLOBALS['DDIR']}/$backup_file");
}



// Restore data files from a single binary file
function DoDataRestore($backup_file)
{   
    $fd = fopen("{$GLOBALS['DDIR']}/$backup_file", "r");

    while( !feof($fd) )
    {
        ## Get the size of the filename
        $file_size = fread($fd, 4);

        if( feof($fd) )
        {
            break;
        }

        $file_size = unpack("i1int", $file_size);

        ## Read the filename
        $file_name = fread($fd, $file_size['int']);

        ## Get the size of the file data
        $data_size = fread($fd, 4);
        $data_size = unpack("i1int", $data_size);

        ## Read the file data
        $data = '';

        if( $data_size['int'] > 0 )
        {
            $data = fread($fd, $data_size['int']);
        }

        ## Restore the file
        FileWrite("{$GLOBALS['DDIR']}/$file_name", $data);
    }

    fclose($fd);
}

?>
Return current item: DDL CMS