Запрашивает у балансировщика slave и мастер сервер для работы
761999
protected function detectServers()
    {
        // TODO: сделать балансировщик

        foreach ($this->servers as $serverId => $server) {
            if ($server instanceof IMasterServer) {
                $this->currentMaster = $this->getServer($serverId);
            } elseif ($server instanceof ISlaveServer) {
                $this->currentSlave = $this->getServer($serverId);
            }
        }
        if (!$this->currentMaster) {
            throw new RuntimeException($this->translate(
                'Cannot detect master server for db connection.'
            ));
        }
        if (!$this->currentSlave) {
            $this->currentSlave = $this->currentMaster;
        }
    }
1251289
static function add($action, $user = NULL, $object = NULL, $target = NULL, $attrs = array())
	{
//		print_dd(compact('object', 'user', 'target'));
		if(!$target)
			$target		= object_property($object, 'target');

		$actor		= bors_load_ex($action, NULL, compact('object', 'user', 'attrs'));

		$category	= object_property($target, 'category');
		$folder		= object_property($target, 'folder');

		$data = array(
			'handler_class_name'=> $action,
			'color' => $actor->color(),

			'object_class_name'	=> object_property($object, 'class_name'),
			'object_id'			=> object_property($object, 'id'),
			'target_class_name'	=> object_property($target, 'class_name'),
			'target_id'			=> object_property($target, 'id'),

			'category_class_name' => object_property($category, 'class_name'),
			'category_id'		=> object_property($category, 'id'),
			'folder_class_name'	=> object_property($folder, 'class_name'),
			'folder_id'			=> object_property($folder, 'id'),
		);

		if(empty($attrs['personal_only']) && ($title = $actor->public_title()))
		{
			$data['title']	= $title;
			$data['text']	= $actor->public_text();
			// Кому идёт сообщение. 0, если публичное.
			$data['user_class_id']	= 0;
			$data['user_id'] = 0;
			bors_new(config('default_events_class', __CLASS__), $data);
		}

		if($user && ($title = $actor->personal_title()))
		{
			$data['title']	= $title;
			$data['text']	= $actor->personal_text();
			// Кому идёт сообщение. 0, если публичное.
			$data['user_class_id']	= $user->class_id();
			$data['user_id']		= $user->id();
			bors_new(config('default_events_class', __CLASS__), $data);
		}
	}
247344
public function fire() {
        $elements = [];
        //добавим геттеры в контейнеры
        //добавим сеттеры в контейнеры
        foreach (Register::$containers as $container) {
            $this->info($container);
            foreach ($this->form_element_methods_get as $method) {
                $params = $this->getMethodParams($container, $method);
                $this->putPhpDoc($container, 'string', $method, $params);
            }
            foreach ($this->form_element_methods_set as $method) {
                $params = $this->getMethodParams($container, $method);
                $this->putPhpDoc($container, $container, $method, $params);
            }
        }
        //добавим элементы в контейнеры
        foreach (Register::$elements as $name => $data) {
            $class = Arr::get($data, 'class');
            foreach (Register::$containers as $container) {
                $params = $this->getMethodParams($class, 'laraform');
                $method = \Illuminate\Support\Str::camel('put_' . $name);
                $this->putPhpDoc($container, $class, $method, $params);
            }
            foreach ($this->form_element_methods_get as $method) {
                $params = $this->getMethodParams($class, $method);
                $this->putPhpDoc($class, 'string', $method, $params);
            }
            foreach ($this->form_element_methods_set as $method) {
                $params = $this->getMethodParams($class, $method);
                $this->putPhpDoc($class, $class, $method, $params);
            }
        }
        $data    = $this->ret;
        $content = \View::make(
            'larakit::!.quickform.ide-helper', [
                'data' => $data,
                'tab'  => "\t",
            ]
        );
        file_put_contents(base_path() . '/_ide_helper_laraform.php', $content);
        $this->info('IDE helper сгенерирован для ' . HelperText::plural_with_number(count($this->classes), 'элемента', 'элементов', 'элементов'));
    }
1141109
function rss_body($foo_object=NULL, $foo_strip=0)
	{
		//TODO: Этот config пока используется только на лентах топиков:
		//TODO: http://www.wrk.ru/society/2014/08/topic-89787-rss.xml
		//TODO: Подумать, как сделать красиво и локально
		if(!\B2\Cfg::get('rss_skip_images') && ($image = object_property($this, 'image')))
 			$image_html = "<p>".$image->thumbnail('300x300')->html_code() . "</p>\n";
		else
			$image_html = '';

		if(($body = $this->description()))
			return $image_html . '<p>'.bors_lcml::bbh($body).'</p>';

//		if(($body = $this->source()))
//			return $image_html . '<p>'.bors_lcml::bbh($body).'</p>';

		return $image_html . '<p>'.$this->body().'</p>';
	}
946545
private final function Render()
    {
        if ($this->request->isBinaryRequest())
            return;

        $renderpage = $this->currentpage;

        if ($this->request->isAjaxRequest()) {

           if(false==$renderpage->renderAjax())  return;
            
        }



        //загружаем  соответсвующий  шаблон
        $template = $this->getTemplate(get_class($renderpage));



        

        $doc = \phpQuery::newDocumentHTML($template);

        $basepage = get_parent_class($renderpage);
        // если  страница  не  базовая   а  дочерняя
        if ($basepage !== "Zippy\\Html\\WebPage") {

            $basetemplate = WebApplication::getApplication()->getTemplate($basepage);
            // if(count($renderpage->_tvars) >0){
            //    $m = new \Mustache_Engine();
            //   $basetemplate= $m->render($basetemplate, $renderpage->_tvars);
            //  }


            $bdoc = \phpQuery::newDocumentHTML($basetemplate);
            //восстанавливаем  по умолчанию


            $bdoc["childpage"]->replaceWith($doc['body']->html());

            $links = $doc['head  > link'];
            foreach ($links as $l) {
                pq('head')->append($l);
            }

            $script = $doc['head  > script'];
            foreach ($script as $sc) {
                pq('head')->append($sc);
            }
            $script = $doc['head  > title'];
            foreach ($script as $sc) {
                $bdoc['title']->remove();
                pq('head')->append($sc);
            }
            $script = $doc['head  > meta'];
            foreach ($script as $sc) {
                pq('head')->append($sc);
            }


            /*
              if (strlen($title) > 0) {
              $bdoc['description']->remove();
              pq('head')->append("<description>{$description}</title>");
              }
              if (strlen($title) > 0) {
              $bdoc['title']->remove();
              pq('head')->append("<title>{$title}</title>");
              } */
        }

        $renderpage->Render();


        if (strlen($renderpage->_title) > 0) {
            pq('title')->text($renderpage->_title);
        }
        if (strlen($renderpage->_keywords) > 0) {
            pq('meta[name="keywords"]')->attr('content', $renderpage->_keywords);
        }
        if (strlen($renderpage->_description) > 0) {
            pq('meta[name="description"]')->attr('content', $renderpage->_description);
        }



        $response = '<!DOCTYPE HTML>' . pq('html')->htmlOuter(); //HTML  в  выходной  поток

        if (count($renderpage->_tvars) > 0) {

            //востанавливаем  скобки  в тегах
            $response = str_replace("\"%7B%7B", "\"{{", $response);
            $response = str_replace("%7D%7D\"", "}}\"", $response);

            $m = new \Mustache_Engine();
            $response = $m->render($response, $renderpage->_tvars);
        }

        if ($this->request->isAjaxRequest()) {
            \phpQuery::newDocumentHTML($response);

            $renderpage->renderAjax(true);
            return;
        }
       
        $this->response->setContent($response);
    }
917885
public function delete()
    {
        // удаление ссылок с удаляемого материала
        $r = $this->getDbConnection()->query("select B.name, B.len, B.type, B.pseudo_type from types A, types_fields B where A.alias='".$this->table."' and B.id=A.id and (B.type=".FIELD_LINKSET." or B.type=".FIELD_MATSET.")");
        while ($f = $r->fetch(\PDO::FETCH_NUM)) {
            $tbl = ObjectDefinition::get_table($f[2], $f[1], $this->objectDefinition->id, $f[3]);
            if ($f[2] != FIELD_LINKSET && $f[3] != PSEUDO_FIELD_TAGS) {
            	$r1 = $this->getDbConnection()->query("select dest from ".$this->table."_".$tbl."_".$f[0]." where id=".$this->id);
            	while ($f1 = $r1->fetch(\PDO::FETCH_NUM)) {
            	   $m = Material::getById($f1[0], $f[1], $tbl);
            	   $m->delete();
            	}
            }
            $this->getDbConnection()->executeQuery("delete from ".$this->table."_".$tbl."_"."$f[0] where id=".$this->id);
        }
        
        // удаление ссылок на этот материал
        if (property_exists($this, 'idcat') && $this->idcat >= 0) {
        	$r = $this->getDbConnection()->query("select A.alias, B.name, B.type from types A, types_fields B where B.id=A.id and B.len=".$this->idcat." and (B.type=".FIELD_LINK." or B.type=".FIELD_LINKSET.")");
        	while ($f = $r->fetch(\PDO::FETCH_NUM)) {
              if ($f[2] == FIELD_LINK) {
        	    $this->getDbConnection()->executeQuery("update $f[0] set $f[1]=0 where $f[1]=".$this->id);
        	  } else {
        	    $this->getDbConnection()->executeQuery("delete from $f[0]"."_".$this->table."_"."$f[1] where dest=".$this->id);
        	  }
        	}
        } else {
        	$r = $this->getDbConnection()->query("select A.alias, B.name from types A, types_fields B where B.id=A.id and B.len = ".$this->objectDefinition->id." and B.type=".FIELD_MATSET);
            while ($f = $r->fetch(\PDO::FETCH_NUM)) {
        	  $this->getDbConnection()->executeQuery("delete from $f[0]"."_".$this->table."_"."$f[1] where dest=".$this->id);
        	}
        }
                
        // удаление самого материала
        $this->getDbConnection()->executeQuery("delete from ".$this->table." where id=".$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());
		}
	}
51362
public function clientRenderContent()
    {
        /** @var TClientUI $page */
        $page = Eresus_Kernel::app()->getPage();
        $request = Eresus_CMS::getLegacyKernel()->request;
        /* Если в URL указано что-либо кроме адреса раздела, отправляет ответ 404 */
        if ($request['file'] || $request['query'] ||
            $page->subpage || $page->topic)
        {
            throw new Eresus_CMS_Exception_NotFound;
        }

        return $page->content;
    }
728074
public function sendHeaders()
    {
        /* Отправляем основной заголовок */
        $statusText = $this->statusText ?: self::getStatusText($this->getStatusCode());
        $header = 'HTTP/'
            . $this->getProtocolVersion() . ' '
            . $this->getStatusCode() . ' '
            . $statusText;
        header($header, true, $this->getStatusCode());

        /* Отправляем дополнительные заголовки */
        foreach ($this->headers as $header)
        {
            header($header);
        }
        return $this;
    }
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;
    }
342612
public function register()
    {
        // Регистрируем конкретный сторэйдж из списка доступных.
        $this->app->singleton(StorageInterface::class, function (Container $app) {
            // Defined driver
            $selectedDriver = config('api-tester.storage_driver');
            $driverClassName = config('api-tester.storage_drivers')[$selectedDriver];
            $requestCollection = $app->make(RequestCollection::class);

            if ($selectedDriver === 'firebase'){
                $tokenGenerator = $app->make(TokenGenerator::class);
                $base = config('api-tester.storage_drivers.firebase.options.base');

                return new FireBaseStorage($requestCollection, $tokenGenerator, $base);
            }

            if ($selectedDriver === 'file'){
                $fileSystem = $app->make(Filesystem::class);
                $path = config('api-tester.storage_drivers.file.options.path');

                return new JsonStorage($fileSystem, $requestCollection, $path);
            }

            throw new Exception("Driver $selectedDriver doesn't exist. Use either 'firebase' or 'file'.");
        });

        // Регистрация токен-генератора. Привязывается к ключу а не классу,
        // чтобы не конфликтовать с пользовательским генератором токенов.
        $this->app->singleton('api-tester.token_generator', function (Container $app) {
            $config = $app['config']['api-tester.storage_drivers.firebase.token'];
            return (new TokenGenerator($config['secret']))
                ->setOptions($config['options'])
                ->setData($config['data']);
        });

        // Подсовываем генератор в сторэйдж
        $this->app
            ->when(FireBaseStorage::class)
            ->needs(TokenGenerator::class)
            ->give('api-tester.token_generator');
    }
289063
public function init()
    {

        if ( empty( $this->action_save ) ){
            throw new HttpException(200, 'Ошибка контроллера. Не передано имя метода для сохранения файла (action).');
        }
        if ( empty( $this->action_read ) ){
            throw new HttpException(200, 'Ошибка виджета. Не передано имя метода для чтения данных (action).');
        }
        if ( empty( $this->action_write ) ){
            throw new HttpException(200, 'Ошибка виджета. Не передано имя метода записи данных (action).');
        }

        parent::init();
    }
95544
public function handle() {
        $path         = base_path('vendor');
        $vendor_paths = \File::directories($path);
        $path         = rtrim(rtrim($path, '\\'), '/');

        $this->info('Сканируем установленные пакеты на наличие папок .git и .svn');

        $check_directories = [];

        foreach ($vendor_paths as $vendor_path) {
            $package_paths = File::directories($vendor_path);
            foreach ($package_paths as $package_path) {
                $check_directories[] = (string)$package_path;
            }
        }


        $progress = new \Symfony\Component\Console\Helper\ProgressBar($this->output, sizeof($check_directories));
        $progress->setFormat('debug');
        $progress->start();
        foreach ($check_directories as $directory) {
            $progress->advance();
            $is_git = $this->checkGit($directory);
            if (!$is_git) {
                $this->checkSvn($directory);
            }
        }
        $progress->finish();
        $this->info('');
        $this->info('Сканирование завершено.');
        $table     = [];
        $separator = [
            '-',
            '-',
            '-',
            '-',
        ];
        if ($this->touched_git) {
            $this->info('Имеются изменные файлы GIT: ');
            foreach ($this->touched_git as $package_path => $files) {
                $package = larasafepath($package_path);
                foreach ($files as $file => $type) {
                    $table[] = [
                        'GIT',
                        $package,
                        larasafepath($file),
                        \Illuminate\Support\Arr::get($this->git_types, $type, $type)
                    ];
                }
                $table[] = $separator;
            }
        }
        if ($this->touched_svn) {
            $this->info('Имеются изменные файлы SVN: ');
            foreach ($this->touched_svn as $package_path => $files) {
                $package = larasafepath($package_path);
                foreach ($files as $file => $type) {
                    $table[] = [
                        'SVN',
                        $package,
                        trim(str_replace($package, '', larasafepath($file)), '/'),
                        \Illuminate\Support\Arr::get($this->svn_types, $type, $type)
                    ];
                }
                $table[] = $separator;
            }
        }


        if ($table) {
            unset($table[sizeof($table) - 1]);
            $this->info('');
            $this->table(
                [
                    'VCS',
                    'package',
                    'file',
                    'type'
                ],
                $table
            );
        }

    }
760320
public static function init()
    {
        /* Разрешаем только однократный вызов этого метода */
        if (self::$inited)
        {
            return;
        }

        // Устанавливаем кодировку по умолчанию для операций mb_*
        mb_internal_encoding('utf-8');

        /* Предотвращает появление ошибок, связанных с неустановленной временной зоной */
        @$timezone = date_default_timezone_get();
        date_default_timezone_set($timezone);

        self::initExceptionHandling();

        self::$inited = true;
    }
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);
		}
	}
1317518
function module_ex($module_name, $attrs)
	{
		$class_name = $this->class_name();
		$class_name = preg_replace('/_(main|edit|view)$/', '', $class_name);
		$module_class = \blib_grammar::plural($class_name).'_modules_'.$module_name;
		set_def($attrs, 'model', $this);
		$mod = bors_load_ex($module_class, $this, $attrs);
		if(!$mod)
			bors_throw(ec("Не могу загрузить модуль '$module_class'"));

		return $mod;
	}
1126603
private function clientCheckRequest()
    {
        /* @var TClientUI $page */
        $page = Eresus_Kernel::app()->getPage();
        /* Собираем вместе ожидаемые элементы URL */
        $acceptUrl = Eresus_CMS::getLegacyKernel()->request['path'] .
            ($page->subpage !== 0 ? 'p' . $page->subpage . '/' : '');

        if ($page->topic)
        {
            $acceptUrl .= $page->topic !== false ? $page->topic . '/' : '';
        }

        /* Сравниваем с переданным URL */
        if ($acceptUrl != Eresus_CMS::getLegacyKernel()->request['url'])
        {
            throw new Eresus_CMS_Exception_NotFound;
        }
    }