View.php 42 KB

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