View.php 34 KB

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