View.php 37 KB

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