Esempio n. 1
0
function _init_loadSettings()
{
    // get settings filenames and paths (either)
    list($hostnameWithoutPort) = explode(':', strtolower(@$_SERVER['HTTP_HOST']));
    $hostnameWithoutPort = preg_replace('/[^\\w\\-\\.]/', '', $hostnameWithoutPort);
    // security: HTTP_HOST is user defined - remove non-filename chars to prevent ../ attacks
    $hostnameWithoutPort = preg_replace('/^www\\./i', '', $hostnameWithoutPort);
    // v2.50 - usability: don't require www. prefix so www.example.com and example.com both check for settings.example.com.php
    $settings_fileName = 'settings.' . preg_replace('/[^\\w\\-\\.]/', '', $hostnameWithoutPort) . '.php';
    $settings_filePath = DATA_DIR . '/' . $settings_fileName;
    // supports host based settings files such as: /data/settings.localhost.php
    define('SETTINGS_DEV_FILENAME', $settings_fileName);
    define('SETTINGS_DEV_FILEPATH', DATA_DIR . '/' . SETTINGS_DEV_FILENAME);
    // set settings name and path for this server
    $useDev = is_file(SETTINGS_DEV_FILEPATH);
    define('SETTINGS_FILENAME', $useDev ? SETTINGS_DEV_FILENAME : 'settings.dat.php');
    define('SETTINGS_FILEPATH', $useDev ? SETTINGS_DEV_FILEPATH : DATA_DIR . '/settings.dat.php');
    // Require hostname-based settings files on development server domains (this section to be expanded)
    if (isInstalled() && isDevServer() && !is_file(SETTINGS_DEV_FILEPATH)) {
        header("Content-type: text/plain");
        die("Development server requires custom settings files.  Delete /data/isInstalled.php and re-install to create one.");
    }
    // load settings
    global $SETTINGS;
    if (!is_file(SETTINGS_FILEPATH)) {
        renameOrRemoveDefaultFiles();
    }
    // rename settings.dat.php.default to settings.dat.php
    $SETTINGS = loadStructOrINI(SETTINGS_FILEPATH);
    // legacy support
    $SETTINGS['advanced']['encryptPasswords'] = 1;
    // added in 2.08, removed in 2.62 (force on for legacy support since encryption is always required now)
    ### set defaults (if not already defined in settings file - this happens when a user upgrades)
    // NOTE: Do this here for future instead of _upgradeSettings()
    $defaults = array('language' => '', 'adminEmail' => '', 'adminUrl' => '', 'cookiePrefix' => substr(md5(mt_rand()), 0, 5) . '_', 'activePlugins' => '', 'headerImageUrl' => '', 'footerHTML' => '', 'dateFormat' => '', 'cssTheme' => 'blue.css', 'webRootDir' => @$_SERVER['DOCUMENT_ROOT'], 'wysiwyg' => array(), 'advanced' => array(), 'bgtasks_lastRun' => '0', 'bgtasks_lastEmail' => '0', 'webPrefixUrl' => '');
    $wysiwygDefaults = array('wysiwygLang' => 'en', 'includeDomainInLinks' => '0');
    $advancedDefaults = array('imageResizeQuality' => 80, 'showExpandedMenu' => 0, 'disableFlashUploader' => 0, 'codeGeneratorExpertMode' => 0, 'hideLanguageSettings' => 0, 'session_cookie_domain' => '', 'session_save_path' => '', 'useDatepicker' => 0, 'requireHTTPS' => 0, 'httpProxyServer' => '', 'allowRelatedRecordsDragSorting' => 0, 'outgoingMail' => 'sendOnly', 'languageDeveloperMode' => 0, 'login_expiry_limit' => '30', 'login_expiry_unit' => 'minutes', 'restrictByIP' => 0, 'restrictByIP_allowed' => '', 'smtp_method' => 'php', 'smtp_hostname' => '', 'smtp_port' => '', 'smtp_username' => '', 'smtp_password' => '', 'phpHideErrors' => '0', 'phpEmailErrors' => '0', 'checkReferer' => '1', 'disableAutocomplete' => '0');
    foreach ($defaults as $key => $value) {
        if (!array_key_exists($key, $SETTINGS)) {
            $SETTINGS[$key] = $value;
        }
    }
    foreach ($wysiwygDefaults as $key => $value) {
        if (!array_key_exists($key, $SETTINGS['wysiwyg'])) {
            $SETTINGS['wysiwyg'][$key] = $value;
        }
    }
    foreach ($advancedDefaults as $key => $value) {
        if (!array_key_exists($key, $SETTINGS['advanced'])) {
            $SETTINGS['advanced'][$key] = $value;
        }
    }
    ### custom defaults
    // adminUrl - update if url path has changed
    if (defined('IS_CMS_ADMIN')) {
        $hasAdminPathChanged = parse_url(thisPageUrl(), PHP_URL_PATH) != parse_url(@$SETTINGS['adminUrl'], PHP_URL_PATH);
        if ($hasAdminPathChanged) {
            // only update adminUrl when in the CMS admin
            $SETTINGS['adminUrl'] = @array_shift(explode('?', thisPageUrl()));
            // added in 2.12 - this must be set when admin.php is being access directly so we get the right URL
            saveSettings();
            alert(sprintf(t("Updating Program Url to: %s") . "<br/>\n", $SETTINGS['adminUrl']));
        }
    }
    // set default uploadDir and uploadUrl (do this here as above defaults code only runs when keys are undefined, not when they are blank)
    if (!$SETTINGS['uploadDir']) {
        $SETTINGS['uploadDir'] = 'uploads/';
        // previously: /../uploads/
    }
    if (!$SETTINGS['uploadUrl'] && !inCLI()) {
        // SCRIPT_NAME is set to filepath not web path when running in CLI, giving us incorrect values
        $SETTINGS['uploadUrl'] = dirname($_SERVER['SCRIPT_NAME']) . "/uploads/";
        // previously: /../uploads/
        $SETTINGS['uploadUrl'] = realUrl($SETTINGS['uploadUrl']);
        // remove ../ parent reference
        $SETTINGS['uploadUrl'] = parse_url($SETTINGS['uploadUrl'], PHP_URL_PATH);
        // remove scheme://hostname and leave /url/path
    }
    // remove old settings
    $removeKeys = array('vendorPoweredBy', 'timezoneOffsetAddMinus', 'timezoneOffsetHours', 'timezoneOffsetMinutes');
    $removeCount = 0;
    foreach ($removeKeys as $key) {
        if (array_key_exists($key, $SETTINGS)) {
            unset($SETTINGS[$key]);
            $removeCount++;
        }
    }
    if ($removeCount) {
        saveSettings();
    }
    // remove/convert old 'isInstalled' setting (from v2.09)
    if (array_key_exists('isInstalled', $SETTINGS)) {
        isInstalled(true);
        // set new installed status (semaphore file)
        unset($SETTINGS['isInstalled']);
        saveSettings();
    }
    // Update PHP config with SMTP values from settings (only effects users who call mail() explicitly)
    if ($GLOBALS['SETTINGS']['advanced']['smtp_hostname']) {
        ini_set('SMTP', $GLOBALS['SETTINGS']['advanced']['smtp_hostname']);
    }
    if ($GLOBALS['SETTINGS']['advanced']['smtp_port']) {
        ini_set('smtp_port', $GLOBALS['SETTINGS']['advanced']['smtp_port']);
    }
    // Note: We don't need to return $SETTINGS because we're modifying the global.
}
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;
}