View.php 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. * @link http://cakephp.org CakePHP(tm) Project
  12. * @since 0.10.0
  13. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  14. */
  15. namespace Cake\View;
  16. use Cake\Cache\Cache;
  17. use Cake\Core\App;
  18. use Cake\Core\Plugin;
  19. use Cake\Event\EventManager;
  20. use Cake\Event\EventManagerTrait;
  21. use Cake\Log\LogTrait;
  22. use Cake\Network\Request;
  23. use Cake\Network\Response;
  24. use Cake\Routing\RequestActionTrait;
  25. use Cake\Routing\Router;
  26. use Cake\Utility\Inflector;
  27. use Cake\View\CellTrait;
  28. use Cake\View\ViewVarsTrait;
  29. use InvalidArgumentException;
  30. use LogicException;
  31. /**
  32. * View, the V in the MVC triad. View interacts with Helpers and view variables passed
  33. * in from the controller to render the results of the controller action. Often this is HTML,
  34. * but can also take the form of JSON, XML, PDF's or streaming files.
  35. *
  36. * CakePHP uses a two-step-view pattern. This means that the view content is rendered first,
  37. * and then inserted into the selected layout. This also means you can pass data from the view to the
  38. * layout using `$this->set()`
  39. *
  40. * View class supports using plugins as themes. You can set
  41. * `$this->theme = 'SuperHot'` in your Controller to use plugin `SuperHot` as a
  42. * theme. Eg. If current action is Posts::index() then View class will look for
  43. * template file `plugins/SuperHot/Template/Posts/index.ctp`. If a theme template
  44. * is not found for the current action the default app template file is used.
  45. *
  46. * @property \Cake\View\Helper\CacheHelper $Cache
  47. * @property \Cake\View\Helper\FormHelper $Form
  48. * @property \Cake\View\Helper\HtmlHelper $Html
  49. * @property \Cake\View\Helper\NumberHelper $Number
  50. * @property \Cake\View\Helper\PaginatorHelper $Paginator
  51. * @property \Cake\View\Helper\RssHelper $Rss
  52. * @property \Cake\View\Helper\SessionHelper $Session
  53. * @property \Cake\View\Helper\TextHelper $Text
  54. * @property \Cake\View\Helper\TimeHelper $Time
  55. * @property \Cake\View\ViewBlock $Blocks
  56. */
  57. class View {
  58. use CellTrait;
  59. use EventManagerTrait;
  60. use LogTrait;
  61. use RequestActionTrait;
  62. use ViewVarsTrait;
  63. /**
  64. * Helpers collection
  65. *
  66. * @var \Cake\View\HelperRegistry
  67. */
  68. protected $_helpers;
  69. /**
  70. * ViewBlock instance.
  71. *
  72. * @var \Cake\View\ViewBlock
  73. */
  74. public $Blocks;
  75. /**
  76. * The name of the plugin.
  77. *
  78. * @var string
  79. */
  80. public $plugin = null;
  81. /**
  82. * Name of the controller that created the View if any.
  83. *
  84. * @var string
  85. */
  86. public $name = null;
  87. /**
  88. * Current passed params. Passed to View from the creating Controller for convenience.
  89. *
  90. * @var array
  91. */
  92. public $passedArgs = array();
  93. /**
  94. * An array of names of built-in helpers to include.
  95. *
  96. * @var mixed
  97. */
  98. public $helpers = array();
  99. /**
  100. * The name of the views subfolder containing views for this View.
  101. *
  102. * @var string
  103. */
  104. public $viewPath = null;
  105. /**
  106. * The name of the view file to render. The name specified
  107. * is the filename in /app/Template/<SubFolder> without the .ctp extension.
  108. *
  109. * @var string
  110. */
  111. public $view = null;
  112. /**
  113. * The name of the layout file to render the view inside of. The name specified
  114. * is the filename of the layout in /app/Template/Layout without the .ctp
  115. * extension.
  116. *
  117. * @var string
  118. */
  119. public $layout = 'default';
  120. /**
  121. * The name of the layouts subfolder containing layouts for this View.
  122. *
  123. * @var string
  124. */
  125. public $layoutPath = null;
  126. /**
  127. * Turns on or off CakePHP's conventional mode of applying layout files. On by default.
  128. * Setting to off means that layouts will not be automatically applied to rendered views.
  129. *
  130. * @var bool
  131. */
  132. public $autoLayout = true;
  133. /**
  134. * File extension. Defaults to CakePHP's template ".ctp".
  135. *
  136. * @var string
  137. */
  138. protected $_ext = '.ctp';
  139. /**
  140. * Sub-directory for this view file. This is often used for extension based routing.
  141. * Eg. With an `xml` extension, $subDir would be `xml/`
  142. *
  143. * @var string
  144. */
  145. public $subDir = null;
  146. /**
  147. * The view theme to use.
  148. *
  149. * @var string
  150. */
  151. public $theme = null;
  152. /**
  153. * True when the view has been rendered.
  154. *
  155. * @var bool
  156. */
  157. public $hasRendered = false;
  158. /**
  159. * List of generated DOM UUIDs.
  160. *
  161. * @var array
  162. */
  163. public $uuids = array();
  164. /**
  165. * An instance of a Cake\Network\Request object that contains information about the current request.
  166. * This object contains all the information about a request and several methods for reading
  167. * additional information about the request.
  168. *
  169. * @var \Cake\Network\Request
  170. */
  171. public $request;
  172. /**
  173. * Reference to the Response object
  174. *
  175. * @var \Cake\Network\Response
  176. */
  177. public $response;
  178. /**
  179. * The Cache configuration View will use to store cached elements. Changing this will change
  180. * the default configuration elements are stored under. You can also choose a cache config
  181. * per element.
  182. *
  183. * @var string
  184. * @see View::element()
  185. */
  186. public $elementCache = 'default';
  187. /**
  188. * Element cache settings
  189. *
  190. * @var array
  191. * @see View::_elementCache();
  192. * @see View::_renderElement
  193. */
  194. public $elementCacheSettings = array();
  195. /**
  196. * List of variables to collect from the associated controller.
  197. *
  198. * @var array
  199. */
  200. protected $_passedVars = array(
  201. 'viewVars', 'autoLayout', 'helpers', 'view', 'layout', 'name', 'theme',
  202. 'layoutPath', 'viewPath', 'plugin', 'passedArgs'
  203. );
  204. /**
  205. * Holds an array of paths.
  206. *
  207. * @var array
  208. */
  209. protected $_paths = array();
  210. /**
  211. * Holds an array of plugin paths.
  212. *
  213. * @var array
  214. */
  215. protected $_pathsForPlugin = array();
  216. /**
  217. * The names of views and their parents used with View::extend();
  218. *
  219. * @var array
  220. */
  221. protected $_parents = array();
  222. /**
  223. * The currently rendering view file. Used for resolving parent files.
  224. *
  225. * @var string
  226. */
  227. protected $_current = null;
  228. /**
  229. * Currently rendering an element. Used for finding parent fragments
  230. * for elements.
  231. *
  232. * @var string
  233. */
  234. protected $_currentType = '';
  235. /**
  236. * Content stack, used for nested templates that all use View::extend();
  237. *
  238. * @var array
  239. */
  240. protected $_stack = array();
  241. /**
  242. * Constant for view file type 'view'
  243. *
  244. * @var string
  245. */
  246. const TYPE_VIEW = 'view';
  247. /**
  248. * Constant for view file type 'element'
  249. *
  250. * @var string
  251. */
  252. const TYPE_ELEMENT = 'element';
  253. /**
  254. * Constant for view file type 'layout'
  255. *
  256. * @var string
  257. */
  258. const TYPE_LAYOUT = 'layout';
  259. /**
  260. * Constructor
  261. *
  262. * @param \Cake\Network\Request $request Request instance.
  263. * @param \Cake\Network\Response $response Response instance.
  264. * @param \Cake\Event\EventManager $eventManager Event manager instance.
  265. * @param array $viewOptions View options. See View::$_passedVars for list of
  266. * options which get set as class properties.
  267. */
  268. public function __construct(Request $request = null, Response $response = null,
  269. EventManager $eventManager = null, array $viewOptions = []) {
  270. foreach ($this->_passedVars as $var) {
  271. if (isset($viewOptions[$var])) {
  272. $this->{$var} = $viewOptions[$var];
  273. }
  274. }
  275. $this->eventManager($eventManager);
  276. $this->request = $request;
  277. $this->response = $response;
  278. if (empty($this->request)) {
  279. $this->request = Router::getRequest(true);
  280. }
  281. if (empty($this->request)) {
  282. $this->request = new Request();
  283. $this->request->base = '';
  284. $this->request->here = $this->request->webroot = '/';
  285. }
  286. if (empty($this->response)) {
  287. $this->response = new Response();
  288. }
  289. $this->Blocks = new ViewBlock();
  290. $this->initialize();
  291. $this->loadHelpers();
  292. }
  293. /**
  294. * Initialization hook method.
  295. *
  296. * Properties like $helpers etc. cannot be initialized statically in your custom
  297. * view class as they are overwritten by values from controller in constructor.
  298. * So this method allows you to manipulate them as required after view instance
  299. * is constructed.
  300. *
  301. * @return void
  302. */
  303. public function initialize() {
  304. }
  305. /**
  306. * Renders a piece of PHP with provided parameters and returns HTML, XML, or any other string.
  307. *
  308. * This realizes the concept of Elements, (or "partial layouts") and the $params array is used to send
  309. * data to be used in the element. Elements can be cached improving performance by using the `cache` option.
  310. *
  311. * @param string $name Name of template file in the/app/Template/Element/ folder,
  312. * or `MyPlugin.template` to use the template element from MyPlugin. If the element
  313. * is not found in the plugin, the normal view path cascade will be searched.
  314. * @param array $data Array of data to be made available to the rendered view (i.e. the Element)
  315. * @param array $options Array of options. Possible keys are:
  316. * - `cache` - Can either be `true`, to enable caching using the config in View::$elementCache. Or an array
  317. * If an array, the following keys can be used:
  318. * - `config` - Used to store the cached element in a custom cache configuration.
  319. * - `key` - Used to define the key used in the Cache::write(). It will be prefixed with `element_`
  320. * - `callbacks` - Set to true to fire beforeRender and afterRender helper callbacks for this element.
  321. * Defaults to false.
  322. * - `ignoreMissing` - Used to allow missing elements. Set to true to not throw exceptions.
  323. * @return string Rendered Element
  324. * @throws \Cake\View\Exception\MissingElementException When an element is missing and `ignoreMissing`
  325. * is false.
  326. */
  327. public function element($name, array $data = array(), array $options = array()) {
  328. $file = $plugin = null;
  329. if (!isset($options['callbacks'])) {
  330. $options['callbacks'] = false;
  331. }
  332. if (isset($options['cache'])) {
  333. $contents = $this->_elementCache($name, $data, $options);
  334. if ($contents !== false) {
  335. return $contents;
  336. }
  337. }
  338. $file = $this->_getElementFilename($name);
  339. if ($file) {
  340. return $this->_renderElement($file, $data, $options);
  341. }
  342. if (empty($options['ignoreMissing'])) {
  343. list ($plugin, $name) = pluginSplit($name, true);
  344. $name = str_replace('/', DS, $name);
  345. $file = $plugin . 'Element' . DS . $name . $this->_ext;
  346. throw new Exception\MissingElementException($file);
  347. }
  348. }
  349. /**
  350. * Checks if an element exists
  351. *
  352. * @param string $name Name of template file in the /app/Template/Element/ folder,
  353. * or `MyPlugin.template` to check the template element from MyPlugin. If the element
  354. * is not found in the plugin, the normal view path cascade will be searched.
  355. * @return bool Success
  356. */
  357. public function elementExists($name) {
  358. return (bool)$this->_getElementFilename($name);
  359. }
  360. /**
  361. * Renders view for given view file and layout.
  362. *
  363. * Render triggers helper callbacks, which are fired before and after the view are rendered,
  364. * as well as before and after the layout. The helper callbacks are called:
  365. *
  366. * - `beforeRender`
  367. * - `afterRender`
  368. * - `beforeLayout`
  369. * - `afterLayout`
  370. *
  371. * If View::$autoRender is false and no `$layout` is provided, the view will be returned bare.
  372. *
  373. * View and layout names can point to plugin views/layouts. Using the `Plugin.view` syntax
  374. * a plugin view/layout can be used instead of the app ones. If the chosen plugin is not found
  375. * the view will be located along the regular view path cascade.
  376. *
  377. * @param string $view Name of view file to use
  378. * @param string $layout Layout to use.
  379. * @return string|null Rendered content or null if content already rendered and returned earlier.
  380. * @throws \Cake\Core\Exception\Exception If there is an error in the view.
  381. */
  382. public function render($view = null, $layout = null) {
  383. if ($this->hasRendered) {
  384. return;
  385. }
  386. if ($view !== false && $viewFileName = $this->_getViewFileName($view)) {
  387. $this->_currentType = static::TYPE_VIEW;
  388. $this->dispatchEvent('View.beforeRender', [$viewFileName]);
  389. $this->Blocks->set('content', $this->_render($viewFileName));
  390. $this->dispatchEvent('View.afterRender', [$viewFileName]);
  391. }
  392. if ($layout === null) {
  393. $layout = $this->layout;
  394. }
  395. if ($layout && $this->autoLayout) {
  396. $this->Blocks->set('content', $this->renderLayout('', $layout));
  397. }
  398. $this->hasRendered = true;
  399. return $this->Blocks->get('content');
  400. }
  401. /**
  402. * Renders a layout. Returns output from _render(). Returns false on error.
  403. * Several variables are created for use in layout.
  404. *
  405. * @param string $content Content to render in a view, wrapped by the surrounding layout.
  406. * @param string $layout Layout name
  407. * @return mixed Rendered output, or false on error
  408. * @throws \Cake\Core\Exception\Exception if there is an error in the view.
  409. */
  410. public function renderLayout($content, $layout = null) {
  411. $layoutFileName = $this->_getLayoutFileName($layout);
  412. if (empty($layoutFileName)) {
  413. return $this->Blocks->get('content');
  414. }
  415. if (empty($content)) {
  416. $content = $this->Blocks->get('content');
  417. } else {
  418. $this->Blocks->set('content', $content);
  419. }
  420. $this->dispatchEvent('View.beforeLayout', [$layoutFileName]);
  421. $title = $this->Blocks->get('title');
  422. if ($title === '') {
  423. $title = Inflector::humanize($this->viewPath);
  424. $this->Blocks->set('title', $title);
  425. }
  426. $this->_currentType = static::TYPE_LAYOUT;
  427. $this->Blocks->set('content', $this->_render($layoutFileName));
  428. $this->dispatchEvent('View.afterLayout', [$layoutFileName]);
  429. return $this->Blocks->get('content');
  430. }
  431. /**
  432. * Returns a list of variables available in the current View context
  433. *
  434. * @return array Array of the set view variable names.
  435. */
  436. public function getVars() {
  437. return array_keys($this->viewVars);
  438. }
  439. /**
  440. * Returns the contents of the given View variable.
  441. *
  442. * @param string $var The view var you want the contents of.
  443. * @param mixed $default The default/fallback content of $var.
  444. * @return mixed The content of the named var if its set, otherwise $default.
  445. */
  446. public function get($var, $default = null) {
  447. if (!isset($this->viewVars[$var])) {
  448. return $default;
  449. }
  450. return $this->viewVars[$var];
  451. }
  452. /**
  453. * Get the names of all the existing blocks.
  454. *
  455. * @return array An array containing the blocks.
  456. * @see ViewBlock::keys()
  457. */
  458. public function blocks() {
  459. return $this->Blocks->keys();
  460. }
  461. /**
  462. * Start capturing output for a 'block'
  463. *
  464. * @param string $name The name of the block to capture for.
  465. * @return void
  466. * @see ViewBlock::start()
  467. */
  468. public function start($name) {
  469. $this->Blocks->start($name);
  470. }
  471. /**
  472. * Append to an existing or new block.
  473. *
  474. * Appending to a new block will create the block.
  475. *
  476. * @param string $name Name of the block
  477. * @param mixed $value The content for the block.
  478. * @return void
  479. * @see ViewBlock::concat()
  480. */
  481. public function append($name, $value = null) {
  482. if ($value !== null) {
  483. $this->Blocks->concat($name, $value);
  484. return;
  485. }
  486. $this->Blocks->start($name);
  487. echo $this->Blocks->get($name);
  488. }
  489. /**
  490. * Prepend to an existing or new block.
  491. *
  492. * Prepending to a new block will create the block.
  493. *
  494. * @param string $name Name of the block
  495. * @param mixed $value The content for the block.
  496. * @return void
  497. * @see ViewBlock::concat()
  498. */
  499. public function prepend($name, $value) {
  500. $this->Blocks->concat($name, $value, ViewBlock::PREPEND);
  501. }
  502. /**
  503. * Set the content for a block. This will overwrite any
  504. * existing content.
  505. *
  506. * @param string $name Name of the block
  507. * @param mixed $value The content for the block.
  508. * @return void
  509. * @see ViewBlock::set()
  510. */
  511. public function assign($name, $value) {
  512. $this->Blocks->set($name, $value);
  513. }
  514. /**
  515. * Fetch the content for a block. If a block is
  516. * empty or undefined '' will be returned.
  517. *
  518. * @param string $name Name of the block
  519. * @param string $default Default text
  520. * @return string default The block content or $default if the block does not exist.
  521. * @see ViewBlock::get()
  522. */
  523. public function fetch($name, $default = '') {
  524. return $this->Blocks->get($name, $default);
  525. }
  526. /**
  527. * End a capturing block. The compliment to View::start()
  528. *
  529. * @return void
  530. * @see ViewBlock::end()
  531. */
  532. public function end() {
  533. $this->Blocks->end();
  534. }
  535. /**
  536. * Provides view or element extension/inheritance. Views can extends a
  537. * parent view and populate blocks in the parent template.
  538. *
  539. * @param string $name The view or element to 'extend' the current one with.
  540. * @return void
  541. * @throws \LogicException when you extend a view with itself or make extend loops.
  542. * @throws \LogicException when you extend an element which doesn't exist
  543. */
  544. public function extend($name) {
  545. if ($name[0] === '/' || $this->_currentType === static::TYPE_VIEW) {
  546. $parent = $this->_getViewFileName($name);
  547. } else {
  548. switch ($this->_currentType) {
  549. case static::TYPE_ELEMENT:
  550. $parent = $this->_getElementFileName($name);
  551. if (!$parent) {
  552. list($plugin, $name) = $this->pluginSplit($name);
  553. $paths = $this->_paths($plugin);
  554. $defaultPath = $paths[0] . 'Element' . DS;
  555. throw new \LogicException(sprintf(
  556. 'You cannot extend an element which does not exist (%s).',
  557. $defaultPath . $name . $this->_ext
  558. ));
  559. }
  560. break;
  561. case static::TYPE_LAYOUT:
  562. $parent = $this->_getLayoutFileName($name);
  563. break;
  564. default:
  565. $parent = $this->_getViewFileName($name);
  566. }
  567. }
  568. if ($parent == $this->_current) {
  569. throw new \LogicException('You cannot have views extend themselves.');
  570. }
  571. if (isset($this->_parents[$parent]) && $this->_parents[$parent] == $this->_current) {
  572. throw new \LogicException('You cannot have views extend in a loop.');
  573. }
  574. $this->_parents[$this->_current] = $parent;
  575. }
  576. /**
  577. * Generates a unique, non-random DOM ID for an object, based on the object type and the target URL.
  578. *
  579. * @param string $object Type of object, i.e. 'form' or 'link'
  580. * @param string $url The object's target URL
  581. * @return string
  582. */
  583. public function uuid($object, $url) {
  584. $c = 1;
  585. $url = Router::url($url);
  586. $hash = $object . substr(md5($object . $url), 0, 10);
  587. while (in_array($hash, $this->uuids)) {
  588. $hash = $object . substr(md5($object . $url . $c), 0, 10);
  589. $c++;
  590. }
  591. $this->uuids[] = $hash;
  592. return $hash;
  593. }
  594. /**
  595. * Retrieve the current view type
  596. *
  597. * @return string
  598. */
  599. public function getCurrentType() {
  600. return $this->_currentType;
  601. }
  602. /**
  603. * Magic accessor for helpers.
  604. *
  605. * @param string $name Name of the attribute to get.
  606. * @return mixed
  607. */
  608. public function __get($name) {
  609. $registry = $this->helpers();
  610. if (isset($registry->{$name})) {
  611. $this->{$name} = $registry->{$name};
  612. return $registry->{$name};
  613. }
  614. return $this->{$name};
  615. }
  616. /**
  617. * Interact with the HelperRegistry to load all the helpers.
  618. *
  619. * @return void
  620. */
  621. public function loadHelpers() {
  622. $registry = $this->helpers();
  623. $helpers = $registry->normalizeArray($this->helpers);
  624. foreach ($helpers as $properties) {
  625. $this->loadHelper($properties['class'], $properties['config']);
  626. }
  627. }
  628. /**
  629. * Renders and returns output for given view filename with its
  630. * array of data. Handles parent/extended views.
  631. *
  632. * @param string $viewFile Filename of the view
  633. * @param array $data Data to include in rendered view. If empty the current
  634. * View::$viewVars will be used.
  635. * @return string Rendered output
  636. * @throws \LogicException When a block is left open.
  637. */
  638. protected function _render($viewFile, $data = array()) {
  639. if (empty($data)) {
  640. $data = $this->viewVars;
  641. }
  642. $this->_current = $viewFile;
  643. $initialBlocks = count($this->Blocks->unclosed());
  644. $this->dispatchEvent('View.beforeRenderFile', [$viewFile]);
  645. $content = $this->_evaluate($viewFile, $data);
  646. $afterEvent = $this->dispatchEvent('View.afterRenderFile', [$viewFile, $content]);
  647. if (isset($afterEvent->result)) {
  648. $content = $afterEvent->result;
  649. }
  650. if (isset($this->_parents[$viewFile])) {
  651. $this->_stack[] = $this->fetch('content');
  652. $this->assign('content', $content);
  653. $content = $this->_render($this->_parents[$viewFile]);
  654. $this->assign('content', array_pop($this->_stack));
  655. }
  656. $remainingBlocks = count($this->Blocks->unclosed());
  657. if ($initialBlocks !== $remainingBlocks) {
  658. throw new LogicException(sprintf(
  659. 'The "%s" block was left open. Blocks are not allowed to cross files.',
  660. $this->Blocks->active()
  661. ));
  662. }
  663. return $content;
  664. }
  665. /**
  666. * Sandbox method to evaluate a template / view script in.
  667. *
  668. * @param string $viewFile Filename of the view
  669. * @param array $dataForView Data to include in rendered view.
  670. * If empty the current View::$viewVars will be used.
  671. * @return string Rendered output
  672. */
  673. protected function _evaluate($viewFile, $dataForView) {
  674. $this->__viewFile = $viewFile;
  675. extract($dataForView);
  676. ob_start();
  677. include $this->__viewFile;
  678. unset($this->__viewFile);
  679. return ob_get_clean();
  680. }
  681. /**
  682. * Get the helper registry in use by this View class.
  683. *
  684. * @return \Cake\View\HelperRegistry
  685. */
  686. public function helpers() {
  687. if ($this->_helpers === null) {
  688. $this->_helpers = new HelperRegistry($this);
  689. }
  690. return $this->_helpers;
  691. }
  692. /**
  693. * Alias for loadHelper() for backwards compatibility.
  694. *
  695. * @param string $helperName Name of the helper to load.
  696. * @param array $config Settings for the helper
  697. * @return Helper a constructed helper object.
  698. * @deprecated 3.0.0 Use loadHelper() instead.
  699. */
  700. public function addHelper($helperName, array $config = []) {
  701. trigger_error(
  702. 'addHelper() is deprecated, use loadHelper() instead.',
  703. E_USER_DEPRECATED
  704. );
  705. return $this->loadHelper($helperName, $config);
  706. }
  707. /**
  708. * Loads a helper. Delegates to the `HelperRegistry::load()` to load the helper
  709. *
  710. * @param string $name Name of the helper to load.
  711. * @param array $config Settings for the helper
  712. * @return Helper a constructed helper object.
  713. * @see HelperRegistry::load()
  714. */
  715. public function loadHelper($name, array $config = []) {
  716. list(, $class) = pluginSplit($name);
  717. $helpers = $this->helpers();
  718. return $this->{$class} = $helpers->load($name, $config);
  719. }
  720. /**
  721. * Returns filename of given action's template file (.ctp) as a string.
  722. * CamelCased action names will be under_scored! This means that you can have
  723. * LongActionNames that refer to long_action_names.ctp views.
  724. *
  725. * @param string $name Controller action to find template filename for
  726. * @return string Template filename
  727. * @throws \Cake\View\Exception\MissingTemplateException when a view file could not be found.
  728. */
  729. protected function _getViewFileName($name = null) {
  730. $subDir = null;
  731. if ($this->subDir !== null) {
  732. $subDir = $this->subDir . DS;
  733. }
  734. if ($name === null) {
  735. $name = $this->view;
  736. }
  737. list($plugin, $name) = $this->pluginSplit($name);
  738. $name = str_replace('/', DS, $name);
  739. if (strpos($name, DS) === false && $name[0] !== '.') {
  740. $name = $this->viewPath . DS . $subDir . Inflector::underscore($name);
  741. } elseif (strpos($name, DS) !== false) {
  742. if ($name[0] === DS || $name[1] === ':') {
  743. if (is_file($name)) {
  744. return $name;
  745. }
  746. $name = trim($name, DS);
  747. } elseif (!$plugin || $this->viewPath !== $this->name) {
  748. $name = $this->viewPath . DS . $subDir . $name;
  749. } else {
  750. $name = DS . $subDir . $name;
  751. }
  752. }
  753. foreach ($this->_paths($plugin) as $path) {
  754. if (file_exists($path . $name . $this->_ext)) {
  755. return $this->_checkFilePath($path . $name . $this->_ext, $path);
  756. }
  757. }
  758. throw new Exception\MissingTemplateException(array('file' => $name . $this->_ext));
  759. }
  760. /**
  761. * Check that a view file path does not go outside of the defined template paths.
  762. *
  763. * Only paths that contain `..` will be checked, as they are the ones most likely to
  764. * have the ability to resolve to files outside of the template paths.
  765. *
  766. * @param string $file The path to the template file.
  767. * @param string $path Base path that $file should be inside of.
  768. * @return string The file path
  769. * @throws \InvalidArgumentException
  770. */
  771. protected function _checkFilePath($file, $path) {
  772. if (strpos($file, '..') === false) {
  773. return $file;
  774. }
  775. $absolute = realpath($file);
  776. if (strpos($absolute, $path) !== 0) {
  777. throw new InvalidArgumentException(sprintf(
  778. 'Cannot use "%s" as a template, it is not within any view template path.',
  779. $file
  780. ));
  781. }
  782. return $absolute;
  783. }
  784. /**
  785. * Splits a dot syntax plugin name into its plugin and filename.
  786. * If $name does not have a dot, then index 0 will be null.
  787. * It checks if the plugin is loaded, else filename will stay unchanged for filenames containing dot
  788. *
  789. * @param string $name The name you want to plugin split.
  790. * @param bool $fallback If true uses the plugin set in the current Request when parsed plugin is not loaded
  791. * @return array Array with 2 indexes. 0 => plugin name, 1 => filename
  792. */
  793. public function pluginSplit($name, $fallback = true) {
  794. $plugin = null;
  795. list($first, $second) = pluginSplit($name);
  796. if (Plugin::loaded($first) === true) {
  797. $name = $second;
  798. $plugin = $first;
  799. }
  800. if (isset($this->plugin) && !$plugin && $fallback) {
  801. $plugin = $this->plugin;
  802. }
  803. return array($plugin, $name);
  804. }
  805. /**
  806. * Returns layout filename for this template as a string.
  807. *
  808. * @param string $name The name of the layout to find.
  809. * @return string Filename for layout file (.ctp).
  810. * @throws \Cake\View\Exception\MissingLayoutException when a layout cannot be located
  811. */
  812. protected function _getLayoutFileName($name = null) {
  813. if ($name === null) {
  814. $name = $this->layout;
  815. }
  816. $subDir = null;
  817. if ($this->layoutPath !== null) {
  818. $subDir = $this->layoutPath . DS;
  819. }
  820. list($plugin, $name) = $this->pluginSplit($name);
  821. $layoutPaths = ['Layout' . DS . $subDir];
  822. if (!empty($this->request->params['prefix'])) {
  823. array_unshift(
  824. $layoutPaths,
  825. Inflector::camelize($this->request->params['prefix']) . DS . $layoutPaths[0]
  826. );
  827. }
  828. foreach ($this->_paths($plugin) as $path) {
  829. foreach ($layoutPaths as $layoutPath) {
  830. $currentPath = $path . $layoutPath;
  831. if (file_exists($currentPath . $name . $this->_ext)) {
  832. return $this->_checkFilePath($currentPath . $name . $this->_ext, $currentPath);
  833. }
  834. }
  835. }
  836. throw new Exception\MissingLayoutException(array(
  837. 'file' => $layoutPaths[0] . $name . $this->_ext
  838. ));
  839. }
  840. /**
  841. * Finds an element filename, returns false on failure.
  842. *
  843. * @param string $name The name of the element to find.
  844. * @return mixed Either a string to the element filename or false when one can't be found.
  845. */
  846. protected function _getElementFileName($name) {
  847. list($plugin, $name) = $this->pluginSplit($name);
  848. $paths = $this->_paths($plugin);
  849. foreach ($paths as $path) {
  850. if (file_exists($path . 'Element' . DS . $name . $this->_ext)) {
  851. return $path . 'Element' . DS . $name . $this->_ext;
  852. }
  853. }
  854. return false;
  855. }
  856. /**
  857. * Return all possible paths to find view files in order
  858. *
  859. * @param string $plugin Optional plugin name to scan for view files.
  860. * @param bool $cached Set to false to force a refresh of view paths. Default true.
  861. * @return array paths
  862. */
  863. protected function _paths($plugin = null, $cached = true) {
  864. if ($cached === true) {
  865. if ($plugin === null && !empty($this->_paths)) {
  866. return $this->_paths;
  867. }
  868. if ($plugin !== null && isset($this->_pathsForPlugin[$plugin])) {
  869. return $this->_pathsForPlugin[$plugin];
  870. }
  871. }
  872. $viewPaths = App::path('Template');
  873. $pluginPaths = $themePaths = [];
  874. if (!empty($plugin)) {
  875. for ($i = 0, $count = count($viewPaths); $i < $count; $i++) {
  876. $pluginPaths[] = $viewPaths[$i] . 'Plugin' . DS . $plugin . DS;
  877. }
  878. $pluginPaths = array_merge($pluginPaths, App::path('Template', $plugin));
  879. }
  880. if (!empty($this->theme)) {
  881. $themePaths = App::path('Template', Inflector::camelize($this->theme));
  882. if ($plugin) {
  883. for ($i = 0, $count = count($viewPaths); $i < $count; $i++) {
  884. array_unshift($themePaths, $themePaths[$i] . 'Plugin' . DS . $plugin . DS);
  885. }
  886. }
  887. }
  888. $paths = array_merge($themePaths, $pluginPaths, $viewPaths, App::core('Template'));
  889. if ($plugin !== null) {
  890. return $this->_pathsForPlugin[$plugin] = $paths;
  891. }
  892. return $this->_paths = $paths;
  893. }
  894. /**
  895. * Checks if an element is cached and returns the cached data if present
  896. *
  897. * @param string $name Element name
  898. * @param array $data Data
  899. * @param array $options Element options
  900. * @return string|null
  901. */
  902. protected function _elementCache($name, $data, $options) {
  903. $plugin = null;
  904. list($plugin, $name) = $this->pluginSplit($name);
  905. $underscored = null;
  906. if ($plugin) {
  907. $underscored = Inflector::underscore($plugin);
  908. }
  909. $keys = array_merge(array($underscored, $name), array_keys($options), array_keys($data));
  910. $this->elementCacheSettings = array(
  911. 'config' => $this->elementCache,
  912. 'key' => implode('_', $keys)
  913. );
  914. if (is_array($options['cache'])) {
  915. $defaults = array(
  916. 'config' => $this->elementCache,
  917. 'key' => $this->elementCacheSettings['key']
  918. );
  919. $this->elementCacheSettings = $options['cache'] + $defaults;
  920. }
  921. $this->elementCacheSettings['key'] = 'element_' . $this->elementCacheSettings['key'];
  922. return Cache::read($this->elementCacheSettings['key'], $this->elementCacheSettings['config']);
  923. }
  924. /**
  925. * Renders an element and fires the before and afterRender callbacks for it
  926. * and writes to the cache if a cache is used
  927. *
  928. * @param string $file Element file path
  929. * @param array $data Data to render
  930. * @param array $options Element options
  931. * @return string
  932. */
  933. protected function _renderElement($file, $data, $options) {
  934. $current = $this->_current;
  935. $restore = $this->_currentType;
  936. $this->_currentType = static::TYPE_ELEMENT;
  937. if ($options['callbacks']) {
  938. $this->dispatchEvent('View.beforeRender', [$file]);
  939. }
  940. $element = $this->_render($file, array_merge($this->viewVars, $data));
  941. if ($options['callbacks']) {
  942. $this->dispatchEvent('View.afterRender', [$file, $element]);
  943. }
  944. $this->_currentType = $restore;
  945. $this->_current = $current;
  946. if (isset($options['cache'])) {
  947. Cache::write($this->elementCacheSettings['key'], $element, $this->elementCacheSettings['config']);
  948. }
  949. return $element;
  950. }
  951. }