Удаляет все заказы и очищает корзину (служебная функция).
773459
public function deleteOrdersClearCart() {
    $query = $this->connection->truncate('site_cart')->execute();
    $query = $this->connection->truncate('site_orders')->execute();
  }
726568
static function load_multi_array($class_names, $fields, $where)
	{
		$union	= array();
		$post	= array();
		foreach($class_names as $class_name)
		{
			$foo = new $class_name(NULL);
			$db_name = $foo->db_name();
			$dbh = new driver_mysql($db_name);
			$table_name = $foo->table_name();
			$class_file = $foo->class_file();
			$where['*fields'] = $fields;
			list($select, $where, $post_functions) = self::__query_data_prepare($foo, $where);

			if(count($select) != count($fields))
				bors_throw(ec('У класса ').$class_name
					.ec(' не хватает нужных полей. В наличии только ').join(', ', $select)
					.ec(' при необходимых ').join(', ', $fields));

			$select[] = "'$class_name' AS `class_name`";
			$post[$class_name] = $post_functions;
			$union[] = array($table_name, join(',', $select), $where, $class_name);
		}

		$datas = $dbh->union_select_array($union);
		$objects = array();

		foreach($datas as $data)
		{
			$class_name = $data['class_name'];
			$object = new $class_name(NULL);
//			$object->set_class_file($class_file);
			$object->set_id(@$data['id']);
			$object->data = $data;

			$object->set_is_loaded(true);

			if(!empty($post[$class_name]))
				self::post_functions_do($object, $post[$class_name]);

			$objects[] = $object;

			save_cached_object($object);
		}

		return $objects;
	}
933654
public function work()
    {
        $workerNeed = self::WORKER_MIN * $this->workerMultiplier;
        $workerCount = count($this->workerPool);

        if (
            ($workerCount < $workerNeed && $workerCount < $this->workerMaxCount)
            && !$this->running
        ) {
            // run new worker
            $this->workerRun = $this->workerStarter->start();
            $this->running = time();
        } elseif ($this->running && $this->running < time() - 10) {
            // timeout 10 sec - не удалось запустить воркер
            $this->running = 0;
            if ($this->workerRun->isRunning()) {
                // убиваем запущенный процесс, если он ещё работает
                $this->workerRun->kill();
            }
        }
    }
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;
    }
1230115
public function init()
    {
        try
        {
            $this->data = $this->httpClientResponse->data;
        } catch (\Exception $e)
        {
            \Yii::error($this->httpClientResponse->content, self::className());

            $this->isError       = true;
            $this->errorMessage  = 'Не удалось отформатировать ответ от сервера';
            $this->errorCode     = $this->httpClientResponse->statusCode;
            $this->errorData     = $this->data;

            return;
        }

        if (!$this->httpClientResponse->isOk)
        {
            \Yii::error($this->httpClientResponse->content, self::className());

            $this->isError       = true;
            $this->errorMessage  = $this->api->getMessageByStatusCode($this->httpClientResponse->statusCode);
            $this->errorCode     = $this->httpClientResponse->statusCode;
            $this->errorData     = $this->data;

            return;
        }
    }
114500
public function postCreateOrder()
	{
		$data = Input::all();
		//Проверяем данные на валидность
		$validator = Validator::make(
			$data,
			Validators::rulesForNewOrder(),
			Validators::messagesForErrors()
		);
		$userMessages = $validator->messages();

		//Если есть ошибки, возвращаем
		if ($validator->fails()) {
			$result['errors'] = array(
				'item'    => $userMessages->first('item'),
				'sum'     => $userMessages->first('sum'),
				'tel'     => $userMessages->first('tel'),
				'comment' => $userMessages->first('comment'),
			);

			return $result;
		}
		//Предполагаем ошибку
		$result['errors'] = array(
			'common' => 'Ошибка. Повторите ещё раз.',
		);

		//Создаём заказ
		$data['user_id'] = Config::get('ff-qiwi-shop::user_id');
		$validity = Setting::find($data['user_id'])->lifetime;
		$data['lifetime'] = date('Y-m-d H:i:s', time() + 3600 * 24 * $validity);

		$order = new Order();
		$order->saveData($data);

		//Если заказ создан, то вместо ошибки отдаём ОК
		if ($order) {
			$result = array(
				'result'   => 'ok',
				'order_id' => $order->id,
				'message'  => 'Заказ №' . $order->id . ' успешно создан.',
			);
		}

		return $result;
	}
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;
            }
        }
    }
482323
protected function execute(InputInterface $input, OutputInterface $output)
    {
        // Находим файлы
        $dir = $input->getArgument(self::ARGUMENT_DIR);
        $exclude = $input->getOption(self::OPTION_EXCLUDE);
        $files = (new Finder())->files()->name('*.php')->in($dir)->exclude($exclude);

        // Извлекаем методы из файлов
        $progress = new ProgressBar($output, count($files));
        $parser = (new ParserFactory())->create(ParserFactory::PREFER_PHP7);
        $methods = (new SourceExtractor($parser, new Standard(), $progress))
            ->setMode($input->getOption(self::OPTION_PUBLIC_ONLY) !== 'no')
            ->extract($files);
        $progress->finish();
        $output->writeln('');

        // Подсчитываем цикломатическую сложность
        $progress = new ProgressBar($output, count($methods));
        $progress->start();
        (new ComplexityCounter($progress))->count($methods);
        $progress->finish();
        $output->writeln('');

        // Сортируем методы
        (new Sorter())->sort(
            $methods,
            $input->getOption(self::OPTION_SORT_BY_NAME)
                ? Sorter::BY_NAME
                : Sorter::BY_COMPLEXITY
        );

        $this->results($output, $methods, (int)$input->getOption(self::OPTION_THRESHOLD));
    }
112851
public function sectionStdList()
	{
		$table = array(
			'name' => 'templates',
			'key'=> 'filename',
			'sortMode' => 'filename',
			'sortDesc' => false,
			'columns' => array(
				array('name' => 'description', 'caption' => 'Описание'),
				#array('name' => 'filename', 'caption' => 'Имя файла'),
			),
			'controls' => array (
				'delete' => '',
				'edit' => '',
			),
			'tabs' => array(
				'width'=>'120px',
				'items'=>array(
					array('caption'=>ADM_ADD, 'name'=>'action', 'value'=>'add'),
				)
			),
		);
		$templates = Templates::getInstance();
		$list = $templates->enum('std');
		$items = array();
		foreach ($list as $key=>$value)
		{
			$items[] = array('filename' => $key, 'description' => $value);
		}
		/** @var TAdminUI $page */
		$page = Eresus_Kernel::app()->getPage();
		$result = $page->renderTable($table, $items);
		return $result;
	}
488286
public function actionDelete($id) {
    Yii::$app->authManager->getRole($id);
    //if (Yii::$app->authManager->remove($id)) {
    //  Yii::$app->session->setFlash('success', 'Роль удалена');
    //}

    Yii::$app->session->setFlash('success', 'Удаление ролей не возможно');

    return $this->redirect(['index']);
  }
295162
public function rewind()
    {
        $this->items = array();

        $this->prepareUrlTemplate();

        /*
         * Если страниц больше чем задано показывать за один раз, то будем показывать только часть
         * страниц, наиболее близких к текущей.
         */
        if ($this->total > $this->size)
        {
            // Начинаем показ с текущей, минус половину видимых
            $first = (int) floor($this->current - $this->size / 2);
            if ($first < 1)
            {
                // Страниц меньше 1-й не существует
                $first = 1;
            }

            $last = $first + $this->size - 1;
            if ($last > $this->total)
            {
                // Но если это больше чем страниц всего, вносим исправления
                $last = $this->total;
                $first = $last - $this->size + 1;
            }
        }
        else
        {
            $first = 1;
            $last = $this->total;
        }


        if ($first > 1)
        {
            $pageNumber = $this->current - $this->size;
            if ($pageNumber < 1)
            {
                $pageNumber = 1;
            }
            $this->items []= $this->itemFactory($pageNumber, '&larr;');
        }

        for ($pageNumber = $first; $pageNumber <= $last; $pageNumber++)
        {
            $item = $this->itemFactory($pageNumber);
            $item['current'] = $pageNumber == $this->current;
            $this->items []= $item;
        }

        if ($last < $this->total)
        {
            $pageNumber = $this->current + $this->size;
            if ($pageNumber > $this->total)
            {
                $pageNumber = $this->total;
            }
            $this->items []= $this->itemFactory($pageNumber, '&rarr;');
        }

        $this->iteration = 1;
    }
1078825
public function delete()
    {
        // нельзя удалить корневой раздел
        if ($this->id == 0) throw new Exception\CMS(Exception\CMS::NO_RIGHTS);
    
    	$tree = new CDBTree('dir_structure');
		
		$ids_arr = array($this->id);
		
		if (!$this->isLink()) {
    
			$r = self::getDbConnection()->query('SELECT A.data_id, A.level, C.tablename, D.alias 
							  FROM dir_structure A, dir_structure B, dir_data C, types D 
							  WHERE C.id=A.data_id and B.data_id='.$this->id.' and A.lft BETWEEN B.lft and B.rght and D.id=C.typ');
			
			while ($f = $r->fetch()) {
				try {
					$r1 = self::getDbConnection()->query('SELECT id FROM '.$f['alias'].' WHERE idcat='.$f['data_id']);
					while ($f1 = $r1->fetch(\PDO::FETCH_NUM)) {
					   $m = Material::getById($f1[0], 0, $f['alias']);
					   $m->delete();
					}
				} catch (Exception $e) {}
				$ids_arr[] = $f['data_id'];
			}
		
		}
    
    	$parent = array();
    	$r = self::getDbConnection()->query('SELECT A.id, B.data_id 
                          FROM dir_structure A, dir_structure B 
                          WHERE A.data_id='.$this->id.' and B.lft<A.lft and B.rght>A.rght and B.level=A.level-1
            			  ORDER BY A.lft DESC');
    	$res = TRUE;
    	while ($f = $r->fetch()) {
    		$parent[] = $f['data_id'];
    		if (!$tree->deleteAll($f['id'])) $res = FALSE;
    	} // while
		
    	if ($res && sizeof($ids_arr))
		{
    		$ids = implode(',',$ids_arr);
        
			self::getDbConnection()->executeQuery("DELETE FROM dir_data WHERE id IN ($ids)");
			self::getDbConnection()->executeQuery("DELETE FROM types_fields_catalogs WHERE catalog_id IN ($ids)");
        
    		$r = self::getDbConnection()->query("SELECT name FROM server_aliases WHERE id IN ($ids)");
    		while ($f = $r->fetch()) {
        		$slot = new Cache\Slot\ServerByDomain($f['name']);
        		$slot->remove();	
    		}
        
    		self::getDbConnection()->executeQuery("DELETE FROM server_aliases where id IN ($ids)");
			self::getDbConnection()->executeQuery("DELETE FROM theme_config where server_id IN ($ids)");
        
    		foreach ($ids_arr as $id1) {
        		self::getDbConnection()->executeQuery("DELETE FROM users_groups_allow_cat where catalog_id=$id1");
                $tpl = new Cache\Tag\CatalogID($id1);
                $tpl->clean();
    		}
			
			// удаляем разделы-ссылки, ссылающиеся на раздел
			$r = self::getDbConnection()->query('SELECT id FROM dir_data WHERE type&'.Catalog::LINKED.'>0 and typ IN ('.$ids.')'); 
			while ($f = $r->fetch()) {
				$c = Catalog::getById($f['id']);
				$c->delete();
			}			
    	}
    	
    	$this->updateCache();
    }
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);
        }
    }
62599
public function editAction()
    {
        /** @var Menus_Entity_Table_Menu $table */
        $table = ORM::getTable($this->plugin, 'Menu');
        /** @var Menus_Entity_Menu $menu */
        $menu = $table->find(arg('id', 'int'));

        if (is_null($menu))
        {
            return 'Такое меню не найдено.';
        }

        $req = Eresus_CMS::getLegacyKernel()->request;

        if ('POST' == $req['method'])
        {
            $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');

            $test = $table->findByName($menu->name);
            if (is_null($test) || $test->id == $menu->id)
            {
                $table->update($menu);
                HTTP::redirect('admin.php?mod=ext-menus&id=' . $menu->id);
            }
            else
            {
                ErrorMessage('Меню с таким именем уже есть');
            }
        }

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

        return $html;
    }
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'];
        }
    }
403577
public function doSuccess()
	{
		$date = date('Y-m-d H:i:s', time() - 60);
		$dateRefund = $this->updated_at; //даём минуту для прохождения оплаты
		if ($date > $dateRefund) {
			Refund::find($this->id)
				->whereStatus(self::C_STATUS_PROCESSING)
				->update(array('status' => self::C_STATUS_SUCCESS));
		}

		return Refund::find($this->id);
	}
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());
		}
	}