View.php 34 KB

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