Example #1
0
 /**
  * Rebuild system cache or cache of a module
  *
  * @param array $params
  *   - Module string Module name or system (Cms) cache if empty
  *
  * @return ServiceResult
  */
 public function actionDb2php($module = '', $workflowId = 0, $path = null)
 {
     if (!$workflowId) {
         $workflowId = WORKFLOW_ID;
     }
     if ($workflowId) {
         $this->actionSync($workflowId);
     }
     //Get module's params in DB
     Yii::import('Xpress.models.Setting', true);
     $criteria = new CDbCriteria();
     $criteria->compare('workflow_id', $workflowId);
     //For Cms module, save settings as system's settings
     if (!in_array($module, array('Xpress', 'Admin'))) {
         $criteria->addCondition("module = '{$module}'");
     } else {
         $criteria->addCondition("module = ''");
     }
     $criteria->order = 'name';
     $params = Setting::model()->findAll($criteria);
     //        if (count($params) < 1) return;
     //For Cms module, save settings as system's settings
     if (in_array($module, array('Xpress', 'Admin'))) {
         $module = '';
     }
     //load user custom setting
     //        UserSetting::model()->findByAttributes(array('user_id'=>Yii::app()->user->id));
     //        if (count($params) <= 0) return;
     $consts = array();
     foreach ($params as $param) {
         if (!is_numeric($param->value)) {
             $param->value = "'" . addslashes($param->value) . "'";
         }
         $consts[] = (empty($param->description) ? "" : "//{$param->description}\n") . "const " . (empty($module) ? 'SETTINGS_' : strtoupper($module) . '_') . "{$param->name} = {$param->value};";
     }
     $consts = implode("\n\n", $consts);
     $php = "<?php\n/**\n* DONOT modify this file as it's automatically generated based on setting parameters.\n**/\n\n{$consts}";
     $filename = $module . 'Settings.php';
     // This works only if the XService is ready to use. Inside XService->init() this won't work
     if ($path === null) {
         $path = cachePath();
     }
     if (!is_dir($path) || !is_writeable($path)) {
         errorHandler()->log(Yii::t('Settings.Api', '{path} does not exist or is not writable.', array('{path}' => $path)));
         $this->result = $path;
         return;
     }
     try {
         Yii::log($path . $filename . '<br/>', CLogger::LEVEL_TRACE);
         file_put_contents($path . $filename, $php);
     } catch (Exception $ex) {
         errorHandler()->log(Yii::t('Settings.Api', 'Cannot create file {filename} under {path}. ', array('{path}' => $path, '{filename}' => $filename)));
     }
     $this->result = $filename;
 }
Example #2
0
 public function getCache()
 {
     if (!$this->enableNestedCache) {
         return NULL;
     }
     if (self::$_cache === NULL) {
         if ($this->nestedCacheID !== NULL && ($cache = Yii::app()->getComponent($this->nestedCacheID)) !== NULL) {
             self::$_cache = $cache;
         } else {
             $cachePath = cachePath();
             self::$_cache = Yii::createComponent(array('class' => 'CFileCache', 'cachePath' => $cachePath));
         }
     }
     return self::$_cache;
 }
Example #3
0
 /**
  * Load module settings
  */
 public function loadSettings()
 {
     static $loaded = false;
     if ($loaded) {
         return;
     }
     if (!array_search($this->id, array('gii', 'Admin', 'Xpress'))) {
         $file = cachePath() . $this->id . 'Settings.php';
         if (!file_exists($file)) {
             Yii::log('Generate settings for ' . $file);
             Application::api('Xpress.Settings.db2php', array('module' => $this->id));
         }
         if (file_exists($file)) {
             include_once $file;
         }
     }
     $loaded = true;
 }
Example #4
0
 public function actionClearCache()
 {
     //clear all cache
     if (YII_DEBUG) {
         //            echo 'Cleanup cache ...' . "\nNote that this tool runs in backend and it clean cache components defined in base.php and main-backend.php only. To delete front-end cache, make sure you define those caches in base.php.\n";
     }
     $components = array_keys(Yii::app()->getComponents(false));
     if (is_array($components) && count($components)) {
         /** @var $compnent CCache */
         foreach ($components as $id) {
             if (strpos($id, 'cache') === 0) {
                 $component = app()->{$id};
                 if (is_a($component, 'CCache')) {
                     $component->flush();
                     //                        echo 'Flush ' . $id . ' cache' . "\n";
                 }
             }
         }
     }
     // Delete cache params
     $moduleIds = array_keys(Yii::app()->Modules);
     foreach ($moduleIds as $id) {
         if ($id == 'gii' || $id == 'Admin') {
             continue;
         }
         if ($id == 'Xpress') {
             $file = cachePath() . 'Settings.php';
         } else {
             $file = cachePath() . $id . 'Settings.php';
         }
         $file = realpath(Yii::app()->basePath . '/../sites/' . SITE_DIR . '/protected/runtime/' . $file);
         if (file_exists($file)) {
             try {
                 unlink($file);
             } catch (CException $ex) {
                 Yii::log($file . ' cant be deleted while clearing cache.');
             }
         }
     }
     //remove assets files
     $assetsPath = realpath(Yii::app()->basePath . '/../sites/' . SITE_DIR . '/assets');
     $this->rmDirRecursive($assetsPath);
     //create assets
     if (!file_exists($assetsPath)) {
         //            echo "Creating directory: $assetsPath \n";
         @mkdir($assetsPath, 0777);
         @chmod($assetsPath, 0777);
     }
     //remove assets admin, crm
     $assetsPath = realpath(Yii::getPathOfAlias('application') . '/../admin/assets');
     if ($assetsPath !== false) {
         $this->rmDirRecursive($assetsPath);
         //create assets
         if (!file_exists($assetsPath)) {
             //                echo "Creating directory: $assetsPath \n";
             @mkdir($assetsPath, 0777);
             @chmod($assetsPath, 0777);
         }
     }
     $assetsPath = realpath(Yii::getPathOfAlias('application') . '/../crm/assets');
     if ($assetsPath !== false) {
         $this->rmDirRecursive($assetsPath);
         //create assets
         if (!file_exists($assetsPath)) {
             //                echo "Creating directory: $assetsPath \n";
             @mkdir($assetsPath, 0777);
             @chmod($assetsPath, 0777);
         }
     }
     //remove cache
     $cachePath = realpath(Yii::app()->basePath . '/../sites/' . SITE_DIR . '/protected/runtime/cache/');
     $this->rmDirRecursive($cachePath);
     //create runtime/cache
     if (!file_exists($cachePath)) {
         @mkdir($cachePath, 0777);
         @chmod($cachePath, 0777);
         $templateCache = $cachePath . DIRECTORY_SEPARATOR . 'templates_c';
         @mkdir($templateCache, 0777);
         @chmod($templateCache, 0777);
         $workflowCache = $cachePath . DIRECTORY_SEPARATOR . WORKFLOW_ID;
         @mkdir($workflowCache, 0777);
         @chmod($workflowCache, 0777);
     }
     // create emails folder
     $emailCachePath = CachePath() . '/emails';
     //        echo 'Creating email cache: ', $emailCachePath, "\n";
     @mkdir($emailCachePath, 0777);
     @chmod($emailCachePath, 0777);
     // Re-generate modules config file
     if (Yii::app() instanceof CWebApplication) {
         app()->XService->run('Xpress.Settings.generateModuleConfig');
     }
     // Clear APC cache
     $this->apcDelete();
 }
Example #5
0
 protected function notifyByMail($error)
 {
     if (YII_DEBUG) {
         return;
     }
     // The SwiftMail lib use SERVER_NAME to generate random ID for some purposes
     if (Yii::app() instanceof CConsoleApplication) {
         $_SERVER['SERVER_NAME'] = 'console';
     }
     if (file_exists(cachePath() . 'Settings.php')) {
         include_once cachePath() . 'Settings.php';
     }
     try {
         $mail = Yii::app()->getComponent('mail');
         $mail->viewPath = 'Xpress.views.mails';
         Yii::import('Xpress.extensions.vendors.mail.YiiMailMessage');
         $message = new YiiMailMessage();
         $message->view = 'error_notification';
         $message->setSubject('Error happens on ' . SETTINGS_SITE_NAME . ' (' . Yii::app()->request->getHostInfo() . ')');
         /**
          * @var CHttpException
          */
         $message->setBody(array('error' => $error));
         if (!empty($this->sendNotificationTo)) {
             foreach (explode(',', $this->sendNotificationTo) as $to) {
                 $message->addTo(trim($to));
             }
         } else {
             foreach (explode(',', SETTINGS_DEV_EMAILS) as $to) {
                 $message->addTo(trim($to));
             }
             $message->addTo(SETTINGS_ADMIN_EMAIL);
         }
         $message->setFrom(SETTINGS_ADMIN_EMAIL);
         $mail->send($message);
     } catch (Exception $ex) {
         throw $ex;
         // well, there is really nothing we can do here !!!
     }
 }
Example #6
0
/**
 * Check if a setting class has a defined constant
 *
 * @param mixed $setting param name
 * @param mixed $default default value if param is not defined
 * @return mixed parameter value or false
 */
function hasParam($setting, $default = null)
{
    // turn off E_WARNING so the constant() function does not cause error
    $oldErrorReporting = error_reporting(E_ALL ^ E_WARNING);
    // old setting syntax using class::constant
    if (strpos($setting, '::') !== false) {
        list($class, $param) = explode('::', $setting);
        if (class_exists($class, false)) {
            $class = new ReflectionClass($class);
            return $class->getConstant($param);
        }
    } else {
        // new setting syntax using define
        foreach (app()->modules as $m) {
            $moduleId = explode('.', $m['class']);
            $moduleId = str_replace('Module', '', array_pop($moduleId));
            if (strpos($setting, strtoupper($moduleId)) === 0) {
                $file = cachePath() . $moduleId . 'Settings.php';
                if (file_exists($file)) {
                    include_once $file;
                }
                break;
            }
        }
        if (!constant($setting) && $default === null) {
            error_reporting($oldErrorReporting);
            defined($setting) or define($setting, $default);
            return false;
        } elseif (!constant($setting) && $default !== null) {
            error_reporting($oldErrorReporting);
            defined($setting) or define($setting, $default);
            return $default;
        } else {
            eval("\$value = {$setting};");
            return $value;
        }
    }
    return false;
}
Example #7
0
 /**
  * Lists all models.
  */
 public function actionIndex()
 {
     $url = parse_url(app()->request->getHostInfo(), PHP_URL_HOST);
     $currentWorkflow = $this->api('Cms.Workflow.getByUrl', array('url' => $url));
     $workflowId = 0;
     $workflows = array();
     $workflow = $this->getWorkflow();
     if (is_object($workflow)) {
         $workflowId = $workflow->id;
     } else {
         $workflow = $currentWorkflow;
         //get workflow by url
         if (is_object($currentWorkflow)) {
             $workflowId = $currentWorkflow->id;
         }
     }
     //find all workflows
     if (is_object($workflow)) {
         //init setting params for current workflow
         $this->api('Xpress.Settings.sync', array('workflowId' => $workflow->id));
         $workflows = Workflow::model()->findAll('site_id=:site_id', array(':site_id' => $workflow->site_id));
         if (count($workflows)) {
             $workflows = CHtml::listData($workflows, 'id', 'name');
         }
     }
     $model = new SettingParam('search');
     $model->unsetAttributes();
     // clear any default values
     if (isset($_POST['SettingParam'])) {
         $model->attributes = $_POST['SettingParam'];
     } elseif (isset($_GET['module'])) {
         $model->module = $_GET['module'];
         if (in_array($model->module, array('Xpress', 'Admin'))) {
             $model->module = 'System';
         }
     } else {
         $model->module = 'System';
     }
     $model->visible = 1;
     $model->workflow_id = $workflowId;
     $dataProvider = $model->search();
     $dataProvider->pagination = false;
     $modules = $model->getModules();
     $data = $dataProvider->getData();
     //override setting use user_setting
     $customizable = array();
     if (count($data)) {
         foreach ($data as $i => $row) {
             /** var CActiveRecord $row */
             if ($row->customizable) {
                 //load data from user_setting
                 $custom = UserSetting::model()->findByAttributes(array('param_name' => $row->name, 'user_id' => Yii::app()->user->id));
                 if (is_object($custom)) {
                     $data[$i]->value = $custom->value;
                 } else {
                     $custom = new UserSetting();
                     $custom->user_id = Yii::app()->user->id;
                     $custom->param_name = $row->name;
                 }
                 $customizable[] = $custom;
             }
         }
     }
     $paramForm = $this->createWidget('Admin.components.ParamForm', array('params' => $data, 'config' => null));
     //TODO: load module param definitions into $config
     // save new values
     if (Yii::app()->request->IsPostRequest) {
         //save User Settings to user_setting
         if (is_array($customizable) && count($customizable)) {
             foreach ($customizable as $custom) {
                 if ($custom instanceof UserSetting && isset($_POST[$custom->param_name])) {
                     $custom->value = $_POST[$custom->param_name];
                     if (!$custom->save()) {
                         Yii::log(CVarDumper::dumpAsString($custom->getErrors()), CLogger::LEVEL_ERROR, 'Admin.Setting');
                     }
                     //force not save global setting
                     unset($_POST[$custom->param_name]);
                 }
             }
         }
         $paramForm->saveParams($_POST, ParamForm::TO_SETTING_TABLE);
         //update Settings Class
         if ($currentWorkflow->id == $workflowId && isset($_POST['SettingParam'], $_POST['SettingParam']['module'])) {
             $module = $_POST['SettingParam']['module'];
             if ($module == 'module_system') {
                 $module = '';
             }
             $this->api('Xpress.Settings.db2php', array('module' => $module));
         }
         //update parameters to global and other workflows
         foreach ($paramForm->params as $param) {
             if (isset($_POST['sync_global'])) {
                 $this->api('Xpress.SettingParam.syncValue', array('attrs' => $param->attributes));
                 //update cache file global
                 $this->api('Xpress.Settings.db2php', array('module' => $param->module, 'path' => cachePath(true)));
             }
             if (isset($_POST['sync_other'])) {
                 $this->api('Xpress.SettingParam.syncValueToOther', array('attrs' => $param->attributes));
             }
         }
         //TODO: need fix validate in ParamForm
         //errorHandler()->getErrorMessages();
     }
     $this->render('index', array('modules' => $modules, 'module' => $model->module, 'form' => $paramForm, 'workflowId' => $workflowId, 'workflows' => $workflows));
 }
Example #8
0
 public function actionBuildTree(array $data, array $attributes = array())
 {
     if (count($data)) {
         $rows = array();
         foreach ($data as $model) {
             if (count($attributes)) {
                 $attributes = CMap::mergeArray($attributes, array('id', 'parent_id'));
                 $rows[] = array_intersect_key($model->attributes, array_combine($attributes, $attributes));
             } else {
                 $rows[] = $model->attributes;
             }
         }
         if (is_object($model)) {
             $raw = serialize($rows);
             //cache tree
             $filename = get_class($model);
             $cachePath = cachePath();
             if (file_exists($cachePath)) {
                 file_put_contents($cachePath . DIRECTORY_SEPARATOR . $filename . 'RawCache.php', $raw);
             }
             $parent = NULL;
             $data = $this->result = $this->buildRecursive($parent, 0, $rows);
             $data = serialize($data);
             //cache tree
             if (file_exists($cachePath)) {
                 file_put_contents($cachePath . DIRECTORY_SEPARATOR . $filename . 'Cache.php', $data);
             }
         }
     } else {
         $this->result = array();
     }
     return $this->result;
 }
            /* PHP/webserver by default can return 'no-cache', so we must modify it */
            header('Cache-Control: public');
            header('Pragma: cache');
            header('Last-Modified: ' . gmdate('D, d M Y H:i:s', 1337) . ' GMT');
            imagepng($image_outfit);
            // cache that image on server
            imagepng($image_outfit, cachePath($outfit_id, $addons, $head, $body, $legs, $feet, true));
            imagedestroy($image_outfit);
        } else {
            exit('Cannot generate painted outfit: ' . $outfit_id . '_' . $addons . '.png');
        }
    } else {
        header('Content-Type: image/png');
        /* PHP/webserver by default can return 'no-cache', so we must modify it */
        header('Cache-Control: public');
        header('Pragma: cache');
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s', 1337) . ' GMT');
        readfile(cachePath($outfit_id, $addons, $head, $body, $legs, $feet, false));
    }
} else {
    if (file_exists('outfit_images/' . $outfit_id . '_0.png')) {
        header('Content-Type: image/png');
        /* PHP/webserver by default can return 'no-cache', so we must modify it */
        header('Cache-Control: public');
        header('Pragma: cache');
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s', 1337) . ' GMT');
        readfile('outfit_images/' . $outfit_id . '_0.png');
    } else {
        exit('Cannot generate not painted outfit: ' . $outfit_id);
    }
}