View.php 32 KB

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