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

@throws Eresus_CMS_Exception_NotFound

@return string|Eresus_HTTP_Response
19665
public function clientRenderContent()
    {
        $result = '';
        if (!isset($this->settings['itemsPerPage']))
        {
            $this->settings['itemsPerPage'] = 0;
        }
        /** @var TClientUI $page */
        $page = Eresus_Kernel::app()->getPage();
        if ($page->topic)
        {
            $result = $this->clientRenderItem();
        }
        else
        {
            $db = Eresus_CMS::getLegacyKernel()->db;
            $this->table['fields'] = $db->fields($this->table['name']);
            $itemsCount = $db->count($this->table['name'], "(`section`='" . $page->id . "')".
                    (in_array('active', $this->table['fields'])?"AND(`active`='1')":''));
            if ($itemsCount)
            {
                $this->pagesCount = $this->settings['itemsPerPage'] ?
                    ((integer) ($itemsCount / $this->settings['itemsPerPage']) +
                        (($itemsCount % $this->settings['itemsPerPage']) > 0)):1;
            }
            if (!$page->subpage)
            {
                $page->subpage = $this->table['sortDesc'] ? $this->pagesCount : 1;
            }
            if ($itemsCount && ($page->subpage > $this->pagesCount))
            {
                throw new Eresus_CMS_Exception_NotFound;
            }
            else
            {
                $result .= $this->clientRenderList();
            }
        }
        return $result;
    }
1218946
public function notFound()
    {
        if (isset($this->request->path_array[1])) {
            switch ($this->request->path_array[1]) {
                case 'methods':
                    return $this->getMethods(true);
                    break;
            }
        }

        return null;
    }
1253926
public function handleRequest()
    {
        try {
            $this->response = parent::handleRequest();
        } catch (HttpException $ex) {
            $this->config->set('page_title', 'Error');

            $view = new View('exception');
            $view->exception = $ex;

            $this->response->setResponseCode($ex->getErrorCode());
            $this->response->setContent($view->render());
        } catch (\Exception $ex) {
            $this->config->set('page_title', 'Error');

            $view = new View('exception');
            $view->exception = $ex;

            $this->response->setResponseCode(500);
            $this->response->setContent($view->render());
        }

        if ($this->response->hasLayout() && $this->controller->layout) {
            $this->setLayoutVariables($this->controller->layout);

            $this->controller->layout->content  = $this->response->getContent();
            $this->response->setContent($this->controller->layout->render());
        }

        return $this->response;
    }
384517
private function coverAction()
    {
        $id = arg('cover', 'int');

        $table = ORM::getTable($this, 'Image');
        /* @var Gallery_Entity_Image $image */
        $image = $table->find($id);
        if (null === $image)
        {
            throw new Eresus_CMS_Exception_NotFound('Запрошенное изображение не найдено');
        }
        $image->album->setCover($image);

        HTTP::goback();
    }
771105
public static function create() 
    {
		$alias = func_get_arg(0);
		$name = func_get_arg(1);
		
        try {
            $m = self::getByAlias($alias);
        } catch (\Exception $e) {}
        
        if ($m) throw new Exception\CMS('Меню c таким алиасом уже существует.');
        
        self::getDbConnection()->insert('menus', array(
			'alias' => $alias,
			'name'  => $name
		));
  		return self::getById( self::getDbConnection()->lastInsertId() );
  	}
568408
public function render()
    {
        /** @var Gallery $plugin */
        // TODO Добавить в этот класс ссылку на плагин
        $plugin = Eresus_Plugin_Registry::getInstance()->load('gallery');

        /** @var TClientUI $page */
        $page = Eresus_Kernel::app()->getPage();
        $page->linkJsLib('jquery');
        $page->linkScripts($plugin->getCodeUrl() . '/client/gallery.js');
        $page->linkStyles($plugin->getCodeUrl() . '/client/gallery.css');

        $tmpl = $plugin->templates()->client('popup.html');
        $popup = $tmpl->compile();
        $html = '<div id="gallery-popup">' . $popup . '</div>';

        $html .= $this->renderImageList();

        return $html;
    }
490212
public function indexAction()
    {
        $service = $this->getLayoutService();
        try {
            $theme = $service->getTheme(
                $this->params()->fromRoute('theme')
            );
        } catch (RuntimeException $e) {
            $this->flashMessenger()->addMessage($e->getMessage());
            return $this->redirect()
                ->toRoute('sc-admin/layout')
                ->setStatusCode(303);
        }

        $event = $this->getRequest()->getPost('suboperation');
        if (! empty($event)) {
            $events = $this->getEventManager();
            $params = $this->request->getPost();
            $params['theme'] = $theme->getName();
            $results = $events->trigger($event, $this, $params);
            foreach ($results as $result) {
                if ($result instanceof Response) {
                    return $result;
                }
            }
        }

        $view = new ViewModel([
            'controlSet' => $service->getControlSet(),
            'regions' => $service->getRegions($theme->getName()),
            'theme' => $theme,
        ]);

        $flashMessenger = $this->flashMessenger();
        if ($flashMessenger->hasMessages()) {
            $view->messages = $flashMessenger->getMessages();
        }

        return $view;
    }
390849
public function postIndex()
	{
		if ( ! Input::hasFile('file'))
		{
			return Response::json(array('error' => 'File is required'), 400);
		}

		$contents = trim(File::get(Input::file('file')->getRealPath()));

		if (substr($contents, 0, 3) !== '---')
		{
			throw new Exception('Bad Markdown Formatting');
		}

		if ( ! ($pos = strpos($contents, '---', 3)))
		{
			throw new Exception('Bad Markdown Formatting');
		}

		$frontMatter = trim(substr($contents, 3, $pos - 3));
		$contents = trim(substr($contents, $pos + 3));

		$yaml = new Parser();

		$fields = $yaml->parse($frontMatter);

		return Response::json(array(
			'fields' => $fields,
			'content' => $contents
		));
	}
246615
private function notFoundResponse() {
        $responseMessage = new Swagger\ResponseMessage();
        $responseMessage->setCode(404);
        $responseMessage->setMessage(ucfirst($this->getModel()->getSource()) . ' not found.');

        return $responseMessage;
    }
206396
public function actionRequest() {
    if (!$this->module->enablePasswordRecovery) {
      throw new NotFoundHttpException();
    }

    /** @var RecoveryForm $model */
    $model = Yii::createObject([
      'class' => RecoveryForm::className(),
      'scenario' => 'request',
    ]);
    $event = $this->getFormEvent($model);

    $this->performAjaxValidation($model);
    $this->trigger(self::EVENT_BEFORE_REQUEST, $event);

    if ($model->load(Yii::$app->request->post()) && $model->sendRecoveryMessage()) {
      $this->trigger(self::EVENT_AFTER_REQUEST, $event);
      return $this->render('/message', [
        'title' => Yii::t('users', 'Recovery message sent'),
        'module' => $this->module,
      ]);
    }

    return $this->render('request', [
      'model' => $model,
    ]);
  }
680260
public function getPage()
    {
        if (null === $this->site || null === $this->layout || null === $this->title) {
            $this->reset();
            throw new \Exception("Required data missing");
        }

        $page = new Page($this->uid);
        $page->setTitle($this->title);
        $page->setSite($this->site);

        if (null !== $this->parent) {
            $page->setParent($this->insureParentIsSection($this->parent));
        }

        $page->setLayout($this->layout, $this->itemToPushInMainZone);

        if (null !== $this->url) {
            $page->setUrl($this->url);
        }

        if (null !== $this->redirect) {
            $page->setRedirect($this->redirect);
        }

        if (null !== $this->target) {
            $page->setTarget($this->target);
        }

        if (null !== $this->altTitle) {
            $page->setAltTitle($this->altTitle);
        }

        if (null !== $this->state) {
            $page->setState($this->state);
        }

        if (null !== $this->publishedAt) {
            $page->setPublishing($this->publishedAt);
        }

        if (null !== $this->createdAt) {
            $page->setCreated($this->createdAt);
        }

        if (null !== $this->archiving) {
            $page->setArchiving($this->archiving);
        }

        $pageContentSet = $page->getContentSet();
        $this->updateContentRevision($pageContentSet);
        while ($column = $pageContentSet->next()) {
            $this->updateContentRevision($column);
        }

        if (0 < count($this->elements)) {
            foreach ($this->elements as $e) {
                $column = $pageContentSet->item($e['content_set_position']);
                if ($e['set_main_node']) {
                    $e['content']->setMainNode($page);
                }

                $column->push($e['content']);
            }

            $pageContentSet->rewind();
        }

        $this->doPersistIfValid($page);

        $this->reset();

        return $page;
    }
599730
protected function call3rdPartyExtension(Eresus_CMS_Request $request)
    {
        $extension = substr($request->getDirectory(), 9);
        if (($p = strpos($extension, '/')) !== false)
        {
            $extension = substr($extension, 0, $p);
        }

        $filename = $this->getFsRoot() . '/ext-3rd/' . $extension . '/eresus-connector.php';
        if ($extension && is_file($filename))
        {
            /** @noinspection PhpIncludeInspection */
            include_once $filename;
            $className = $extension . 'Connector';
            /** @var EresusExtensionConnector $connector */
            $connector = new $className;
            $connector->proxy();
        }
        else
        {
            header('404 Not Found', true, 404);
            echo '404 Not Found';
        }
    }
53443
public function render(Eresus_CMS_Request $request)
    {
        Eresus_Kernel::log(__METHOD__, LOG_DEBUG, 'starting...');

        try
        {
            $this->init();

            $plugins = Eresus_Plugin_Registry::getInstance();

            $response = $plugins->clientRenderContent($request);
            if (!($response instanceof Eresus_HTTP_Response))
            {
                Eresus_Kernel::log(__METHOD__, LOG_DEBUG, 'got string content');
                $content = new Eresus_CMS_Page_Content($this, $response);
                $response = $this->createPageForContent($content);
            }
        }
        catch (Eresus_CMS_Exception $e)
        {
            Eresus_Kernel::log(__METHOD__, LOG_NOTICE, '%s: "%s"', get_class($e), $e->getMessage());
            $httpStatusCode = $e->getHttpException()->getCode();
            $content = new Eresus_CMS_Page_Content($this,
                $e->getMessage() ?: Eresus_HTTP_Response::getStatusText($httpStatusCode));
            $response = $this->createPageForContent($content, $httpStatusCode);
        }

        // TODO: Обратная совместимость (убрать)
        $response->setContent($this->replaceMacros($response->getContent()));

        $event = new Eresus_Event_Response($response);
        Eresus_Kernel::app()->getEventDispatcher()->dispatch('cms.client.response', $event);

        return $response;
    }
698039
public function index()
    {
        try {
            $uri = null;
            if ($this->hasRequestParameter("uri")) {
                $uri = $this->getRequestParameter("uri");
                if (!common_Utils::isUri($uri)) {
                    throw new common_exception_InvalidArgumentType();
                }
            }

            switch ($this->getRequestMethod()) {
                case "GET":
                    $response = $this->get($uri);
                    break;
                case "PUT":
                    $response = $this->put($uri);
                    break;
                case "POST":
                    $response = $this->post();
                    break;
                case "DELETE":
                    $response = $this->delete($uri);
                    break;
                default:
                    throw new common_exception_BadRequest($this->getRequestURI());
            }

            $this->returnSuccess($response);

        } catch (Exception $e) {
            if ($e instanceof \common_exception_ValidationFailed &&
                $alias = $this->reverseSearchAlias($e->getField())
            ) {
                $e = new \common_exception_ValidationFailed($alias, null, $e->getCode());
            }

            $this->returnFailure($e);
        }
    }
64213
private function renderUI(Eresus_CMS_Request $request)
    {
        Eresus_Kernel::log(__METHOD__, LOG_DEBUG, '()');
        $response = $this->renderContent($request);

        if (!($response instanceof Eresus_HTTP_Response))
        {
            $data = array();
            $data['page'] = $this;
            $data['content'] = $response;
            $data['siteName'] = option('siteName');
            $data['body'] = $this->renderBodySection();
            $opened = -1;
            $data['sectionMenu'] = $this->renderPagesMenu($opened);
            $data['controlMenu'] = $this->renderControlMenu();
            $data['user'] = Eresus_CMS::getLegacyKernel()->user;

            $tmpl = new Eresus_Template('admin/themes/default/page.default.html');
            $response = new Eresus_HTTP_Response($tmpl->compile($data), 200, $this->headers);
        }

        return $response;
    }
834083
public function httpAction()
	{
	    $status		= self::STATUS_SUCCESS;
	    $responses	= array();
	    $exception	= null;
	    $data       = null;
        $debug      = $this->getRouteParam('debug', false); 
        
        try {
            $service	= $this->fetchService();
            $operation	= $service ? $this->fetchOperation() : false;
            
            if(!$service){
                throw new ServiceNotFoundException("Route doesn't contain service information");
            } elseif (!$operation) {
                throw new OperationNotFoundException("Route doesn't contain operation information");
            }
            
            try {
                $params = $this->fetchParams();
            } catch(\Exception $e) {
                $status = self::STATUS_MALFORMED_REQUEST;
                $exception = $e;
            }
            
            if ($status === self::STATUS_SUCCESS) {
                if (isset($params[self::HEADER_FORCE_CONTENT_HTML])) {
                    
                    if ($params[self::HEADER_FORCE_CONTENT_HTML]) {
                        $this->getRequest()->getHeaders()->addHeaders([
                                self::HEADER_FORCE_CONTENT_HTML => true
                                ]);
                    }
                    unset($params[self::HEADER_FORCE_CONTENT_HTML]);
                }
                
                $data = $this->exec(
                        $service,
                        $operation,
                        $params,
                        Command::CONTEXT_HTTP);
            }
            
        } catch (PermissionDeniedException $exception) {
            $status = self::STATUS_PERMISSION_DENIED;
        } catch (NotFoundException $exception) {
            $status = self::STATUS_NOT_FOUND;
        } catch (ServiceException $exception) {
            $status = self::STATUS_UNKNOWN_EXCEPTION;
        } catch (\Exception $exception) {
            $status = self::STATUS_UNKNOWN_EXCEPTION;
        }
	    
        // Log error
	    if ($exception) {
	        error_log($exception->getMessage() . ' (' . $exception->getFile().':'.$exception->getLine().')');
	        
	        if ($debug) {
	            throw $exception;
	        }
	    }
    
		return $this->prepareHttpResponse(
			$data, 
	        $status,
			$exception);
	}
663450
public function getStatusText()
    {
        switch ($this->getStatus()) {
            case self::Status_Success:
                return $this->t('message_response_success');
            case self::Status_Notices:
                return $this->t('message_response_notices');
            case self::Status_Warnings:
                return $this->t('message_response_warnings');
            case self::Status_Errors:
                return $this->t('message_response_errors');
            case self::Status_Exception:
                return $this->t('message_response_exception');
            case null:
                return $this->t('message_response_not_set');
            default:
                return sprintf($this->t('message_response_unknown'), $this->getStatus());
        }
    }