function _upgradeToVersion2_09()
{
    global $SETTINGS;
    if ($SETTINGS['programVersion'] >= '2.09') {
        return;
    }
    // create missing table "_settings"
    createMissingSchemaTablesAndFields();
    //
    makeAllUploadRecordsRelative();
    //
    saveAndRefresh('2.09');
}
function installIfNeeded()
{
    global $SETTINGS, $APP, $TABLE_PREFIX;
    if (isInstalled()) {
        return;
    }
    // skip if already installed
    // rename default files
    renameOrRemoveDefaultFiles();
    // error checking
    if ($SETTINGS['uploadDir'] && !is_dir($SETTINGS['uploadDir'])) {
        print "Upload directory doesn't exist, please update 'uploadDir' in /data/" . SETTINGS_FILENAME . "<br/>\n";
        print "Current uploadDir value: " . htmlencode($SETTINGS['uploadDir']) . "<br/>\n";
        print "Suggested uploadDir value: uploads/ or ../uploads/<br/>\n";
        exit;
    }
    // error checking
    checkFilePermissions();
    // display license
    if (@$_REQUEST['menu'] == 'license') {
        showInterface('license.php');
    }
    // save
    if (@$_REQUEST['save']) {
        // error checking
        if (!$_REQUEST['licenseCompanyName']) {
            alert("Please enter your 'Company Name'<br/>\n");
        }
        if (!$_REQUEST['licenseDomainName']) {
            alert("Please enter your 'Domain Name'<br/>\n");
        }
        if (!$_REQUEST['licenseProductId']) {
            alert("Please enter your 'Product Id'<br/>\n");
        } else {
            if (!isValidProductId($_REQUEST['licenseProductId'])) {
                alert("Invalid Product Id!<br/>\n");
            }
        }
        if (!$_REQUEST['agreeToOneInstall']) {
            alert("Please check 'I agree not to use this 'Product Id' for multiple installs'<br/>\n");
        }
        if (!$_REQUEST['understandTermination']) {
            alert("Please check 'I understand doing so may cause be to lose my right to use this software'<br/>\n");
        }
        if (!$_REQUEST['agreeToLicense']) {
            alert("Please check 'I accept the terms of the License Agreement'<br/>\n");
        }
        if (!$_REQUEST['mysqlHostname']) {
            alert("Please enter your 'MySQL Hostname'<br/>\n");
        }
        if (!$_REQUEST['mysqlDatabase']) {
            alert("Please enter your 'MySQL Database'<br/>\n");
        }
        if (!$_REQUEST['mysqlUsername']) {
            alert("Please enter your 'MySQL Username'<br/>\n");
        }
        if (!$_REQUEST['mysqlTablePrefix']) {
            alert("Please enter your 'MySQL Table Prefix'<br/>\n");
        } elseif (preg_match("/[A-Z]/", $_REQUEST['mysqlTablePrefix'])) {
            alert("Value for 'MySQL Table Prefix' must be lowercase.<br/>\n");
        } elseif (!preg_match("/^[a-z]/i", $_REQUEST['mysqlTablePrefix'])) {
            alert("Value for 'MySQL Table Prefix' must start with a letter.<br/>\n");
        } elseif (!preg_match("/_\$/", $_REQUEST['mysqlTablePrefix'])) {
            alert("Value for 'MySQL Table Prefix' must end in underscore.<br/>\n");
        }
        // New Installation
        if (!@$_REQUEST['restoreFromBackup']) {
            if (!$_REQUEST['adminFullname']) {
                alert("Please enter 'Admin Full Name'<br/>\n");
            }
            if (!$_REQUEST['adminEmail']) {
                alert("Please enter 'Admin Email'<br/>\n");
            } elseif (!isValidEmail($_REQUEST['adminEmail'])) {
                alert("Please enter a valid email for 'Admin Email' (Example: user@example.com)<br/>\n");
            }
            if (!$_REQUEST['adminUsername']) {
                alert("Please enter 'Admin Username'<br/>\n");
            }
            $passwordErrors = getNewPasswordErrors($_REQUEST['adminPassword1'], $_REQUEST['adminPassword2'], $_REQUEST['adminUsername']);
            // v2.52
            if ($passwordErrors) {
                alert(nl2br(htmlencode($passwordErrors)));
            }
        }
        // Restore from Backup
        if (@$_REQUEST['restoreFromBackup']) {
            if (!$_REQUEST['restore']) {
                alert("Please select a backup file to restore<br/>\n");
            }
        }
        // Advanced - v2.53
        if (!@$_REQUEST['useCustomSettingsFile']) {
            if (is_file(SETTINGS_DEV_FILEPATH)) {
                alert(t("You must select 'Use Custom Settings File' since a custom settings file for this domain already exists!") . "<br/>\n");
            } elseif (isDevServer()) {
                alert("This is a development server, you must select 'Use Custom Settings File'." . "<br/>\n");
            }
        }
        if (@$_REQUEST['webPrefixUrl'] != '') {
            if (!preg_match("|^(\\w+:/)?/|", $_REQUEST['webPrefixUrl'])) {
                alert(t("Website Prefix URL must start with /") . "<br/>\n");
            }
            if (preg_match("|/\$|", $_REQUEST['webPrefixUrl'])) {
                alert(t("Website Prefix URL cannot end with /") . "<br/>\n");
            }
        }
        // update settings (not saved unless there are no errors)
        $SETTINGS['cookiePrefix'] = substr(md5(mt_rand()), 0, 5) . '_';
        //v2.51 shortened prefix so it's easy to see full cookie names in browser cookie list
        $SETTINGS['adminEmail'] = @$SETTINGS['adminEmail'] ? $SETTINGS['adminEmail'] : $_REQUEST['adminEmail'];
        $SETTINGS['licenseCompanyName'] = $_REQUEST['licenseCompanyName'];
        $SETTINGS['licenseDomainName'] = $_REQUEST['licenseDomainName'];
        $SETTINGS['licenseProductId'] = $_REQUEST['licenseProductId'];
        $SETTINGS['webRootDir'] = @$SETTINGS['webRootDir'] ? $SETTINGS['webRootDir'] : @$_SERVER['DOCUMENT_ROOT'];
        $SETTINGS['mysql']['hostname'] = $_REQUEST['mysqlHostname'];
        $SETTINGS['mysql']['database'] = $_REQUEST['mysqlDatabase'];
        $SETTINGS['mysql']['username'] = $_REQUEST['mysqlUsername'];
        $SETTINGS['mysql']['password'] = $_REQUEST['mysqlPassword'];
        $SETTINGS['mysql']['tablePrefix'] = $_REQUEST['mysqlTablePrefix'];
        $TABLE_PREFIX = $_REQUEST['mysqlTablePrefix'];
        // update TABLE_PREFIX global as well.
        $SETTINGS['webPrefixUrl'] = $_REQUEST['webPrefixUrl'];
        // display errors
        if (alert()) {
            require "lib/menus/install.php";
            exit;
        }
        // connect to mysql
        $errors = connectToMySQL('returnErrors');
        if ($errors) {
            alert($errors);
            require "lib/menus/install.php";
            exit;
        } else {
            connectToMySQL();
        }
        // create schema tables
        createMissingSchemaTablesAndFields();
        clearAlertsAndNotices();
        // don't show "created table/field" alerts
        // New Installation: check if admin user already exists
        if (!@$_REQUEST['restoreFromBackup']) {
            $passwordHash = getPasswordDigest($_REQUEST['adminPassword1']);
            $identicalUserExists = mysql_count('accounts', array('username' => $_REQUEST['adminUsername'], 'password' => $passwordHash, 'isAdmin' => '1'));
            if (!$identicalUserExists) {
                // if the don't exist, check if a user with the same username exists and show an error if they do
                $count = mysql_count('accounts', array('username' => $_REQUEST['adminUsername']));
                if (!$identicalUserExists && $count > 0) {
                    alert("Admin username already exists, please choose another.<br/>\n");
                }
            }
            // create admin user
            if (!$identicalUserExists && !alert()) {
                mysqlStrictMode(false);
                // disable Mysql strict errors for when a field isn't defined below (can be caused when fields are added later)
                mysql_query("INSERT INTO `{$TABLE_PREFIX}accounts` SET\n                          createdDate      = NOW(),\n                          createdByUserNum = '0',\n                          updatedDate      = NOW(),\n                          updatedByUserNum = '0',\n                          fullname         = '" . mysql_escape($_REQUEST['adminFullname']) . "', email    = '" . mysql_escape($_REQUEST['adminEmail']) . "',\n                          username         = '******'adminUsername']) . "', password = '******',\n                          disabled         = '0',\n                          isAdmin          = '1',\n                          expiresDate      = '0000-00-00 00:00:00',\n                          neverExpires     = '1'") or alert("MySQL Error Creating Admin User:<br/>\n" . htmlencode(mysql_error()) . "\n");
                // create accesslist entry
                mysql_query("INSERT INTO `{$TABLE_PREFIX}_accesslist` (userNum, tableName, accessLevel, maxRecords, randomSaveId)\n                          VALUES (LAST_INSERT_ID(), 'all', '9', NULL, '1234567890')") or alert("MySQL Error Creating Admin Access List:<br/>\n" . htmlencode(mysql_error()) . "\n");
            }
        }
        // Restore from Backup: Restore backup file
        if (@$_REQUEST['restoreFromBackup']) {
            $userCount = mysql_count('accounts');
            if ($userCount) {
                $userTable = $TABLE_PREFIX . 'accounts';
                $errorMessage = sprintf("Can't restore from backup because it would overwrite the %s existing user accounts in the specified database location.<br/>\n", $userCount);
                $errorMessage .= sprintf("Try changing the MySQL Database or Table Prefix to restore to a different location, or remove existing users from '%s'.<br/>\n", $userTable);
                alert($errorMessage);
            } else {
                // restore database
                $filename = @$_REQUEST['restore'];
                mysqlStrictMode(false);
                // disable Mysql strict errors
                restoreDatabase(DATA_DIR . '/backups/' . $filename);
                notice("Restored backup file /data/backups/{$filename}");
                makeAllUploadRecordsRelative();
            }
        }
        // save settings
        if (!alert()) {
            saveSettings(@$_REQUEST['useCustomSettingsFile']);
            isInstalled(true);
            // save installed status
            redirectBrowserToURL('?menu=home', true);
            // refresh page
            exitl;
        }
    }
    // set defaults
    if (!array_key_exists('licenseDomainName', $_REQUEST)) {
        $_REQUEST['licenseDomainName'] = $_SERVER['HTTP_HOST'];
    }
    if (!array_key_exists('mysqlHostname', $_REQUEST)) {
        $_REQUEST['mysqlHostname'] = $SETTINGS['mysql']['hostname'];
    }
    if (!array_key_exists('mysqlDatabase', $_REQUEST)) {
        $_REQUEST['mysqlDatabase'] = $SETTINGS['mysql']['database'];
    }
    if (!array_key_exists('mysqlUsername', $_REQUEST)) {
        $_REQUEST['mysqlUsername'] = $SETTINGS['mysql']['username'];
    }
    if (!array_key_exists('mysqlTablePrefix', $_REQUEST)) {
        $_REQUEST['mysqlTablePrefix'] = $SETTINGS['mysql']['tablePrefix'];
    }
    // show form
    require "lib/menus/install.php";
    exit;
}
function admin_dispatchAction($action)
{
    if ($action == 'general') {
        showInterface('admin/general.php');
    } elseif ($action == 'adminSave') {
        admin_saveSettings('admin/general.php');
    } elseif ($action == 'vendor') {
        showInterface('admin/vendor.php');
    } elseif ($action == 'vendorSave') {
        admin_saveSettings('admin/vendor.php');
    } elseif ($action == 'phpinfo') {
        disableInDemoMode('', 'admin/general.php');
        phpinfo();
        print "<h2>get_loaded_extensions()</h2>\n" . implode("<br/>\n", get_loaded_extensions()) . "\n";
        if (function_exists('apache_get_modules')) {
            print "<h2>apache_get_modules()</h2>\n" . implode("<br/>\n", apache_get_modules()) . "\n";
        }
        print "<h2>get_defined_constants()</h2>\n<xmp>" . print_r(get_defined_constants(), true) . "</xmp>\n";
        //
        $mbInfo = mb_get_info();
        ksort($mbInfo);
        print "<h2>mb_get_info()</h2>\n<xmp>" . print_r($mbInfo, true) . "</xmp>\n";
        exit;
    } elseif ($action == 'ulimit') {
        disableInDemoMode('', 'admin/general.php');
        print "<h2>Soft Resource Limits (ulimit -a -S)</h2>\n";
        list($maxCpuSeconds, $memoryLimitKbytes, $maxProcessLimit, $ulimitOutput) = getUlimitValues('soft');
        showme($ulimitOutput);
        print "<h2>Hard Resource Limits (ulimit -a -H)</h2>\n";
        list($maxCpuSeconds, $memoryLimitKbytes, $maxProcessLimit, $ulimitOutput) = getUlimitValues('soft');
        showme($ulimitOutput);
        exit;
    } elseif ($action == 'updateDate') {
        getAjaxDate();
    } elseif ($action == 'getUploadPathPreview') {
        getUploadPathPreview(@$_REQUEST['dirOrUrl'], @$_REQUEST['inputValue'], @$_REQUEST['isCustomField'], true);
    } elseif ($action == 'plugins') {
        // allow disabling plugins
        if (file_exists("{$GLOBALS['PROGRAM_DIR']}/plugins/_disable_all_plugins.txt")) {
            alert('Development Mode: Plugins are disabled.  Remove or rename /plugins/_disable_all_plugins.txt to enable.<br/>');
        } else {
        }
        showInterface('admin/plugins.php');
    } elseif ($action == 'pluginHooks') {
        showInterface('admin/pluginHooks.php');
    } elseif ($action == 'deactivatePlugin') {
        security_dieUnlessPostForm();
        security_dieUnlessInternalReferer();
        security_dieOnInvalidCsrfToken();
        disableInDemoMode('plugins', 'admin/plugins.php');
        deactivatePlugin(@$_REQUEST['file']);
        redirectBrowserToURL('?menu=admin&action=plugins', true);
        exit;
    } elseif ($action == 'activatePlugin') {
        security_dieUnlessPostForm();
        security_dieUnlessInternalReferer();
        security_dieOnInvalidCsrfToken();
        disableInDemoMode('plugins', 'admin/plugins.php');
        activatePlugin(@$_REQUEST['file']);
        redirectBrowserToURL('?menu=admin&action=plugins', true);
        exit;
    } elseif ($action == 'backup') {
        security_dieUnlessPostForm();
        security_dieUnlessInternalReferer();
        security_dieOnInvalidCsrfToken();
        disableInDemoMode('', 'admin/general.php');
        $filename = backupDatabase(null, @$_REQUEST['backupTable']);
        notice(sprintf(t('Created backup file %1$s (%2$s seconds)'), $filename, showExecuteSeconds(true)));
        showInterface('admin/general.php');
        exit;
    } elseif ($action == 'restore') {
        security_dieUnlessPostForm();
        security_dieUnlessInternalReferer();
        security_dieOnInvalidCsrfToken();
        disableInDemoMode('', 'admin/general.php');
        $filename = @$_REQUEST['file'];
        restoreDatabase(DATA_DIR . '/backups/' . $filename);
        notice("Restored backup file /data/backups/{$filename}");
        makeAllUploadRecordsRelative();
        showInterface('admin/general.php');
        exit;
    } elseif ($action == 'bgtasksLogsClear') {
        security_dieUnlessPostForm();
        security_dieUnlessInternalReferer();
        security_dieOnInvalidCsrfToken();
        disableInDemoMode('', 'admin/general.php');
        mysql_delete('_cron_log', null, 'true');
        notice(t("Background Task logs have been cleared."));
        showInterface('admin/general.php');
        exit;
    } else {
        showInterface('admin/general.php');
    }
}