View.php 34 KB

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