/** * Retrieves the view renderer object * * @return Zend_Controller_Action_Helper_ViewRenderer|null * @throws Glitch_Application_Resource_Exception */ public function getViewRenderer() { if (null === $this->_viewRenderer) { // Pull in the front controller; bootstrap first if necessary $this->_bootstrap->bootstrap('FrontController'); $front = $this->_bootstrap->getResource('FrontController'); // Ignore if no view renderer is to be used if ($front->getParam('noViewRenderer')) { return null; } // Get existing renderer, if any, or create a new one $this->_viewRenderer = Zend_Controller_Action_HelperBroker::hasHelper('viewRenderer') ? Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer') : new $this->_className(null, $this->getOptions()); // Dynamic class loading; perform sanity check if (!$this->_viewRenderer instanceof Zend_Controller_Action_Helper_ViewRenderer) { throw new Glitch_Application_Resource_Exception('Class is not a valid view renderer instance'); } // Register the view as the default view for handling view scripts $this->_bootstrap->bootstrap('View'); $view = $this->_bootstrap->getResource('View'); $this->_viewRenderer->setView($view); // It is paramount to set this base path spec: ZF otherwise uses its own // spec, causing it to create a path to a conventional ZF-style directory $this->_viewRenderer->setViewBasePathSpec(':module/' . Glitch_View::PATH_VIEW); // Set empty inflector settings: all path translations are handled by the custom dispatcher $inflector = new Zend_Filter_Inflector(); $inflector->addRules(array(':module' => array(), ':controller' => array(), ':action' => array())); $this->_viewRenderer->setInflector($inflector, true); if (!Zend_Controller_Action_HelperBroker::hasHelper('viewRenderer')) { Zend_Controller_Action_HelperBroker::addHelper($this->_viewRenderer); } } return $this->_viewRenderer; }
/** * Construct view script path * * Used by render() to determine the path to the view script. * * @param string $action Defaults to action registered in request object * @param bool $noController Defaults to false; i.e. use controller name as subdir in which to search for view script * @return string * @throws Zend_Controller_Exception with bad $action */ public function getViewScript($action = null, $noController = null) { if (!$this->getInvokeArg('noViewRenderer') && $this->_helper->hasHelper('viewRenderer')) { $viewRenderer = $this->_helper->getHelper('viewRenderer'); if (null !== $noController) { $viewRenderer->setNoController($noController); } return $viewRenderer->getViewScript($action); } $request = $this->getRequest(); if (null === $action) { $action = $request->getActionName(); } elseif (!is_string($action)) { throw new Zend_Controller_Exception('Invalid action specifier for view render'); } if (null === $this->_delimiters) { $dispatcher = Zend_Controller_Front::getInstance()->getDispatcher(); $wordDelimiters = $dispatcher->getWordDelimiter(); $pathDelimiters = $dispatcher->getPathDelimiter(); $this->_delimiters = array_unique(array_merge($wordDelimiters, (array) $pathDelimiters)); } $action = str_replace($this->_delimiters, '-', $action); $script = $action . '.' . $this->viewSuffix; if (!$noController) { $controller = $request->getControllerName(); $controller = str_replace($this->_delimiters, '-', $controller); $script = $controller . DIRECTORY_SEPARATOR . $script; } return $script; }
/** * @param \Zend_Controller_Request_Abstract $request * @throws mixed */ protected function _handleError(\Zend_Controller_Request_Abstract $request) { // remove zend error handler $front = \Zend_Controller_Front::getInstance(); $front->unregisterPlugin("Zend_Controller_Plugin_ErrorHandler"); $response = $this->getResponse(); if ($response->isException() && !$this->_isInsideErrorHandlerLoop) { // get errorpage try { // enable error handler $front->setParam('noErrorHandler', false); $errorPath = Config::getSystemConfig()->documents->error_pages->default; if (Site::isSiteRequest()) { $site = Site::getCurrentSite(); $errorPath = $site->getErrorDocument(); } if (empty($errorPath)) { $errorPath = "/"; } $document = Document::getByPath($errorPath); if (!$document instanceof Document\Page) { // default is home $document = Document::getById(1); } if ($document instanceof Document\Page) { $params = Tool::getRoutingDefaults(); if ($module = $document->getModule()) { $params["module"] = $module; } if ($controller = $document->getController()) { $params["controller"] = $controller; $params["action"] = "index"; } if ($action = $document->getAction()) { $params["action"] = $action; } $this->setErrorHandler($params); $request->setParam("document", $document); \Zend_Registry::set("pimcore_error_document", $document); // ensure that a viewRenderer exists, and is enabled if (!\Zend_Controller_Action_HelperBroker::hasHelper("viewRenderer")) { $viewRenderer = new \Pimcore\Controller\Action\Helper\ViewRenderer(); \Zend_Controller_Action_HelperBroker::addHelper($viewRenderer); } $viewRenderer = \Zend_Controller_Action_HelperBroker::getExistingHelper("viewRenderer"); $viewRenderer->setNoRender(false); if ($viewRenderer->view === null) { $viewRenderer->initView(PIMCORE_WEBSITE_PATH . "/views"); } } } catch (\Exception $e) { \Logger::emergency("error page not found"); } } // call default ZF error handler parent::_handleError($request); }
/** * Sets up the fixture, for example, open a network connection. * This method is called before a test is executed. * * @return void */ public function setUp() { Zend_Controller_Front::getInstance()->resetInstance(); Zend_Layout_PluginTest_Layout::$_mvcInstance = null; if (Zend_Controller_Action_HelperBroker::hasHelper('Layout')) { Zend_Controller_Action_HelperBroker::removeHelper('Layout'); } if (Zend_Controller_Action_HelperBroker::hasHelper('viewRenderer')) { Zend_Controller_Action_HelperBroker::removeHelper('viewRenderer'); } }
/** * Sets up the fixture, for example, open a network connection. * This method is called before a test is executed. * * @return void */ public function setUp() { Zend_Controller_Front::getInstance()->resetInstance(); if (Zend_Controller_Action_HelperBroker::hasHelper('Layout')) { Zend_Controller_Action_HelperBroker::removeHelper('Layout'); } if (Zend_Controller_Action_HelperBroker::hasHelper('viewRenderer')) { Zend_Controller_Action_HelperBroker::removeHelper('viewRenderer'); } Zend_View_Helper_LayoutTest_Layout::resetMvcInstance(); }
public function viewAction() { if (Zend_Controller_Action_HelperBroker::hasHelper('redirector')) { $redirector = Zend_Controller_Action_HelperBroker::getExistingHelper('redirector'); } $hometargeturl = $this->_urlHelper->url(array('controller' => 'index', 'action' => 'index', 'language' => $this->view->language), 'lang_default', true); // Get user identity $auth = Zend_Auth::getInstance(); // Disable edit profile by default $userEdit = false; // Get params $params = $this->getRequest()->getParams(); if (isset($params['user'])) { // Get username from params $username = $params['user']; } else { $redirector->gotoUrl($hometargeturl); } // Get content types $contentTypes = new Default_Model_ContentTypes(); $this->view->content_types = $contentTypes->getAllNamesAndIds(); // Get user data from User Model $user = new Default_Model_User(); $data = $user->getUserByName($username); if ($data == null) { $redirector->gotoUrl($hometargeturl); } $this->view->user = $data; $id = $data['id_usr']; // Get public user data from UserProfiles Model $userProfile = new Default_Model_UserProfiles(); $dataa = $userProfile->getPublicData($id); // $dataa is an array with key=>val like firstname => "Joel Peeloten" // This was replaced with get public data and the foreach above // Kept here just in case for the future /* $dataa['gender'] = $userprofile->getUserProfileValue($id, 'gender'); $dataa['surname'] = $userprofile->getUserProfileValue($id, 'surname'); $dataa['firstname'] = $userprofile->getUserProfileValue($id, 'firstname'); $dataa['category'] = $userprofile->getUserProfileValue($id, 'user category'); $dataa['profession'] = $userprofile->getUserProfileValue($id, 'profession'); $dataa['company'] = $userprofile->getUserProfileValue($id, 'company'); $dataa['biography'] = $userprofile->getUserProfileValue($id, 'biography'); $dataa['city'] = $userprofile->getUserProfileValue($id, 'city'); $dataa['phone'] = $userprofile->getUserProfileValue($id, 'phone'); $dataa['birthday'] = $userprofile->getUserProfileValue($id, 'birthday'); */ // No countries in countries_ctr and not very good table at all? // This would be better: http://snipplr.com/view/6636/mysql-table--iso-country-list-with-abbreviations/ /* $dataa['country'] = $userProfile->getUserProfileValue($id, 'country'); $userCountry = new Default_Model_UserCountry(); $dataa['country'] = $userCountry->getCountryNameById( $dataa['country']['profile_value_usp'] ); */ // Get content user has released $type = isset($params['type']) ? $params['type'] : 0; $contentList = $user->getUserContent($data['id_usr']); $temp = array(); // Initialize content counts $dataa['contentCounts']['all'] = 0; $dataa['contentCounts']['user_edit'] = 0; $dataa['contentCounts']['problem'] = 0; $dataa['contentCounts']['finfo'] = 0; $dataa['contentCounts']['idea'] = 0; // Count amount of content user has published // and check unpublished so only owner can see it. foreach ($contentList as $k => $c) { // If user not logged in and content not published, // remove content from list if (!$auth->hasIdentity() && $c['published_cnt'] == 0) { unset($contentList[$k]); // Else if user logged in and not owner of unpublished content, // remove content from list } else { if ($auth->hasIdentity() && $c['id_usr'] != $auth->getIdentity()->user_id && $c['published_cnt'] == 0) { unset($contentList[$k]); // Else increase content counts and sort content by content type } else { if (isset($c['key_cty'])) { // Set content to array by its content type //$temp[$c['key_cty']][] = $c; //$temp[] = $c; // Increase total count $dataa['contentCounts']['all']++; // Set content type count to 0 if count is not set if (!isset($dataa['contentCounts'][$c['key_cty']])) { $dataa['contentCounts'][$c['key_cty']] = 0; } // Increase content type count $dataa['contentCounts'][$c['key_cty']]++; } } } if ($c['published_cnt'] == 0) { $dataa['contentCounts']['user_edit']++; } } // end foreach // If user is logged in, and viewing self; allow edit if ($auth->hasIdentity()) { $identity = $auth->getIdentity(); if ($data['id_usr'] == $identity->user_id) { $userEdit = true; } } if ($auth->hasIdentity() && $data['id_usr'] == $auth->getIdentity()->user_id) { $favouriteModel = new Default_Model_UserHasFavourites(); $favouriteType = isset($params['favourite']) ? $params['favourite'] : 0; $favouriteList = $user->getUserFavouriteContent($data['id_usr']); // Initialize Favourite counts $dataa['favouriteCounts']['totalCount'] = 0; $dataa['favouriteCounts']['problem'] = 0; $dataa['favouriteCounts']['finfo'] = 0; $dataa['favouriteCounts']['idea'] = 0; foreach ($favouriteList as $k => $favourite) { /* * If content Id doesn't exist anymore: * unset from Favouritelist and remove all lines from user_has_favourites table that * refers to this content id */ if ($favourite['id_cnt'] == '') { unset($favouriteList[$k]); $favouriteModel->removeAllContentFromFavouritesByContentId($favourite['id_cnt_fvr']); } if (isset($favourite['key_cty'])) { // Increase total count $dataa['favouriteCounts']['totalCount']++; // Set content type count to 0 if count is not set if (!isset($dataa['favouriteCounts'][$favourite['key_cty']])) { $dataa['favouriteCounts'][$favourite['key_cty']] = 0; } // Increase content type count $dataa['favouriteCounts'][$favourite['key_cty']]++; } } //print_r($dataa);print_r($favouriteList);die; } //Zend_Debug::dump("" === null); //Zend_Debug::dump($dataa['contentCounts']['idea']); //Zend_Debug::dump($dataa['contentCounts']['idea'] == ""); //die; // My Posts box data $box = new Oibs_Controller_Plugin_AccountViewBox(); $box->setHeader("My Posts")->setClass("right")->setName("my-posts")->addTab("All", "all", "all selected", $dataa['contentCounts']['all'])->addTab("Challenges", "problem", "challenges", $dataa['contentCounts']['problem'])->addTab("Ideas", "idea", "ideas", $dataa['contentCounts']['idea'])->addTab("Visions", "finfo", "visions", $dataa['contentCounts']['finfo']); if ($dataa['contentCounts']['user_edit'] && $userEdit) { $box->addTab("Saved", "user_edit", "saved", $dataa['contentCounts']['user_edit']); } $boxes[] = $box; $views = new Default_Model_ContentViews(); $myViews = $views->getUserViewedContents($data['id_usr']); $box = new Oibs_Controller_Plugin_AccountViewBox(); $box->setHeader("My Views")->setName("my-views")->setClass("right")->addTab("Views", "views", "all selected"); //$boxes[] = $box; $myReaders = $user->getUsersViewers($data['id_usr']); $box = new Oibs_Controller_Plugin_AccountViewBox(); $box->setHeader("My Reads")->setClass("right")->setName("my-reads")->addTab("Readers", "readers", "all selected"); //$boxes[] = $box; // Set to view $this->view->user_has_image = $user->userHasProfileImage($data['id_usr']); $this->view->userprofile = $dataa; $this->view->authorContents = $contentList; /*$temp*/ $this->view->boxes = $boxes; $this->view->myViews = $myViews; $this->view->myReaders = $myReaders; //$this->view->authorFavourites = $favouriteList; $this->view->user_edit = $userEdit; $this->view->type = $type; /* Waiting for layout that is maybe coming // MyViews $viewsModel = new Default_Model_ContentViews(); Zend_Debug::dump($viewsModel->getUserViewedContents($data['id_usr'])); // MyReaders Zend_Debug::dump($user->getUsersViewers($data['id_usr'])); die;*/ $group_model = new Default_Model_UserHasGroup(); $usergroups = $group_model->getGroupsByUserId($id); $this->view->usergroups = $usergroups; }
public function testResettingMvcInstanceUnregistersHelperAndPlugin() { $this->testGetMvcInstanceReturnsLayoutInstanceWhenStartMvcHasBeenCalled(); Zend_Layout::resetMvcInstance(); $front = Zend_Controller_Front::getInstance(); $this->assertFalse($front->hasPlugin('Zend_Layout_Controller_Plugin_Layout'), 'Plugin not unregistered'); $this->assertFalse(Zend_Controller_Action_HelperBroker::hasHelper('Layout'), 'Helper not unregistered'); }
/** * Initialize action helper * * @return void */ protected function _initHelper() { $helperClass = $this->getHelperClass(); if (!Zend_Controller_Action_HelperBroker::hasHelper('layout')) { if (!class_exists($helperClass)) { Zend_Loader::loadClass($helperClass); } Zend_Controller_Action_HelperBroker::getStack()->offsetSet(-90, new $helperClass($this)); } }
public function testViewRendererHelperRegisteredByDefault() { $this->_controller->resetInstance(); $this->assertTrue(Zend_Controller_Action_HelperBroker::hasHelper('viewRenderer')); }
/** * Dispatch an HTTP request to a controller/action. * * @param Zend_Controller_Request_Abstract|null $request * @param Zend_Controller_Response_Abstract|null $response * @return void|Zend_Controller_Response_Abstract Returns response object if returnResponse() is true */ public function dispatch(Zend_Controller_Request_Abstract $request = null, Zend_Controller_Response_Abstract $response = null) { if (!$this->getParam('noErrorHandler') && !$this->_plugins->hasPlugin('Zend_Controller_Plugin_ErrorHandler')) { // Register with stack index of 100 #require_once 'Zend/Controller/Plugin/ErrorHandler.php'; $this->_plugins->registerPlugin(new Zend_Controller_Plugin_ErrorHandler(), 100); } if (!$this->getParam('noViewRenderer') && !Zend_Controller_Action_HelperBroker::hasHelper('viewRenderer')) { #require_once 'Zend/Controller/Action/Helper/ViewRenderer.php'; Zend_Controller_Action_HelperBroker::getStack()->offsetSet(-80, new Zend_Controller_Action_Helper_ViewRenderer()); } /** * Instantiate default request object (HTTP version) if none provided */ if (null !== $request) { $this->setRequest($request); } elseif (null === $request && null === ($request = $this->getRequest())) { #require_once 'Zend/Controller/Request/Http.php'; $request = new Zend_Controller_Request_Http(); $this->setRequest($request); } /** * Set base URL of request object, if available */ if (is_callable(array($this->_request, 'setBaseUrl'))) { if (null !== $this->_baseUrl) { $this->_request->setBaseUrl($this->_baseUrl); } } /** * Instantiate default response object (HTTP version) if none provided */ if (null !== $response) { $this->setResponse($response); } elseif (null === $this->_response && null === ($this->_response = $this->getResponse())) { #require_once 'Zend/Controller/Response/Http.php'; $response = new Zend_Controller_Response_Http(); $this->setResponse($response); } /** * Register request and response objects with plugin broker */ $this->_plugins->setRequest($this->_request)->setResponse($this->_response); /** * Initialize router */ $router = $this->getRouter(); $router->setParams($this->getParams()); /** * Initialize dispatcher */ $dispatcher = $this->getDispatcher(); $dispatcher->setParams($this->getParams())->setResponse($this->_response); // Begin dispatch try { /** * Route request to controller/action, if a router is provided */ /** * Notify plugins of router startup */ $this->_plugins->routeStartup($this->_request); $router->route($this->_request); /** * Notify plugins of router completion */ $this->_plugins->routeShutdown($this->_request); /** * Notify plugins of dispatch loop startup */ $this->_plugins->dispatchLoopStartup($this->_request); /** * Attempt to dispatch the controller/action. If the $this->_request * indicates that it needs to be dispatched, move to the next * action in the request. */ do { $this->_request->setDispatched(true); /** * Notify plugins of dispatch startup */ $this->_plugins->preDispatch($this->_request); /** * Skip requested action if preDispatch() has reset it */ if (!$this->_request->isDispatched()) { continue; } /** * Dispatch request */ try { $dispatcher->dispatch($this->_request, $this->_response); } catch (Exception $e) { if ($this->throwExceptions()) { throw $e; } $this->_response->setException($e); } /** * Notify plugins of dispatch completion */ $this->_plugins->postDispatch($this->_request); } while (!$this->_request->isDispatched()); } catch (Exception $e) { if ($this->throwExceptions()) { throw $e; } $this->_response->setException($e); } /** * Notify plugins of dispatch loop completion */ try { $this->_plugins->dispatchLoopShutdown(); } catch (Exception $e) { if ($this->throwExceptions()) { throw $e; } $this->_response->setException($e); } if ($this->returnResponse()) { return $this->_response; } $this->_response->sendResponse(); }
/** * @return void */ public function testHelperClassPassedToStartMvcIsUsed() { $layout = Zend_Layout::startMvc(array('helperClass' => 'Zend_Layout_LayoutTest_Controller_Action_Helper_Layout')); $this->assertTrue(Zend_Controller_Action_HelperBroker::hasHelper('layout')); $helper = Zend_Controller_Action_HelperBroker::getStaticHelper('layout'); $this->assertTrue($helper instanceof Zend_Layout_LayoutTest_Controller_Action_Helper_Layout); }
/** * setActionController() * * @param Zend_Controller_Action $oActionController * @return Zend_Controller_ActionHelper_Abstract */ public function setActionController(Zend_Controller_Action $oActionController = null) { static $bSmartyInitialized; foreach ($this->_aTranslationsPaths as $sName => $sPath) { $this->_aTranslationsPaths[$sName] = Volcano_Tools::fixPath($sPath); } $aProposedLocales = array(); if ($this->_sRequestParamName && ($sParam = $oActionController->getRequest()->getParam($this->_sRequestParamName))) { $aProposedLocales[] = $sParam; } $sCookieLocale = false; if ($this->_sCookieName && ($sCookieLocale = $oActionController->getRequest()->getCookie($this->_sCookieName))) { $aProposedLocales[] = $sCookieLocale; } $oLocalizer = new Volcano_Localizer($aProposedLocales, $this->_sTranslationAdapterName, $this->_aTranslationsPaths, $this->_bParseRequestHeaders); if ($sCookieLocale != $oLocalizer->getLocale()->getLanguage()) { setcookie($this->_sCookieName, $oLocalizer->getLocale()->getLanguage(), time() + 60 * 60 * 24 * 30, "/"); } parent::setActionController($oActionController); $oActionController->localizer = $oLocalizer; //add localizer to smarty if (Zend_Controller_Action_HelperBroker::hasHelper('Smarty') && !$bSmartyInitialized) { $oSmartyHelper = Zend_Controller_Action_HelperBroker::getExistingHelper('Smarty'); $oSmartyHelper->addCustomFunction('modifier', array($oLocalizer, 'translate'), 'translate'); $oSmartyHelper->locale = array('language' => $oLocalizer->getLocale()->getLanguage(), 'region' => $oLocalizer->getLocale()->getRegion()); $bSmartyInitialized = TRUE; } return $this; }
/** * Adds the given action helper to the broker. * * @param Zend_Controller_Action_Helper_Abstract $helper */ protected function addActionHelper(Zend_Controller_Action_Helper_Abstract $helper) { $this->helpersToRemove[] = $helper->getName(); Zend_Controller_Action_HelperBroker::addHelper($helper); $message = 'Helper "' . $helper->getName() . '" was not added.'; $this->assertTrue(Zend_Controller_Action_HelperBroker::hasHelper($helper->getName()), $message); }
/** * Hook 12: Called after an action is dispatched by \Zend_Controller_Dispatcher. * * This callback allows for proxy or filter behavior. By altering the * request and resetting its dispatched flag (via {@link * \Zend_Controller_Request_Abstract::setDispatched() setDispatched(false)}), * a new action may be specified for dispatching. * * \Zend_Layout_Controller_Plugin_Layout uses this event to change the output * of the $response with the rendering of the layout. As the Layout plugin * has a priority of 99, this Escort event will take place before the layout * is rendered, unless $this->run() was called with a stackIndex lower than zero. * * Previous hook: controllerAfterAction() * Actions since: ob_get_clean(); $response->appendBody() * Actions after: while (! Request->isDispatched()) or back to Hook 8 preDispatch() * Next hook: dispatchLoopShutdown() * * @param \Zend_Controller_Request_Abstract $request * @return void */ public function postDispatch(\Zend_Controller_Request_Abstract $request) { if ($request->isDispatched()) { $response = \Zend_Controller_Front::getInstance()->getResponse(); $response->setHeader('X-UA-Compatible', 'IE=edge,chrome=1', true); if ($this->project->offsetExists('x-frame')) { $response->setHeader('X-Frame-Options', $this->project->offsetGet('x-frame'), true); } // Only when we need to render the layout, we run the layout prepare if (\Zend_Controller_Action_HelperBroker::hasHelper('layout') && \Zend_Controller_Action_HelperBroker::getExistingHelper('layout')->isEnabled()) { // Per project layout preparation if (isset($this->project->layoutPrepare)) { foreach ($this->project->layoutPrepare as $prepare => $type) { if ($type) { $function = '_layout' . ucfirst($prepare); if (isset($this->project->layoutPrepareArgs, $this->project->layoutPrepareArgs[$prepare])) { $args = $this->project->layoutPrepareArgs[$prepare]; } else { $args = array(); } $result = $this->{$function}($args); // When a result is returned, add it to the view, // according to the type method if (null !== $result) { if (is_numeric($type)) { $this->view->{$prepare} = $result; } else { if (!isset($this->view->{$type})) { $this->view->{$type} = new \MUtil_Html_Sequence(); } $sequence = $this->view->{$type}; $sequence[$prepare] = $result; } } } } } } // For AJAX calls we sometimes need to add JQuery onload scripts since otherwise they won't get rendered: // We expect JQuery to be loaded in the master page, since the call is probably made using JQuery if ($request instanceof \Zend_Controller_Request_Http && $request->isXmlHttpRequest()) { \MUtil_JQuery::enableView($this->view); $scripts = $this->view->jQuery()->getOnLoadActions(); $content = ''; foreach ($scripts as $script) { $content .= "<script type='text/javascript'>{$script}</script>\n"; } $content .= $this->view->inlineScript(); // Now cleanup the rendered content (just to make sure) $this->view->jQuery()->clearOnLoadActions(); $this->view->inlineScript()->exchangeArray(array()); if (!empty($content)) { $response->appendBody($content); } } } }
public function testViewRendererHelperNotRegisteredIfNoViewRendererSet() { $this->assertFalse(Zend_Controller_Action_HelperBroker::hasHelper('viewRenderer')); $this->_controller->setParam('noViewRenderer', true); $request = new Zend_Controller_Request_Http('http://example.com/index/index'); $this->_controller->setResponse(new Zend_Controller_Response_Cli()); $response = $this->_controller->dispatch($request); $this->assertFalse(Zend_Controller_Action_HelperBroker::hasHelper('viewRenderer')); }
/** * RouteShutdown is the earliest event in the dispatch cycle, where a * fully routed request object is available */ public function routeShutdown(Zend_Controller_Request_Abstract $request) { if (isset($request->noListRedirect)) { return; } $ontoWiki = OntoWiki::getInstance(); // TODO: Refactor! The list helper is from an extension! Do not access extensions // from core code! if (!Zend_Controller_Action_HelperBroker::hasHelper('List')) { return; } $listHelper = Zend_Controller_Action_HelperBroker::getStaticHelper('List'); // only once and only when possible if (!$this->_isSetup && $ontoWiki->selectedModel != null && (isset($request->init) || isset($request->instancesconfig) || isset($request->s) || isset($request->class) || isset($request->p) || isset($request->limit))) { $frontController = Zend_Controller_Front::getInstance(); $store = $ontoWiki->erfurt->getStore(); $resource = $ontoWiki->selectedResource; $session = $ontoWiki->session; // when switching to another class: // reset session vars (regarding the list) if (isset($request->init)) { //echo 'kill list session'; // reset the instances object unset($session->instances); //reset config from tag explorer unset($session->cloudproperties); } //react on m parameter to set the selected model if (isset($request->m)) { try { $model = $store->getModel($request->getParam('m', null, false)); $ontoWiki->selectedModel = $model; } catch (Erfurt_Store_Exception $e) { $model = null; $ontoWiki->selectedModel = null; } } $list = $listHelper->getLastList(); if (!isset($request->list) && $list == null || isset($request->init)) { // instantiate model, that selects all resources $list = new OntoWiki_Model_Instances($store, $ontoWiki->selectedModel, array()); } else { // use the object from the session if (isset($request->list) && $request->list != $listHelper->getLastListName()) { if ($listHelper->listExists($request->list)) { $list = $listHelper->getList($request->list); $ontoWiki->appendMessage(new OntoWiki_Message('reuse list')); } else { throw new OntoWiki_Exception('your trying to configure a list, but there is no list name specified'); } } $list->setStore($store); // store is not serialized in session! reset it } //local function :) function _json_decode($string) { /* PHP 5.3 DEPRECATED ; REMOVE IN PHP 6.0 */ if (get_magic_quotes_gpc()) { // add slashes for unicode chars in json $string = str_replace('\\u', '\\\\u', $string); //$string = str_replace('\\u000a','', $string); $string = stripslashes($string); } /* ---- */ return json_decode($string, true); } //a shortcut for search param if (isset($request->s)) { if (isset($request->instancesconfig)) { $config = _json_decode($request->instancesconfig); if (null === $config) { throw new OntoWiki_Exception('Invalid parameter instancesconfig (json_decode failed): ' . $this->_request->setup); } } else { $config = array(); } if (!isset($config['filter'])) { $config['filter'] = array(); } $config['filter'][] = array('action' => 'add', 'mode' => 'search', 'searchText' => $request->s); $request->setParam('instancesconfig', json_encode($config)); } //a shortcut for class param if (isset($request->class)) { if (isset($request->instancesconfig)) { $config = _json_decode($request->instancesconfig); if (null === $config) { throw new OntoWiki_Exception('Invalid parameter instancesconfig (json_decode failed): ' . $this->_request->setup); } } else { $config = array(); } if (!isset($config['filter'])) { $config['filter'] = array(); } $config['filter'][] = array('action' => 'add', 'mode' => 'rdfsclass', 'rdfsclass' => $request->class); $request->setParam('instancesconfig', json_encode($config)); } //check for change-requests if (isset($request->instancesconfig)) { $config = _json_decode($request->instancesconfig); if (null === $config) { throw new OntoWiki_Exception('Invalid parameter instancesconfig (json_decode failed)'); } // TODO is this a bug? why access sort->asc when it is null? if (isset($config['sort'])) { if ($config['sort'] == null) { $list->orderByUri($config['sort']['asc']); } else { $list->setOrderProperty($config['sort']['uri'], $config['sort']['asc']); } } if (isset($config['shownProperties'])) { foreach ($config['shownProperties'] as $prop) { if ($prop['action'] == 'add') { $list->addShownProperty($prop['uri'], $prop['label'], $prop['inverse']); } else { $list->removeShownProperty($prop['uri'], $prop['inverse']); } } } if (isset($config['filter'])) { foreach ($config['filter'] as $filter) { // set default value for action and mode if they're not assigned if (!isset($filter['action'])) { $filter['action'] = 'add'; } if (!isset($filter['mode'])) { $filter['mode'] = 'box'; } if ($filter['action'] == 'add') { if ($filter['mode'] == 'box') { $list->addFilter($filter['property'], isset($filter['isInverse']) ? $filter['isInverse'] : false, isset($filter['propertyLabel']) ? $filter['propertyLabel'] : 'defaultLabel', $filter['filter'], isset($filter['value1']) ? $filter['value1'] : null, isset($filter['value2']) ? $filter['value2'] : null, isset($filter['valuetype']) ? $filter['valuetype'] : 'literal', isset($filter['literaltype']) ? $filter['literaltype'] : null, isset($filter['hidden']) ? $filter['hidden'] : false, isset($filter['id']) ? $filter['id'] : null, isset($filter['negate']) ? $filter['negate'] : false); } else { if ($filter['mode'] == 'search') { $list->addSearchFilter($filter['searchText'], isset($filter['id']) ? $filter['id'] : null); } else { if ($filter['mode'] == 'rdfsclass') { $list->addTypeFilter($filter['rdfsclass'], isset($filter['id']) ? $filter['id'] : null); } else { if ($filter['mode'] == 'cnav') { $list->addTripleFilter(NavigationHelper::getInstancesTriples($filter['uri'], $filter['cnav']), isset($filter['id']) ? $filter['id'] : null); } else { if ($filter['mode'] == 'query') { try { //echo $filter->query." "; $query = Erfurt_Sparql_Query2::initFromString($filter['query']); // TODO what the hell is this?! if (!$query instanceof Exception) { $list->addTripleFilter($query->getWhere()->getElements(), isset($filter['id']) ? $filter['id'] : null); } //echo $query->getSparql(); } catch (Erfurt_Sparql_ParserException $e) { $ontoWiki->appendMessage('the query could not be parsed'); } } } } } } } else { $list->removeFilter($filter['id']); } } } if (isset($config['order'])) { foreach ($config['order'] as $prop) { if ($prop['action'] == 'set') { if ($prop['mode'] == 'var') { $list->setOrderVar($prop['var']); } else { $list->setOrderUri($prop['uri']); } } } } } if (isset($request->limit)) { // how many results per page $list->setLimit($request->limit); } else { $list->setLimit(10); } if (isset($request->p)) { // p is the page number $list->setOffset($request->p * $list->getLimit() - $list->getLimit()); } else { $list->setOffset(0); } //save to session $name = isset($request->list) ? $request->list : 'instances'; $listHelper->updateList($name, $list, true); // avoid setting up twice $this->_isSetup = true; // redirect normal requests if config-params are given to a param-free uri // (so a browser reload by user does nothing unwanted) if (!$request->isXmlHttpRequest()) { //strip of url parameters that modify the list $url = new OntoWiki_Url(array(), null, array('init', 'instancesconfig', 's', 'p', 'limit', 'class', 'list')); //redirect $redirector = Zend_Controller_Action_HelperBroker::getStaticHelper('redirector'); $redirector->gotoUrl($url); } } }
public function testInitAddsHelperToBroker() { $this->resource->init(); $this->assertTrue(Zend_Controller_Action_HelperBroker::hasHelper('Param')); }
public function testLoadingAndRemovingHelpersStatically() { $helper = new Zend_Controller_Action_Helper_Redirector(); Zend_Controller_Action_HelperBroker::addHelper($helper); $this->assertTrue(Zend_Controller_Action_HelperBroker::hasHelper('redirector')); Zend_Controller_Action_HelperBroker::removeHelper('redirector'); $this->assertFalse(Zend_Controller_Action_HelperBroker::hasHelper('redirector')); }
/** * static function to render a document outside of a view * * @static * @param Document $document * @param array $params * @param bool $useLayout * @return string */ public static function render(Document $document, $params = array(), $useLayout = false) { $layout = null; $existingActionHelper = null; if (\Zend_Controller_Action_HelperBroker::hasHelper("layout")) { $existingActionHelper = \Zend_Controller_Action_HelperBroker::getExistingHelper("layout"); } $layoutInCurrentAction = \Zend_Layout::getMvcInstance() instanceof \Zend_Layout ? \Zend_Layout::getMvcInstance()->getLayout() : false; $viewHelper = \Zend_Controller_Action_HelperBroker::getExistingHelper("ViewRenderer"); if ($viewHelper) { if ($viewHelper->view === null) { $viewHelper->initView(PIMCORE_WEBSITE_PATH . "/views"); } $view = $viewHelper->view; } else { $view = new \Pimcore\View(); } // add the view script path from the website module to the view, because otherwise it's not possible to call // this method out of other modules to render documents, eg. sending e-mails out of an plugin with Pimcore_Mail $moduleDirectory = \Zend_Controller_Front::getInstance()->getModuleDirectory($document->getModule()); if (!empty($moduleDirectory)) { $view->addScriptPath($moduleDirectory . "/views/layouts"); $view->addScriptPath($moduleDirectory . "/views/scripts"); } else { $view->addScriptPath(PIMCORE_FRONTEND_MODULE . "/views/layouts"); $view->addScriptPath(PIMCORE_FRONTEND_MODULE . "/views/scripts"); } $documentBackup = null; if ($view->document) { $documentBackup = $view->document; } $view->document = $document; if ($useLayout) { if (!($layout = \Zend_Layout::getMvcInstance())) { $layout = \Zend_Layout::startMvc(); $layout->setViewSuffix(View::getViewScriptSuffix()); if ($layoutHelper = $view->getHelper("layout")) { $layoutHelper->setLayout($layout); } } $layout->setLayout("--modification-indicator--"); } $params["document"] = $document; foreach ($params as $key => $value) { if (!$view->{$key}) { $view->{$key} = $value; } } $content = $view->action($document->getAction(), $document->getController(), $document->getModule(), $params); //has to be called after $view->action so we can determine if a layout is enabled in $view->action() if ($useLayout) { if ($layout instanceof \Zend_Layout) { $layout->{$layout->getContentKey()} = $content; if (is_array($params)) { foreach ($params as $key => $value) { $layout->getView()->{$key} = $value; } } // when using Document\Service::render() you have to set a layout in the view ($this->layout()->setLayout("mylayout")) if ($layout->getLayout() != "--modification-indicator--") { $content = $layout->render(); } //deactivate the layout if it was not activated in the called action //otherwise we would activate the layout in the called action \Zend_Layout::resetMvcInstance(); if (!$layoutInCurrentAction) { $layout->disableLayout(); } else { $layout = \Zend_Layout::startMvc(); $layout->setViewSuffix(View::getViewScriptSuffix()); // set pimcore specifiy view suffix $layout->setLayout($layoutInCurrentAction); $view->getHelper("Layout")->setLayout($layout); if ($existingActionHelper) { \Zend_Controller_Action_HelperBroker::removeHelper("layout"); \Zend_Controller_Action_HelperBroker::addHelper($existingActionHelper); $pluginClass = $layout->getPluginClass(); $front = $existingActionHelper->getFrontController(); if ($front->hasPlugin($pluginClass)) { $plugin = $front->getPlugin($pluginClass); $plugin->setLayoutActionHelper($existingActionHelper); } } } $layout->{$layout->getContentKey()} = null; //reset content } } if ($documentBackup) { $view->document = $documentBackup; } if (\Pimcore\Config::getSystemConfig()->outputfilters->less) { $content = \Pimcore\Tool\Less::processHtml($content); } return $content; }
/** * Initialize action helper * * @return void */ protected function _initHelper() { $helperClass = $this->getHelperClass(); require_once 'Zend/Controller/Action/HelperBroker.php'; if (!Zend_Controller_Action_HelperBroker::hasHelper('layout')) { require_once 'Zend/Loader.php'; Zend_Loader::loadClass($helperClass); Zend_Controller_Action_HelperBroker::getStack()->offsetSet(-90, new $helperClass($this)); } }
public function viewAction() { if (Zend_Controller_Action_HelperBroker::hasHelper('redirector')) { $redirector = Zend_Controller_Action_HelperBroker::getExistingHelper('redirector'); } $hometargeturl = $this->_urlHelper->url(array('controller' => 'index', 'action' => 'index', 'language' => $this->view->language), 'lang_default', true); // Get user identity $auth = Zend_Auth::getInstance(); // Disable edit profile by default $userEdit = false; // Get params $params = $this->getRequest()->getParams(); if (isset($params['user'])) { // Get username from params $username = $params['user']; } else { $redirector->gotoUrl($hometargeturl); } // Get content types $contentTypes = new Default_Model_ContentTypes(); $this->view->content_types = $contentTypes->getAllNamesAndIds(); // Get user data from User Model $user = new Default_Model_User(); $data = $user->getUserByName($username); if ($data == null) { $redirector->gotoUrl($hometargeturl); } $this->view->user = $data; $id = $data['id_usr']; $topListClasses = $user->getUserTopList(); $topListUsers = $topListClasses['Users']; if ($id != 0) { $topListUsers->addUser($id); } $topList = $topListUsers->getTopList(); // Get public user data from UserProfiles Model $userProfile = new Default_Model_UserProfiles(); $dataa = $userProfile->getPublicData($id); if (isset($dataa['biography'])) { $dataa['biography'] = str_replace("\n", '<br>', $dataa['biography']); } // User weblinks $userWeblinksModel = new Default_Model_UserWeblinks(); $dataa['userWeblinks'] = $userWeblinksModel->getUserWeblinks($id); $i = 0; foreach ($dataa['userWeblinks'] as $weblink) { if (strlen($weblink['name_uwl']) == 0 || strlen($weblink['url_uwl']) == 0) { unset($dataa['userWeblinks'][$i]); } $i++; } // $dataa is an array with key=>val like firstname => "Joel Peeloten" // This was replaced with get public data and the foreach above // Kept here just in case for the future /* $dataa['gender'] = $userprofile->getUserProfileValue($id, 'gender'); $dataa['surname'] = $userprofile->getUserProfileValue($id, 'surname'); $dataa['firstname'] = $userprofile->getUserProfileValue($id, 'firstname'); $dataa['category'] = $userprofile->getUserProfileValue($id, 'user category'); $dataa['profession'] = $userprofile->getUserProfileValue($id, 'profession'); $dataa['company'] = $userprofile->getUserProfileValue($id, 'company'); $dataa['biography'] = $userprofile->getUserProfileValue($id, 'biography'); $dataa['city'] = $userprofile->getUserProfileValue($id, 'city'); $dataa['phone'] = $userprofile->getUserProfileValue($id, 'phone'); $dataa['birthday'] = $userprofile->getUserProfileValue($id, 'birthday'); */ // No countries in countries_ctr and not very good table at all? // This would be better: http://snipplr.com/view/6636/mysql-table--iso-country-list-with-abbreviations/ /* $dataa['country'] = $userProfile->getUserProfileValue($id, 'country'); $userCountry = new Default_Model_UserCountry(); $dataa['country'] = $userCountry->getCountryNameById( $dataa['country']['profile_value_usp'] ); */ // Get content user has released $type = isset($params['type']) ? $params['type'] : 0; $temp = array(); // Initialize content counts $dataa['contentCounts']['all'] = 0; $dataa['contentCounts']['user_edit'] = 0; $dataa['contentCounts']['problem'] = 0; $dataa['contentCounts']['finfo'] = 0; $dataa['contentCounts']['idea'] = 0; // Count amount of content user has published // and check unpublished so only owner can see it. $cntModel = new Default_Model_Content(); $contentList = array(); foreach ($user->getUserContent($data['id_usr'], array('order' => 'DESC')) as $k => $c) { // If user not logged in and content not published, // remove content from list if (!$auth->hasIdentity() && $c['published_cnt'] == 0) { //unset($contentList[$k]); // Else if user logged in and not owner of unpublished content, // remove content from list } else { if (isset($c['id_usr']) && $auth->hasIdentity() && $c['id_usr'] != $auth->getIdentity()->user_id && $c['published_cnt'] == 0) { //unset($contentList[$k]); // Else increase content counts and sort content by content type } else { if (isset($c['key_cty'])) { // Set content to array by its content type //$temp[$c['key_cty']][] = $c; //$temp[] = $c; // Increase total count $dataa['contentCounts']['all']++; // Set content type count to 0 if count is not set if (!isset($dataa['contentCounts'][$c['key_cty']])) { $dataa['contentCounts'][$c['key_cty']] = 0; } // Increase content type count $dataa['contentCounts'][$c['key_cty']]++; } if ($c['published_cnt'] == 0) { $dataa['contentCounts']['user_edit']++; } $c['hasCntLinks'] = $cntModel->hasCntLinks($c['id_cnt']); $c['hasCmpLinks'] = $cntModel->hasCmpLinks($c['id_cnt']); $contentList[] = $c; } } } // end foreach // If user is logged in, and viewing self; allow edit if ($auth->hasIdentity()) { $identity = $auth->getIdentity(); if ($data['id_usr'] == $identity->user_id) { $userEdit = true; } } // if ($auth->hasIdentity() && $data['id_usr'] == $auth->getIdentity()->user_id) { $myFavourites = $this->getFavouriteRows($data['id_usr']); //print_r($dataa);print_r($favouriteList);die; //} //Zend_Debug::dump("" === null); //Zend_Debug::dump($dataa['contentCounts']['idea']); //Zend_Debug::dump($dataa['contentCounts']['idea'] == ""); //die; // My Posts box data $box = new Oibs_Controller_Plugin_AccountViewBox(); $box->setHeader("My Posts")->setClass("right")->setName("my-posts")->addTab("All", "all", "all selected", $dataa['contentCounts']['all'])->addTab("Challenges", "problem", "challenges", $dataa['contentCounts']['problem'])->addTab("Ideas", "idea", "ideas", $dataa['contentCounts']['idea'])->addTab("Visions", "finfo", "visions", $dataa['contentCounts']['finfo']); //Zend_Debug::dump($dataa); die; if ($dataa['contentCounts']['user_edit'] && $userEdit) { $box->addTab("Saved", "user_edit", "saved", $dataa['contentCounts']['user_edit']); } $boxes[] = $box; $box = new Oibs_Controller_Plugin_AccountViewBox(); $box->setHeader("My Groups")->setClass("left")->setName("my_groups")->addTab("All", "all", "all selected"); $boxes[] = $box; $views = new Default_Model_ContentViews(); $myViews = $this->getViewRows($data['id_usr']); $myViews = array_merge($myViews, $myFavourites['contents']); //print_r($myViews);die; $box = new Oibs_Controller_Plugin_AccountViewBox(); $box->setHeader("My Views & Favourites")->setName("my-views")->setClass("right")->addTab("Views", "views", "views selected")->addTab("Updated", "updated", "fvr_updated", $myFavourites['counts']['updated'])->addTab("Challenges", "problem", "fvr_problem", $myFavourites['counts']['problem'])->addTab("Ideas", "idea", "fvr_idea", $myFavourites['counts']['idea'])->addTab("Visions", "finfo", "fvr_finfo", $myFavourites['counts']['finfo']); //$boxes[] = $box; $myReaders = $user->getUsersViewers($data['id_usr']); $box = new Oibs_Controller_Plugin_AccountViewBox(); $box->setHeader("My Readers")->setClass("left")->setName("my-reads")->addTab("Readers", "readers", "all selected"); //$boxes[] = $box; /*Box for user profile custom layout settings*/ $box = new Oibs_Controller_Plugin_AccountViewBox(); $box->setHeader("Custom Layout")->setClass("wide")->setName("my-custom-layout")->addTab("Customize", "fonts", "all selected"); //$boxes[] = $box; $customLayoutForm = new Default_Form_AccountCustomLayoutSettingsForm(); // Set to view // Comment module $comments = new Oibs_Controller_Plugin_Comments("account", $id); $this->view->jsmetabox->append('commentUrls', $comments->getUrls()); // enable comment form if ($auth->hasIdentity()) { $comments->allowComments(true); } $comments->loadComments(); $this->view->user_has_image = $user->userHasProfileImage($data['id_usr']); $this->view->userprofile = $dataa; $this->view->comments = $comments; $this->view->authorContents = $contentList; /*$temp*/ $this->view->boxes = $boxes; $this->view->myViews = $myViews; $this->view->myReaders = $myReaders; $this->view->user_edit = $userEdit; $this->view->topList = $topList; $this->view->type = $type; $this->view->customLayoutSettingsForm = $customLayoutForm; $group_model = new Default_Model_UserHasGroup(); $usergroups = $group_model->getGroupsByUserId($id); $this->view->usergroups = $usergroups; }
/** * Send file to browser from file on the filesystem * * @param string $file Path to file * @param string $type MIME type * @param string $disposition Content disposition */ public function sendFromFile($file, $type = 'application/octet-stream', $disposition = self::CONTENT_DISPOSITION_ATTACHMENT) { if (!file_exists($file)) { /** * @see Zym_Controller_Action_Helper_Exception */ require_once 'Zym/Controller/Action/Helper/Exception.php'; throw new Zym_Controller_Action_Helper_Exception(sprintf('File helper could not find file "%s"', $file)); } $response = $this->getRequest(); $response->setHeader('Content-Disposition', sprintf('%s, filename="%s"', $disposition, pathinfo($file, PATHINFO_BASENAME)), true)->setHeader('Content-Type', $type, true); // Required for IE, otherwise Content-disposition is ignored if (ini_get('zlib.output_compression')) { ini_set('zlib.output_compression', false); } if (self::isXSendFile()) { $response->setHeader('X-SendFile', $file, true); } else { $request = $this->getRequest(); $filesize = filesize($file); $time = gmdate('D, d M Y H:i:s', filemtime($file)) . ' GMT'; $begin = 0; $end = $filesize - 1; $httpRange = $request->getServer('HTTP_RANGE'); $matches = null; if ($httpRange) { if (preg_match('/bytes=\\h*(\\d+)-(\\d*)[\\D.*]?/i', $httpRange, $matches)) { $begin = (int) $matches[1]; $end = !empty($matches[2]) ? (int) $matches[2] : $filesize; if ($begin > 0 || $end < $filesize - 1) { // Partial Content $response->setHttpResponseCode(206); } } } // Only set last-modified time if none have been set foreach ($response->getHeaders() as $header) { if (strcasecmp($header['name'], 'Last-Modified')) { $lastModifiedExists = true; } } if (!isset($lastModifiedExists)) { $response->setHeader('Last-Modified', $time); } // Normal file headers $response->setHeader('Content-Length', $end - $begin, true)->setHeader(sprintf('Content-Range: bytes %s/%s', $begin - $end, $filesize), true)->setHeader('Accept-Ranges', 'bytes', true)->setHeader('Connection', 'close', true); $response->sendHeaders(); set_time_limit(0); if ($response->getHttpResponseCode() == 206) { // Handle partial response $pos = $begin; $fp = fopen($file, 'rb'); fseek($fp, $begin, 0); while (!feof($fp) && $pos < $end && connection_status() == 0) { print fread($fp, min(1024 * 16, $end + 1 - $pos)); $pos += 1024 * 16; } } else { readfile($file); } } // Disable layout if (Zend_Controller_Action_HelperBroker::hasHelper('Layout')) { $this->getActionController()->getHelper('Layout')->disableLayout(); } // Disable ViewRenderer if (Zend_Controller_Action_HelperBroker::hasHelper('ViewRenderer')) { $this->getActionController()->getHelper('ViewRenderer')->setNoRender(); } }
/** * Resets all object properties of the singleton instance * * Primarily used for testing; could be used to chain front controllers. * * @return void */ public function resetInstance() { $reflection = new ReflectionObject($this); foreach ($reflection->getProperties() as $property) { $name = $property->getName(); switch ($name) { case '_instance': break; case '_controllerDir': case '_invokeParams': $this->{$name} = array(); break; case '_plugins': $this->{$name} = new Zend_Controller_Plugin_Broker(); $this->{$name}->registerPlugin(new Zend_Controller_Plugin_ErrorHandler()); break; case '_throwExceptions': case '_returnResponse': $this->{$name} = false; break; case '_moduleControllerDirectoryName': $this->{$name} = 'controllers'; break; default: $this->{$name} = null; break; } } if (!Zend_Controller_Action_HelperBroker::hasHelper('viewRenderer')) { Zend_Controller_Action_HelperBroker::addHelper(new Zend_Controller_Action_Helper_ViewRenderer()); } }