View.php 33 KB

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