View.php 34 KB

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