@inheritdoc

@throws \Throwable
@throws \craft\errors\ElementNotFoundException
@throws \yii\base\Exception
@throws \yii\db\Exception
777718
public function safeUp()
    {
        // 1. Run the install migration
	    if (!$this->db->tableExists(Map::TableName))
	        (new Install())->safeUp();

	    // 2. Upgrade the data
	    if ($this->db->tableExists('{{%simplemap_maps}}'))
	    	$this->_upgrade2();
	    else
	    	$this->_upgrade3();
    }
65872
public function init()
    {
        $this->conf = $this->getConfiguration();
        if (!isset($this->conf)) {
            throw new Exception("Adapter configuration not set, cannot initialize");
        }
        $this->adapters = array();
        foreach ($this->conf['adapters'] as $key => $adapter) {
            $adapterConf = ArrayHelper::merge($this->conf['common'], $adapter);

            $adapterConf['paymentHandler'] = $this;
            $adapterConf['adapterTag'] = $key;
            $this->adapters[$key] = \Yii::createObject($adapterConf);
        }
    }
705601
public function run($id)
    {
        if (! $id) throw new BadRequestHttpException(yii::t('cms', "Id doesn't exit"));
        /* @var $model yii\db\ActiveRecord */
        $model = call_user_func([$this->modelClass, 'findOne'], $id);
        if (! $model) throw new BadRequestHttpException(yii::t('cms', "Cannot find model by $id"));
        $model->setScenario( $this->scenario );

        if (yii::$app->getRequest()->getIsPost()) {
            if ($model->load(Yii::$app->getRequest()->post()) && $model->save()) {
                if( yii::$app->getRequest()->getIsAjax() ){
                    return [];
                }else {
                    yii::$app->getSession()->setFlash('success', yii::t('cms', 'Success'));
                    return $this->controller->redirect(['update', 'id' => $model->getPrimaryKey()]);
                }
            } else {
                $errors = $model->getErrors();
                $err = '';
                foreach ($errors as $v) {
                    $err .= $v[0] . '<br>';
                }
                if( yii::$app->getRequest()->getIsAjax() ){
                    throw new UnprocessableEntityHttpException($err);
                }else {
                    yii::$app->getSession()->setFlash('error', $err);
                }
                $model = call_user_func([$this->modelClass, 'findOne'], $id);
            }
        }

        return $this->controller->render('update', [
            'model' => $model,
        ]);
    }
728037
public function init()
    {
        $path = Yii::getAlias($this->configFile);
        if (file_exists($path)) {
            $config = (include($path));
            foreach ($config as $name => $closure) {
                if (is_array($closure)) {
                    $this->addElement($name, $closure[0], $closure[1]);
                } else {
                    $this->addElement($name, $closure);
                }
            }
        }
    }
747040
public function execute()
    {
        $this->rendered['sub-elements'] = array();
        try {
            $this->hook('pre-render');
            $this->hook('beforeRender');
            $this->recursiveRender();
            if (isset($_GET['cut_object'])) {
                throw new BaseException("Unable to cut object with name='".$_GET['cut_object']."'. ".
                    "It wasn't initialized");
            }
            if (isset($_GET['cut_region'])) {
                // @todo Imants: This looks something obsolete. At least property cut_region_result is never defined.
                if (!$this->cut_region_result) {
                    throw new BaseException("Unable to cut region with name='".$_GET['cut_region']."'");
                }
                echo $this->cut_region_result;

                return;
            }
        } catch (Exception $e) {
            if ($e instanceof Exception_Stop) {
                $this->hook('cut-output');
                if (isset($e->result)) {
                    echo $e->result;
                }
                $this->hook('post-render-output');

                return;
            }
            throw $e;
        }
    }
346783
public function actionEdit ()
		{
			if (Yii::$app->request->isAjax)
			{
				$setting = Setting::findOne([ 'name' => Yii::$app->request->post('name') ]);
				if ($setting !== null and $setting->fixed == 0)
				{
					$setting->setAttributes([ 'value' => Yii::$app->request->post('value'), 'description' => Yii::$app->request->post('description') ]);
					if (!$setting->save())
						echo Json::encode(current($setting->firstErrors));
					else
						echo 0;
				}
			}
			Yii::$app->end();
		}
760449
public function actionMain()
    {
        switch (yii::$app->getDb()->driverName) {
            case "mysql":
                $dbInfo = 'MySQL ' . (new Query())->select('version()')->one()['version()'];
                break;
            case "pgsql":
                $dbInfo = (new Query())->select('version()')->one()['version'];
                break;
            default:
                $dbInfo = "Unknown";
        }
        $info = [
            'OPERATING_ENVIRONMENT' => PHP_OS . ' ' . $_SERVER['SERVER_SOFTWARE'],
            'PHP_RUN_MODE' => php_sapi_name(),
            'DB_INFO' => $dbInfo,
            'PROGRAM_VERSION' => "1.0",
            'UPLOAD_MAX_FILESIZE' => ini_get('upload_max_filesize'),
            'MAX_EXECUTION_TIME' => ini_get('max_execution_time') . "s"
        ];
        $obj = new ServerInfo();
        $serverInfo = $obj->getinfo();
        error_reporting(E_ALL);
        $status = [
            'DISK_SPACE' => [
                'NUM' => ceil( $serverInfo['diskTotal'] - $serverInfo['freeSpace'] ) . 'G' . ' / ' . ceil($serverInfo['diskTotal']) . 'G',
                'PERCENTAGE' => (floatval($serverInfo['diskTotal']) != 0) ? round(($serverInfo['diskTotal'] - $serverInfo['freeSpace']) / $serverInfo['diskTotal'] * 100, 2) : 0,
            ],
            'MEM' => [
                'NUM' => $serverInfo["UsedMemory"] . ' / ' . $serverInfo['TotalMemory'],
                'PERCENTAGE' => $serverInfo["memPercent"],
            ],
            'REAL_MEM' => [
                'NUM' => $serverInfo["memRealUsed"] . "(Cached {$serverInfo['CachedMemory']})" . ' / ' . $serverInfo['TotalMemory'],
                'PERCENTAGE' => $serverInfo['memRealPercent'] . '%',
            ],
        ];
        $temp = [
            'ARTICLE' => ArticleModel::find()->where(['type' => ArticleModel::ARTICLE])->count('id'),
            'COMMENT' => Comment::find()->count('id'),
            'USER' => User::find()->count('id'),
            'FRIEND_LINK' => FriendlyLink::find()->count('id'),
        ];
        $statics = [
            'ARTICLE' => [
                $temp['ARTICLE'],
                $temp['ARTICLE'] == 0 ? 0 :
                number_format(ArticleModel::find()->where([
                        'between',
                        'created_at',
                        strtotime(date('Y-m-01')),
                        strtotime(date('Y-m-01 23:59:59') . " +1 month -1 day")
                    ])->count('id') / $temp['ARTICLE'] * 100, 2)
            ],
            'COMMENT' => [
                $temp['COMMENT'],
                $temp['COMMENT'] == 0 ? 0 :
                number_format(Comment::find()->where([
                        'between',
                        'created_at',
                        strtotime(date('Y-m-d 00:00:00')),
                        time()
                    ])->count('id') / $temp['COMMENT'] * 100, 2)
            ],
            'USER' => [
                $temp['USER'],
                $temp['USER'] == 0 ? 0 :
                number_format(User::find()->where([
                        'between',
                        'created_at',
                        strtotime(date('Y-m-01')),
                        strtotime(date('Y-m-01 23:59:59') . " +1 month -1 day")
                    ])->count('id') / $temp['USER'] * 100, 2)
            ],
            'FRIEND_LINK' => [
                $temp['FRIEND_LINK'],
                $temp['FRIEND_LINK'] == 0 ? 0 :
                number_format(FriendlyLink::find()->where([
                        'between',
                        'created_at',
                        strtotime(date('Y-m-01')),
                        strtotime(date('Y-m-01 23:59:59') . " +1 month -1 day")
                    ])->count('id') / $temp['FRIEND_LINK'] * 100, 2)
            ],
        ];
        $comments = BackendComment::getRecentComments(6);
        return $this->render('main', [
            'info' => $info,
            'status' => $status,
            'statics' => $statics,
            'comments' => $comments,
        ]);
    }
444181
public function end(): QueryBuilderInterface
    {
        if (null === $this->node = $this->node->getParent()) {
            throw new \Exception(sprintf('You cannot call %s on main node', __FUNCTION__));
        }

        return $this;
    }
1155062
public function run()
    {
        // Prepare data
        $view = $this->getView();

        // Render input for results
        if ($this->_renderInput) {
            if ($this->hasModel()) {
                echo Html::activeHiddenInput($this->model, $this->attribute, $this->options);
            } else {
                echo Html::hiddenInput($this->name, $this->value, $this->options);
            }
        }

        // Render editor container
        $containerOptions = $this->containerOptions;
        $tag              = ArrayHelper::remove($containerOptions, 'tag', 'div');
        echo Html::tag($tag, '', $containerOptions);

        // Prepare client options
        $clientOptions           = $this->clientOptions;
        $clientOptions['schema'] = $this->schema;

        try {
            $parsedValue = Json::decode($this->value);
        } catch (\Exception $e) {
            $parsedValue = null;
            \Yii::error($e->getMessage(), __METHOD__);
        }

        if (!empty($parsedValue)) {
            $clientOptions['startval'] = $parsedValue;
        }

        $clientOptions = Json::encode($clientOptions);

        // Prepare element IDs
        $widgetId    = $this->id;
        $inputId     = $this->inputId;
        $containerId = $this->containerOptions['id'];

        // Add the "JSONEditor" instance to the global window object, otherwise the instance is only available in "ready()" function scope
        $widgetJs = "window.{$widgetId} = new JSONEditor(document.getElementById('{$containerId}'), {$clientOptions});\n";
        // Add the "JSONEditor" instance to the global window.jsonEditors array.
        $widgetJs .= "if (!window.jsonEditors) { window.jsonEditors = []; } window.jsonEditors.push(window.{$widgetId});";

        $readyFunction = '';
        $readyFunction .= "{$widgetId}.on('change', function() { document.getElementById('{$inputId}').value = JSON.stringify({$widgetId}.getValue()); });\n";

        $widgetJs .= "{$widgetId}.on('ready', function() {\n{$readyFunction}\n});";

        // Register js code
        $view->registerJs($widgetJs, $view::POS_READY);

        parent::run();
    }
559386
public function run($id)
    {
        if (Yii::$app->request->isAjax) {
            Yii::$app->response->format = Response::FORMAT_JSON;

            $model = $this->findModel($id);

            if (Yii::$app->request->isPost) {
                $post = Yii::$app->request->post();
                $parentId = isset($post['parent_id']) ? $post['parent_id'] : 0;
                $prevId = isset($post['prev_id']) ? $post['prev_id'] : 0;
                $nextId = isset($post['next_id']) ? $post['next_id'] : 0;

                try {
                    if (empty($parentId)) {
                        if ($this->isMultipleTree) {    ///[isMultipleTree]
                            if (!$model->isRoot()) {
                                $result = $model->makeRoot();
                            }

                            ///?????root sorting logic

                        } else {
                            return [
                                'status' => 'error',
                                'error' => 'Tree root operations are protected when "isMultipleTree" is false!',
                            ];
                        }
                    } elseif (!empty($prevId)) {
                        $prevModel = $this->findModel($prevId);
                        $result = $model->insertAfter($prevModel);
                    } elseif (!empty($nextId)) {
                        $nextModel = $this->findModel($nextId);
                        $result = $model->insertBefore($nextModel);
                    } else {
                        $parentModel = $this->findModel($parentId);
                        $result = $model->appendTo($parentModel);
                    }
                } catch (\Exception $e) {
                    return [
                        'status' => 'error',
                        'error' => $e->getMessage(),
                    ];
                }

                ///Note: remove `save()` when using `creocoder/yii2-nested-sets`!
                return is_bool($result) ? $result : $result->save();
            }
        }

        ///Redirect to this controller's default action
        return $this->controller->redirect([$this->controller->defaultAction]);
    }
155305
private function _checkJoinArray()
	{
		$defaultJoinArray = array('way' => null, 'tables' => null, 'conditionType' => null, 'condition' => null);
		if($this->joinArray === $defaultJoinArray)
		{
			throw new \Exception('one of the methods: inner(), natural(), left[Outer](), right[Outer] must called before!');
		}
	}
1327468
private function resolveElements()
    {
        foreach ($this->unresolvedColumns as $name => $info) {
            $this->columns[$name] = $this->createColumn($name, $info['type'], $info['options']);
        }
        $this->unresolvedColumns = [];

        foreach ($this->unresolvedFilters as $name => $info) {
            $this->filters[$name] = $this->createFilter($name, $info['type'], $info['options']);
        }
        $this->unresolvedFilters = [];

        foreach ($this->unresolvedActions as $name => $info) {
            $this->actions[$name] = $this->createAction($name, $info['type'], $info['options']);
        }
        $this->unresolvedActions = [];
    }
368908
public function update()
    {
        //get params from request
        $this->primaryKey = yii::app()->request->getParam('pk');
        $this->attribute = yii::app()->request->getParam('name');
        $this->value = yii::app()->request->getParam('value');
        $this->scenario = yii::app()->request->getParam('scenario');

        //checking params
        if (empty($this->attribute)) {
            throw new CException(Yii::t('EditableSaver.editable','Property "attribute" should be defined.'));
        }
        
        $this->model = new $this->modelClass();
        
        $isFormModel = $this->model instanceOf CFormModel;
        $isMongo = EditableField::isMongo($this->model);
        
        if (empty($this->primaryKey) && !$isFormModel) {
            throw new CException(Yii::t('EditableSaver.editable','Property "primaryKey" should be defined.'));
        }
        
        //loading model
        if($isMongo) {
        	$this->model = $this->model->findByPk(new MongoID($this->primaryKey));
		} elseif(!$isFormModel) {
			$this->model = $this->model->findByPk($this->primaryKey);
		}
        
        if (!$this->model) {
            throw new CException(Yii::t('EditableSaver.editable', 'Model {class} not found by primary key "{pk}"', array(
               '{class}'=>get_class($this->model), '{pk}' => is_array($this->primaryKey) ? CJSON::encode($this->primaryKey) : $this->primaryKey)));
        }
        
        //keep parent model for mongo
        $originalModel = $this->model;
        
        //resolve model only for mongo! we should check attribute safety
        if($isMongo) {
			$resolved = EditableField::resolveModels($this->model, $this->attribute);
			$this->model = $resolved['model']; //can be related model now
			$this->attribute = $resolved['attribute'];
			$staticModel = $resolved['staticModel'];	        	
		} else {
			$staticModel = $this->model;
		}

        //set scenario for main model
        if($this->scenario) {
            $originalModel->setScenario($this->scenario);
        }

        //is attribute safe
        if (!$this->model->isAttributeSafe($this->attribute)) {
            throw new CException(Yii::t('editable', 'Model {class} rules do not allow to update attribute "{attr}"', array(
                    '{class}'=>get_class($this->model), '{attr}'=>$this->attribute)));
        }

        //setting new value
        $this->setAttribute($this->attribute, $this->value);

        //validate attribute
        $this->model->validate(array($this->attribute));
        $this->checkErrors();

        //trigger beforeUpdate event
        $this->beforeUpdate();
        $this->checkErrors();
        
        //remove virtual attributes (which NOT in DB table)
        if(!$isMongo) {
            $this->changedAttributes = array_intersect($this->changedAttributes, $originalModel->attributeNames()); 
            if(count($this->changedAttributes) == 0) {
                //can not pass empty array in model->save() method!
                $this->changedAttributes = null;
            }
        }
        
        //saving (no validation, only changed attributes) note: for mongo save all!
        if($isMongo) {
            $result = $originalModel->save(false, null);
        } elseif(!$isFormModel) {
            $result = $originalModel->save(false, $this->changedAttributes);
        } else {
            $result = true;
        } 
        if ($result) {
            $this->afterUpdate();
        } else {
            $this->error(Yii::t('EditableSaver.editable', 'Error while saving record!'));
        }
    }
1180546
public function init()
	{
		parent::init();

		if (!in_array($this->column->type, $this->supportedTypes)) {
			throw new CException(Yii::t(
				'zii',
				'Unsupported column type. Supported column types are: "{types}"',
				array(
					'{types}' => implode(', ', $this->supportedTypes)
				)
			));
		}
	}
556407
public function render()
    {
        // Set the request arguments as GET parameters
        $_GET = $this->getRequestArguments();

        try {
            $this->controllerContext->getRequest()->setOriginalRequestMappingResults($this->validationErrors);

            // Render the content element
            $result = $this->beautify($GLOBALS['TSFE']->cObj->cObjGetSingle('RECORDS', $this->config));

            // In case of an error
        } catch (\Exception $e) {
            $result = '<pre class="error"><strong>'.$e->getMessage().'</strong>'.PHP_EOL
                      .$e->getTraceAsString().'</pre>';
        }

        return $result;
    }
533206
public function callback() {
        $xml = app('request')->input();
        if (empty($xml)) {
            throw new Exception(
                __('xml error')
            );
        }
        /**
         * 禁止引用外部xml实体
         */
        $disableLibxmlEntityLoader = libxml_disable_entity_loader(true);
        $args = Xml::specialDecode($xml);
        libxml_disable_entity_loader($disableLibxmlEntityLoader);
        Factory::log()
            ->info('WECHAT PAY CALLBACK: '.app('request')->input());
        if (!is_array($args)) {
            throw new Exception(
                __('xml error')
            );
        }
        if ($args['return_code'] != 'SUCCESS') {
            throw new Exception($args['return_msg']);
        }
        if (!$this->verify($args)) {
            throw new Exception(
                __('verify sign error')
            );
        }
        return $args;
    }
329160
public function main()
    {
        // Check if all required data is present.
        $this->checkRequirements();

        $document               = new \DOMDocument('1.0', 'UTF-8');
        $document->formatOutput = true;

        // Create the root 'ruleset' element.
        $root_element = $document->createElement('ruleset');
        $root_element->setAttribute('name', 'NextEuropa_default');
        $document->appendChild($root_element);

        // Add the description.
        $element = $document->createElement(
            'description',
            'Default PHP CodeSniffer configuration for NextEuropa subsites.'
        );
        $root_element->appendChild($element);

        // Add the coding standards.
        foreach ($this->_standards as $standard) {
            if (substr($standard, -4) === '.xml') {
                if (file_exists($standard)) {
                    $element = $document->createElement('rule');
                    $element->setAttribute('ref', $standard);
                    $root_element->appendChild($element);
                }
            }
            else {
                $element = $document->createElement('rule');
                $element->setAttribute('ref', $standard);
                $root_element->appendChild($element);
            }
        }

        // Add the files to check.
        foreach ($this->_files as $file) {
            $element = $document->createElement('file', $file);
            $root_element->appendChild($element);
        }

        // Add file extensions.
        if (!empty($this->_extensions)) {
            $extensions = implode(',', $this->_extensions);
            $this->appendArgument(
                $document,
                $root_element,
                $extensions,
                'extensions'
            );
        }

        // Add ignore patterns.
        foreach ($this->_ignorePatterns as $pattern) {
            $element = $document->createElement('exclude-pattern', $pattern);
            $root_element->appendChild($element);
        }

        // Add the requested Reports..
        foreach ($this->_reports as $report) {
            // Add the report type.
            $this->appendArgument($document, $root_element, $report, 'report');
        }

        // Add the shorthand options.
        $shorthand_options = array(
            'p' => '_showProgress',
            's' => '_showSniffCodes',
        );

        $options = array_filter(
            $shorthand_options,
            function ($value) {
                return $this->$value;
            }
        );

        if (!empty($options)) {
            $this->appendArgument(
                $document,
                $root_element,
                implode('', array_flip($options))
            );
        }

        // Save the file.
        $configSaved = file_put_contents(
            $this->_configFile,
            $document->saveXML()
        );

    }