Добавить UF
@throws \Exception
558469
public function add()
    {
        $uf = new \CUserTypeEntity();
        $result = $uf->Add($this->getFieldsWithDefault());

        if (!$result) {
            global $APPLICATION;
            throw new \Exception($APPLICATION->GetException());
        }

        Logger::log("Добавлен UF {$this->fields['FIELD_NAME']} для {$this->fields['ENTITY_ID']}", Logger::COLOR_GREEN);

        return $result;
    }
283529
private function init_request()
	{
		global $request;

		# Значения по умолчанию
		$request = array(
			'method' => $_SERVER['REQUEST_METHOD'],
			'scheme' => isset($_SERVER['HTTPS']) && !empty($_SERVER['HTTPS']) ? 'https' : 'http',
			'host' => strtolower($_SERVER['HTTP_HOST']),
			'port' => '',
			'user' => isset($_SERVER['PHP_AUTH_USER']) ? $_SERVER['PHP_AUTH_USER'] : '',
			'pass' => isset($_SERVER['PHP_AUTH_PW']) ? $_SERVER['PHP_AUTH_PW'] : '',
			'path' => '',
			'query' => '',
			'fragment' => '',
			'referer' => isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '',
		);

		$request['url'] = $request['scheme'] . '://' . $request['host'] . $_SERVER['REQUEST_URI'];

		$request = array_merge($request, parse_url($request['url']));
		$request['file'] = substr($request['path'], strrpos($request['path'], '/')+1);
		if ($request['file'])
		{
			$request['path'] = substr($request['path'], 0, -strlen($request['file']));
		}

		# Создаем заготовку URL для GET-запросов с параметрами
		$request['link'] = $request['url'];
		if (substr($request['link'], -1) == '/')
		{
			$request['link'] .= '?';
		}
		elseif (strpos($request['link'], '?') === false)
		{
			$request['link'] .= '?';
		}
		else
		{
			$request['link'] .= '&';
		}

		if (is_null($this->path))
		{
			$s = $this->froot;
			$s = substr($s,
				strlen(realpath($_SERVER['DOCUMENT_ROOT'])) - (Eresus_Kernel::isWindows() ? 2 : 0));
			if (!strlen($s) || substr($s, -1) != '/')
			{
				$s .= '/';
			}
			$this->path = (substr($s, 0, 1) != '/' ? '/' : '').$s;
		}

		/*
		 * Установка свойств объекта $Eresus
		 * Должна выполняться ДО вызова __clearargs
		 */
		$root = $request['scheme'] . '://' . $request['host'] .
			($request['port'] ? ':'.$request['port'] : '');
		$this->root = $root.$this->path;
		$this->data = $this->root.'data/';
		$this->style = $this->root.'style/';


		# Сбор аргументов вызова
		$request['arg'] = __clearargs(array_merge($_GET, $_POST));
		# Разбивка параметров вызова скрипта
		$s = substr($request['path'], strlen($this->path));
		$request['params'] = $s ? explode('/', substr($s, 0, -1)) : array();

		$request['path'] = $root.$request['path'];

		# Обратная совместимость
		# <= 2.9
		$this->request = &$request;
        /**
         * @deprecated с 3.01
         */
		define('httpPath', $this->path);
        /**
         * @deprecated с 3.01
         */
		define('httpHost', $this->request['host']);
        /**
         * @deprecated с 3.01
         */
        define('httpRoot', $this->root);
        /**
         * @deprecated с 3.01
         */
		define('styleRoot', $this->style);
        /**
         * @deprecated с 3.01
         */
		define('dataRoot', $this->data);
        /**
         * @deprecated с 3.01
         */
		define('cookieHost', $this->request['host']);
        /**
         * @deprecated с 3.01
         */
		define('cookiePath', $this->path);
	}
726940
function captureException(E $e, $data=null, $logger=null, $vars=null) {
        if (in_array(get_class($e), $this->exclude)) {
            return null;
        }
        if ($data === null) {
            $data = [];
        }
        $eOriginal = $e; /** @var E $eOriginal */
        do {
			$isDFE = $e instanceof DFE;
            $exc_data = [
            	'type' => $isDFE ? $e->sentryType() : get_class($e)
				,'value' => $this->serializer->serialize($isDFE ? $e->messageSentry() : $e->getMessage())
			];
            /**'exception'
             * Exception::getTrace doesn't store the point at where the exception
             * was thrown, so we have to stuff it in ourselves. Ugh.
             */
            $trace = $e->getTrace();
            /**
			 * 2016-12-22
			 * Убираем @see \Magento\Framework\App\ErrorHandler
			 * 2016-12-23
			 * И @see Breadcrumbs\ErrorHandler тоже убираем.
			 */
            /** @var bool $needAddFaceFrame */
            $needAddFakeFrame = !self::needSkipFrame($trace[0]);
			while (self::needSkipFrame($trace[0])) {
				array_shift($trace);
			}
            if ($needAddFakeFrame) {
				$frame_where_exception_thrown = array(
					'file' => $e->getFile(),
					'line' => $e->getLine(),
				);
				array_unshift($trace, $frame_where_exception_thrown);
			}
            $exc_data['stacktrace'] = array(
                'frames' => Stacktrace::get_stack_info(
                    $trace, $this->trace, $vars, $this->message_limit, $this->prefixes,
                    $this->app_path, $this->excluded_app_paths, $this->serializer, $this->reprSerializer
                ),
            );
            $exceptions[] = $exc_data;
        } while ($e = $e->getPrevious());
        $data['exception'] = array('values' => array_reverse($exceptions),);
        if ($logger !== null) {
            $data['logger'] = $logger;
        }
        if (empty($data['level'])) {
            if (method_exists($eOriginal, 'getSeverity')) {
                $data['level'] = $this->translateSeverity($eOriginal->getSeverity());
            }
            else {
                $data['level'] = self::ERROR;
            }
        }
        return $this->capture($data, $trace, $vars);
    }
492525
final protected function _process() {
		/**
		 * 2016-08-22
		 * Помимо добавления поля в таблицу «customer_entity» надо ещё добавить атрибут,
		 * иначе данные не будут сохраняться:
		 *		$attribute = $this->getAttribute($k);
		 *		if (empty($attribute)) {
		 *			continue;
		 *		}
		 * https://github.com/magento/magento2/blob/2.1.0/app/code/Magento/Eav/Model/Entity/AbstractEntity.php#L1262-L1265
		 */
		if ($this->v('1.7.4')) {
			df_eav_setup()->addAttribute('customer', UpgradeSchema::F__DF, [
				'input' => 'text'
				,'label' => 'Mage2.PRO'
				,'position' => 1000
				,'required' => false
				,'sort_order' => 1000
				,'system' => false
				,'type' => 'static'
				,'visible' => false
			]);
		}
	}
1104894
public function load()
	{
		$filename = $this->getFile();
		if (!file_exists($filename))
			return;

		$json = file_get_contents($filename);
		if (strlen($json) == 0)
			return;

		$data = $this->decode($json);
		if ($data === null)
			throw new Exception('Error while trying to decode ' . $filename . '.');

		$this->data = $data;

		if (!$this->verify())
			throw new Exception($filename . ' failed checksum validation.');
	}
813540
public function update($id)
    {
        $obj = new \CIBlockProperty();
        if (!$obj->Update($id, $this->fields)) {
            throw new \Exception($obj->LAST_ERROR);
        }

        Logger::log("Обновлено свойство инфоблока {$id}", Logger::COLOR_GREEN);
    }
741246
protected function _exception() {
        $url = '.' . $this->request->src . '.' . $this->request->controller . '.' . $this->request->action;

        if (in_array($url, $this->config['user']['security']['spam']['config']['exception'])) {
            $this->_exception = true;
        }

        return $this->_exception;
    }
1094989
public function generatePK()
    {
        $format = $this->pkFormat;
        $pk     = $this->_properties['primary_key'];
        if (isset($pk[1]))
            throw new Exception(sprintf(self::E_Composit, get_called_class(), __FUNCTION__), 1);

        $pk     = array_shift($pk);
        if (!$pk)
            throw new Exception(sprintf(self::E_PrimaryKey, get_called_class()), 1);

        $last = (int) $this
            ->select(($format['serial']?
                'right('.$pk.', '.$format['serial'].')':
                $pk).' as last')
            ->order($pk.' desc')
            ->read(1)
            ->last;

        // compile prefix format
        if (preg_match('/\{(?<date>.+)\}/', $format['prefix'], $match))
            $newPK = preg_replace('/\{.+\}/', date($match['date']), $format['prefix']);
        else
            $newPK = $format['prefix'];

        $newPK .= trim(str_pad($last+1, $format['serial'], $format['prefix']?'0':' ', STR_PAD_LEFT));

        return $newPK;
    }
995921
public static function delete($id)
    {
        $result = (new \CUserTypeEntity())->Delete($id);

        if (!$result) {
            global $APPLICATION;
            throw new \Exception($APPLICATION->GetException());
        }

        Logger::log("Удален UF {$id}", Logger::COLOR_GREEN);
    }
27250
public function run()
    {
        // Insert
        \DB::table('modules')->insert([
            ['name' => 'articles', 'title' => null, 'icon' => 'fa fa-newspaper-o', 'info' => 'No description available', 'on_mainpage' => 1, ],
            ['name' => 'categories', 'title' => null, 'icon' => 'fa fa-folder-open-o', 'info' => 'No description available', 'on_mainpage' => 1, ],
            ['name' => 'tags', 'title' => null, 'icon' => 'fa fa-tags', 'info' => 'No description available', 'on_mainpage' => 1, ],
            ['name' => 'users', 'title' => null, 'icon' => 'fa fa-users', 'info' => 'No description available', 'on_mainpage' => 1, ],
            ['name' => 'comments', 'title' => null, 'icon' => 'fa fa-comments-o', 'info' => 'No description available', 'on_mainpage' => 1, ],
            ['name' => 'polls', 'title' => null, 'icon' => 'fa fa-list-ol', 'info' => 'No description available', 'on_mainpage' => 1, ],
            ['name' => 'files', 'title' => 'filemanager', 'icon' => 'fa fa-files-o', 'info' => 'Файловый менеджер', 'on_mainpage' => 1, ],
            ['name' => 'system', 'title' => null, 'icon' => 'fa fa-list-alt', 'info' => 'No description available', 'on_mainpage' => 1, ],
            ['name' => 'themes', 'title' => 'design', 'icon' => 'fa fa-paint-brush', 'info' => 'No description available', 'on_mainpage' => null, ],
            ['name' => 'x_fields', 'title' => 'x_fields', 'icon' => 'fa fa-columns', 'info' => 'Extra fields', 'on_mainpage' => 1, ],
        ]);
    }
1194338
public function add()
    {
        $obj = new \CIBlockType();
        if (!$obj->Add($this->getFieldsWithDefault())) {
            throw new \Exception($obj->LAST_ERROR);
        }

        Logger::log("Добавлен тип инфоблока {$this->fields['ID']}", Logger::COLOR_GREEN);
    }
850441
private function initLocale()
	{
		global $locale;

		$locale['lang'] = $this->conf['lang'];
		$locale['prefix'] = '';

		# Подключение строковых данных
		$filename = $this->froot.'lang/'.$locale['lang'].'.php';
		if (is_file($filename))
		{
            /** @noinspection PhpIncludeInspection */
            include_once $filename;
		}
		else
		{
            throw new Eresus_Exception_ComponentCorrupted(
                sprintf('Locale file "%s" not found!', $filename));
		}
	}
143761
public function run()
    {
        if (!$grantType = GrantType::getRequestValue('grant_type')) {
            throw new Exception(Yii::t('yuncms', 'The grant type was not specified in the request'));
        }
        if (isset($this->grantTypes[$grantType])) {
            $grantModel = Yii::createObject($this->grantTypes[$grantType]);
        } else {
            throw new Exception(Yii::t('yuncms', "An unsupported grant type was requested"), Exception::UNSUPPORTED_GRANT_TYPE);
        }
        $grantModel->validate();
        Yii::$app->response->data = $grantModel->getResponseData();
    }
751195
public function update()
    {
        //translate model data to sql data
        if (is_null($this->schema)) {
            throw Exception::forNoSchema();
        }

        $data = $this->schema->toSql();

        //queries to run
        $queries = [];
        //this is used to determine whether to add/alter/remove columns
        $exists = [];

        //if there's no system
        if (!$this->exists($data['name'])) {
            //go to create mode
            return $this->create($data, true);
        }

        $primary = $this->resource->getPrimaryKey($data['name']);
        $columns = $this->resource->getColumns($data['name']);
        $query = $this->resource->getAlterQuery($data['name']);

        //remove or change fields
        foreach ($columns as $current) {
            //don't do primary
            if ($primary === $current['Field']) {
                continue;
            }

            $exists[] = $name = $current['Field'];

            //if there is no field in the data
            if (!isset($data['columns'][$name])) {
                $query->removeField($name);
                continue;
            }

            $column = $data['columns'][$name];

            $attributes = ['type' => $column['type']];

            if (isset($column['length'])) {
                $attributes['type'] .= '(' . $column['length'] . ')';
            }

            if (isset($column['default']) && strlen($column['default'])) {
                $attributes['default'] = $column['default'];
            } else if (!isset($column['required']) || !$column['required']) {
                $attributes['null'] = true;
            }

            if (isset($column['required']) && $column['required']) {
                $attributes['null'] = false;
            }

            if (isset($column['attribute']) && $column['attribute']) {
                $attributes['attribute'] = $column['attribute'];
            }

            $default = null;
            if (isset($attributes['default'])) {
                $default = $attributes['default'];
            }

            //if all matches
            if ($attributes['type'] === $current['Type']
                && $attributes['null'] == ($current['Null'] === 'YES')
                && $default === $current['Default']
            ) {
                continue;
            }

            //do the alter
            $query->changeField($name, $attributes);
        }

        //add fields
        foreach ($data['columns'] as $name => $column) {
            if (in_array($name, $exists)) {
                continue;
            }

            $attributes = ['type' => $column['type']];

            if (isset($column['length'])) {
                $attributes['type'] .= '(' . $column['length'] . ')';
            }

            if (isset($column['default']) && strlen($column['default'])) {
                $attributes['default'] = $column['default'];
            } else if (!isset($column['required']) || !$column['required']) {
                $attributes['null'] = true;
            }

            if (isset($column['required']) && $column['required']) {
                $attributes['null'] = false;
            }

            if (isset($column['attribute']) && $column['attribute']) {
                $attributes['attribute'] = $column['attribute'];
            }

            $query->addField($name, $attributes);

            if (isset($column['index']) && $column['index']) {
                $query->addKey($name, [$name]);
            }

            if (isset($column['unique']) && $column['unique']) {
                $query->addUniqueKey($name, [$name]);
            }

            if (isset($column['primary']) && $column['primary']) {
                $query->addPrimaryKey($name);
            }
        }

        $query = (string) $query;
        if ($query !== 'ALTER TABLE `' . $data['name'] . '` ;') {
            $queries[] = $query;
        }

        $installed = $this->resource->getTables($data['name'] . '_%');
        $relations = array_keys($data['relations']);

        //determine the relation tables that need to be removed
        foreach ($installed as $relation) {
            //uninstall if it's not in the schema
            if (!in_array($relation, $relations)) {
                $queries[] = 'DROP TABLE IF EXISTS `' . $relation . '`;';
            }
        }

        //determine the relation tables that need to be added
        foreach ($data['relations'] as $table => $relation) {
            //install if it's installed
            if (in_array($table, $installed)) {
                continue;
            }

            $query = $this->resource->getCreateQuery($table);

            $query->addPrimaryKey($relation['primary1']);
            $query->addField($relation['primary1'], [
                'type' => 'int(10)',
                'null' => false,
                'attribute' => 'UNSIGNED'
            ]);

            $query->addPrimaryKey($relation['primary2']);
            $query->addField($relation['primary2'], [
                'type' => 'int(10)',
                'null' => false,
                'attribute' => 'UNSIGNED'
            ]);

            $queries[] = 'DROP TABLE IF EXISTS `'. $table . '`;';
            $queries[] = (string) $query;
        }

        //execute queries
        $results = [];
        foreach ($queries as $query) {
            $results[] = [
                'query' => $query,
                'results' => $this->resource->query($query)
            ];
        }

        return $results;
    }
392497
private function checkProperties()
    {
        if (!isset($this->listId)) {
            throw new \Exception('[listId] is not set', 1);
        }

        if (!isset($this->installationUrl)) {
            throw new \Exception('[installationUrl] is not set', 1);
        }

        if (!isset($this->apiKey)) {
            throw new \Exception('[apiKey] is not set', 1);
        }
    }
1045364
public function blockUser(): bool
    {
        $this->deactivate();
        if (!$this->save()) {
            print_r($this->getErrors());
            throw new Exception(\Yii::t('app', 'Ошибка при блокировании пользователя'));
        }
        return true;
    }
427198
protected function initAllowedCalls()
    {
        if ($this->allowedCalls) {
            $errMsg = 'Список разрешенных команд уже инициализирован';
            throw new RuntimeException($errMsg);
        }

        $this->allowedCalls = array_combine(static::$defaultAllowedCalls, static::$defaultAllowedCalls);
    }