View.php 31 KB

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