View.php 34 KB

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