Сливает корзины из сессии и из БД
12836
public function merge()
    {
        $sessionProducts = Yii::$app->session->get($this->owner->storageName, []);

        // Сливаем корзины из сессии и из БД в соответствии с выбранным методом
        switch($this->owner->mergeMethod) {
            // корзина в сессии и корзина в БД (если такая была) будут объеденины, а кол-во одинаковых товаров просуммируются
            case 'sum':
                $this->mergeBasket_sum( $sessionProducts );
                break;

            // корзина в БД будет полностью заменена новой
            case 'new':
                $this->mergeBasket_new( $sessionProducts );
                break;

            // в БД будут добавлены новые товары, а у совпадающих сохраниться наибольшее кол-во
            case 'max':
                $this->mergeBasket_max( $sessionProducts );
                break;

            // в БД будут добавлены только новые товары
            default:
                $this->mergeBasket_merge( $sessionProducts );
        }

        // Очищаем корзину в сессии
        Yii::$app->session->set($this->owner->storageName, null);
    }
106120
function __content() // пока не используется, т.к. более древнее в base_object
	{
		if(($render_class = $this->render_class()))
		{
			if($render_class == 'self')
				$render = $this;
			elseif(!($render = bors_load($render_class)))
				debug_exit("Can't load global render engine {$render_class} for object '{$this}'");

			return $render->rendering($this);
		}
	}
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;
	}
575809
public function actionUserRole ()
		{
			$userClass = $this->module->modelUser;
			$post = Yii::$app->request->post();
			$user = $userClass::findOne($post[ 'id' ]);
			if (!is_null($user))
			{

				LogManager::info(Yii::tr('Пользователю {user} забрали права {roles}', [ 'user' => Html::a($user->name, Url::toRoute([ 'user/view', 'id' => $user->id ])), 'roles' => implode(',', $user->getRolesNames()) ]));
				$user->revokeAllRoles();
				if (is_array($post[ 'roles' ]))
				{
					foreach ($post[ 'roles' ] as $item)
					{
						$user->assignRole($item);
					}
					LogManager::info(Yii::tr('Пользователю {user} добавили права {roles}', [ 'user' => Html::a($user->name, Url::toRoute([ 'user/view', 'id' => $user->id ])), 'roles' => implode(',', $post[ 'roles' ]) ]));
				}
			}
			Yii::$app->end();
		}
960121
protected function adaptSourcesSearchPhrases()
    {
        $dataArray = [];

        //Формируем массив
        foreach ($this->data['data'] as $item) {
            $dataArray['data'][] = [
                'searchPhrase'            => $item['dimensions'][0]['name'],
                'searchEngineRoot'        => $item['dimensions'][1]['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;
    }
956917
private function adminAddGroupDialog()
    {
        $form = array(
            'name' => 'AddForm',
            'caption' => 'Добавление группы',
            'width' => '600px',
            'fields' => array (
                array ('type' => 'hidden', 'name' => 'action', 'value' => 'group_insert'),
                array ('type' => 'hidden', 'name' => 'section', 'value' => arg('section', 'int')),
                array ('type' => 'edit', 'name' => 'title', 'label' => 'Название',
                    'width' => '100%', 'maxlength' => '255'),
                array('type' => 'html', 'name' => 'description', 'height' => '400px',
                    'label' => 'Описание'),
            ),
            'buttons' => array('ok', 'cancel'),
        );

        /* @var TAdminUI $page */
        $page = Eresus_Kernel::app()->getPage();
        $result = $page->renderForm($form);

        return $result;
    }
291631
private function linkAdminResources()
    {
        $page = Eresus_Kernel::app()->getPage();
        /** @var Eresus_Plugin $plugin */
        $plugin = $this->getModule();

        $resource = 'admin/default.css'; // В будущем «default» можно заменить именем темы
        if (file_exists($plugin->getCodeDir() . '/' . $resource))
        {
            $page->linkStyles($plugin->getCodeUrl() . $resource);
        }

        $resource = 'admin/scripts.js';
        if (file_exists($plugin->getCodeDir() . '/' . $resource))
        {
            $page->linkScripts($plugin->getCodeUrl() . $resource);
        }
    }
227340
function execute(O $o) {
		$c = df_customer($o['customer']); /** @var Customer $c */
		$s = df_customer_session(); /** @var Session $s */
		if ($s->getDfSsoId()) {
			$c[Schema::fIdC($s->getDfSsoProvider())] = $s->getDfSsoId();
			/**
			 * 2016-12-04
			 * Нельзя использовать здесь @see df_eav_update(),
			 * потому что наше поле не является атрибутом EAV,
			 * а является просто полем таблицы customer_entity.
			 */
			$c->save();
		}
		$s->unsDfSsoId()->unsDfSsoProvider()->unsDfSsoRegistrationData();
		$s->setDfNeedConfirm(df_customer_is_need_confirm($c));
	}
1212638
public function addAction()
    {
        $req = Eresus_CMS::getLegacyKernel()->request;

        if ('POST' == $req['method'])
        {
            $menu = new Menus_Entity_Menu();
            $menu->name = arg('name', 'word');
            $menu->caption = arg('caption', 'dbsafe');
            $menu->active = true;
            $menu->root = arg('root', 'int');
            $menu->rootLevel = arg('rootLevel', 'int');
            $menu->invisible = arg('invisible', 'int');
            $menu->expandLevelAuto = arg('expandLevelAuto', 'int');
            $menu->expandLevelMax = arg('expandLevelMax', 'int');
            $menu->dropDown = arg('dropDown', 'int');
            $menu->template = arg('template', 'dbsafe');

            /** @var Menus_Entity_Table_Menu $table */
            $table = $menu->getTable();
            if (is_null($table->findByName($menu->name)))
            {
                $table->persist($menu);
                HTTP::redirect('admin.php?mod=ext-menus');
            }
            else
            {
                ErrorMessage('Меню с таким именем уже есть');
            }
        }
        else
        {
            $menu = null;
        }

        $form = new EresusForm($this->plugin->templates()->adminPath('form.html', false));
        $form->setValue('sections', $this->adminSectionBranch());
        $form->setValue('action', 'create');
        $form->setValue('menu', $menu);
        $html = $form->compile();

        return $html;
    }
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 );
        }
    }
105839
public function indexAction()
    {
        $this->view->roles = (new \Cms\Orm\CmsRoleQuery)->find();
        //jeśli niewybrana rola - przekierowanie na pierwszą istniejącą
        if (!$this->roleId && count($this->view->roles)) {
            $this->getResponse()->redirect('cmsAdmin', 'categoryAcl', 'index', ['roleId' => $this->view->roles[0]->id]);
        }
        //formularz edycji uprawnień
        $form = new Form\CategoryAclForm(null, ['roleId' => $this->roleId]);
        //po zapisie
        if ($form->isSaved()) {
            $this->getMessenger()->addMessage('messenger.categoryAcl.permissions.saved', true);
            //przekierowanie na zapisaną stronę
            $this->getResponse()->redirect('cmsAdmin', 'categoryAcl', 'index', ['roleId' => $this->roleId]);
        }
        $this->view->categoryAclForm = $form;
    }
132916
function on() {
        if($this->is_used) {
            return true;
        }
        $route   = \Route::currentRouteName();
        $exclude = self::maxIs($this->exclude, $route);
        $include = self::maxIs($this->include, $route);
        if($exclude > $include || true === $exclude) {
            // исключаем
        } else {
            // подключаем
            //сперва подключим на страницу зависимости
            foreach((array) $this->require as $require => $scopes) {
                Manager::package($require)
                    ->on();
            }
            
            foreach($this->deferred_scopes as $scope) {
                $this->scope($scope);
            }
            
            //затем подключим CSS
            foreach($this->css as $url => $item) {
                $condition = Arr::get($item, 'condition', null);
                $media     = Arr::get($item, 'media', null);
                $no_build  = (bool) Arr::get($item, 'no_build', false);
                Css::instance()
                    ->add($url, $media, $condition, $no_build);
            }
            //затем подключим JS
            foreach($this->js as $url => $item) {
                $condition = Arr::get($item, 'condition', null);
                $no_build  = (int) Arr::get($item, 'no_build', false);
                Js::instance()
                    ->add($url, $condition, $no_build);
            }
        }
        $this->is_used = true;
        
        return true;
    }
1034666
function reset_login()
	{
		$this->user['auth'] = isset($this->user['auth']) ? $this->user['auth'] : false;
		if ($this->user['auth'])
		{
			$item = $this->db->selectItem('users', "`id`='".$this->user['id']."'");
			if (!is_null($item))
			{
				# Если такой пользователь есть...
				if ($item['active'])
				{
					# Если учетная запись активна...
					$this->user['name'] = $item['name'];
					$this->user['mail'] = $item['mail'];
					$this->user['access'] = $item['access'];
					$this->user['profile'] = decodeOptions($item['profile']);
				}
				else
				{
                    Eresus_Kernel::app()->getPage()->addErrorMessage(
                        sprintf(ERR_ACCOUNT_NOT_ACTIVE, $item['login']));
					$this->logout();
				}
			}
			else
			{
				$this->logout();
			}
		}
		else
		{
			$this->user['access'] = GUEST;
		}
	}
983308
public static function CalculateResize($width, $height, $orig_width, $orig_height)
  {
    $ratio = $orig_width / $orig_height;

    if (!$width) {
      $width = $orig_width;
    }

    if (!$height) {
      $height = $orig_height;
    }

    //Если изначальные размеры меньше необходимых - ничего не меняем
    if ($width >= $orig_width && $height >= $orig_height) {
      return array($orig_width, $orig_height);
    }

    $new_width  = $width;
    $new_height = $height;

    if ($width < $orig_width) {
      $new_width  = $width;
      $new_height = floor($width / $ratio);
    }

    if ($new_height > $height) {
      $new_width  = floor($new_width * ($new_height / $height));
      $new_height = $height;
    }

    if ($new_height < $orig_height) {
      $new_width = floor($new_height * $ratio);
    }

    return array($new_width, $new_height);
  }
386352
public function indexAction()
    {
        $year = $this->year ? $this->year : date('Y');
        $month = $this->month ? $this->month : date('m');
        //form filtrujący
        $form = new \CmsAdmin\Form\Stat\StatObject(null, ['object' => $this->object,
            'year' => $year,
            'month' => $month,
        ]);
        //przekazanie formularza
        $this->view->objectForm = $form;
        if ($form->isMine()) {
            //przekierowanie po odczycie pól z formularza
            if ($form->getElement('object')->getValue() && $form->getElement('month')->getValue() >= 1 && $form->getElement('month')->getValue() <= 12 && $form->getElement('year')->getValue() <= date('Y')) {
                $this->getResponse()->redirect('cmsAdmin', 'stat', 'index', ['object' => $form->getElement('object')->getValue(),
                    'year' => $form->getElement('year')->getValue(),
                    'month' => $form->getElement('month')->getValue(),
                ]);
            }
            //przekierowanie na dany miesiąc - bez zmiany obiektu
            $this->getResponse()->redirect('cmsAdmin', 'stat', 'index', ['year' => $form->getElement('year')->getValue(),
                'month' => $form->getValue('month'),
            ]);
        }
        if (!$this->object || !$this->year || !$this->month) {
            return;
        }
        $object = $this->object;
        $year = intval($year);
        $month = intval($month);
        $label = \Cms\Orm\CmsStatLabelQuery::byObject($object)
            ->findFirst();
        if ($label === null) {
            return;
        }
        $this->view->label = $label;
        //staty dzienne

        $prevMonth = ($month - 1) > 0 ? $month - 1 : 12;
        $prevYear = ($prevMonth == 12) ? $year - 1 : $year;
        $day = (ltrim(date('m'), '0') == $month) ? date('d') : date('t', strtotime($year . '-' . $month));

        //statystyki dzienne
        $this->view->dailyChart = \Cms\Model\StatFlot::getCode('dailyChart', [
                //bieżący miesiąc
                ['object' => $label->object,
                    'label' => $label->label . ': ' . $this->view->_('dni'),
                    'data' => \Cms\Model\Stat::toDate($object, null, $year, $month, $day)
                ],
                //poprzedni miesiąc
                ['object' => $label->object,
                    'label' => $this->view->_('Poprzedni miesiąc: dni'),
                    'data' => \Cms\Model\Stat::toDate($object, null, $prevYear, $prevMonth, $day)
                ]], 'lines', true);
        //statystyki miesięczne
        $this->view->monthlyChart = \Cms\Model\StatFlot::getCode('monthlyChart', [
                ['object' => $label->object,
                    'label' => $label->label . ': ' . $this->view->_('miesiące'),
                    'data' => \Cms\Model\Stat::monthly($object, null, $year)
                ]], 'bars');
        //statystyki roczne
        $this->view->yearlyChart = \Cms\Model\StatFlot::getCode('yearlyChart', [
                ['object' => $label->object,
                    'label' => $label->label . ': ' . $this->view->_('lata'),
                    'data' => \Cms\Model\Stat::yearly($object, null)
                ]], 'bars');
        //rozkład godzinowy
        $this->view->avgHourlyChart = \Cms\Model\StatFlot::getCode('avgHourlyChart', [
                ['object' => $label->object,
                    'label' => $label->label . ': ' . $this->view->_('rozkład godzinowy'),
                    'data' => \Cms\Model\Stat::avgHourly($object, null, $year, $month)
                ]], 'bars');
        //rozkład godzinowy
        $this->view->avgHourlyAllChart = \Cms\Model\StatFlot::getCode('avgHourlyAllChart', [
                ['object' => $label->object,
                    'label' => $label->label . ': ' . $this->view->_('rozkład ogólny'),
                    'data' => \Cms\Model\Stat::avgHourly($object, null, null, null)
                ]], 'bars');
    }
1253960
private function adminAddItem()
    {
        $request = Eresus_CMS::getLegacyKernel()->request;
        if ('POST' == $request['method'])
        {
            $image = new Gallery_Entity_Image();
            $image->section = arg('section');
            $image->groupId = arg('group') ? arg('group') : 0;
            $_SESSION['gallery_default_group'] = arg('group');
            $image->title = arg('title');
            $image->cover = arg('cover') ? arg('cover') : false;
            $image->active = arg('active');
            $image->posted = new DateTime();
            $image->image = 'image'; // $_FILES['image'];

            if ($this->isImageInputValid($image))
            {
                $table = ORM::getTable($this, 'Image');
                try
                {
                    $table->persist($image);
                }
                catch (Gallery_Exception_FileTooBigException $e)
                {
                    throw new DomainException('Размер загружаемого файла превышает максимально допустимый');
                }

                $url = 'admin.php?mod=content&section=' . $image->section;
                if (arg('pg'))
                {
                    $url .= '&pg=' . arg('pg', 'int');
                }
                HTTP::redirect($url);
            }
        }

        Eresus_Kernel::app()->getPage()->linkStyles($this->urlCode . 'admin.css');

        // Данные для подстановки в шаблон
        $data = array();
        $data['this'] = $this;
        $data['page'] = Eresus_Kernel::app()->getPage();
        $data['sectionId'] = arg('section', 'int');
        $data['defaultGroup'] = isset($_SESSION['gallery_default_group'])
            ? $_SESSION['gallery_default_group']
            : null;
        $data['image'] = isset($image) ? $image : null;

        if ($this->settings['useGroups'])
        {
            $data['groups'] = $this->dbSelect('groups', "`section` = " . arg('section', 'int'),
                'position');
        }

        // Создаём экземпляр шаблона
        $tmpl = $this->templates()->admin('add-image.html');

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

        return $html;
    }
1258112
public function find()
    {
        if ($this->owner->isNewRecord === false && SeoSlug::getDb()->getSchema()->getTableSchema(SeoSlug::tableName(), true) !== null) {
            //Сначала попробуем найти запись в кеше
            $this->_slugModel = $this->_cache->get($this->owner);
            if (is_null($this->_slugModel)) {
                $this->_slugModel = SeoSlug::find()
                    ->where([
                        'AND',
                        ['=', 'model', $this->owner->className()],
                        ['=', 'model_id', $this->owner->getPrimaryKey()],
                    ])
                    ->orderBy(['id' => SORT_DESC])
                    ->one();
                //Если запись найдена положим найденную запись в кеш
                if ($this->_slugModel) {
                    $this->_cache->set($this->owner, $this->_slugModel);
                }
            }
            //Если запись найдена и указано поле в родительской модели то присвоем ему значение этого алиаса
            if ($this->_slugModel && $this->slugAttribute) {
                $this->owner->{$this->slugAttribute} = $this->_slugModel->slug;
            }
        }
    }