View.php 29 KB

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