Example #1
0
 public function run($args)
 {
     $encryption = new EncryptUtil('protected/config/encryption.key', 'protected/config/encryption.iv');
     if ($encryption->saveNew()) {
         echo "\nSuccessfully saved new encryption key/iv\n";
     }
 }
Example #2
0
 public function run($args)
 {
     $encryption = new EncryptUtil('config/encryption.key', 'config/encryption.iv');
     try {
         $encryption->saveNew();
         $this->setConfigPermissions(100600);
         echo "\nSuccessfully saved new encryption key/iv\n";
     } catch (Exception $e) {
         throw new CException(Yii::t('admin', "Failed to create a secure encryption key. The error message was: {message}", array('{message}' => $e->getMessage())));
     }
 }
 /**
  * Decrypts the attribute for setting/use in the interface.
  * @param string $name Attribute to be transformed
  * @return string
  */
 public function unpackAttribute($name)
 {
     if ($this->getOwner()->{$name}) {
         return self::$encrypt ? self::$encryption->decrypt($this->getOwner()->{$name}) : $this->getOwner()->{$name};
     } else {
         return null;
     }
 }
Example #4
0
 /**
  * 根据传入的 key 生成一个 43 位的key.
  *
  * @param string $token
  */
 public static function generate_weixin_aeskey($token)
 {
     $current_length = mb_strlen($token, 'UTF-8');
     $aeskey = '';
     if ($current_length <= 43) {
         $aeskey = EncryptUtil::rand_code(43 - $current_length);
         $aeskey .= $token;
     } else {
         $aeskey = mb_substr($token, 0, 43, 'utf-8');
     }
     return $aeskey;
 }
Example #5
0
 public static function encrypt($content, $offset, $key, $times)
 {
     $tempInt = EncryptUtil::bytesToInteger($content, $offset);
     $y = $tempInt[0];
     $z = $tempInt[1];
     $sum = 0;
     $a = $key[0];
     $b = $key[1];
     $c = $key[2];
     $d = $key[3];
     $delta = 0x9e3779b9;
     for ($i = 0; $i < $times; $i++) {
         $sum += $delta;
         $y += ($z << 4) + $a ^ $z + $sum ^ ($z >> 5) + $b;
         $z += ($y << 4) + $c ^ $y + $sum ^ ($y >> 5) + $d;
     }
     $tempInt[0] = $y;
     $tempInt[1] = $z;
     return EncryptUtil::integerToBytes($tempInt, 0);
 }
Example #6
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])));
    }
}
Example #7
0
 /**
  * Check user password and echo either an error message or a unique id which gets used on
  * subsequent requests to ensure that the user confirmed the action with their password
  */
 public static function superMassActionPasswordConfirmation()
 {
     if (!isset($_POST['password'])) {
         throw new CHttpException(400, Yii::t('app', 'Bad Request'));
     }
     $loginForm = new LoginForm();
     $loginForm->username = Yii::app()->params->profile->username;
     $loginForm->password = $_POST['password'];
     if ($loginForm->validate()) {
         do {
             $uid = EncryptUtil::secureUniqueIdHash64();
         } while (isset($_SESSION[self::SESSION_KEY_PREFIX_PASS_CONFIRM . $uid]));
         $_SESSION[self::SESSION_KEY_PREFIX_PASS_CONFIRM . $uid] = true;
         echo CJSON::encode(array(true, $uid));
     } else {
         echo CJSON::encode(array(false, Yii::t('app', 'incorrect password')));
     }
 }
Example #8
0
 /**
  * Rebuilds the configuration file and performs the final few little update tasks.
  * 
  * @param type $newversion If set, change the version to this value in the resulting config file
  * @param type $newupdaterVersion If set, change the updater version to this value in the resulting config file
  * @param type $newbuildDate If set, change the build date to this value in the resulting config file
  * @param string $newAppName If set, will be used to replace the app name in the config file. 
  * @return bool
  * @throws Exception
  */
 public function regenerateConfig($newversion = Null, $newupdaterVersion = Null, $newbuildDate = null, $newAppName = null)
 {
     $newbuildDate = $newbuildDate == null ? time() : $newbuildDate;
     $basePath = Yii::app()->basePath;
     $configPath = implode(DIRECTORY_SEPARATOR, array($basePath, 'config', self::$configFilename));
     if (!file_exists($configPath)) {
         // App is using the old config files. New ones will be generated.
         include implode(DIRECTORY_SEPARATOR, array($basePath, 'config', 'emailConfig.php'));
         include implode(DIRECTORY_SEPARATOR, array($basePath, 'config', 'dbConfig.php'));
     } else {
         include $configPath;
     }
     if (!isset($appName)) {
         if (!empty(Yii::app()->name)) {
             $appName = Yii::app()->name;
         } else {
             $appName = "X2Engine";
         }
     }
     if ($newAppName) {
         $appName = $newAppName;
     }
     if (!isset($email)) {
         if (!empty($this->settings->emailFromAddr)) {
             $email = $this->settings->emailFromAddr;
         } else {
             $email = 'contact@' . $_SERVER['SERVER_NAME'];
         }
     }
     if (!isset($language)) {
         if (!empty(Yii::app()->language)) {
             $language = Yii::app()->language;
         } else {
             $language = 'en';
         }
     }
     $config = "<?php\n";
     if (!isset($buildDate)) {
         $buildDate = $newbuildDate;
     }
     if (!isset($updaterVersion)) {
         $updaterVersion = '';
     }
     foreach (array('version', 'updaterVersion', 'buildDate') as $var) {
         if (${'new' . $var} !== null) {
             ${$var} = ${'new' . $var};
         }
     }
     foreach (self::$_configVarNames as $var) {
         if (!empty(${"new{$var}"})) {
             ${$var} = ${"new{$var}"};
         }
         $config .= "\${$var}=" . var_export(${$var}, 1) . ";\n";
     }
     $config .= "?>";
     if (file_put_contents($configPath, $config) === false) {
         $contents = $this->isConsole ? "\n{$config}" : "<br /><pre>\n{$config}\n</pre>";
         throw new CException(Yii::t('admin', "Failed to set version info in the configuration. To fix this issue, edit {file} and ensure its contents are as follows: {contents}", array('{file}' => $configPath, '{contents}' => $contents)));
     } else {
         // Create a new encryption key if none exists
         $key = implode(DIRECTORY_SEPARATOR, array(Yii::app()->basePath, 'config', 'encryption.key'));
         $iv = implode(DIRECTORY_SEPARATOR, array(Yii::app()->basePath, 'config', 'encryption.iv'));
         if (!file_exists($key) || !file_exists($iv)) {
             try {
                 $encryption = new EncryptUtil($key, $iv);
                 $encryption->saveNew();
             } catch (Exception $e) {
                 throw new CException(Yii::t('admin', "Succeeded in setting the version info in the configuration, but failed to create a secure encryption key. The error message was: {message}", array('{message}' => $e->getMessage())));
             }
         }
         // Set permissions on encryption
         $this->configPermissions = 100600;
         // Reset config vars property
         if (isset($this->_configVars)) {
             unset($this->_configVars);
         }
         // Finally done.
         return true;
     }
 }
Example #9
0
 public function testSecureUniqueIdHash64()
 {
     foreach (range(1, 3) as $method) {
         foreach (range(1, 2) as $hash) {
             $id = EncryptUtil::secureUniqueIdHash64($method, $hash);
             if (VERBOSE_MODE >= 1) {
                 echo "\nmethod {$method} hash {$hash} {$id}";
             }
             $this->assertEquals(64, strlen($id));
         }
     }
 }
Example #10
0
 public function insert($attributes = null)
 {
     $this->id = EncryptUtil::secureUniqueIdHash64();
     $this->requested = time();
     $this->getIpAddr();
     return parent::insert($attributes);
 }