Обновляет значение количества в корзине.
354048
public function updateCartQuantity($data) {
    $query = $this->connection->update('site_cart');
    $query->fields([
      'quantity' => $data['quantity'],
    ]);
    $query->condition('cid', $data['cid']);
    $query->execute();
    return $query;
  }
1284679
private function add()
    {
        $data = array();

        /* Составляем список доступных плагинов */
        $files = glob(Eresus_CMS::getLegacyKernel()->froot . 'ext/*.php');
        if (false === $files)
        {
            $files = array();
        }

        /* Составляем список установленных плагинов */
        $items = Eresus_CMS::getLegacyKernel()->db->select('plugins', '', 'name, version');
        $installed = array();
        foreach ($items as $item)
        {
            $installed []= Eresus_CMS::getLegacyKernel()->froot . 'ext/' . $item['name'] . '.php';
        }
        // Оставляем только неустановленные
        $files = array_diff($files, $installed);

        /*
         * Собираем информацию о неустановленных плагинах
         */
        $data['plugins'] = array();
        if (count($files))
        {
            // Удаляем из версии CMS все буквы, чтобы сравнивать только цифры
            $kernelVersion = preg_replace('/[^\d\.]/', '', Eresus_Kernel::app()->version);

            foreach ($files as $file)
            {
                $errors = array();
                try
                {
                    $info = Eresus_PluginInfo::loadFromFile($file);
                    $required = $info->getRequiredKernel();
                    if (
                        version_compare($kernelVersion, $required[0], '<')/* ||
						version_compare($kernelVersion, $required[1], '>')*/
                    )
                    {
                        $msg =  I18n::getInstance()->getText('admPluginsInvalidVersion', $this);
                        $errors []= sprintf($msg, /*implode(' - ', */$required[0]/*)*/);
                    }
                }
                catch (RuntimeException $e)
                {
                    $errors []= $e->getMessage();
                    $info = new Plugin(); // TODO: Придумать решение без Plugin
                    $info->title = $info->name = basename($file, '.php');
                    $info->version = '';
                }
                $available[$info->name] = $info->version;
                $data['plugins'][$info->title] = array('info' => $info, 'errors' => $errors);
            }
        }

        $plugins = Eresus_Plugin_Registry::getInstance();

        foreach ($data['plugins'] as &$item)
        {
            if ($item['info'] instanceof Eresus_PluginInfo)
            {
                $required = $item['info']->getRequiredPlugins();
                foreach ($required as $plugin)
                {
                    list ($name, $minVer, $maxVer) = $plugin;
                    if (
                        !isset($plugins->items[$name]) ||
                        ($minVer && version_compare($plugins->items[$name]->version, $minVer, '<')) ||
                        ($maxVer && version_compare($plugins->items[$name]->version, $maxVer, '>'))
                    )
                    {
                        {
                            $msg = I18n::getInstance()->getText('Requires plugin: %s', $this);
                            $item['errors'] []= sprintf($msg, $name . ' ' . $minVer . '-' . $maxVer);
                        }
                    }
                }
            }
        }

        ksort($data['plugins']);

        /* @var TAdminUI $page */
        $page = Eresus_Kernel::app()->getPage();
        $tmpl = $page->getUITheme()->getTemplate('PluginManager/add-dialog.html');
        $html = $tmpl->compile($data);

        return $html;
    }
1129122
public function init()
	{
		if ($this->conf['timezone'])
		{
			date_default_timezone_set($this->conf['timezone']);
		}
		# Определение путей
		$this->init_resolve();
		# Инициализация сессии
		$this->init_session();
		# Изменяем путь поиска подключаемых файлов
		set_include_path(dirname(__FILE__) . '/lib' . PATH_SEPARATOR . get_include_path());
		# Читаем настройки
		$this->initSettings();
		# Первичный разбор запроса
		$this->init_request();
		# Настройка локали
		$this->initLocale();
		# Подключение базовых классов
		$this->initClasses();
		# Инициализация расширений
		$this->init_extensions();
		# Подключение к источнику данных
		$this->initDataSource();
        $this->plugins = Eresus_Plugin_Registry::getInstance();
        $this->plugins->init();
		# Проверка сессии
		$this->check_session();
		# Проверка логина/логаута
		$this->check_loginout();
		# Попытка cookie-логина
		$this->check_cookies();
		# Обновление данных о пользователе
		$this->reset_login();
		$this->sections = new Sections;
		$GLOBALS['KERNEL']['loaded'] = true; # Флаг загрузки ядра
	}
892565
function render()
    {
        $result = '';     # Выходной код

        if (empty($this->form['name'])) $result .= ErrorBox(errFormHasNoName);
        if (count($this->form['fields'])) foreach($this->form['fields'] as $item) {
            # Проверяем права доступа к элементу
            if ((!isset($item['access'])) || (UserRights($item['access']))) {
                $this->field_prep($item);
                $control = 'render_'.$item['type'];
                #if (method_exists($this, $control)) $result .= call_user_func(array($this, $control), $item);
                if (method_exists($this, $control)) {
                    $result .= $this->$control($item);
                }
                else
                {
                    Eresus_Kernel::app()->getPage()->addErrorMessage(
                        sprintf(errFormUnknownType, $item['type'], $this->form['name']));
                }
            }
        }
        $this->onsubmit .= $this->validator;
        if (!empty($this->onsubmit))
        {
            Eresus_Kernel::app()->getPage()->addScripts("
				function ".$this->form['name']."Submit()
				{
					var result = true;
					var form = document.forms.namedItem('".$this->form['name']."');
					".$this->onsubmit.";
					return result;
				}
			");
        }
        # FIXME: sub_id - устаревший элемент
        $referer = arg('sub_id') ?
            Eresus_Kernel::app()->getPage()->url(array('sub_id'=>'')) :
            Eresus_Kernel::app()->getPage()->url(array('id'=>''));
        $this->hidden .= "\t\t".'<input type="hidden" name="submitURL" value="'.$referer.'" />';
        $this->hidden = "\t<div class=\"hidden\">\n\t\t{$this->hidden}\n\t</div>";
        $result =
            "<form ".(empty($this->form['name'])?'':'name="'.$this->form['name'].'" id="'.$this->form['name'].'" ')."action=\"".
            Eresus_Kernel::app()->getPage()->url()."\" method=\"post\"".(empty($this->onsubmit)?'':' onsubmit="return '.$this->form['name'].'Submit();"').($this->file?' enctype="multipart/form-data"':'').">\n".
            $this->hidden.
            "\n\t<table width=\"100%\">\n".
            "\t\t<tr><td style=\"height: 0px; font-size: 0px; padding: 0px;\">".img('style/dot.gif')."</td><td style=\"width: 100%; height: 0px; font-size: 0px; padding: 0px;\">".img('style/dot.gif')."</td>\n\t\t</tr>\n".
            $result.
            "\t\t<tr><td colspan=\"2\" class=\"ui-button-box\"><br />".
            ((isset($this->form['buttons']) && isset($this->form['buttons']['ok']))?'<button name="form_ok" type="submit">'.$this->form['buttons']['ok'].'</button> ':'').
            (!isset($this->form['buttons']) || in_array('ok', $this->form['buttons'])?"<button name=\"form_ok\" type=\"submit\">".strOk."</button> ":'').

            ((isset($this->form['buttons']) && isset($this->form['buttons']['apply']))?'<button name="form_apply" type="submit" onclick="formApplyClick(\''.$this->form['name'].'\')">'.$this->form['buttons']['apply']."</button> ":'').
            (!isset($this->form['buttons']) || in_array('apply', $this->form['buttons'])?"<button name=\"form_apply\" type=\"submit\" onclick=\"formApplyClick('".$this->form['name']."')\">" . strApply . '</button> ':'').

            ((isset($this->form['buttons']) && isset($this->form['buttons']['reset']))?'<button name="form_reset" type="reset">'.$this->form['buttons']['reset'].'</button> ':'').
            (isset($this->form['buttons']) && in_array('reset', $this->form['buttons'])?"<button name=\"form_reset\" type=\"reset\">".strReset."</button> ":'').

            ((isset($this->form['buttons']) && isset($this->form['buttons']['cancel']) && (!is_array($this->form['buttons']['cancel'])))?'<input name="form_cancel" type="button" onclick="javascript:history.back();">' . $this->form['buttons']['cancel'] . '</button>' : '').
            ((!isset($this->form['buttons']) || (in_array('cancel', $this->form['buttons'])))?"<button name=\"form_cancel\" type=\"button\" onclick=\"javascript:history.back();\">".strCancel . '</button>' :'').
            ((isset($this->form['buttons']['cancel']) && (is_array($this->form['buttons']['cancel'])))?"<button name=\"form_cancel\" type=\"button\" onclick=\"window.location.href='".$this->form['buttons']['cancel']['url']."'\">" . $this->form['buttons']['cancel']['label'] . '</button>':'').

            "</td>\n\t\t</tr>\n".
            "\t</table>\n</form>\n";

        return $result;
    }
466673
function id_field()
	{
		$class_name = $this->class_name();
		if(!empty(self::$id_fields_cache[$class_name]))
			return self::$id_fields_cache[$class_name];

		if(method_exists($this, 'table_fields') && $this->storage_engine() != 'storage_db_mysql_smart')
		{
			// Новый формат
			foreach(\bors_lib_orm::main_fields($this) as $f)
			{
				if($f['property'] == 'id')
				{
					self::$id_fields_cache[$class_name] = $f['name'];
					return $f['name'];
				}
			}
		}

		$ff = $this->fields_map();

		if(count($ff) == 1) //FIXME: костыль для поддержки древних field() методов.
							//В списке полей одна запись, если по дефолту прочиталось function table_fields() { return array('id'); }
			$ff = array_shift(array_shift($this->fields()));

		if($id_field = @$ff['id'])
		{
			if(is_array($id_field))
			{
				bors_lib_orm::field('id', $id_field);
				self::$id_fields_cache[$class_name] = $id_field['name'];
				return $id_field['name'];
			}
			else
			{
				self::$id_fields_cache[$class_name] = $id_field;
				return $id_field;
			}
		}

		//FIXME: исправить на возможность id в ненулевой позиции
		$id_field = @$ff[0] == 'id' ? 'id' : NULL;
		self::$id_fields_cache[$class_name] = $id_field;
		return $id_field;
	}
73309
protected function adaptTechPlatforms()
    {
        $dataArray = [];

        //Формируем массив
        foreach ($this->data['data'] as $item) {
            $dataArray['data'][] = [
                'browser'                 => $item['dimensions'][0]['name'],
                'visits'                  => $item['metrics'][0],
                //Визиты
                'bounceRate'              => $item['metrics'][1],
                //Отказы %
                'pageDepth'               => $item['metrics'][2],
                //Глубина просмотра
                'avgVisitDurationSeconds' => date("i:s", $item['metrics'][3])
                //Время проведенное на сайте мин:сек.
            ];
        }

        //Итого и средние значения
        $dataArray['totals'] = [
            'visits'                  => $this->data['totals'][0],
            'bounceRate'              => $this->data['totals'][1],
            'pageDepth'               => $this->data['totals'][2],
            'avgVisitDurationSeconds' => date("i:s", $this->data['totals'][3]),
        ];

        $this->adaptData = $dataArray;
    }
497836
private function adminRenderImagesList()
    {
        // Определяем текущую страницу списка
        $pg = arg('pg') ? arg('pg', 'int') : 1;

        $section = arg('section', 'int');

        $maxCount = $this->settings['useGroups'] ?
            $this->settings['groupsPerPage'] :
            $this->settings['itemsPerPage'];

        $startFrom = ($pg - 1) * $maxCount;

        /* @var Gallery_Entity_Table_AbstractContent $table */
        if ($this->settings['useGroups'])
        {
            $table = ORM::getTable($this, 'Group');
        }
        else
        {
            $table = ORM::getTable($this, 'Image');
        }

        $items = $table->findInSection($section, $maxCount, $startFrom, false);

        // Данные для подстановки в шаблон
        $vars = array();
        $vars['this'] = $this;
        $vars['page'] = Eresus_Kernel::app()->getPage();
        $vars['Eresus'] = Eresus_CMS::getLegacyKernel();
        $vars['sectionId'] = arg('section', 'int');
        $vars['items'] = $items;

        /* Шаблоны адресов действий */
        $vars['urlEdit'] = str_replace('&', '&amp;',
            Eresus_Kernel::app()->getPage()->url(array('id' => '%s')));
        $vars['urlToggle'] = str_replace('&', '&amp;',
            Eresus_Kernel::app()->getPage()->url(array('toggle' => '%s')));
        $vars['urlCover'] = str_replace('&', '&amp;',
            Eresus_Kernel::app()->getPage()->url(array('cover' => '%s')));
        $vars['urlUp'] = str_replace('&', '&amp;',
            Eresus_Kernel::app()->getPage()->url(array('up' => '%s')));
        $vars['urlDown'] = str_replace('&', '&amp;',
            Eresus_Kernel::app()->getPage()->url(array('down' => '%s')));
        $vars['urlDelete'] = str_replace('&', '&amp;',
            Eresus_Kernel::app()->getPage()->url(array('delete' => '%s')));

        $totalPages = ceil($table->countInSection($section) / $maxCount);

        if ($totalPages > 1)
        {
            $pager = new PaginationHelper($totalPages, $pg,
                Eresus_Kernel::app()->getPage()->url(array('pg' => '%s')));
            $vars['pager'] = $pager->render();
        }
        else
        {
            $vars['pager'] = '';
        }

        /* Создаём экземпляр шаблона */
        if ($this->settings['useGroups'])
        {
            $tmpl = $this->templates()->admin('image-grouped-list.html');
            // Изображения вне групп
            $table = ORM::getTable($this, 'Album');
            /* @var Gallery_Entity_Album $album */
            $album = $table->find($section);
            $vars['orphans'] = $album->getOrphans();
        }
        else
        {
            $tmpl = $this->templates()->admin('image-list.html');
        }

        // Компилируем шаблон и данные
        $html = $tmpl->compile($vars);

        return $html;
    }
634697
public function addMails()
	{
		//Выбор адресатов в зависимости от условий
		$this->clearMails();
		foreach ($this->config->mails as $name => $mail) {
			if ($this->name == $name  && !empty($name)){
				$this->_mails[] = $mail;
			}
		}
		if(empty($this->_mails)){
			foreach ($this->config->mails as $name => $mail) {
				foreach ($this->config->mailExc as $exc) {
					if($name !== $exc){
						$this->_mails[] = $mail;
					}
				}
			}
		}
		return $this->_mails;
	}
508784
function add($js, $condition = null, $no_build = false) {
        //если начинается с / значит надо в урл добавить хост
        if (mb_strpos($js, '/') === 0) {
            $js = $this->host() . $js;
        }
        $this->js_external[$js] = array(
            'condition' => $condition,
            'no_build' => $no_build,
        );
        return $this;
    }
1089302
function() {
        var builder = this.builder;

        builder.register( 'View', new ViewBuilder() );
        builder.register( 'InlineView', new InlineViewBuilder() );
        builder.register( 'AutoView', new MetadataViewBuilder() );

        builder.register( 'StackPanel', new StackPanelBuilder() );
        builder.register( 'GridPanel', new GridPanelBuilder() );
        builder.register( 'ScrollPanel', new ScrollPanelBuilder() );
        builder.register( 'Panel', new PanelBuilder() );
        builder.register( 'ScrollPanel', new ScrollPanelBuilder() );
        builder.register( 'ViewPanel', new ViewPanelBuilder() );
        builder.register( 'TabPanel', new TabPanelBuilder() );
        builder.register( 'TabPage', new TabPageBuilder() );

        builder.register( 'TablePanel', new TablePanelBuilder() );
        builder.register( 'Cell', new CellBuilder() );
        builder.register( 'Row', new RowBuilder() );

        builder.register( 'MenuBar', new MenuBarBuilder() );

        builder.register( 'DataGrid', new DataGridBuilder() );
        // служебный элемент, в документировании не нуждается
        builder.register( 'DataGridRow', new DataGridRowBuilder() );

        builder.register( 'DataGridColumn', new DataGridColumnBuilder() );
        builder.register( 'ListBox', new ListBoxBuilder() );

        builder.register( 'TextBox', new TextBoxBuilder() );
        builder.register( 'PasswordBox', new PasswordBoxBuilder() );
        builder.register( 'CheckBox', new CheckBoxBuilder() );
        builder.register( 'IndeterminateCheckBox', new IndeterminateCheckBoxBuilder() );
        builder.register( 'ImageBox', new ImageBoxBuilder() );
        builder.register( 'FileBox', new FileBoxBuilder() );
        builder.register( 'Label', new LabelBuilder() );
        builder.register( 'Link', new LinkBuilder() );
        builder.register( 'Form', new FormBuilder() );
        builder.register( 'Icon', new IconBuilder() );
        builder.register( 'DateTimePicker', new DateTimePickerBuilder() );
        builder.register( 'DatePicker', new DatePickerBuilder() );
        builder.register( 'TimePicker', new TimePickerBuilder() );
        builder.register( 'ToggleButton', new ToggleButtonBuilder() );
        builder.register( 'NumericBox', new NumericBoxBuilder() );
        builder.register( 'Button', new ButtonBuilder() );
        builder.register( 'ToolBar', new ToolBarBuilder() );
        builder.register( 'ToolBarButton', new ButtonBuilder() );
        builder.register( 'ComboBox', new ComboBoxBuilder() );
        builder.register( 'RadioGroup', new RadioGroupBuilder() );
        builder.register( 'ExtensionPanel', new ExtensionPanelBuilder() );
        builder.register( 'PopupButton', new PopupButtonBuilder() );
        builder.register( 'DataNavigation', new DataNavigationBuilder() );
        builder.register( 'TreeView', new TreeViewBuilder() );
        builder.register( 'Frame', new FrameBuilder() );
        builder.register( 'ButtonEdit', new ButtonEditBuilder() );

        builder.register( 'RestDataSource', new RestDataSourceBuilder() );
        builder.register( 'DocumentDataSource', new DocumentDataSourceBuilder() );
        builder.register( 'PropertyBinding', new DataBindingBuilder() );
        builder.register( 'ObjectDataSource', new ObjectDataSourceBuilder() );
        builder.register( 'Parameter', new ParameterBuilder() );

        builder.register( 'AcceptAction', new AcceptActionBuilder() );
        builder.register( 'AddAction', new AddActionBuilder() );
        builder.register( 'CreateItemAction', new CreateItemActionBuilder() );
        builder.register( 'CancelAction', new CancelActionBuilder() );
        builder.register( 'DeleteAction', new DeleteActionBuilder() );
        builder.register( 'EditAction', new EditActionBuilder() );
        builder.register( 'OpenAction', new OpenActionBuilder() );
        builder.register( 'SaveAction', new SaveActionBuilder() );
        builder.register( 'SelectAction', new SelectActionBuilder() );
        builder.register( 'UpdateAction', new UpdateActionBuilder() );
        builder.register( 'ServerAction', new ServerActionBuilder() );

        builder.register( 'RouteToAction', new RouteToActionBuilder() );

        builder.register( 'BooleanFormat', new BooleanFormatBuilder() );
        builder.register( 'DateTimeFormat', new DateTimeFormatBuilder() );
        builder.register( 'NumberFormat', new NumberFormatBuilder() );
        builder.register( 'ObjectFormat', new ObjectFormatBuilder() );

        builder.register( 'Script', new ScriptBuilder() );

        builder.register( 'Divider', new DividerBuilder() );
        builder.register( 'ContextMenu', new ContextMenuBuilder() );

        // служебный элемент, в документировании не нуждается
        builder.register( 'ToolTip', new InfinniUI.TooltipBuilder() );

        var registerQueue = ApplicationBuilder.registerQueue;

        for( var i = 0, ii = registerQueue.length; i < ii; i++ ) {
            builder.register( registerQueue[ i ].name, registerQueue[ i ].builder );
        }
    }
324996
protected function _initAutoFilters()
    {
        //Если автоопределение колонок не включено
        if (!$this->isEnabledAutoFilters) {
            return $this;
        }

        if (!$this->dataProvider) {
            return $this;
        }

        $dataProvider = clone $this->dataProvider;
        $models = $dataProvider->getModels();


        /**
         * @var $model Model
         * @var $model ActiveRecord
         */
        $model = reset($models);

        if (!$model) {
            $modelClass = $dataProvider->query->modelClass;
            $model = new $modelClass();
        }

        $result = [];

        $result['attributeDefines'] = [];
        if (method_exists($model, 'attributes')) {
            $result['attributeDefines'] = $model->attributes();
        }

        $result['attributeLabels'] = [];
        if (method_exists($model, 'attributeLabels')) {
            $result['attributeLabels'] = $model->attributeLabels();
        }


        $rules = [];
        $fields = [];

        if ($model instanceof ActiveRecord) {
            foreach ($model::getTableSchema()->columns as $key => $column) {
                if (in_array($column->type, ['string', 'text'])) {
                    $fields[(string)$key] = [
                        'class' => StringFilterField::class,
                    ];

                    $rules[] = [(string)$key, 'safe'];
                } else if (in_array($column->type, ['integer', 'decimal'])) {

                    $realKey = $key;
                    if (!empty($key) && strcasecmp($key, 'id')) {
                        if (substr_compare($key, 'id', -2, 2, true) === 0) {
                            $key = rtrim(substr($key, 0, -2), '_');
                        } elseif (substr_compare($key, 'id', 0, 2, true) === 0) {
                            $key = ltrim(substr($key, 2, strlen($key)), '_');
                        }
                    }

                    $keyMany = Inflector::pluralize($key);

                    $keyName = lcfirst(Inflector::id2camel($key, '_'));
                    $keyManyName = lcfirst(Inflector::id2camel($keyMany, '_'));


                    if ($relation = $model->getRelation($keyName, false)) {
                        if ($relation->modelClass && $relation->link) {

                            $arr = array_keys($relation->link);
                            $idName = $arr[0];
                            $modelClassName = $relation->modelClass;

                            $query = $modelClassName::find();

                            if ($query->count() > 1000) {
                                $fields[(string)$realKey] = [
                                    'class' => NumberFilterField::class,
                                ];
                            } else {
                                $fields[(string)$realKey] = [
                                    'class'             => NumberFilterField::class,
                                    'isAllowChangeMode' => false,
                                    'field'             => [
                                        'class'    => SelectField::class,
                                        'items'    => function () use ($idName, $query) {

                                            return ArrayHelper::map(
                                                $query->all(),
                                                $idName,
                                                'asText'
                                            );
                                        },
                                        'multiple' => true,
                                    ],
                                ];
                            }

                        }

                    }

                    if (!isset($fields[(string)$realKey])) {
                        $fields[(string)$realKey] = [
                            'class' => NumberFilterField::class,
                        ];
                    }

                    $rules[] = [(string)$realKey, 'safe'];

                } else {
                    $fields[(string)$key] = [
                        'class' => StringFilterField::class,
                    ];

                    $rules[] = [(string)$key, 'safe'];
                }

            }
        } elseif (is_array($model) || is_object($model)) {
            foreach ($model as $name => $value) {
                if ($value === null || is_scalar($value) || is_callable([$value, '__toString'])) {
                    $fields[(string)$name] = [
                        'class' => StringFilterField::class,
                    ];

                    $rules[] = [(string)$name, 'safe'];
                }
            }
        }

        $result['rules'] = $rules;
        $result['fields'] = $fields;
        $this->_autoDynamicModelData = $result;

        return $this;
    }
1049012
public static function check()
    {
        // Проверим значение установленной текущей локализации, если оно не входит в список доступных локализаций
        // установим локализацию по умолчанию
        if (!in_array(strtolower(self::$current_locale), self::$locales)) self::$current_locale = self::DEF;
    }
97869
public function registerData()
	{
		$fieldsAndTabs = array('FIELDS' => array(), 'TABS' => array());
		$tabsWithFields = $this->fields();

		// приводим массив хелперов к формату класс => настройки
		$helpers = array();

		foreach ($this->helpers() as $key => $value) {
			if (is_array($value)) {
				$helpers[$key] = $value;
			}
			else {
				$helpers[$value] = array();
			}
		}

		$helperClasses = array_keys($helpers);
		/**
		 * @var \Bitrix\Main\Entity\DataManager
		 */
		$model = $helperClasses[0]::getModel();
		foreach ($tabsWithFields as $tabCode => $tab) {
			$fieldsAndTabs['TABS'][$tabCode] = $tab['NAME'];

			foreach ($tab['FIELDS'] as $fieldCode => $field) {
				if (empty($field['TITLE']) && $model) {
				    //Битрикс не использует параметр title при создании экземпляра ReferenceField.
                    if (is_a($model::getEntity()->getField($fieldCode), 'Bitrix\Main\Entity\ReferenceField')) {
                        $map = $model::getMap();
                        if(isset($map[$fieldCode]['title'])){
                            $field['TITLE'] = $map[$fieldCode]['title'];
                        }
                    } else {
                        $field['TITLE'] = $model::getEntity()->getField($fieldCode)->getTitle();
                    }
				}

				$field['TAB'] = $tabCode;
				$fieldsAndTabs['FIELDS'][$fieldCode] = $field;
			}
		}

		AdminBaseHelper::setInterfaceSettings($fieldsAndTabs, $helpers, $helperClasses[0]::getModule());

		foreach ($helperClasses as $helperClass) {
			/**
			 * @var AdminBaseHelper $helperClass
			 */
			$helperClass::setInterfaceClass(get_called_class());
		}
	}
273618
static function activate()
    {
        if (get_magic_quotes_gpc()){
            $process = array(&$_GET, &$_POST, &$_COOKIE, &$_REQUEST);
            while (list($key, $val) = each($process)){
                foreach ($val as $k => $v){
                    unset($process[$key][$k]);
                    if (is_array($v)){
                        $process[$key][stripslashes($k)] = $v;
                        $process[] = &$process[$key][stripslashes($k)];
                    }else{
                        $process[$key][stripslashes($k)] = stripslashes($v);
                    }
                }
            }
            unset($process);
        }
        // Нормализация массива $_FILES в соответствии с именованием полей формы
        if (isset($_FILES)){
            // Перегруппировка элементов массива $_FILES
            $rec_to_array = function ($array, $name) use (&$rec_to_array){
                $result = [];
                foreach ($array as $key => $value){
                    if (is_array($value)){
                        $result[$key] = $rec_to_array($value, $name);
                    }else{
                        $result[$key][$name] = $value;
                    }
                }
                return $result;
            };
            $files = [];
            foreach ($_FILES as $field => $data){
                $files[$field] = [];
                foreach ($data as $name => $value){
                    if (is_array($value)){
                        $files[$field] = F::arrayMergeRecursive($files[$field], $rec_to_array($value, $name));
                    }else{
                        $files[$field][$name] = $value;
                    }
                }
            }
        }else{
            $files = [];
        }

        self::$source = array(
            'REQUEST' => [],
            'FILES' => $files,
            'COOKIE' => isset($_COOKIE)? $_COOKIE : [],
            'RAW' => file_get_contents("php://input"), // Неформатированные данные
            'SERVER' => $_SERVER
        );
        if (isset($_SERVER['REQUEST_URI'])){
            $_SERVER['REQUEST_URI'] = preg_replace('#\?{1}#u', '&', $_SERVER['REQUEST_URI'], 1);
//            $request_uri = preg_replace('#^'.preg_quote(DIR_WEB).'#u', '/', $_SERVER['REQUEST_URI'], 1);
            parse_str('path='.$_SERVER['REQUEST_URI'], self::$source['REQUEST']);
            self::$source['SERVER']['argv'] = self::$source['REQUEST'];
            self::$source['SERVER']['argc'] = sizeof(self::$source['REQUEST']);
        }
        // Элементы пути URI
        if (isset(self::$source['REQUEST']['path']) && (self::$source['REQUEST']['path'] = rtrim(self::$source['REQUEST']['path'],'/ '))){
            self::$source['PATH'] = explode('/', trim(self::$source['REQUEST']['path'],' /'));
        }else{
            self::$source['PATH'] = [];
        }
        if (isset($_POST)){
            self::$source['REQUEST'] = array_replace_recursive(self::$source['REQUEST'], $_POST);
        }
        // Аргументы из консоли (режим CLI)
        if (php_sapi_name() == 'cli' && isset($_SERVER['argv'])){
            self::$source['REQUEST']['method'] = 'CLI';
            self::$source['SERVER']['argv'] = $_SERVER['argv'];
            self::$source['SERVER']['argc'] = $_SERVER['argc'];
        }
        self::$source['ARG'] = self::$source['SERVER']['argv'];
        // Метод запроса
        if (isset(self::$source['SERVER']['REQUEST_METHOD']) && !isset(self::$source['REQUEST']['method'])){
            self::$source['REQUEST']['method'] = self::$source['SERVER']['REQUEST_METHOD'];
        }
    }
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);
	}
1351910
function onFormInitialized() {
		parent::onFormInitialized();
		$this->addClass('df-font'); // 2016-07-30 This CSS class will be applied to the <fieldset> DOM node.
		$this->checkbox(O::enabled, 'Setup?');
		$row1 = $this->fieldsetInline('df-checkboxes')->hide(); /** @var FInline $row1 */
		$row1->checkbox(O::bold, 'B', ['title' => 'Bold']);
		$row1->checkbox(O::italic, 'I', ['title' => 'Italic']);
		$row1->checkbox(O::underline, 'U', ['title' => 'Underline']);
		$row1->color(O::color, null, ['title' => 'Font Color']);
		$row2 = $this->fieldsetInline('df-family')->hide(); /** @var FInline $row2 */
		$row2->field(O::family, GoogleFont::class, null, ['title' => 'Font Family']);
		/** @var array(array(string => string)) $sizeValues */
		$sizeValues = [Q::P__VALUES => SizeUnit::s()->toOptionArray()];
		$row2->quantity(O::size, null, $sizeValues + ['title' => 'Font Size']);
		$row3 = $this->fieldsetInline('row3')->hide(); /** @var FInline $row3 */
		// 2015-12-13
		// Намеренно указываем в качестве подписи пустую строку, а не null,
		// чтобы получить пустые теги <label><span></span></label>
		// и потом стилизовать их своей иконкой.
		$row3->quantity(O::letter_spacing, '', $sizeValues + ['title' => 'Letter Spacing']);
		/**
		 * 2015-12-13
		 * Передаём в качестве подписи название класса Font Awesome.
		 * Такое стало возможным благодаря моему плагину
		 * @used-by \Df\Framework\Plugin\Data\Form\Element\AbstractElement::aroundGetLabelHtml()
		 * https://github.com/mage2pro/core/tree/73bed4fbb751ab47ad1bb70a8d90f455da26b500/Framework/Data/Form/Element/AbstractElementPlugin.php#L53
		 */
		/**
		 * 2015-12-13
		 *	.test {
		 *		transform : scale(1,1.5);
		 *		-webkit-transform:scale(1,1.5); // Safari and Chrome
		 *		-moz-transform:scale(1,1.5); // Firefox
		 *		-ms-transform:scale(1,1.5); // IE 9+
		 *		-o-transform:scale(1,1.5); // Opera
		 *		letter-spacing: 10px;
		 *	}
		 * https://developer.mozilla.org/en-US/docs/Web/CSS/transform-function#scale()
		 * http://stackoverflow.com/a/16447826
		 */
		$row3->percent(O::scale_horizontal, 'fa-text-width', 100, ['title' => 'Horizontal Scale']);
		$row3->percent(O::scale_vertical, 'fa-text-height', 100, ['title' => 'Vertical Scale']);
		/**
		 * 2015-12-13
		 * Намеренно указываем в качестве подписи пустую строку, а не null,
		 * чтобы получить пустые теги <label><span></span></label>
		 * и потом стилизовать их своей иконкой.
		 */
		df_hide($this->select(O::letter_case, '', LetterCase::s(), ['title' => 'Letter Case']));
		df_fe_init($this, __CLASS__, df_fa());
	}
448172
public function boot()
    {
        /**
         * Подключаем базовые маршруты
         * пока оставляем это для ручной работы
         */
        // if (Config::get('qwertcms.include_routes')) {
        //     include __DIR__ . '/routes.php';
        // }

        /**
         * Языки (резерв)
         */
        // $this->loadTranslationsFrom(__DIR__ . '/lang', 'qwertcms');
        
        /**
         * Настройки
         */
        $this->publishes([
            __DIR__ . '/config/qwertcms.php' => base_path('config/qwertcms.php'),
        ], 'qwertcms_config');

        /**
         * Роуты
         */
        $this->publishes([
            __DIR__ . '/routes' => base_path('routes/'),
        ], 'qwertcms_routes');

        /**
         * Шаблоны для админки
         */
        $this->loadViewsFrom(__DIR__.'/views', 'qwertcms');

        $this->publishes([
            __DIR__ . '/public' => public_path('vendor/qwertcms'),
        ], 'qwertcms_public');

        $this->publishes([
            __DIR__.'/views'  => base_path('resources/views/'),
        ], 'qwertcms_view');

        /**
         * Шаблоны авторизации
         */
        // $this->publishes([
        //     __DIR__.'/views/auth'  => base_path('resources/views/auth'),
        // ], 'qwertcms_view');

        /**
         * Миграции и seeds
         */
        $this->publishes([
            __DIR__ . '/database/migrations/' => database_path('migrations')
        ], 'qwertcms_migrations');

        $this->publishes([
            __DIR__ . '/database/seeds/' => database_path('seeds')
        ], 'qwertcms_seeds');

        /**
         * Базовые контроллеры
         */
        $this->publishes([
            __DIR__ . '/controllers/' => app_path('Http/controllers')
        ], 'qwertcms_controllers');

        /**
         * Модели
         */
        $this->publishes([
            __DIR__ . '/Models/' => app_path()
        ], 'qwertcms_models');

        /**
         * Шаблоны писем
         */
        $this->publishes([
            __DIR__ . '/Mail/' => app_path('Mail')
        ], 'qwertcms_mail');

        /**
         * Функции хелперы
         */
        $this->publishes([
            __DIR__ . '/Helpers/' => app_path('Helpers')
        ], 'qwertcms_helpers');

        /**
         * Языковые файлы
         */        
        $this->publishes([
            __DIR__ . '/lang/adminlte/ru' => base_path('resources/lang/vendor/adminlte/ru/')
        ], 'qwertcms_adminlang');
        $this->publishes([
            __DIR__ . '/lang/laravel/ru' => base_path('resources/lang/ru/')
        ], 'qwertcms_lang');

        /**
         * Middleware для мультиязычности
         */
        $this->publishes([
            __DIR__ . '/Middleware' => app_path('Http/Middleware/')
        ], 'qwertcms_lang');
        
    }