View.php 30 KB

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