/** * 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]))); } }
/** * Test the consistency of the $_SERVER global. * * This function, based on the similarly-named function of the Yii requirements * check, validates several essential elements of $_SERVER * * @author Qiang Xue <*****@*****.**> * @link http://www.yiiframework.com/ * @copyright Copyright © 2008-2011 Yii Software LLC * @license http://www.yiiframework.com/license/ * @parameter string $thisFile * @return string */ function checkServerVar($thisFile = null) { $vars = array('HTTP_HOST', 'SERVER_NAME', 'SERVER_PORT', 'SCRIPT_NAME', 'SCRIPT_FILENAME', 'PHP_SELF', 'HTTP_ACCEPT', 'HTTP_USER_AGENT'); $missing = array(); foreach ($vars as $var) { if (!isset($_SERVER[$var])) { $missing[] = $var; } } if (!empty($missing)) { return installer_tr('$_SERVER does not have {vars}.', array('{vars}' => implode(', ', $missing))); } if (empty($thisFile)) { $thisFile = __FILE__; } if (realpath($_SERVER["SCRIPT_FILENAME"]) !== realpath($thisFile)) { return installer_t('$_SERVER["SCRIPT_FILENAME"] must be the same as the entry script file path.'); } if (!isset($_SERVER["REQUEST_URI"]) && isset($_SERVER["QUERY_STRING"])) { return installer_t('Either $_SERVER["REQUEST_URI"] or $_SERVER["QUERY_STRING"] must exist.'); } if (!isset($_SERVER["PATH_INFO"]) && strpos($_SERVER["PHP_SELF"], $_SERVER["SCRIPT_NAME"]) !== 0) { return installer_t('Unable to determine URL path info. Please make sure $_SERVER["PATH_INFO"] (or $_SERVER["PHP_SELF"] and $_SERVER["SCRIPT_NAME"]) contains proper value.'); } return ''; }
<?php // Dummy testing file for the codebase parser. // Valid: Yii::t('app', 'This and that thing\'s thing'); Yii::t("admin", "This and that \"thing\""); Yii::t("admin", "Messages (with parentheses)"); Yii::t('app', 'multiple') . ' ' . Yii::t('app', 'messages') . ' ' . Yii::t('app', 'on') . ' ' . Yii::t('app', 'the') . ' ' . Yii::t('app', 'same') . ' ' . Yii::t('app', 'line'); Yii::t('users', "multiline\nmessage"); Yii::t('app', 'message with params and {stuff}', array('{stuff}' => 'things')); Yii::t('app', 'Multi-line translation ' . 'message with splitting text.'); Yii::t('app', 'Multi-line translation ' . 'message with {param} text.', array('{param}' => 'things')); Yii::t('app', 'The maximum number of ' . 'hooks ({n}) has been reached for events of this type.', array('{n}' => $max)); installer_t('installer message'); installer_tr('installer message with {p}', array('{p}' => 'params')); // "Cheating" in utility classes by using a locally-defined function / looking for exceptions: $installer_t('Weekdays'); throw new Exception('Exceptions too'); // Miscellaneous things that were found but not parsed, and added here for extending the regex: Yii::t('profile', 'Manage Passwords for Third-Party Applications'); Yii::t('admin', 'Define how the system sends email by default.'); Yii::t('admin', 'Note that this will not supersede other email settings. Usage of these particular settings is a legacy feature. Unless this web server also serves as your company\'s primary mail server, it is recommended to instead use "{ma}" to set up email accounts for system usage instead.', array('{ma}' => CHtml::link(Yii::t('app', 'Manage Apps'), array('profile/manageCredentials')))); Yii::t('admin', 'Configure how X2Engine sends email when responding to new service case requests.'); // Not valid/ignored: Yii::t('users', $notastring); Yii::t('users', "this {$string} contains a variable");