View.php 34 KB

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