Обновление настроек

@throws RuntimeException

@return void
338344
public function updateSettings()
    {
        /*
         * Загрузка логотипа
         */
        if (isset($_FILES['logoImage']['tmp_name']) &&
            is_uploaded_file($_FILES['logoImage']['tmp_name']))
        {
            if (substr($_FILES['logoImage']['name'], -3) == 'png')
            {
                upload('logoImage', $this->getDataDir() .'/logo.png');
            }
            else
            {
                Eresus_Kernel::app()->getPage()
                    ->addErrorMessage('Логотип должен быть в формате PNG');
            }
        }

        try
        {
            $this->templates()->clientWrite('image-list.html', arg('tmplImageList'));
            $this->templates()->clientWrite('image-list.html', arg('tmplImageList'));
            $this->templates()->clientWrite('image-grouped-list.html', arg('tmplImageGroupedList'));
            $this->templates()->clientWrite('image.html', arg('tmplImage'));
            $this->templates()->clientWrite('popup.html', arg('tmplPopup'));
        }
        catch (Exception $e)
        {
            throw new RuntimeException(
                'Не удалось изменить один или несколько шаблонов. Подробная информация доступна в журнале.',
                0,
                $e);
        }

        parent::updateSettings();
    }
1136248
public function run()
	{
		if($this->getIsContentCached())
		{
			if($this->getController()->isCachingStackEmpty())
				echo $this->getController()->processDynamicOutput($this->_content);
			else
				echo $this->_content;
		}
		elseif($this->_cache!==null)
		{
			$this->_content=ob_get_clean();
			$this->getController()->getCachingStack()->pop();
			$data=array($this->_content,$this->_actions);
			if(is_array($this->dependency))
				$this->dependency=Yii::createComponent($this->dependency);
			$this->_cache->set($this->getCacheKey(),$data,$this->duration,$this->dependency);

			if($this->getController()->isCachingStackEmpty())
				echo $this->getController()->processDynamicOutput($this->_content);
			else
				echo $this->_content;
		}
	}
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();
    }
1218427
public function start()
    {
        if (!session_id() || !$this->isActive()) {
            $file = $line = null;
            if (headers_sent($file, $line)) {
                throw new \RuntimeException(sprintf('Unable to start session, output started at %s:%s', $file, $line));
            }
            session_start();
        }

        if ($this->namespace) {
            if (!isset($_SESSION[$this->namespace])) {
                $_SESSION[$this->namespace] = array();
            }
            $this->data = &$_SESSION[$this->namespace];
        } else {
            $this->data = &$_SESSION;
        }
    }
718494
public function indexAction()
    {
        $request = $this->getRequest();
        $type    = $request->getParam( 'type' );

        if ( ! $request instanceof ConsoleRequest )
        {
            throw new \RuntimeException( sprintf(
                '%s can only be used from a console.',
                __METHOD__
            ) );
        }

        $phpSelf = realpath( static::PHP_SELF );

        if ( empty( $phpSelf ) || ! is_file( $phpSelf ) )
        {
            throw new \RuntimeException( sprintf(
                '%s: php not found at "%s" (in "%s").',
                __METHOD__,
                static::PHP_SELF,
                getcwd()
            ) );
        }

        $result = 'Running ' . $type . ' cron(s) ...' . PHP_EOL . PHP_EOL;

        foreach ( $this->mimicSiteInfos() as $siteInfo )
        {
            $domain  = $siteInfo->getDomain();
            $process = new Process( array(
                'command'   => 'php',
                'arguments' => array(
                    $phpSelf,
                    'cron',
                    $domain,
                    $type,
                ),
                'environmentVariables'  => array(
                    'GRIDGUYZ_HOST'     => $domain,
                    'HTTP_HOST'         => $domain,
                ),
            ) );

            $result .= 'Calling process ...' . PHP_EOL .
                       $process->getRunCommand() . PHP_EOL;

            $output = tempnam( './data/', $domain );
            $descr  = array( Process::TYPE_FILE, $output, Process::MODE_APPEND );
            file_put_contents( $output, '' );

            $process->open( array(
                Process::STREAM_STDOUT => $descr,
                Process::STREAM_STDERR => $descr,
            ) );

            $return     = $process->close();
            $messages   = rtrim( file_get_contents( $output ), PHP_EOL );
            unlink( $output );

            if ( $messages )
            {
                $result .= static::PADDING . preg_replace(
                    '/[' . PHP_EOL . ']+/',
                    '$0' . static::PADDING,
                    $messages
                ) . PHP_EOL;
            }

            $result .= sprintf(
                'Process returned with #%d: %s' . PHP_EOL . PHP_EOL,
                $return,
                $return ? 'error!' : 'success.'
            );
        }

        $result .= 'Done.' . PHP_EOL;
        return $result;
    }
832892
public function register()
    {
        if ($this->getIsNewRecord() == false) {
            throw new \RuntimeException('Calling "' . __CLASS__ . '::' . __METHOD__ . '" on existing user');
        }

        $transaction = $this->getDb()->beginTransaction();

        try {
            $this->confirmed_at = $this->module->enableConfirmation ? null : time();
            $this->password     = $this->module->enableGeneratingPassword ? Password::generate(8) : $this->password;

            $this->trigger(self::BEFORE_REGISTER);

            if (!$this->save()) {
                $transaction->rollBack();
                return false;
            }

            if ($this->module->enableConfirmation) {
                /** @var Token $token */
                $token = \Yii::createObject(['class' => Token::className(), 'type' => Token::TYPE_CONFIRMATION]);
                $token->link('user', $this);
            }

            $this->mailer->sendWelcomeMessage($this, isset($token) ? $token : null);
            $this->trigger(self::AFTER_REGISTER);

            $transaction->commit();

            return true;
        } catch (\Exception $e) {
            $transaction->rollBack();
            \Yii::warning($e->getMessage());
            throw $e;
        }
    }
511147
public function run() {
        try {
            $this
                ->loadComposerFile()
                ->loadArgs()
                ->parseOptions()
                ->parseArguments()
                ->loadOptionalConfigFiles()
                ->loadAdditionalConfigFiles()
                ->addRuntimeSettings()
                ->configureLogger()
                ->satisfyUserChoice();
        } catch (Exception $exception) {
            $this->abort($exception);
        }
    }
540503
public function connect()
    {
        if ($this->ssl) {
            $this->connection = ftp_ssl_connect($this->getHost(), $this->getPort(), $this->getTimeout());
        } else {
            $this->connection = ftp_connect($this->getHost(), $this->getPort(), $this->getTimeout());
        }

        if ( ! $this->connection) {
            throw new RuntimeException('Could not connect to host: ' . $this->getHost() . ', port:' . $this->getPort());
        }

        $this->login();
        $this->setUtf8Mode();
        $this->setConnectionPassiveMode();
        $this->setConnectionRoot();
        $this->isPureFtpd = $this->isPureFtpdServer();
    }
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; # Флаг загрузки ядра
	}
1160139
public function load()
    {
        $raw = parent::load();

        try {
            return $raw !== false ? $this->formatter->decode($raw) : false;
        } catch (RuntimeException $e) {
            throw new RuntimeException(sprintf("Failed to load file '%s': %s", $this->getFilePath(), $e->getMessage()), $e->getCode(), $e);
        }
    }
600982
public function execute()
    {
        foreach (array_unique($this->bootstrappers->all()) as $class) {
            $bootstrapper = $this->create($class);

            if (!method_exists($bootstrapper, 'run')) {
                throw new \RuntimeException("$class must have run() method");
            }

            $bootstrapper->run();
        }
    }
800720
public function beforeCompile(): void
	{
		// Breaks at other mode then CLI
		if (PHP_SAPI !== 'cli') return;

		$builder = $this->getContainerBuilder();

		// Verify that we have http.request
		if (!$builder->hasDefinition('http.request')) {
			throw new RuntimeException('Service http.request is needed');
		}

		$config = $this->validateConfig($this->defaults);
		$builder->getDefinition('http.request')
			->setFactory(Request::class, [
				new Statement(UrlScript::class, [$config['url']]),
				$config['query'],
				$config['post'],
				$config['files'],
				$config['cookies'],
				$config['headers'],
				$config['method'],
				$config['remoteAddress'],
				$config['remoteHost'],
				$config['rawBodyCallback'],
			]);
	}
831903
public function initialize()
    {
        $modules = $this->loader->getModules();

        if (empty($modules)) {
            throw new RuntimeException('No modules found. Initialization halted');
        } else {
            $this->loadAll($modules);
            $this->modules = $modules;

            // Validate on demand
            $this->validateCoreModuleNames();
        }
    }
627561
public function commit()
    {
        try {
            $this->dbHandler->commit();
        } catch (Exception $e) {
            throw new RuntimeException($e->getMessage(), 0, $e);
        }
    }
427198
protected function initAllowedCalls()
    {
        if ($this->allowedCalls) {
            $errMsg = 'Список разрешенных команд уже инициализирован';
            throw new RuntimeException($errMsg);
        }

        $this->allowedCalls = array_combine(static::$defaultAllowedCalls, static::$defaultAllowedCalls);
    }
1286645
public function create()
    {
        if ($this->getIsNewRecord() == false) {
            throw new \RuntimeException('Calling "' . __CLASS__ . '::' . __METHOD__ . '" on existing user');
        }

        $transaction = $this->getDb()->beginTransaction();

        try {
            $this->password = ($this->password == null && $this->module->enableGeneratingPassword) ? Password::generate(8) : $this->password;

            $this->trigger(self::BEFORE_CREATE);

            if (!$this->save()) {
                $transaction->rollBack();
                return false;
            }

            $this->confirm();

            $this->mailer->sendWelcomeMessage($this, null, true);
            $this->trigger(self::AFTER_CREATE);

            $transaction->commit();

            return true;
        } catch (\Exception $e) {
            $transaction->rollBack();
            \Yii::warning($e->getMessage());
            throw $e;
        }
    }
291915
public function run()
	{
		// Lets make sure we have a database
		if (!$this->taskCreateDb()
				->host($this->host)
				->user($this->user)
				->pass($this->pass)
				->name($this->name)
				->dropTables(true)
			->run()->wasSuccessful()
		){
			throw new RuntimeException('We failed to create the db.');
		}

		// Do we need to uncompress it first?
		if (strpos($this->dump, '.gz') !== false)
		{
			// Create a temp dump file
			$temp_dump = tempnam(sys_get_temp_dir(), 'dump');

			// Decompress the dump file
			if ($fp_out = fopen($temp_dump, 'wb'))
			{
				if ($fp_in = gzopen($this->dump, 'rb'))
				{
					while (!gzeof($fp_in))
					{
						fwrite($fp_out, gzread($fp_in, 1024 * 512));
					}

					fclose($fp_in);
				}
				else
				{
					throw new RuntimeException
					(
						'Failed to open source dump file for reading.'
					);
				}

				gzclose($fp_out);
			}
			else
			{
				throw new RuntimeException
				(
					'Failed to open temp dump file for writing.'
				);
			}

			// Set the dump the deflated version
			$this->dump = $temp_dump;

			// Delete the temp later
			$delete_me = $this->dump;
		}

		// Construct the command to import the dump
		$cmd = 'mysql -h'.$this->host.' -u'.$this->user;
		if (!empty($this->pass)) $cmd .= ' -p'.$this->pass;
		$cmd .= ' '.$this->name.' < '.$this->dump;

		// Run the command
		if (!$this->taskExec($cmd)->run()->wasSuccessful())
		{
			throw new RuntimeException
			(
				'We failed to import your dump. '.
				'HINT: Is the `mysql` binary in your "PATH"?'
			);
		}

		// Delete the deflated temp dump file
		if (isset($delete_me))
		{
			$this->printTaskInfo('Deleting temp dump file.');
			if (!unlink($delete_me))
			{
				return Result::error($this, 'Couldn`t delete temp file.');
			}
		}

		// If we get to here assume everything worked
		return Result::success($this);
	}