View.php 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118
  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-2012, 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-2012, 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 $controller = null) {
  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)) {
  299. $this->_eventManager = new CakeEventManager();
  300. }
  301. if (!$this->_eventManagerConfigured) {
  302. $this->_eventManager->attach($this->Helpers);
  303. $this->_eventManagerConfigured = true;
  304. }
  305. return $this->_eventManager;
  306. }
  307. /**
  308. * Renders a piece of PHP with provided parameters and returns HTML, XML, or any other string.
  309. *
  310. * This realizes the concept of Elements, (or "partial layouts") and the $params array is used to send
  311. * data to be used in the element. Elements can be cached improving performance by using the `cache` option.
  312. *
  313. * @param string $name Name of template file in the/app/View/Elements/ folder,
  314. * or `MyPlugin.template` to use the template element from MyPlugin. If the element
  315. * is not found in the plugin, the normal view path cascade will be searched.
  316. * @param array $data Array of data to be made available to the rendered view (i.e. the Element)
  317. * @param array $options Array of options. Possible keys are:
  318. * - `cache` - Can either be `true`, to enable caching using the config in View::$elementCache. Or an array
  319. * If an array, the following keys can be used:
  320. * - `config` - Used to store the cached element in a custom cache configuration.
  321. * - `key` - Used to define the key used in the Cache::write(). It will be prefixed with `element_`
  322. * - `plugin` - Load an element from a specific plugin. This option is deprecated, see below.
  323. * - `callbacks` - Set to true to fire beforeRender and afterRender helper callbacks for this element.
  324. * Defaults to false.
  325. * @return string Rendered Element
  326. * @deprecated The `$options['plugin']` is deprecated and will be removed in CakePHP 3.0. Use
  327. * `Plugin.element_name` instead.
  328. */
  329. public function element($name, $data = array(), $options = array()) {
  330. $file = $plugin = $key = null;
  331. $callbacks = false;
  332. if (isset($options['plugin'])) {
  333. $name = Inflector::camelize($options['plugin']) . '.' . $name;
  334. }
  335. if (isset($options['callbacks'])) {
  336. $callbacks = $options['callbacks'];
  337. }
  338. if (isset($options['cache'])) {
  339. $underscored = null;
  340. if ($plugin) {
  341. $underscored = Inflector::underscore($plugin);
  342. }
  343. $keys = array_merge(array($underscored, $name), array_keys($options), array_keys($data));
  344. $caching = array(
  345. 'config' => $this->elementCache,
  346. 'key' => implode('_', $keys)
  347. );
  348. if (is_array($options['cache'])) {
  349. $defaults = array(
  350. 'config' => $this->elementCache,
  351. 'key' => $caching['key']
  352. );
  353. $caching = array_merge($defaults, $options['cache']);
  354. }
  355. $key = 'element_' . $caching['key'];
  356. $contents = Cache::read($key, $caching['config']);
  357. if ($contents !== false) {
  358. return $contents;
  359. }
  360. }
  361. $file = $this->_getElementFilename($name);
  362. if ($file) {
  363. if (!$this->_helpersLoaded) {
  364. $this->loadHelpers();
  365. }
  366. if ($callbacks) {
  367. $this->getEventManager()->dispatch(new CakeEvent('View.beforeRender', $this, array($file)));
  368. }
  369. $this->_currentType = self::TYPE_ELEMENT;
  370. $element = $this->_render($file, array_merge($this->viewVars, $data));
  371. if ($callbacks) {
  372. $this->getEventManager()->dispatch(new CakeEvent('View.afterRender', $this, array($file, $element)));
  373. }
  374. if (isset($options['cache'])) {
  375. Cache::write($key, $element, $caching['config']);
  376. }
  377. return $element;
  378. }
  379. $file = 'Elements' . DS . $name . $this->ext;
  380. if (Configure::read('debug') > 0) {
  381. return __d('cake_dev', 'Element Not Found: %s', $file);
  382. }
  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. if (!$this->_helpersLoaded) {
  411. $this->loadHelpers();
  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 (!$this->_helpersLoaded) {
  458. $this->loadHelpers();
  459. }
  460. if (empty($content)) {
  461. $content = $this->Blocks->get('content');
  462. }
  463. $this->getEventManager()->dispatch(new CakeEvent('View.beforeLayout', $this, array($layoutFileName)));
  464. $scripts = implode("\n\t", $this->_scripts);
  465. $scripts .= $this->Blocks->get('meta') . $this->Blocks->get('css') . $this->Blocks->get('script');
  466. $this->viewVars = array_merge($this->viewVars, array(
  467. 'content_for_layout' => $content,
  468. 'scripts_for_layout' => $scripts,
  469. ));
  470. if (!isset($this->viewVars['title_for_layout'])) {
  471. $this->viewVars['title_for_layout'] = Inflector::humanize($this->viewPath);
  472. }
  473. $this->_currentType = self::TYPE_LAYOUT;
  474. $this->Blocks->set('content', $this->_render($layoutFileName));
  475. $this->getEventManager()->dispatch(new CakeEvent('View.afterLayout', $this, array($layoutFileName)));
  476. return $this->Blocks->get('content');
  477. }
  478. /**
  479. * Render cached view. Works in concert with CacheHelper and Dispatcher to
  480. * render cached view files.
  481. *
  482. * @param string $filename the cache file to include
  483. * @param string $timeStart the page render start time
  484. * @return boolean Success of rendering the cached file.
  485. */
  486. public function renderCache($filename, $timeStart) {
  487. ob_start();
  488. include ($filename);
  489. if (Configure::read('debug') > 0 && $this->layout != 'xml') {
  490. echo "<!-- Cached Render Time: " . round(microtime(true) - $timeStart, 4) . "s -->";
  491. }
  492. $out = ob_get_clean();
  493. if (preg_match('/^<!--cachetime:(\\d+)-->/', $out, $match)) {
  494. if (time() >= $match['1']) {
  495. @unlink($filename);
  496. unset ($out);
  497. return false;
  498. } else {
  499. if ($this->layout === 'xml') {
  500. header('Content-type: text/xml');
  501. }
  502. $commentLength = strlen('<!--cachetime:' . $match['1'] . '-->');
  503. echo substr($out, $commentLength);
  504. return true;
  505. }
  506. }
  507. }
  508. /**
  509. * Returns a list of variables available in the current View context
  510. *
  511. * @return array Array of the set view variable names.
  512. */
  513. public function getVars() {
  514. return array_keys($this->viewVars);
  515. }
  516. /**
  517. * Returns the contents of the given View variable(s)
  518. *
  519. * @param string $var The view var you want the contents of.
  520. * @return mixed The content of the named var if its set, otherwise null.
  521. * @deprecated Will be removed in 3.0 Use View::get() instead.
  522. */
  523. public function getVar($var) {
  524. return $this->get($var);
  525. }
  526. /**
  527. * Returns the contents of the given View variable or a block.
  528. * Blocks are checked before view variables.
  529. *
  530. * @param string $var The view var you want the contents of.
  531. * @return mixed The content of the named var if its set, otherwise null.
  532. */
  533. public function get($var) {
  534. if (!isset($this->viewVars[$var])) {
  535. return null;
  536. }
  537. return $this->viewVars[$var];
  538. }
  539. /**
  540. * Get the names of all the existing blocks.
  541. *
  542. * @return array An array containing the blocks.
  543. * @see ViewBlock::keys()
  544. */
  545. public function blocks() {
  546. return $this->Blocks->keys();
  547. }
  548. /**
  549. * Start capturing output for a 'block'
  550. *
  551. * @param string $name The name of the block to capture for.
  552. * @return void
  553. * @see ViewBlock::start()
  554. */
  555. public function start($name) {
  556. return $this->Blocks->start($name);
  557. }
  558. /**
  559. * Append to an existing or new block. Appending to a new
  560. * block will create the block.
  561. *
  562. * @param string $name Name of the block
  563. * @param string $value The content for the block.
  564. * @return void
  565. * @throws CakeException when you use non-string values.
  566. * @see ViewBlock::append()
  567. */
  568. public function append($name, $value = null) {
  569. return $this->Blocks->append($name, $value);
  570. }
  571. /**
  572. * Set the content for a block. This will overwrite any
  573. * existing content.
  574. *
  575. * @param string $name Name of the block
  576. * @param string $value The content for the block.
  577. * @return void
  578. * @throws CakeException when you use non-string values.
  579. * @see ViewBlock::assign()
  580. */
  581. public function assign($name, $value) {
  582. return $this->Blocks->set($name, $value);
  583. }
  584. /**
  585. * Fetch the content for a block. If a block is
  586. * empty or undefined '' will be returned.
  587. *
  588. * @param string $name Name of the block
  589. * @return The block content or '' if the block does not exist.
  590. * @see ViewBlock::fetch()
  591. */
  592. public function fetch($name) {
  593. return $this->Blocks->get($name);
  594. }
  595. /**
  596. * End a capturing block. The compliment to View::start()
  597. *
  598. * @return void
  599. * @see ViewBlock::start()
  600. */
  601. public function end() {
  602. return $this->Blocks->end();
  603. }
  604. /**
  605. * Provides view or element extension/inheritance. Views can extends a
  606. * parent view and populate blocks in the parent template.
  607. *
  608. * @param string $name The view or element to 'extend' the current one with.
  609. * @return void
  610. * @throws LogicException when you extend a view with itself or make extend loops.
  611. * @throws LogicException when you extend an element which doesn't exist
  612. */
  613. public function extend($name) {
  614. if ($name[0] === '/' || $this->_currentType === self::TYPE_VIEW) {
  615. $parent = $this->_getViewFileName($name);
  616. } else {
  617. switch ($this->_currentType) {
  618. case self::TYPE_ELEMENT:
  619. $parent = $this->_getElementFileName($name);
  620. if (!$parent) {
  621. list($plugin, $name) = $this->pluginSplit($name);
  622. $paths = $this->_paths($plugin);
  623. $defaultPath = $paths[0] . 'Elements' . DS;
  624. throw new LogicException(__d(
  625. 'cake_dev',
  626. 'You cannot extend an element which does not exist (%s).',
  627. $defaultPath . $name . $this->ext
  628. ));
  629. }
  630. break;
  631. case self::TYPE_LAYOUT:
  632. $parent = $this->_getLayoutFileName($name);
  633. break;
  634. default:
  635. $parent = $this->_getViewFileName($name);
  636. }
  637. }
  638. if ($parent == $this->_current) {
  639. throw new LogicException(__d('cake_dev', 'You cannot have views extend themselves.'));
  640. }
  641. if (isset($this->_parents[$parent]) && $this->_parents[$parent] == $this->_current) {
  642. throw new LogicException(__d('cake_dev', 'You cannot have views extend in a loop.'));
  643. }
  644. $this->_parents[$this->_current] = $parent;
  645. }
  646. /**
  647. * Adds a script block or other element to be inserted in $scripts_for_layout in
  648. * the `<head />` of a document layout
  649. *
  650. * @param string $name Either the key name for the script, or the script content. Name can be used to
  651. * update/replace a script element.
  652. * @param string $content The content of the script being added, optional.
  653. * @return void
  654. * @deprecated Will be removed in 3.0. Supersceeded by blocks functionality.
  655. * @see View::start()
  656. */
  657. public function addScript($name, $content = null) {
  658. if (empty($content)) {
  659. if (!in_array($name, array_values($this->_scripts))) {
  660. $this->_scripts[] = $name;
  661. }
  662. } else {
  663. $this->_scripts[$name] = $content;
  664. }
  665. }
  666. /**
  667. * Generates a unique, non-random DOM ID for an object, based on the object type and the target URL.
  668. *
  669. * @param string $object Type of object, i.e. 'form' or 'link'
  670. * @param string $url The object's target URL
  671. * @return string
  672. */
  673. public function uuid($object, $url) {
  674. $c = 1;
  675. $url = Router::url($url);
  676. $hash = $object . substr(md5($object . $url), 0, 10);
  677. while (in_array($hash, $this->uuids)) {
  678. $hash = $object . substr(md5($object . $url . $c), 0, 10);
  679. $c++;
  680. }
  681. $this->uuids[] = $hash;
  682. return $hash;
  683. }
  684. /**
  685. * Allows a template or element to set a variable that will be available in
  686. * a layout or other element. Analogous to Controller::set().
  687. *
  688. * @param mixed $one A string or an array of data.
  689. * @param mixed $two Value in case $one is a string (which then works as the key).
  690. * Unused if $one is an associative array, otherwise serves as the values to $one's keys.
  691. * @return void
  692. */
  693. public function set($one, $two = null) {
  694. $data = null;
  695. if (is_array($one)) {
  696. if (is_array($two)) {
  697. $data = array_combine($one, $two);
  698. } else {
  699. $data = $one;
  700. }
  701. } else {
  702. $data = array($one => $two);
  703. }
  704. if ($data == null) {
  705. return false;
  706. }
  707. $this->viewVars = $data + $this->viewVars;
  708. }
  709. /**
  710. * Magic accessor for helpers. Provides access to attributes that were deprecated.
  711. *
  712. * @param string $name Name of the attribute to get.
  713. * @return mixed
  714. */
  715. public function __get($name) {
  716. if (isset($this->Helpers->{$name})) {
  717. return $this->Helpers->{$name};
  718. }
  719. switch ($name) {
  720. case 'base':
  721. case 'here':
  722. case 'webroot':
  723. case 'data':
  724. return $this->request->{$name};
  725. case 'action':
  726. return $this->request->params['action'];
  727. case 'params':
  728. return $this->request;
  729. case 'output':
  730. return $this->Blocks->get('content');
  731. default:
  732. return $this->{$name};
  733. }
  734. }
  735. /**
  736. * Magic accessor for deprecated attributes.
  737. *
  738. * @param string $name Name of the attribute to set.
  739. * @param string $value Value of the attribute to set.
  740. * @return mixed
  741. */
  742. public function __set($name, $value) {
  743. switch ($name) {
  744. case 'output':
  745. return $this->Blocks->set('content', $value);
  746. default:
  747. $this->{$name} = $value;
  748. }
  749. }
  750. /**
  751. * Magic isset check for deprecated attributes.
  752. *
  753. * @param string $name Name of the attribute to check.
  754. * @return boolean
  755. */
  756. public function __isset($name) {
  757. if (isset($this->{$name})) {
  758. return true;
  759. }
  760. $magicGet = array('base', 'here', 'webroot', 'data', 'action', 'params', 'output');
  761. if (in_array($name, $magicGet)) {
  762. return $this->__get($name) !== null;
  763. }
  764. return false;
  765. }
  766. /**
  767. * Interact with the HelperCollection to load all the helpers.
  768. *
  769. * @return void
  770. */
  771. public function loadHelpers() {
  772. $helpers = HelperCollection::normalizeObjectArray($this->helpers);
  773. foreach ($helpers as $name => $properties) {
  774. list($plugin, $class) = pluginSplit($properties['class']);
  775. $this->{$class} = $this->Helpers->load($properties['class'], $properties['settings']);
  776. }
  777. $this->_helpersLoaded = true;
  778. }
  779. /**
  780. * Renders and returns output for given view filename with its
  781. * array of data. Handles parent/extended views.
  782. *
  783. * @param string $viewFile Filename of the view
  784. * @param array $data Data to include in rendered view. If empty the current View::$viewVars will be used.
  785. * @return string Rendered output
  786. * @throws CakeException when a block is left open.
  787. */
  788. protected function _render($viewFile, $data = array()) {
  789. if (empty($data)) {
  790. $data = $this->viewVars;
  791. }
  792. $this->_current = $viewFile;
  793. $initialBlocks = count($this->Blocks->unclosed());
  794. $this->getEventManager()->dispatch(new CakeEvent('View.beforeRenderFile', $this, array($viewFile)));
  795. $content = $this->_evaluate($viewFile, $data);
  796. $afterEvent = new CakeEvent('View.afterRenderFile', $this, array($viewFile, $content));
  797. //TODO: For BC puporses, set extra info in the event object. Remove when appropriate
  798. $afterEvent->modParams = 1;
  799. $this->getEventManager()->dispatch($afterEvent);
  800. $content = $afterEvent->data[1];
  801. if (isset($this->_parents[$viewFile])) {
  802. $this->_stack[] = $this->fetch('content');
  803. $this->assign('content', $content);
  804. $content = $this->_render($this->_parents[$viewFile]);
  805. $this->assign('content', array_pop($this->_stack));
  806. }
  807. $remainingBlocks = count($this->Blocks->unclosed());
  808. if ($initialBlocks !== $remainingBlocks) {
  809. throw new CakeException(__d('cake_dev', 'The "%s" block was left open. Blocks are not allowed to cross files.', $this->Blocks->active()));
  810. }
  811. return $content;
  812. }
  813. /**
  814. * Sandbox method to evaluate a template / view script in.
  815. *
  816. * @param string $___viewFn Filename of the view
  817. * @param array $___dataForView Data to include in rendered view.
  818. * If empty the current View::$viewVars will be used.
  819. * @return string Rendered output
  820. */
  821. protected function _evaluate($___viewFn, $___dataForView) {
  822. extract($___dataForView, EXTR_SKIP);
  823. ob_start();
  824. include $___viewFn;
  825. return ob_get_clean();
  826. }
  827. /**
  828. * Loads a helper. Delegates to the `HelperCollection::load()` to load the helper
  829. *
  830. * @param string $helperName Name of the helper to load.
  831. * @param array $settings Settings for the helper
  832. * @return Helper a constructed helper object.
  833. * @see HelperCollection::load()
  834. */
  835. public function loadHelper($helperName, $settings = array()) {
  836. return $this->Helpers->load($helperName, $settings);
  837. }
  838. /**
  839. * Returns filename of given action's template file (.ctp) as a string.
  840. * CamelCased action names will be under_scored! This means that you can have
  841. * LongActionNames that refer to long_action_names.ctp views.
  842. *
  843. * @param string $name Controller action to find template filename for
  844. * @return string Template filename
  845. * @throws MissingViewException when a view file could not be found.
  846. */
  847. protected function _getViewFileName($name = null) {
  848. $subDir = null;
  849. if (!is_null($this->subDir)) {
  850. $subDir = $this->subDir . DS;
  851. }
  852. if ($name === null) {
  853. $name = $this->view;
  854. }
  855. $name = str_replace('/', DS, $name);
  856. list($plugin, $name) = $this->pluginSplit($name);
  857. if (strpos($name, DS) === false && $name[0] !== '.') {
  858. $name = $this->viewPath . DS . $subDir . Inflector::underscore($name);
  859. } elseif (strpos($name, DS) !== false) {
  860. if ($name[0] === DS || $name[1] === ':') {
  861. if (is_file($name)) {
  862. return $name;
  863. }
  864. $name = trim($name, DS);
  865. } elseif ($name[0] === '.') {
  866. $name = substr($name, 3);
  867. } elseif (!$plugin || $this->viewPath !== $this->name) {
  868. $name = $this->viewPath . DS . $subDir . $name;
  869. }
  870. }
  871. $paths = $this->_paths($plugin);
  872. $exts = $this->_getExtensions();
  873. foreach ($exts as $ext) {
  874. foreach ($paths as $path) {
  875. if (file_exists($path . $name . $ext)) {
  876. return $path . $name . $ext;
  877. }
  878. }
  879. }
  880. $defaultPath = $paths[0];
  881. if ($this->plugin) {
  882. $pluginPaths = App::path('plugins');
  883. foreach ($paths as $path) {
  884. if (strpos($path, $pluginPaths[0]) === 0) {
  885. $defaultPath = $path;
  886. break;
  887. }
  888. }
  889. }
  890. throw new MissingViewException(array('file' => $defaultPath . $name . $this->ext));
  891. }
  892. /**
  893. * Splits a dot syntax plugin name into its plugin and filename.
  894. * If $name does not have a dot, then index 0 will be null.
  895. * It checks if the plugin is loaded, else filename will stay unchanged for filenames containing dot
  896. *
  897. * @param string $name The name you want to plugin split.
  898. * @param boolean $fallback If true uses the plugin set in the current CakeRequest when parsed plugin is not loaded
  899. * @return array Array with 2 indexes. 0 => plugin name, 1 => filename
  900. */
  901. public function pluginSplit($name, $fallback = true) {
  902. $plugin = null;
  903. list($first, $second) = pluginSplit($name);
  904. if (CakePlugin::loaded($first) === true) {
  905. $name = $second;
  906. $plugin = $first;
  907. }
  908. if (isset($this->plugin) && !$plugin && $fallback) {
  909. $plugin = $this->plugin;
  910. }
  911. return array($plugin, $name);
  912. }
  913. /**
  914. * Returns layout filename for this template as a string.
  915. *
  916. * @param string $name The name of the layout to find.
  917. * @return string Filename for layout file (.ctp).
  918. * @throws MissingLayoutException when a layout cannot be located
  919. */
  920. protected function _getLayoutFileName($name = null) {
  921. if ($name === null) {
  922. $name = $this->layout;
  923. }
  924. $subDir = null;
  925. if (!is_null($this->layoutPath)) {
  926. $subDir = $this->layoutPath . DS;
  927. }
  928. list($plugin, $name) = $this->pluginSplit($name);
  929. $paths = $this->_paths($plugin);
  930. $file = 'Layouts' . DS . $subDir . $name;
  931. $exts = $this->_getExtensions();
  932. foreach ($exts as $ext) {
  933. foreach ($paths as $path) {
  934. if (file_exists($path . $file . $ext)) {
  935. return $path . $file . $ext;
  936. }
  937. }
  938. }
  939. throw new MissingLayoutException(array('file' => $paths[0] . $file . $this->ext));
  940. }
  941. /**
  942. * Get the extensions that view files can use.
  943. *
  944. * @return array Array of extensions view files use.
  945. */
  946. protected function _getExtensions() {
  947. $exts = array($this->ext);
  948. if ($this->ext !== '.ctp') {
  949. array_push($exts, '.ctp');
  950. }
  951. return $exts;
  952. }
  953. /**
  954. * Finds an element filename, returns false on failure.
  955. *
  956. * @param string $name The name of the element to find.
  957. * @return mixed Either a string to the element filename or false when one can't be found.
  958. */
  959. protected function _getElementFileName($name) {
  960. list($plugin, $name) = $this->pluginSplit($name);
  961. $paths = $this->_paths($plugin);
  962. $exts = $this->_getExtensions();
  963. foreach ($exts as $ext) {
  964. foreach ($paths as $path) {
  965. if (file_exists($path . 'Elements' . DS . $name . $ext)) {
  966. return $path . 'Elements' . DS . $name . $ext;
  967. }
  968. }
  969. }
  970. return false;
  971. }
  972. /**
  973. * Return all possible paths to find view files in order
  974. *
  975. * @param string $plugin Optional plugin name to scan for view files.
  976. * @param boolean $cached Set to true to force a refresh of view paths.
  977. * @return array paths
  978. */
  979. protected function _paths($plugin = null, $cached = true) {
  980. if ($plugin === null && $cached === true && !empty($this->_paths)) {
  981. return $this->_paths;
  982. }
  983. $paths = array();
  984. $viewPaths = App::path('View');
  985. $corePaths = array_merge(App::core('View'), App::core('Console/Templates/skel/View'));
  986. if (!empty($plugin)) {
  987. $count = count($viewPaths);
  988. for ($i = 0; $i < $count; $i++) {
  989. if (!in_array($viewPaths[$i], $corePaths)) {
  990. $paths[] = $viewPaths[$i] . 'Plugin' . DS . $plugin . DS;
  991. }
  992. }
  993. $paths = array_merge($paths, App::path('View', $plugin));
  994. }
  995. $paths = array_unique(array_merge($paths, $viewPaths));
  996. if (!empty($this->theme)) {
  997. $themePaths = array();
  998. foreach ($paths as $path) {
  999. if (strpos($path, DS . 'Plugin' . DS) === false) {
  1000. if ($plugin) {
  1001. $themePaths[] = $path . 'Themed' . DS . $this->theme . DS . 'Plugin' . DS . $plugin . DS;
  1002. }
  1003. $themePaths[] = $path . 'Themed' . DS . $this->theme . DS;
  1004. }
  1005. }
  1006. $paths = array_merge($themePaths, $paths);
  1007. }
  1008. $paths = array_merge($paths, $corePaths);
  1009. if ($plugin !== null) {
  1010. return $paths;
  1011. }
  1012. return $this->_paths = $paths;
  1013. }
  1014. }