function phpAds_performAutoMaintenance()
{
    global $phpAds_config;
    // Make sure that the output is sent to the browser before
    // loading libraries and connecting to the db
    flush();
    // Include required files
    if (!defined('LIBLOCKS_INCLUDED')) {
        require phpAds_path . '/libraries/lib-locks.inc.php';
    }
    // Load config from the db
    phpAds_LoadDbConfig();
    $last_run = $phpAds_config['maintenance_timestamp'];
    // Make sure that negative values don't break the script
    if ($last_run > 0) {
        $last_run = strtotime(date('Y-m-d H:00:05', $last_run));
    }
    if (time() >= $last_run + 3600) {
        if ($lock = phpAds_maintenanceGetLock()) {
            require phpAds_path . "/libraries/lib-userlog.inc.php";
            require phpAds_path . "/maintenance/lib-maintenance.inc.php";
            // Got the advisory lock, we can proceed running maintenance
            phpAds_userlogSetUser(phpAds_userAutoMaintenance);
            // Finally run maintenance
            phpAds_performMaintenance();
            // Release lock
            phpAds_maintenanceReleaseLock($lock);
        }
    }
}
// Figure out our location
if (strlen(__FILE__) > strlen(basename(__FILE__))) {
    define('phpAds_path', ereg_replace("[/\\\\]maintenance[/\\\\][^/\\\\]+\$", '', __FILE__));
} else {
    define('phpAds_path', '..');
}
// Include required files
require phpAds_path . "/config.inc.php";
require phpAds_path . "/libraries/lib-db.inc.php";
require phpAds_path . "/libraries/lib-dbconfig.inc.php";
require phpAds_path . "/libraries/lib-cache.inc.php";
require phpAds_path . "/libraries/lib-userlog.inc.php";
require phpAds_path . "/maintenance/lib-maintenance.inc.php";
// Make database connection and load config
phpAds_dbConnect();
phpAds_LoadDbConfig();
// Set maintenance usertype
phpAds_userlogSetUser(phpAds_userMaintenance);
// Sometimes cron jobs could start before the exact minute they were set,
// especially if many are scheduled at the same time (e.g. midnight)
//
// Wait a few seconds if needed, to ensure all goes well, otherwise
// maintenance won't work as it should
if (date('i') == 59 && date('s') >= 45) {
    sleep(60 - date('s'));
}
// Finally run maintenance
if (phpAds_performMaintenance()) {
    // Update the timestamp
    $res = phpAds_dbQuery("\n\t\tUPDATE\n\t\t\t" . $phpAds_config['tbl_config'] . "\n\t\tSET\n\t\t\tmaintenance_cron_timestamp = '" . time() . "'\n\t");
}