View.php 34 KB

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