示例#1
0
/**
 * Exception handler.
 *
 * @global type $document
 * @global array $totalFailure
 * @global boolean $responding
 * @global type $standalone
 * @param type $e
 */
function handleReqException($e)
{
    global $document, $totalFailure, $responding, $standalone;
    $responding = true;
    $message = 'Exception: "' . $e->getMessage() . '" in ' . $e->getFile() . ' L' . $e->getLine() . "\n";
    foreach ($e->getTrace() as $stackLevel) {
        $message .= $stackLevel['file'] . ' L' . $stackLevel['line'] . ' ';
        if ($stackLevel['class'] != '') {
            $message .= $stackLevel['class'];
            $message .= '->';
        }
        $message .= $stackLevel['function'];
        $message .= "();\n";
    }
    $message = str_replace('{scenario}', 'uncaught exception', $totalFailure[0] . $message . $totalFailure[1]);
    echo strtr($document, array('{headerContent}' => '', '{bodyContent}' => $message));
    RIP();
}
示例#2
0
/**
 * Runs a named stage of the installation.
 *
 * @param $stage The named stage of installation.
 */
function installStage($stage)
{
    global $editions, $dbConfig, $dbKeys, $dateFields, $enabledModules, $dbo, $config, $confMap, $response, $silent, $stageLabels, $write, $nonFreeTables, $editionHierarchy;
    switch ($stage) {
        case 'validate':
            if ($config['dummy_data'] == 1 && $config['adminUsername'] != 'admin') {
                addValidationError('adminUsername', 'Cannot change administrator username if installing with sample data.');
            } else {
                if (empty($config['adminUsername'])) {
                    addValidationError('adminUsername', 'Admin username cannot be blank.');
                } elseif (is_int(strpos($config['adminUsername'], "'"))) {
                    addValidationError('adminUsername', 'Admin username cannot contain apostrophes');
                } elseif (preg_match('/^\\d+$/', $config['adminUsername'])) {
                    addValidationError('adminUsername', 'Admin username must contain at least one non-numeric character.');
                } elseif (!preg_match('/^\\w+$/', $config['adminUsername'])) {
                    addValidationError('adminUsername', 'Admin username may contain only alphanumeric characters and underscores.');
                }
            }
            if (empty($config['adminEmail']) || !preg_match('/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}$/i', $config['adminEmail'])) {
                addValidationError('adminEmail', 'Please enter a valid email address.');
            }
            if ($config['adminPass'] == '') {
                addValidationError('adminPass', 'Admin password cannot be blank.');
            }
            if (!$silent && !isset($_POST['adminPass2'])) {
                addValidationError('adminPass2', 'Please confirm the admin password.');
            } else {
                if (!$silent && $config['adminPass'] != $_POST['adminPass2']) {
                    addValidationError('adminPass2', 'Admin passwords did not match.');
                }
            }
            if (!empty($response['errors'])) {
                if (!$silent) {
                    RIP(installer_t('Please correct the following errors:'));
                } else {
                    outputErrors();
                }
            }
            break;
        case 'module':
            if (isset($_GET['module'])) {
                // Install only a named module
                installModule($_GET['module']);
            } else {
                // Install all modules:
                foreach ($enabledModules as $module) {
                    installModule($module, $silent);
                }
            }
            break;
        case 'config':
            // Configure with initial data and write files
            // Generate config file content:
            $gii = 1;
            if ($gii == '1') {
                $gii = "array(\n\t'class'=>'system.gii.GiiModule',\n\t'password'=>'" . str_replace("'", "\\'", $config['adminPass']) . "', \n\t/* If the following is removed, Gii defaults to localhost only. Edit carefully to taste: */\n\t 'ipFilters'=>false,\n)";
            } else {
                $gii = "array(\n\t'class'=>'system.gii.GiiModule',\n\t'password'=>'password',\n\t/* If the following is removed, Gii defaults to localhost only. Edit carefully to taste: */\n\t 'ipFilters'=>array('127.0.0.1', '::1'),\n)";
            }
            $X2Config = "<?php\n";
            foreach (array('appName', 'email', 'host', 'user', 'pass', 'dbname', 'version') as $confKey) {
                $X2Config .= "\${$confKey} = " . var_export($config[$confMap[$confKey]], 1) . ";\n";
            }
            $X2Config .= "\$buildDate = {$config['buildDate']};\n\$updaterVersion = '{$config['updaterVersion']}';\n";
            $X2Config .= empty($config['language']) ? '$language=null;' : "\$language='{$config['language']}';\n?>";
            // Save config values to be inserted in the database:
            $config['time'] = time();
            foreach ($dbKeys as $property) {
                $dbConfig['{' . $property . '}'] = $config[$property];
            }
            $contents = file_get_contents('webConfig.php');
            $contents = preg_replace('/\\$url\\s*=\\s*\'\'/', "\$url=" . var_export($config['baseUrl'] . $config['baseUri'], 1), $contents);
            $contents = preg_replace('/\\$user\\s*=\\s*\'\'/', "\$user="******"\$userKey=" . var_export($config['adminUserKey'], 1), $contents);
            file_put_contents('webConfig.php', $contents);
            if ($config['test_db']) {
                $filename = implode(DIRECTORY_SEPARATOR, array(__DIR__, 'protected', 'config', 'X2Config-test.php'));
                if (!empty($config['test_url'])) {
                    $defaultConfig = file_get_contents(implode(DIRECTORY_SEPARATOR, array(__DIR__, 'protected', 'tests', 'WebTestConfig_example.php')));
                    $webTestConfigFile = implode(DIRECTORY_SEPARATOR, array(__DIR__, 'protected', 'tests', 'WebTestConfig.php'));
                    $webTestUrl = rtrim($config['test_url'], '/') . '/';
                    $webTestRoot = rtrim(preg_replace('#index-test\\.php/?$#', '', trim($config['test_url'])), '/') . '/';
                    $testConstants = array('TEST_BASE_URL' => var_export($webTestUrl, 1), 'TEST_WEBROOT_URL' => var_export($webTestRoot, 1));
                    $webTestConfig = $defaultConfig;
                    foreach ($testConstants as $name => $value) {
                        $webTestConfig = preg_replace("/^defined\\('{$name}'\\) or define\\('{$name}'\\s*,.*\$/m", "defined('{$name}') or define('{$name}',{$value});", $webTestConfig);
                    }
                    file_put_contents($webTestConfigFile, $webTestConfig);
                }
            } else {
                $filename = implode(DIRECTORY_SEPARATOR, array(__DIR__, 'protected', 'config', 'X2Config.php'));
            }
            $handle = fopen($filename, 'w') or RIP(installer_tr('Could not create configuration file: {filename}.', array('{filename}' => $filename)));
            // Write core application configuration:
            fwrite($handle, $X2Config);
            fclose($handle);
            // Create an encryption key for credential storage:
            if (extension_loaded('openssl') && extension_loaded('mcrypt')) {
                $encryption = new EncryptUtil('protected/config/encryption.key', 'protected/config/encryption.iv');
                $encryption->saveNew();
            }
            $dbConfig['{adminPass}'] = md5($config['adminPass']);
            $dbConfig['{adminUserKey}'] = $config['adminUserKey'];
            try {
                foreach (array('', '-pro', '-pla') as $suffix) {
                    $sqlPath = "protected/data/config{$suffix}.sql";
                    $sqlFile = realpath($sqlPath);
                    if ($sqlFile) {
                        $sql = explode('/*&*/', strtr(file_get_contents($sqlFile), $dbConfig));
                        foreach ($sql as $sqlLine) {
                            $installConf = $dbo->prepare($sqlLine);
                            if (!$installConf->execute()) {
                                RIP(installer_t('Error applying initial configuration') . ': ' . implode(',', $installConf->errorInfo()));
                            }
                        }
                    } else {
                        if ($suffix == '') {
                            // Minimum requirement
                            RIP(installer_t('Could not find database configuration script') . " {$sqlPath}");
                        }
                    }
                }
            } catch (PDOException $e) {
                die($e->getMessage());
            }
            //			saveCrontab();
            break;
        case 'finalize':
            /**
             * Look for additional initialization files and perform final tasks
             */
            foreach ($editions as $ed) {
                // Add editional prefixes as necessary
                if (file_exists("initialize_{$ed}.php")) {
                    include "initialize_{$ed}.php";
                }
            }
            break;
        default:
            // Look for a named SQL file and run it:
            $stagePath = "protected/data/{$stage}.sql";
            if ($stage == 'dummy_data') {
                $stageLabels['dummy_data'] = sprintf($stageLabels['dummy_data'], $config['dummy_data'] ? 'insert' : 'delete');
            }
            if ((bool) (int) $config['dummy_data'] || $stage != 'dummy_data') {
                if ($sqlFile = realpath($stagePath)) {
                    $sql = explode('/*&*/', file_get_contents($sqlFile));
                    foreach ($sql as $sqlLine) {
                        $statement = $dbo->prepare($sqlLine);
                        try {
                            if (!$statement->execute()) {
                                RIP(installer_tr('Could not {stage}. SQL statement "{sql}" from {file} failed', array('{stage}' => $stageLabels[$stage], '{sql}' => substr(trim($sqlLine), 0, 50) . (strlen(trim($sqlLine)) > 50 ? '...' : ''), '{file}' => $sqlFile)) . '; ' . implode(',', $statement->errorInfo()));
                            }
                        } catch (PDOException $e) {
                            RIP(installer_tr("Could not {stage}", array('{stage}' => $stageLabels[$stage])) . '; ' . $e->getMessage());
                        }
                    }
                    // Hunt for init SQL files associated with other editions:
                    foreach ($editions as $ed) {
                        if ($sqlFile = realpath("protected/data/{$stage}-{$ed}.sql")) {
                            $sql = explode('/*&*/', file_get_contents($sqlFile));
                            foreach ($sql as $sqlLine) {
                                $statement = $dbo->prepare($sqlLine);
                                try {
                                    if (!$statement->execute()) {
                                        RIP(installer_tr('Could not {stage}. SQL statement "{sql}" from {file} failed', array('{stage}' => $stageLabels[$stage], '{sql}' => substr(trim($sqlLine), 0, 50) . (strlen($sqlLine) > 50 ? '...' : ''), '{file}' => $sqlFile)) . '; ' . implode(',', $statement->errorInfo()));
                                    }
                                } catch (PDOException $e) {
                                    RIP(installer_tr("Could not {stage}", array('{stage}' => $stageLabels[$stage])) . '; ' . $e->getMessage());
                                }
                            }
                        }
                    }
                    if ($stage == 'dummy_data') {
                        // Need to update the timestamp fields on all the sample data that has been inserted.
                        $dateGen = @file_get_contents(realpath("protected/data/dummy_data_date")) or RIP("Sample data generation date not set.");
                        $time = time();
                        $time2 = $time * 2;
                        $timeDiff = $time - (int) trim($dateGen);
                        foreach ($dateFields as $table => $fields) {
                            $tableEdition = 'opensource';
                            foreach ($editions as $ed) {
                                if (in_array($table, $nonFreeTables[$ed])) {
                                    $tableEdition = $ed;
                                    break;
                                }
                            }
                            if (!(bool) $editionHierarchy[$config['edition']][$tableEdition]) {
                                // Table not "contained" in the current edition
                                continue;
                            }
                            foreach ($fields as $field) {
                                try {
                                    $dbo->exec("UPDATE `{$table}` SET `{$field}`=`{$field}`+{$timeDiff} WHERE `{$field}` IS NOT NULL AND `{$field}`!=0 AND `{$field}`!=''");
                                } catch (Exception $e) {
                                    // Ignore it and move on; table/column doesn't exist.
                                    continue;
                                }
                            }
                            // Fix timestamps that are in the future.
                            /*
                             $ordered = array('lastUpdated','createDate');
                             if(count(array_intersect($ordered,$fields)) == count($ordered)) {
                             $affected = 0;
                             foreach($ordered as $field) {
                             $affected += $dbo->exec("UPDATE `$table` SET `$field`=$time2-`$field` WHERE `$field` > $time");
                             }
                             if($affected)
                             $dbo->exec("UPDATE `$table` set `lastUpdated`=`createDate`,`createDate`=`lastUpdated` WHERE `createDate` > `lastUpdated`");
                             }
                            */
                        }
                    }
                } else {
                    RIP(installer_t("Could not find installation stage database script") . " {$stagePath}");
                }
            } else {
                // This is the dummy data stage, and we need to clear out all unneeded files.
                // However, we should leave the files alone if this is a testing database reinstall.
                $stageLabels[$stage] = sprintf($stageLabels[$stage], 'remove');
                if (($paths = @(require_once realpath('protected/data/dummy_data_files.php'))) && !$config['test_db']) {
                    foreach ($paths as $pathClear) {
                        if ($path = realpath($pathClear)) {
                            FileUtil::rrmdir($path, '/\\.htaccess$/');
                        }
                    }
                }
            }
            break;
    }
    if (in_array($stage, array_keys($stageLabels)) && $stage != 'finalize' && !($stage == 'validate' && $silent)) {
        ResponseUtil::respond(installer_tr("Completed: {stage}", array('{stage}' => $stageLabels[$stage])));
    }
}