View.php 33 KB

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