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 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. * Element cache settings
  199. *
  200. * @var array
  201. * @see View::_elementCache();
  202. * @see View::_renderElement
  203. */
  204. public $elementCacheSettings = array();
  205. /**
  206. * List of variables to collect from the associated controller.
  207. *
  208. * @var array
  209. */
  210. protected $_passedVars = array(
  211. 'viewVars', 'autoLayout', 'ext', 'helpers', 'view', 'layout', 'name', 'theme',
  212. 'layoutPath', 'viewPath', 'request', 'plugin', 'passedArgs', 'cacheAction'
  213. );
  214. /**
  215. * Scripts (and/or other <head /> tags) for the layout.
  216. *
  217. * @var array
  218. */
  219. protected $_scripts = array();
  220. /**
  221. * Holds an array of paths.
  222. *
  223. * @var array
  224. */
  225. protected $_paths = array();
  226. /**
  227. * Indicate that helpers have been loaded.
  228. *
  229. * @var boolean
  230. */
  231. protected $_helpersLoaded = false;
  232. /**
  233. * The names of views and their parents used with View::extend();
  234. *
  235. * @var array
  236. */
  237. protected $_parents = array();
  238. /**
  239. * The currently rendering view file. Used for resolving parent files.
  240. *
  241. * @var string
  242. */
  243. protected $_current = null;
  244. /**
  245. * Currently rendering an element. Used for finding parent fragments
  246. * for elements.
  247. *
  248. * @var string
  249. */
  250. protected $_currentType = '';
  251. /**
  252. * Content stack, used for nested templates that all use View::extend();
  253. *
  254. * @var array
  255. */
  256. protected $_stack = array();
  257. /**
  258. * Instance of the CakeEventManager this View object is using
  259. * to dispatch inner events. Usually the manager is shared with
  260. * the controller, so it it possible to register view events in
  261. * the controller layer.
  262. *
  263. * @var CakeEventManager
  264. */
  265. protected $_eventManager = null;
  266. /**
  267. * Whether the event manager was already configured for this object
  268. *
  269. * @var boolean
  270. */
  271. protected $_eventManagerConfigured = false;
  272. /**
  273. * Constant for view file type 'view'
  274. */
  275. const TYPE_VIEW = 'view';
  276. /**
  277. * Constant for view file type 'element'
  278. */
  279. const TYPE_ELEMENT = 'element';
  280. /**
  281. * Constant for view file type 'layout'
  282. */
  283. const TYPE_LAYOUT = 'layout';
  284. /**
  285. * Constructor
  286. *
  287. * @param Controller $controller A controller object to pull View::_passedVars from.
  288. */
  289. public function __construct(Controller $controller = null) {
  290. if (is_object($controller)) {
  291. $count = count($this->_passedVars);
  292. for ($j = 0; $j < $count; $j++) {
  293. $var = $this->_passedVars[$j];
  294. $this->{$var} = $controller->{$var};
  295. }
  296. $this->_eventManager = $controller->getEventManager();
  297. }
  298. if (empty($this->request) && !($this->request = Router::getRequest(true))) {
  299. $this->request = new CakeRequest(null, false);
  300. $this->request->base = '';
  301. $this->request->here = $this->request->webroot = '/';
  302. }
  303. if (is_object($controller) && isset($controller->response)) {
  304. $this->response = $controller->response;
  305. } else {
  306. $this->response = new CakeResponse();
  307. }
  308. $this->Helpers = new HelperCollection($this);
  309. $this->Blocks = new ViewBlock();
  310. parent::__construct();
  311. }
  312. /**
  313. * Returns the CakeEventManager manager instance that is handling any callbacks.
  314. * You can use this instance to register any new listeners or callbacks to the
  315. * controller events, or create your own events and trigger them at will.
  316. *
  317. * @return CakeEventManager
  318. */
  319. public function getEventManager() {
  320. if (empty($this->_eventManager)) {
  321. $this->_eventManager = new CakeEventManager();
  322. }
  323. if (!$this->_eventManagerConfigured) {
  324. $this->_eventManager->attach($this->Helpers);
  325. $this->_eventManagerConfigured = true;
  326. }
  327. return $this->_eventManager;
  328. }
  329. /**
  330. * Renders a piece of PHP with provided parameters and returns HTML, XML, or any other string.
  331. *
  332. * This realizes the concept of Elements, (or "partial layouts") and the $params array is used to send
  333. * data to be used in the element. Elements can be cached improving performance by using the `cache` option.
  334. *
  335. * @param string $name Name of template file in the/app/View/Elements/ folder,
  336. * or `MyPlugin.template` to use the template element from MyPlugin. If the element
  337. * is not found in the plugin, the normal view path cascade will be searched.
  338. * @param array $data Array of data to be made available to the rendered view (i.e. the Element)
  339. * @param array $options Array of options. Possible keys are:
  340. * - `cache` - Can either be `true`, to enable caching using the config in View::$elementCache. Or an array
  341. * If an array, the following keys can be used:
  342. * - `config` - Used to store the cached element in a custom cache configuration.
  343. * - `key` - Used to define the key used in the Cache::write(). It will be prefixed with `element_`
  344. * - `plugin` - Load an element from a specific plugin. This option is deprecated, see below.
  345. * - `callbacks` - Set to true to fire beforeRender and afterRender helper callbacks for this element.
  346. * Defaults to false.
  347. * - `ignoreMissing` - Used to allow missing elements. Set to true to not trigger notices.
  348. * @return string Rendered Element
  349. * @deprecated The `$options['plugin']` is deprecated and will be removed in CakePHP 3.0. Use
  350. * `Plugin.element_name` instead.
  351. */
  352. public function element($name, $data = array(), $options = array()) {
  353. $file = $plugin = null;
  354. if (isset($options['plugin'])) {
  355. $name = Inflector::camelize($options['plugin']) . '.' . $name;
  356. }
  357. if (!isset($options['callbacks'])) {
  358. $options['callbacks'] = false;
  359. }
  360. if (isset($options['cache'])) {
  361. $contents = $this->_elementCache($name, $data, $options);
  362. if ($contents !== false) {
  363. return $contents;
  364. }
  365. }
  366. $file = $this->_getElementFilename($name);
  367. if ($file) {
  368. return $this->_renderElement($file, $data, $options);
  369. }
  370. if (empty($options['ignoreMissing'])) {
  371. list ($plugin, $name) = pluginSplit($name, true);
  372. $name = str_replace('/', DS, $name);
  373. $file = $plugin . 'Elements' . DS . $name . $this->ext;
  374. trigger_error(__d('cake_dev', 'Element Not Found: %s', $file), E_USER_NOTICE);
  375. }
  376. }
  377. /**
  378. * Checks if an element exists
  379. *
  380. * @param string $name Name of template file in the /app/View/Elements/ folder,
  381. * or `MyPlugin.template` to check the template element from MyPlugin. If the element
  382. * is not found in the plugin, the normal view path cascade will be searched.
  383. * @return boolean Success
  384. */
  385. public function elementExists($name) {
  386. return (bool)$this->_getElementFilename($name);
  387. }
  388. /**
  389. * Renders view for given view file and layout.
  390. *
  391. * Render triggers helper callbacks, which are fired before and after the view are rendered,
  392. * as well as before and after the layout. The helper callbacks are called:
  393. *
  394. * - `beforeRender`
  395. * - `afterRender`
  396. * - `beforeLayout`
  397. * - `afterLayout`
  398. *
  399. * If View::$autoRender is false and no `$layout` is provided, the view will be returned bare.
  400. *
  401. * View and layout names can point to plugin views/layouts. Using the `Plugin.view` syntax
  402. * a plugin view/layout can be used instead of the app ones. If the chosen plugin is not found
  403. * the view will be located along the regular view path cascade.
  404. *
  405. * @param string $view Name of view file to use
  406. * @param string $layout Layout to use.
  407. * @return string Rendered Element
  408. * @throws CakeException if there is an error in the view.
  409. */
  410. public function render($view = null, $layout = null) {
  411. if ($this->hasRendered) {
  412. return true;
  413. }
  414. if (!$this->_helpersLoaded) {
  415. $this->loadHelpers();
  416. }
  417. $this->Blocks->set('content', '');
  418. if ($view !== false && $viewFileName = $this->_getViewFileName($view)) {
  419. $this->_currentType = self::TYPE_VIEW;
  420. $this->getEventManager()->dispatch(new CakeEvent('View.beforeRender', $this, array($viewFileName)));
  421. $this->Blocks->set('content', $this->_render($viewFileName));
  422. $this->getEventManager()->dispatch(new CakeEvent('View.afterRender', $this, array($viewFileName)));
  423. }
  424. if ($layout === null) {
  425. $layout = $this->layout;
  426. }
  427. if ($layout && $this->autoLayout) {
  428. $this->Blocks->set('content', $this->renderLayout('', $layout));
  429. }
  430. $this->hasRendered = true;
  431. return $this->Blocks->get('content');
  432. }
  433. /**
  434. * Renders a layout. Returns output from _render(). Returns false on error.
  435. * Several variables are created for use in layout.
  436. *
  437. * - `title_for_layout` - A backwards compatible place holder, you should set this value if you want more control.
  438. * - `content_for_layout` - contains rendered view file
  439. * - `scripts_for_layout` - Contains content added with addScript() as well as any content in
  440. * the 'meta', 'css', and 'script' blocks. They are appended in that order.
  441. *
  442. * Deprecated features:
  443. *
  444. * - `$scripts_for_layout` is deprecated and will be removed in CakePHP 3.0.
  445. * Use the block features instead. `meta`, `css` and `script` will be populated
  446. * by the matching methods on HtmlHelper.
  447. * - `$title_for_layout` is deprecated and will be removed in CakePHP 3.0
  448. * - `$content_for_layout` is deprecated and will be removed in CakePHP 3.0.
  449. * Use the `content` block instead.
  450. *
  451. * @param string $content Content to render in a view, wrapped by the surrounding layout.
  452. * @param string $layout Layout name
  453. * @return mixed Rendered output, or false on error
  454. * @throws CakeException if there is an error in the view.
  455. */
  456. public function renderLayout($content, $layout = null) {
  457. $layoutFileName = $this->_getLayoutFileName($layout);
  458. if (empty($layoutFileName)) {
  459. return $this->Blocks->get('content');
  460. }
  461. if (!$this->_helpersLoaded) {
  462. $this->loadHelpers();
  463. }
  464. if (empty($content)) {
  465. $content = $this->Blocks->get('content');
  466. }
  467. $this->getEventManager()->dispatch(new CakeEvent('View.beforeLayout', $this, array($layoutFileName)));
  468. $scripts = implode("\n\t", $this->_scripts);
  469. $scripts .= $this->Blocks->get('meta') . $this->Blocks->get('css') . $this->Blocks->get('script');
  470. $this->viewVars = array_merge($this->viewVars, array(
  471. 'content_for_layout' => $content,
  472. 'scripts_for_layout' => $scripts,
  473. ));
  474. if (!isset($this->viewVars['title_for_layout'])) {
  475. $this->viewVars['title_for_layout'] = Inflector::humanize($this->viewPath);
  476. }
  477. $this->_currentType = self::TYPE_LAYOUT;
  478. $this->Blocks->set('content', $this->_render($layoutFileName));
  479. $this->getEventManager()->dispatch(new CakeEvent('View.afterLayout', $this, array($layoutFileName)));
  480. return $this->Blocks->get('content');
  481. }
  482. /**
  483. * Render cached view. Works in concert with CacheHelper and Dispatcher to
  484. * render cached view files.
  485. *
  486. * @param string $filename the cache file to include
  487. * @param string $timeStart the page render start time
  488. * @return boolean Success of rendering the cached file.
  489. */
  490. public function renderCache($filename, $timeStart) {
  491. ob_start();
  492. include ($filename);
  493. if (Configure::read('debug') > 0 && $this->layout != 'xml') {
  494. echo "<!-- Cached Render Time: " . round(microtime(true) - $timeStart, 4) . "s -->";
  495. }
  496. $out = ob_get_clean();
  497. if (preg_match('/^<!--cachetime:(\\d+)-->/', $out, $match)) {
  498. if (time() >= $match['1']) {
  499. //@codingStandardsIgnoreStart
  500. @unlink($filename);
  501. //@codingStandardsIgnoreEnd
  502. unset ($out);
  503. return false;
  504. } else {
  505. if ($this->layout === 'xml') {
  506. header('Content-type: text/xml');
  507. }
  508. $commentLength = strlen('<!--cachetime:' . $match['1'] . '-->');
  509. return substr($out, $commentLength);
  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. Supersceeded 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. }