View.php 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202
  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 Name of controller
  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 A single name as a string or a list of names as an array.
  90. */
  91. public $helpers = array();
  92. /**
  93. * Path to View.
  94. *
  95. * @var string Path to View
  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 Path to Layout
  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 boolean
  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 boolean
  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. * The names of views and their parents used with View::extend();
  227. *
  228. * @var array
  229. */
  230. protected $_parents = array();
  231. /**
  232. * The currently rendering view file. Used for resolving parent files.
  233. *
  234. * @var string
  235. */
  236. protected $_current = null;
  237. /**
  238. * Currently rendering an element. Used for finding parent fragments
  239. * for elements.
  240. *
  241. * @var string
  242. */
  243. protected $_currentType = '';
  244. /**
  245. * Content stack, used for nested templates that all use View::extend();
  246. *
  247. * @var array
  248. */
  249. protected $_stack = array();
  250. /**
  251. * Instance of the CakeEventManager this View object is using
  252. * to dispatch inner events. Usually the manager is shared with
  253. * the controller, so it it possible to register view events in
  254. * the controller layer.
  255. *
  256. * @var CakeEventManager
  257. */
  258. protected $_eventManager = null;
  259. /**
  260. * Whether the event manager was already configured for this object
  261. *
  262. * @var boolean
  263. */
  264. protected $_eventManagerConfigured = false;
  265. /**
  266. * Constant for view file type 'view'
  267. */
  268. const TYPE_VIEW = 'view';
  269. /**
  270. * Constant for view file type 'element'
  271. */
  272. const TYPE_ELEMENT = 'element';
  273. /**
  274. * Constant for view file type 'layout'
  275. */
  276. const TYPE_LAYOUT = 'layout';
  277. /**
  278. * Constructor
  279. *
  280. * @param Controller $controller A controller object to pull View::_passedVars from.
  281. */
  282. public function __construct(Controller $controller = null) {
  283. if (is_object($controller)) {
  284. $count = count($this->_passedVars);
  285. for ($j = 0; $j < $count; $j++) {
  286. $var = $this->_passedVars[$j];
  287. $this->{$var} = $controller->{$var};
  288. }
  289. $this->_eventManager = $controller->getEventManager();
  290. }
  291. if (empty($this->request) && !($this->request = Router::getRequest(true))) {
  292. $this->request = new CakeRequest(null, false);
  293. $this->request->base = '';
  294. $this->request->here = $this->request->webroot = '/';
  295. }
  296. if (is_object($controller) && isset($controller->response)) {
  297. $this->response = $controller->response;
  298. } else {
  299. $this->response = new CakeResponse();
  300. }
  301. $this->Helpers = new HelperCollection($this);
  302. $this->Blocks = new ViewBlock();
  303. $this->loadHelpers();
  304. parent::__construct();
  305. }
  306. /**
  307. * Returns the CakeEventManager manager instance that is handling any callbacks.
  308. * You can use this instance to register any new listeners or callbacks to the
  309. * controller events, or create your own events and trigger them at will.
  310. *
  311. * @return CakeEventManager
  312. */
  313. public function getEventManager() {
  314. if (empty($this->_eventManager)) {
  315. $this->_eventManager = new CakeEventManager();
  316. }
  317. if (!$this->_eventManagerConfigured) {
  318. $this->_eventManager->attach($this->Helpers);
  319. $this->_eventManagerConfigured = true;
  320. }
  321. return $this->_eventManager;
  322. }
  323. /**
  324. * Renders a piece of PHP with provided parameters and returns HTML, XML, or any other string.
  325. *
  326. * This realizes the concept of Elements, (or "partial layouts") and the $params array is used to send
  327. * data to be used in the element. Elements can be cached improving performance by using the `cache` option.
  328. *
  329. * @param string $name Name of template file in the/app/View/Elements/ folder,
  330. * or `MyPlugin.template` to use the template element from MyPlugin. If the element
  331. * is not found in the plugin, the normal view path cascade will be searched.
  332. * @param array $data Array of data to be made available to the rendered view (i.e. the Element)
  333. * @param array $options Array of options. Possible keys are:
  334. * - `cache` - Can either be `true`, to enable caching using the config in View::$elementCache. Or an array
  335. * If an array, the following keys can be used:
  336. * - `config` - Used to store the cached element in a custom cache configuration.
  337. * - `key` - Used to define the key used in the Cache::write(). It will be prefixed with `element_`
  338. * - `plugin` - Load an element from a specific plugin. This option is deprecated, see below.
  339. * - `callbacks` - Set to true to fire beforeRender and afterRender helper callbacks for this element.
  340. * Defaults to false.
  341. * - `ignoreMissing` - Used to allow missing elements. Set to true to not trigger notices.
  342. * @return string Rendered Element
  343. * @deprecated The `$options['plugin']` is deprecated and will be removed in CakePHP 3.0. Use
  344. * `Plugin.element_name` instead.
  345. */
  346. public function element($name, $data = array(), $options = array()) {
  347. $file = $plugin = null;
  348. if (isset($options['plugin'])) {
  349. $name = Inflector::camelize($options['plugin']) . '.' . $name;
  350. }
  351. if (!isset($options['callbacks'])) {
  352. $options['callbacks'] = false;
  353. }
  354. if (isset($options['cache'])) {
  355. $contents = $this->_elementCache($name, $data, $options);
  356. if ($contents !== false) {
  357. return $contents;
  358. }
  359. }
  360. $file = $this->_getElementFilename($name);
  361. if ($file) {
  362. return $this->_renderElement($file, $data, $options);
  363. }
  364. if (empty($options['ignoreMissing'])) {
  365. list ($plugin, $name) = pluginSplit($name, true);
  366. $name = str_replace('/', DS, $name);
  367. $file = $plugin . 'Elements' . DS . $name . $this->ext;
  368. trigger_error(__d('cake_dev', 'Element Not Found: %s', $file), E_USER_NOTICE);
  369. }
  370. }
  371. /**
  372. * Checks if an element exists
  373. *
  374. * @param string $name Name of template file in the /app/View/Elements/ folder,
  375. * or `MyPlugin.template` to check the template element from MyPlugin. If the element
  376. * is not found in the plugin, the normal view path cascade will be searched.
  377. * @return boolean Success
  378. */
  379. public function elementExists($name) {
  380. return (bool)$this->_getElementFilename($name);
  381. }
  382. /**
  383. * Renders view for given view file and layout.
  384. *
  385. * Render triggers helper callbacks, which are fired before and after the view are rendered,
  386. * as well as before and after the layout. The helper callbacks are called:
  387. *
  388. * - `beforeRender`
  389. * - `afterRender`
  390. * - `beforeLayout`
  391. * - `afterLayout`
  392. *
  393. * If View::$autoRender is false and no `$layout` is provided, the view will be returned bare.
  394. *
  395. * View and layout names can point to plugin views/layouts. Using the `Plugin.view` syntax
  396. * a plugin view/layout can be used instead of the app ones. If the chosen plugin is not found
  397. * the view will be located along the regular view path cascade.
  398. *
  399. * @param string $view Name of view file to use
  400. * @param string $layout Layout to use.
  401. * @return string Rendered Element
  402. * @throws CakeException If there is an error in the view.
  403. */
  404. public function render($view = null, $layout = null) {
  405. if ($this->hasRendered) {
  406. return true;
  407. }
  408. $this->Blocks->set('content', '');
  409. if ($view !== false && $viewFileName = $this->_getViewFileName($view)) {
  410. $this->_currentType = self::TYPE_VIEW;
  411. $this->getEventManager()->dispatch(new CakeEvent('View.beforeRender', $this, array($viewFileName)));
  412. $this->Blocks->set('content', $this->_render($viewFileName));
  413. $this->getEventManager()->dispatch(new CakeEvent('View.afterRender', $this, array($viewFileName)));
  414. }
  415. if ($layout === null) {
  416. $layout = $this->layout;
  417. }
  418. if ($layout && $this->autoLayout) {
  419. $this->Blocks->set('content', $this->renderLayout('', $layout));
  420. }
  421. $this->hasRendered = true;
  422. return $this->Blocks->get('content');
  423. }
  424. /**
  425. * Renders a layout. Returns output from _render(). Returns false on error.
  426. * Several variables are created for use in layout.
  427. *
  428. * - `title_for_layout` - A backwards compatible place holder, you should set this value if you want more control.
  429. * - `content_for_layout` - contains rendered view file
  430. * - `scripts_for_layout` - Contains content added with addScript() as well as any content in
  431. * the 'meta', 'css', and 'script' blocks. They are appended in that order.
  432. *
  433. * Deprecated features:
  434. *
  435. * - `$scripts_for_layout` is deprecated and will be removed in CakePHP 3.0.
  436. * Use the block features instead. `meta`, `css` and `script` will be populated
  437. * by the matching methods on HtmlHelper.
  438. * - `$title_for_layout` is deprecated and will be removed in CakePHP 3.0
  439. * - `$content_for_layout` is deprecated and will be removed in CakePHP 3.0.
  440. * Use the `content` block instead.
  441. *
  442. * @param string $content Content to render in a view, wrapped by the surrounding layout.
  443. * @param string $layout Layout name
  444. * @return mixed Rendered output, or false on error
  445. * @throws CakeException if there is an error in the view.
  446. */
  447. public function renderLayout($content, $layout = null) {
  448. $layoutFileName = $this->_getLayoutFileName($layout);
  449. if (empty($layoutFileName)) {
  450. return $this->Blocks->get('content');
  451. }
  452. if (empty($content)) {
  453. $content = $this->Blocks->get('content');
  454. } else {
  455. $this->Blocks->set('content', $content);
  456. }
  457. $this->getEventManager()->dispatch(new CakeEvent('View.beforeLayout', $this, array($layoutFileName)));
  458. $scripts = implode("\n\t", $this->_scripts);
  459. $scripts .= $this->Blocks->get('meta') . $this->Blocks->get('css') . $this->Blocks->get('script');
  460. $this->viewVars = array_merge($this->viewVars, array(
  461. 'content_for_layout' => $content,
  462. 'scripts_for_layout' => $scripts,
  463. ));
  464. if (!isset($this->viewVars['title_for_layout'])) {
  465. $this->viewVars['title_for_layout'] = Inflector::humanize($this->viewPath);
  466. }
  467. $this->_currentType = self::TYPE_LAYOUT;
  468. $this->Blocks->set('content', $this->_render($layoutFileName));
  469. $this->getEventManager()->dispatch(new CakeEvent('View.afterLayout', $this, array($layoutFileName)));
  470. return $this->Blocks->get('content');
  471. }
  472. /**
  473. * Render cached view. Works in concert with CacheHelper and Dispatcher to
  474. * render cached view files.
  475. *
  476. * @param string $filename the cache file to include
  477. * @param string $timeStart the page render start time
  478. * @return boolean Success of rendering the cached file.
  479. */
  480. public function renderCache($filename, $timeStart) {
  481. $response = $this->response;
  482. ob_start();
  483. include $filename;
  484. $type = $response->mapType($response->type());
  485. if (Configure::read('debug') > 0 && $type === 'html') {
  486. echo "<!-- Cached Render Time: " . round(microtime(true) - $timeStart, 4) . "s -->";
  487. }
  488. $out = ob_get_clean();
  489. if (preg_match('/^<!--cachetime:(\\d+)-->/', $out, $match)) {
  490. if (time() >= $match['1']) {
  491. //@codingStandardsIgnoreStart
  492. @unlink($filename);
  493. //@codingStandardsIgnoreEnd
  494. unset($out);
  495. return false;
  496. }
  497. return substr($out, strlen($match[0]));
  498. }
  499. }
  500. /**
  501. * Returns a list of variables available in the current View context
  502. *
  503. * @return array Array of the set view variable names.
  504. */
  505. public function getVars() {
  506. return array_keys($this->viewVars);
  507. }
  508. /**
  509. * Returns the contents of the given View variable(s)
  510. *
  511. * @param string $var The view var you want the contents of.
  512. * @return mixed The content of the named var if its set, otherwise null.
  513. * @deprecated Will be removed in 3.0. Use View::get() instead.
  514. */
  515. public function getVar($var) {
  516. return $this->get($var);
  517. }
  518. /**
  519. * Returns the contents of the given View variable or a block.
  520. * Blocks are checked before view variables.
  521. *
  522. * @param string $var The view var you want the contents of.
  523. * @return mixed The content of the named var if its set, otherwise null.
  524. */
  525. public function get($var) {
  526. if (!isset($this->viewVars[$var])) {
  527. return null;
  528. }
  529. return $this->viewVars[$var];
  530. }
  531. /**
  532. * Get the names of all the existing blocks.
  533. *
  534. * @return array An array containing the blocks.
  535. * @see ViewBlock::keys()
  536. */
  537. public function blocks() {
  538. return $this->Blocks->keys();
  539. }
  540. /**
  541. * Start capturing output for a 'block'
  542. *
  543. * @param string $name The name of the block to capture for.
  544. * @return void
  545. * @see ViewBlock::start()
  546. */
  547. public function start($name) {
  548. $this->Blocks->start($name);
  549. }
  550. /**
  551. * Start capturing output for a 'block' if it has no content
  552. *
  553. * @param string $name The name of the block to capture for.
  554. * @return void
  555. * @see ViewBlock::startIfEmpty()
  556. */
  557. public function startIfEmpty($name) {
  558. $this->Blocks->startIfEmpty($name);
  559. }
  560. /**
  561. * Append to an existing or new block. Appending to a new
  562. * block will create the block.
  563. *
  564. * @param string $name Name of the block
  565. * @param mixed $value The content for the block.
  566. * @return void
  567. * @see ViewBlock::concat()
  568. */
  569. public function append($name, $value = null) {
  570. $this->Blocks->concat($name, $value);
  571. }
  572. /**
  573. * Prepend to an existing or new block. Prepending to a new
  574. * block will create the block.
  575. *
  576. * @param string $name Name of the block
  577. * @param mixed $value The content for the block.
  578. * @return void
  579. * @see ViewBlock::concat()
  580. */
  581. public function prepend($name, $value = null) {
  582. $this->Blocks->concat($name, $value, ViewBlock::PREPEND);
  583. }
  584. /**
  585. * Set the content for a block. This will overwrite any
  586. * existing content.
  587. *
  588. * @param string $name Name of the block
  589. * @param mixed $value The content for the block.
  590. * @return void
  591. * @see ViewBlock::set()
  592. */
  593. public function assign($name, $value) {
  594. $this->Blocks->set($name, $value);
  595. }
  596. /**
  597. * Fetch the content for a block. If a block is
  598. * empty or undefined '' will be returned.
  599. *
  600. * @param string $name Name of the block
  601. * @param string $default Default text
  602. * @return string $default The block content or $default if the block does not exist.
  603. * @see ViewBlock::get()
  604. */
  605. public function fetch($name, $default = '') {
  606. return $this->Blocks->get($name, $default);
  607. }
  608. /**
  609. * End a capturing block. The compliment to View::start()
  610. *
  611. * @return void
  612. * @see ViewBlock::end()
  613. */
  614. public function end() {
  615. $this->Blocks->end();
  616. }
  617. /**
  618. * Provides view or element extension/inheritance. Views can extends a
  619. * parent view and populate blocks in the parent template.
  620. *
  621. * @param string $name The view or element to 'extend' the current one with.
  622. * @return void
  623. * @throws LogicException when you extend a view with itself or make extend loops.
  624. * @throws LogicException when you extend an element which doesn't exist
  625. */
  626. public function extend($name) {
  627. if ($name[0] === '/' || $this->_currentType === self::TYPE_VIEW) {
  628. $parent = $this->_getViewFileName($name);
  629. } else {
  630. switch ($this->_currentType) {
  631. case self::TYPE_ELEMENT:
  632. $parent = $this->_getElementFileName($name);
  633. if (!$parent) {
  634. list($plugin, $name) = $this->pluginSplit($name);
  635. $paths = $this->_paths($plugin);
  636. $defaultPath = $paths[0] . 'Elements' . DS;
  637. throw new LogicException(__d(
  638. 'cake_dev',
  639. 'You cannot extend an element which does not exist (%s).',
  640. $defaultPath . $name . $this->ext
  641. ));
  642. }
  643. break;
  644. case self::TYPE_LAYOUT:
  645. $parent = $this->_getLayoutFileName($name);
  646. break;
  647. default:
  648. $parent = $this->_getViewFileName($name);
  649. }
  650. }
  651. if ($parent == $this->_current) {
  652. throw new LogicException(__d('cake_dev', 'You cannot have views extend themselves.'));
  653. }
  654. if (isset($this->_parents[$parent]) && $this->_parents[$parent] == $this->_current) {
  655. throw new LogicException(__d('cake_dev', 'You cannot have views extend in a loop.'));
  656. }
  657. $this->_parents[$this->_current] = $parent;
  658. }
  659. /**
  660. * Adds a script block or other element to be inserted in $scripts_for_layout in
  661. * the `<head />` of a document layout
  662. *
  663. * @param string $name Either the key name for the script, or the script content. Name can be used to
  664. * update/replace a script element.
  665. * @param string $content The content of the script being added, optional.
  666. * @return void
  667. * @deprecated Will be removed in 3.0. Superseded by blocks functionality.
  668. * @see View::start()
  669. */
  670. public function addScript($name, $content = null) {
  671. if (empty($content)) {
  672. if (!in_array($name, array_values($this->_scripts))) {
  673. $this->_scripts[] = $name;
  674. }
  675. } else {
  676. $this->_scripts[$name] = $content;
  677. }
  678. }
  679. /**
  680. * Generates a unique, non-random DOM ID for an object, based on the object type and the target URL.
  681. *
  682. * @param string $object Type of object, i.e. 'form' or 'link'
  683. * @param string $url The object's target URL
  684. * @return string
  685. */
  686. public function uuid($object, $url) {
  687. $c = 1;
  688. $url = Router::url($url);
  689. $hash = $object . substr(md5($object . $url), 0, 10);
  690. while (in_array($hash, $this->uuids)) {
  691. $hash = $object . substr(md5($object . $url . $c), 0, 10);
  692. $c++;
  693. }
  694. $this->uuids[] = $hash;
  695. return $hash;
  696. }
  697. /**
  698. * Allows a template or element to set a variable that will be available in
  699. * a layout or other element. Analogous to Controller::set().
  700. *
  701. * @param string|array $one A string or an array of data.
  702. * @param string|array $two Value in case $one is a string (which then works as the key).
  703. * Unused if $one is an associative array, otherwise serves as the values to $one's keys.
  704. * @return void
  705. */
  706. public function set($one, $two = null) {
  707. $data = null;
  708. if (is_array($one)) {
  709. if (is_array($two)) {
  710. $data = array_combine($one, $two);
  711. } else {
  712. $data = $one;
  713. }
  714. } else {
  715. $data = array($one => $two);
  716. }
  717. if (!$data) {
  718. return false;
  719. }
  720. $this->viewVars = $data + $this->viewVars;
  721. }
  722. /**
  723. * Magic accessor for helpers. Provides access to attributes that were deprecated.
  724. *
  725. * @param string $name Name of the attribute to get.
  726. * @return mixed
  727. */
  728. public function __get($name) {
  729. switch ($name) {
  730. case 'base':
  731. case 'here':
  732. case 'webroot':
  733. case 'data':
  734. return $this->request->{$name};
  735. case 'action':
  736. return $this->request->params['action'];
  737. case 'params':
  738. return $this->request;
  739. case 'output':
  740. return $this->Blocks->get('content');
  741. }
  742. if (isset($this->Helpers->{$name})) {
  743. $this->{$name} = $this->Helpers->{$name};
  744. return $this->Helpers->{$name};
  745. }
  746. return $this->{$name};
  747. }
  748. /**
  749. * Magic accessor for deprecated attributes.
  750. *
  751. * @param string $name Name of the attribute to set.
  752. * @param mixed $value Value of the attribute to set.
  753. * @return mixed
  754. */
  755. public function __set($name, $value) {
  756. switch ($name) {
  757. case 'output':
  758. return $this->Blocks->set('content', $value);
  759. default:
  760. $this->{$name} = $value;
  761. }
  762. }
  763. /**
  764. * Magic isset check for deprecated attributes.
  765. *
  766. * @param string $name Name of the attribute to check.
  767. * @return boolean
  768. */
  769. public function __isset($name) {
  770. if (isset($this->{$name})) {
  771. return true;
  772. }
  773. $magicGet = array('base', 'here', 'webroot', 'data', 'action', 'params', 'output');
  774. if (in_array($name, $magicGet)) {
  775. return $this->__get($name) !== null;
  776. }
  777. return false;
  778. }
  779. /**
  780. * Interact with the HelperCollection to load all the helpers.
  781. *
  782. * @return void
  783. */
  784. public function loadHelpers() {
  785. $helpers = HelperCollection::normalizeObjectArray($this->helpers);
  786. foreach ($helpers as $properties) {
  787. list(, $class) = pluginSplit($properties['class']);
  788. $this->{$class} = $this->Helpers->load($properties['class'], $properties['settings']);
  789. }
  790. }
  791. /**
  792. * Renders and returns output for given view filename with its
  793. * array of data. Handles parent/extended views.
  794. *
  795. * @param string $viewFile Filename of the view
  796. * @param array $data Data to include in rendered view. If empty the current View::$viewVars will be used.
  797. * @return string Rendered output
  798. * @throws CakeException when a block is left open.
  799. */
  800. protected function _render($viewFile, $data = array()) {
  801. if (empty($data)) {
  802. $data = $this->viewVars;
  803. }
  804. $this->_current = $viewFile;
  805. $initialBlocks = count($this->Blocks->unclosed());
  806. $eventManager = $this->getEventManager();
  807. $beforeEvent = new CakeEvent('View.beforeRenderFile', $this, array($viewFile));
  808. $eventManager->dispatch($beforeEvent);
  809. $content = $this->_evaluate($viewFile, $data);
  810. $afterEvent = new CakeEvent('View.afterRenderFile', $this, array($viewFile, $content));
  811. $afterEvent->modParams = 1;
  812. $eventManager->dispatch($afterEvent);
  813. $content = $afterEvent->data[1];
  814. if (isset($this->_parents[$viewFile])) {
  815. $this->_stack[] = $this->fetch('content');
  816. $this->assign('content', $content);
  817. $content = $this->_render($this->_parents[$viewFile]);
  818. $this->assign('content', array_pop($this->_stack));
  819. }
  820. $remainingBlocks = count($this->Blocks->unclosed());
  821. if ($initialBlocks !== $remainingBlocks) {
  822. throw new CakeException(__d('cake_dev', 'The "%s" block was left open. Blocks are not allowed to cross files.', $this->Blocks->active()));
  823. }
  824. return $content;
  825. }
  826. /**
  827. * Sandbox method to evaluate a template / view script in.
  828. *
  829. * @param string $viewFn Filename of the view
  830. * @param array $dataForView Data to include in rendered view.
  831. * If empty the current View::$viewVars will be used.
  832. * @return string Rendered output
  833. */
  834. protected function _evaluate($viewFile, $dataForView) {
  835. $this->__viewFile = $viewFile;
  836. extract($dataForView);
  837. ob_start();
  838. include $this->__viewFile;
  839. unset($this->__viewFile);
  840. return ob_get_clean();
  841. }
  842. /**
  843. * Loads a helper. Delegates to the `HelperCollection::load()` to load the helper
  844. *
  845. * @param string $helperName Name of the helper to load.
  846. * @param array $settings Settings for the helper
  847. * @return Helper a constructed helper object.
  848. * @see HelperCollection::load()
  849. */
  850. public function loadHelper($helperName, $settings = array()) {
  851. return $this->Helpers->load($helperName, $settings);
  852. }
  853. /**
  854. * Returns filename of given action's template file (.ctp) as a string.
  855. * CamelCased action names will be under_scored! This means that you can have
  856. * LongActionNames that refer to long_action_names.ctp views.
  857. *
  858. * @param string $name Controller action to find template filename for
  859. * @return string Template filename
  860. * @throws MissingViewException when a view file could not be found.
  861. */
  862. protected function _getViewFileName($name = null) {
  863. $subDir = null;
  864. if ($this->subDir !== null) {
  865. $subDir = $this->subDir . DS;
  866. }
  867. if ($name === null) {
  868. $name = $this->view;
  869. }
  870. $name = str_replace('/', DS, $name);
  871. list($plugin, $name) = $this->pluginSplit($name);
  872. if (strpos($name, DS) === false && $name[0] !== '.') {
  873. $name = $this->viewPath . DS . $subDir . Inflector::underscore($name);
  874. } elseif (strpos($name, DS) !== false) {
  875. if ($name[0] === DS || $name[1] === ':') {
  876. if (is_file($name)) {
  877. return $name;
  878. }
  879. $name = trim($name, DS);
  880. } elseif ($name[0] === '.') {
  881. $name = substr($name, 3);
  882. } elseif (!$plugin || $this->viewPath !== $this->name) {
  883. $name = $this->viewPath . DS . $subDir . $name;
  884. }
  885. }
  886. $paths = $this->_paths($plugin);
  887. $exts = $this->_getExtensions();
  888. foreach ($exts as $ext) {
  889. foreach ($paths as $path) {
  890. if (file_exists($path . $name . $ext)) {
  891. return $path . $name . $ext;
  892. }
  893. }
  894. }
  895. $defaultPath = $paths[0];
  896. if ($this->plugin) {
  897. $pluginPaths = App::path('plugins');
  898. foreach ($paths as $path) {
  899. if (strpos($path, $pluginPaths[0]) === 0) {
  900. $defaultPath = $path;
  901. break;
  902. }
  903. }
  904. }
  905. throw new MissingViewException(array('file' => $defaultPath . $name . $this->ext));
  906. }
  907. /**
  908. * Splits a dot syntax plugin name into its plugin and filename.
  909. * If $name does not have a dot, then index 0 will be null.
  910. * It checks if the plugin is loaded, else filename will stay unchanged for filenames containing dot
  911. *
  912. * @param string $name The name you want to plugin split.
  913. * @param boolean $fallback If true uses the plugin set in the current CakeRequest when parsed plugin is not loaded
  914. * @return array Array with 2 indexes. 0 => plugin name, 1 => filename
  915. */
  916. public function pluginSplit($name, $fallback = true) {
  917. $plugin = null;
  918. list($first, $second) = pluginSplit($name);
  919. if (CakePlugin::loaded($first) === true) {
  920. $name = $second;
  921. $plugin = $first;
  922. }
  923. if (isset($this->plugin) && !$plugin && $fallback) {
  924. $plugin = $this->plugin;
  925. }
  926. return array($plugin, $name);
  927. }
  928. /**
  929. * Returns layout filename for this template as a string.
  930. *
  931. * @param string $name The name of the layout to find.
  932. * @return string Filename for layout file (.ctp).
  933. * @throws MissingLayoutException when a layout cannot be located
  934. */
  935. protected function _getLayoutFileName($name = null) {
  936. if ($name === null) {
  937. $name = $this->layout;
  938. }
  939. $subDir = null;
  940. if ($this->layoutPath !== null) {
  941. $subDir = $this->layoutPath . DS;
  942. }
  943. list($plugin, $name) = $this->pluginSplit($name);
  944. $paths = $this->_paths($plugin);
  945. $file = 'Layouts' . DS . $subDir . $name;
  946. $exts = $this->_getExtensions();
  947. foreach ($exts as $ext) {
  948. foreach ($paths as $path) {
  949. if (file_exists($path . $file . $ext)) {
  950. return $path . $file . $ext;
  951. }
  952. }
  953. }
  954. throw new MissingLayoutException(array('file' => $paths[0] . $file . $this->ext));
  955. }
  956. /**
  957. * Get the extensions that view files can use.
  958. *
  959. * @return array Array of extensions view files use.
  960. */
  961. protected function _getExtensions() {
  962. $exts = array($this->ext);
  963. if ($this->ext !== '.ctp') {
  964. $exts[] = '.ctp';
  965. }
  966. return $exts;
  967. }
  968. /**
  969. * Finds an element filename, returns false on failure.
  970. *
  971. * @param string $name The name of the element to find.
  972. * @return mixed Either a string to the element filename or false when one can't be found.
  973. */
  974. protected function _getElementFileName($name) {
  975. list($plugin, $name) = $this->pluginSplit($name);
  976. $paths = $this->_paths($plugin);
  977. $exts = $this->_getExtensions();
  978. foreach ($exts as $ext) {
  979. foreach ($paths as $path) {
  980. if (file_exists($path . 'Elements' . DS . $name . $ext)) {
  981. return $path . 'Elements' . DS . $name . $ext;
  982. }
  983. }
  984. }
  985. return false;
  986. }
  987. /**
  988. * Return all possible paths to find view files in order
  989. *
  990. * @param string $plugin Optional plugin name to scan for view files.
  991. * @param boolean $cached Set to false to force a refresh of view paths. Default true.
  992. * @return array paths
  993. */
  994. protected function _paths($plugin = null, $cached = true) {
  995. if ($plugin === null && $cached === true && !empty($this->_paths)) {
  996. return $this->_paths;
  997. }
  998. $paths = array();
  999. $viewPaths = App::path('View');
  1000. $corePaths = array_merge(App::core('View'), App::core('Console/Templates/skel/View'));
  1001. if (!empty($plugin)) {
  1002. $count = count($viewPaths);
  1003. for ($i = 0; $i < $count; $i++) {
  1004. if (!in_array($viewPaths[$i], $corePaths)) {
  1005. $paths[] = $viewPaths[$i] . 'Plugin' . DS . $plugin . DS;
  1006. }
  1007. }
  1008. $paths = array_merge($paths, App::path('View', $plugin));
  1009. }
  1010. $paths = array_unique(array_merge($paths, $viewPaths));
  1011. if (!empty($this->theme)) {
  1012. $theme = Inflector::camelize($this->theme);
  1013. $themePaths = array();
  1014. foreach ($paths as $path) {
  1015. if (strpos($path, DS . 'Plugin' . DS) === false) {
  1016. if ($plugin) {
  1017. $themePaths[] = $path . 'Themed' . DS . $theme . DS . 'Plugin' . DS . $plugin . DS;
  1018. }
  1019. $themePaths[] = $path . 'Themed' . DS . $theme . DS;
  1020. }
  1021. }
  1022. $paths = array_merge($themePaths, $paths);
  1023. }
  1024. $paths = array_merge($paths, $corePaths);
  1025. if ($plugin !== null) {
  1026. return $paths;
  1027. }
  1028. return $this->_paths = $paths;
  1029. }
  1030. /**
  1031. * Checks if an element is cached and returns the cached data if present
  1032. *
  1033. * @param string $name Element name
  1034. * @param string $data Data
  1035. * @param array $options Element options
  1036. * @return string|null
  1037. */
  1038. protected function _elementCache($name, $data, $options) {
  1039. $plugin = null;
  1040. list($plugin, $name) = $this->pluginSplit($name);
  1041. $underscored = null;
  1042. if ($plugin) {
  1043. $underscored = Inflector::underscore($plugin);
  1044. }
  1045. $keys = array_merge(array($underscored, $name), array_keys($options), array_keys($data));
  1046. $this->elementCacheSettings = array(
  1047. 'config' => $this->elementCache,
  1048. 'key' => implode('_', $keys)
  1049. );
  1050. if (is_array($options['cache'])) {
  1051. $defaults = array(
  1052. 'config' => $this->elementCache,
  1053. 'key' => $this->elementCacheSettings['key']
  1054. );
  1055. $this->elementCacheSettings = array_merge($defaults, $options['cache']);
  1056. }
  1057. $this->elementCacheSettings['key'] = 'element_' . $this->elementCacheSettings['key'];
  1058. return Cache::read($this->elementCacheSettings['key'], $this->elementCacheSettings['config']);
  1059. }
  1060. /**
  1061. * Renders an element and fires the before and afterRender callbacks for it
  1062. * and writes to the cache if a cache is used
  1063. *
  1064. * @param string $file Element file path
  1065. * @param array $data Data to render
  1066. * @param array $options Element options
  1067. * @return string
  1068. */
  1069. protected function _renderElement($file, $data, $options) {
  1070. if ($options['callbacks']) {
  1071. $this->getEventManager()->dispatch(new CakeEvent('View.beforeRender', $this, array($file)));
  1072. }
  1073. $current = $this->_current;
  1074. $restore = $this->_currentType;
  1075. $this->_currentType = self::TYPE_ELEMENT;
  1076. $element = $this->_render($file, array_merge($this->viewVars, $data));
  1077. $this->_currentType = $restore;
  1078. $this->_current = $current;
  1079. if ($options['callbacks']) {
  1080. $this->getEventManager()->dispatch(new CakeEvent('View.afterRender', $this, array($file, $element)));
  1081. }
  1082. if (isset($options['cache'])) {
  1083. Cache::write($this->elementCacheSettings['key'], $element, $this->elementCacheSettings['config']);
  1084. }
  1085. return $element;
  1086. }
  1087. }