View.php 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221
  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 http://www.opensource.org/licenses/mit-license.php MIT License
  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. $response = $this->response;
  493. ob_start();
  494. include ($filename);
  495. $type = $response->mapType($response->type());
  496. if (Configure::read('debug') > 0 && $type === 'html') {
  497. echo "<!-- Cached Render Time: " . round(microtime(true) - $timeStart, 4) . "s -->";
  498. }
  499. $out = ob_get_clean();
  500. if (preg_match('/^<!--cachetime:(\\d+)-->/', $out, $match)) {
  501. if (time() >= $match['1']) {
  502. //@codingStandardsIgnoreStart
  503. @unlink($filename);
  504. //@codingStandardsIgnoreEnd
  505. unset($out);
  506. return false;
  507. }
  508. return substr($out, strlen($match[0]));
  509. }
  510. }
  511. /**
  512. * Returns a list of variables available in the current View context
  513. *
  514. * @return array Array of the set view variable names.
  515. */
  516. public function getVars() {
  517. return array_keys($this->viewVars);
  518. }
  519. /**
  520. * Returns the contents of the given View variable(s)
  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. * @deprecated Will be removed in 3.0. Use View::get() instead.
  525. */
  526. public function getVar($var) {
  527. return $this->get($var);
  528. }
  529. /**
  530. * Returns the contents of the given View variable or a block.
  531. * Blocks are checked before view variables.
  532. *
  533. * @param string $var The view var you want the contents of.
  534. * @return mixed The content of the named var if its set, otherwise null.
  535. */
  536. public function get($var) {
  537. if (!isset($this->viewVars[$var])) {
  538. return null;
  539. }
  540. return $this->viewVars[$var];
  541. }
  542. /**
  543. * Get the names of all the existing blocks.
  544. *
  545. * @return array An array containing the blocks.
  546. * @see ViewBlock::keys()
  547. */
  548. public function blocks() {
  549. return $this->Blocks->keys();
  550. }
  551. /**
  552. * Start capturing output for a 'block'
  553. *
  554. * @param string $name The name of the block to capture for.
  555. * @return void
  556. * @see ViewBlock::start()
  557. */
  558. public function start($name) {
  559. return $this->Blocks->start($name);
  560. }
  561. /**
  562. * Start capturing output for a 'block' if it has no content
  563. *
  564. * @param string $name The name of the block to capture for.
  565. * @return void
  566. * @see ViewBlock::startIfEmpty()
  567. */
  568. public function startIfEmpty($name) {
  569. return $this->Blocks->startIfEmpty($name);
  570. }
  571. /**
  572. * Append to an existing or new block. Appending to a new
  573. * block will create the block.
  574. *
  575. * @param string $name Name of the block
  576. * @param string $value The content for the block.
  577. * @return void
  578. * @throws CakeException when you use non-string values.
  579. * @see ViewBlock::concat()
  580. */
  581. public function append($name, $value = null) {
  582. return $this->Blocks->concat($name, $value);
  583. }
  584. /**
  585. * Prepend to an existing or new block. Prepending to a new
  586. * block will create the block.
  587. *
  588. * @param string $name Name of the block
  589. * @param string $value The content for the block.
  590. * @return void
  591. * @throws CakeException when you use non-string values.
  592. * @see ViewBlock::concat()
  593. */
  594. public function prepend($name, $value = null) {
  595. return $this->Blocks->concat($name, $value, ViewBlock::PREPEND);
  596. }
  597. /**
  598. * Set the content for a block. This will overwrite any
  599. * existing content.
  600. *
  601. * @param string $name Name of the block
  602. * @param string $value The content for the block.
  603. * @return void
  604. * @throws CakeException when you use non-string values.
  605. * @see ViewBlock::set()
  606. */
  607. public function assign($name, $value) {
  608. return $this->Blocks->set($name, $value);
  609. }
  610. /**
  611. * Fetch the content for a block. If a block is
  612. * empty or undefined '' will be returned.
  613. *
  614. * @param string $name Name of the block
  615. * @param string $default Default text
  616. * @return string $default The block content or $default if the block does not exist.
  617. * @see ViewBlock::get()
  618. */
  619. public function fetch($name, $default = '') {
  620. return $this->Blocks->get($name, $default);
  621. }
  622. /**
  623. * End a capturing block. The compliment to View::start()
  624. *
  625. * @return void
  626. * @see ViewBlock::end()
  627. */
  628. public function end() {
  629. return $this->Blocks->end();
  630. }
  631. /**
  632. * Provides view or element extension/inheritance. Views can extends a
  633. * parent view and populate blocks in the parent template.
  634. *
  635. * @param string $name The view or element to 'extend' the current one with.
  636. * @return void
  637. * @throws LogicException when you extend a view with itself or make extend loops.
  638. * @throws LogicException when you extend an element which doesn't exist
  639. */
  640. public function extend($name) {
  641. if ($name[0] === '/' || $this->_currentType === self::TYPE_VIEW) {
  642. $parent = $this->_getViewFileName($name);
  643. } else {
  644. switch ($this->_currentType) {
  645. case self::TYPE_ELEMENT:
  646. $parent = $this->_getElementFileName($name);
  647. if (!$parent) {
  648. list($plugin, $name) = $this->pluginSplit($name);
  649. $paths = $this->_paths($plugin);
  650. $defaultPath = $paths[0] . 'Elements' . DS;
  651. throw new LogicException(__d(
  652. 'cake_dev',
  653. 'You cannot extend an element which does not exist (%s).',
  654. $defaultPath . $name . $this->ext
  655. ));
  656. }
  657. break;
  658. case self::TYPE_LAYOUT:
  659. $parent = $this->_getLayoutFileName($name);
  660. break;
  661. default:
  662. $parent = $this->_getViewFileName($name);
  663. }
  664. }
  665. if ($parent == $this->_current) {
  666. throw new LogicException(__d('cake_dev', 'You cannot have views extend themselves.'));
  667. }
  668. if (isset($this->_parents[$parent]) && $this->_parents[$parent] == $this->_current) {
  669. throw new LogicException(__d('cake_dev', 'You cannot have views extend in a loop.'));
  670. }
  671. $this->_parents[$this->_current] = $parent;
  672. }
  673. /**
  674. * Adds a script block or other element to be inserted in $scripts_for_layout in
  675. * the `<head />` of a document layout
  676. *
  677. * @param string $name Either the key name for the script, or the script content. Name can be used to
  678. * update/replace a script element.
  679. * @param string $content The content of the script being added, optional.
  680. * @return void
  681. * @deprecated Will be removed in 3.0. Superseded by blocks functionality.
  682. * @see View::start()
  683. */
  684. public function addScript($name, $content = null) {
  685. if (empty($content)) {
  686. if (!in_array($name, array_values($this->_scripts))) {
  687. $this->_scripts[] = $name;
  688. }
  689. } else {
  690. $this->_scripts[$name] = $content;
  691. }
  692. }
  693. /**
  694. * Generates a unique, non-random DOM ID for an object, based on the object type and the target URL.
  695. *
  696. * @param string $object Type of object, i.e. 'form' or 'link'
  697. * @param string $url The object's target URL
  698. * @return string
  699. */
  700. public function uuid($object, $url) {
  701. $c = 1;
  702. $url = Router::url($url);
  703. $hash = $object . substr(md5($object . $url), 0, 10);
  704. while (in_array($hash, $this->uuids)) {
  705. $hash = $object . substr(md5($object . $url . $c), 0, 10);
  706. $c++;
  707. }
  708. $this->uuids[] = $hash;
  709. return $hash;
  710. }
  711. /**
  712. * Allows a template or element to set a variable that will be available in
  713. * a layout or other element. Analogous to Controller::set().
  714. *
  715. * @param string|array $one A string or an array of data.
  716. * @param string|array $two Value in case $one is a string (which then works as the key).
  717. * Unused if $one is an associative array, otherwise serves as the values to $one's keys.
  718. * @return void
  719. */
  720. public function set($one, $two = null) {
  721. $data = null;
  722. if (is_array($one)) {
  723. if (is_array($two)) {
  724. $data = array_combine($one, $two);
  725. } else {
  726. $data = $one;
  727. }
  728. } else {
  729. $data = array($one => $two);
  730. }
  731. if (!$data) {
  732. return false;
  733. }
  734. $this->viewVars = $data + $this->viewVars;
  735. }
  736. /**
  737. * Magic accessor for helpers. Provides access to attributes that were deprecated.
  738. *
  739. * @param string $name Name of the attribute to get.
  740. * @return mixed
  741. */
  742. public function __get($name) {
  743. switch ($name) {
  744. case 'base':
  745. case 'here':
  746. case 'webroot':
  747. case 'data':
  748. return $this->request->{$name};
  749. case 'action':
  750. return $this->request->params['action'];
  751. case 'params':
  752. return $this->request;
  753. case 'output':
  754. return $this->Blocks->get('content');
  755. }
  756. if (isset($this->Helpers->{$name})) {
  757. $this->{$name} = $this->Helpers->{$name};
  758. return $this->Helpers->{$name};
  759. }
  760. return $this->{$name};
  761. }
  762. /**
  763. * Magic accessor for deprecated attributes.
  764. *
  765. * @param string $name Name of the attribute to set.
  766. * @param string $value Value of the attribute to set.
  767. * @return mixed
  768. */
  769. public function __set($name, $value) {
  770. switch ($name) {
  771. case 'output':
  772. return $this->Blocks->set('content', $value);
  773. default:
  774. $this->{$name} = $value;
  775. }
  776. }
  777. /**
  778. * Magic isset check for deprecated attributes.
  779. *
  780. * @param string $name Name of the attribute to check.
  781. * @return boolean
  782. */
  783. public function __isset($name) {
  784. if (isset($this->{$name})) {
  785. return true;
  786. }
  787. $magicGet = array('base', 'here', 'webroot', 'data', 'action', 'params', 'output');
  788. if (in_array($name, $magicGet)) {
  789. return $this->__get($name) !== null;
  790. }
  791. return false;
  792. }
  793. /**
  794. * Interact with the HelperCollection to load all the helpers.
  795. *
  796. * @return void
  797. */
  798. public function loadHelpers() {
  799. $helpers = HelperCollection::normalizeObjectArray($this->helpers);
  800. foreach ($helpers as $properties) {
  801. list(, $class) = pluginSplit($properties['class']);
  802. $this->{$class} = $this->Helpers->load($properties['class'], $properties['settings']);
  803. }
  804. $this->_helpersLoaded = true;
  805. }
  806. /**
  807. * Renders and returns output for given view filename with its
  808. * array of data. Handles parent/extended views.
  809. *
  810. * @param string $viewFile Filename of the view
  811. * @param array $data Data to include in rendered view. If empty the current View::$viewVars will be used.
  812. * @return string Rendered output
  813. * @throws CakeException when a block is left open.
  814. */
  815. protected function _render($viewFile, $data = array()) {
  816. if (empty($data)) {
  817. $data = $this->viewVars;
  818. }
  819. $this->_current = $viewFile;
  820. $initialBlocks = count($this->Blocks->unclosed());
  821. $eventManager = $this->getEventManager();
  822. $beforeEvent = new CakeEvent('View.beforeRenderFile', $this, array($viewFile));
  823. $eventManager->dispatch($beforeEvent);
  824. $content = $this->_evaluate($viewFile, $data);
  825. $afterEvent = new CakeEvent('View.afterRenderFile', $this, array($viewFile, $content));
  826. $afterEvent->modParams = 1;
  827. $eventManager->dispatch($afterEvent);
  828. $content = $afterEvent->data[1];
  829. if (isset($this->_parents[$viewFile])) {
  830. $this->_stack[] = $this->fetch('content');
  831. $this->assign('content', $content);
  832. $content = $this->_render($this->_parents[$viewFile]);
  833. $this->assign('content', array_pop($this->_stack));
  834. }
  835. $remainingBlocks = count($this->Blocks->unclosed());
  836. if ($initialBlocks !== $remainingBlocks) {
  837. throw new CakeException(__d('cake_dev', 'The "%s" block was left open. Blocks are not allowed to cross files.', $this->Blocks->active()));
  838. }
  839. return $content;
  840. }
  841. /**
  842. * Sandbox method to evaluate a template / view script in.
  843. *
  844. * @param string $viewFn Filename of the view
  845. * @param array $dataForView Data to include in rendered view.
  846. * If empty the current View::$viewVars will be used.
  847. * @return string Rendered output
  848. */
  849. protected function _evaluate($viewFile, $dataForView) {
  850. $this->__viewFile = $viewFile;
  851. extract($dataForView);
  852. ob_start();
  853. include $this->__viewFile;
  854. unset($this->__viewFile);
  855. return ob_get_clean();
  856. }
  857. /**
  858. * Loads a helper. Delegates to the `HelperCollection::load()` to load the helper
  859. *
  860. * @param string $helperName Name of the helper to load.
  861. * @param array $settings Settings for the helper
  862. * @return Helper a constructed helper object.
  863. * @see HelperCollection::load()
  864. */
  865. public function loadHelper($helperName, $settings = array()) {
  866. return $this->Helpers->load($helperName, $settings);
  867. }
  868. /**
  869. * Returns filename of given action's template file (.ctp) as a string.
  870. * CamelCased action names will be under_scored! This means that you can have
  871. * LongActionNames that refer to long_action_names.ctp views.
  872. *
  873. * @param string $name Controller action to find template filename for
  874. * @return string Template filename
  875. * @throws MissingViewException when a view file could not be found.
  876. */
  877. protected function _getViewFileName($name = null) {
  878. $subDir = null;
  879. if (!is_null($this->subDir)) {
  880. $subDir = $this->subDir . DS;
  881. }
  882. if ($name === null) {
  883. $name = $this->view;
  884. }
  885. $name = str_replace('/', DS, $name);
  886. list($plugin, $name) = $this->pluginSplit($name);
  887. if (strpos($name, DS) === false && $name[0] !== '.') {
  888. $name = $this->viewPath . DS . $subDir . Inflector::underscore($name);
  889. } elseif (strpos($name, DS) !== false) {
  890. if ($name[0] === DS || $name[1] === ':') {
  891. if (is_file($name)) {
  892. return $name;
  893. }
  894. $name = trim($name, DS);
  895. } elseif ($name[0] === '.') {
  896. $name = substr($name, 3);
  897. } elseif (!$plugin || $this->viewPath !== $this->name) {
  898. $name = $this->viewPath . DS . $subDir . $name;
  899. }
  900. }
  901. $paths = $this->_paths($plugin);
  902. $exts = $this->_getExtensions();
  903. foreach ($exts as $ext) {
  904. foreach ($paths as $path) {
  905. if (file_exists($path . $name . $ext)) {
  906. return $path . $name . $ext;
  907. }
  908. }
  909. }
  910. $defaultPath = $paths[0];
  911. if ($this->plugin) {
  912. $pluginPaths = App::path('plugins');
  913. foreach ($paths as $path) {
  914. if (strpos($path, $pluginPaths[0]) === 0) {
  915. $defaultPath = $path;
  916. break;
  917. }
  918. }
  919. }
  920. throw new MissingViewException(array('file' => $defaultPath . $name . $this->ext));
  921. }
  922. /**
  923. * Splits a dot syntax plugin name into its plugin and filename.
  924. * If $name does not have a dot, then index 0 will be null.
  925. * It checks if the plugin is loaded, else filename will stay unchanged for filenames containing dot
  926. *
  927. * @param string $name The name you want to plugin split.
  928. * @param boolean $fallback If true uses the plugin set in the current CakeRequest when parsed plugin is not loaded
  929. * @return array Array with 2 indexes. 0 => plugin name, 1 => filename
  930. */
  931. public function pluginSplit($name, $fallback = true) {
  932. $plugin = null;
  933. list($first, $second) = pluginSplit($name);
  934. if (CakePlugin::loaded($first) === true) {
  935. $name = $second;
  936. $plugin = $first;
  937. }
  938. if (isset($this->plugin) && !$plugin && $fallback) {
  939. $plugin = $this->plugin;
  940. }
  941. return array($plugin, $name);
  942. }
  943. /**
  944. * Returns layout filename for this template as a string.
  945. *
  946. * @param string $name The name of the layout to find.
  947. * @return string Filename for layout file (.ctp).
  948. * @throws MissingLayoutException when a layout cannot be located
  949. */
  950. protected function _getLayoutFileName($name = null) {
  951. if ($name === null) {
  952. $name = $this->layout;
  953. }
  954. $subDir = null;
  955. if (!is_null($this->layoutPath)) {
  956. $subDir = $this->layoutPath . DS;
  957. }
  958. list($plugin, $name) = $this->pluginSplit($name);
  959. $paths = $this->_paths($plugin);
  960. $file = 'Layouts' . DS . $subDir . $name;
  961. $exts = $this->_getExtensions();
  962. foreach ($exts as $ext) {
  963. foreach ($paths as $path) {
  964. if (file_exists($path . $file . $ext)) {
  965. return $path . $file . $ext;
  966. }
  967. }
  968. }
  969. throw new MissingLayoutException(array('file' => $paths[0] . $file . $this->ext));
  970. }
  971. /**
  972. * Get the extensions that view files can use.
  973. *
  974. * @return array Array of extensions view files use.
  975. */
  976. protected function _getExtensions() {
  977. $exts = array($this->ext);
  978. if ($this->ext !== '.ctp') {
  979. $exts[] = '.ctp';
  980. }
  981. return $exts;
  982. }
  983. /**
  984. * Finds an element filename, returns false on failure.
  985. *
  986. * @param string $name The name of the element to find.
  987. * @return mixed Either a string to the element filename or false when one can't be found.
  988. */
  989. protected function _getElementFileName($name) {
  990. list($plugin, $name) = $this->pluginSplit($name);
  991. $paths = $this->_paths($plugin);
  992. $exts = $this->_getExtensions();
  993. foreach ($exts as $ext) {
  994. foreach ($paths as $path) {
  995. if (file_exists($path . 'Elements' . DS . $name . $ext)) {
  996. return $path . 'Elements' . DS . $name . $ext;
  997. }
  998. }
  999. }
  1000. return false;
  1001. }
  1002. /**
  1003. * Return all possible paths to find view files in order
  1004. *
  1005. * @param string $plugin Optional plugin name to scan for view files.
  1006. * @param boolean $cached Set to true to force a refresh of view paths.
  1007. * @return array paths
  1008. */
  1009. protected function _paths($plugin = null, $cached = true) {
  1010. if ($plugin === null && $cached === true && !empty($this->_paths)) {
  1011. return $this->_paths;
  1012. }
  1013. $paths = array();
  1014. $viewPaths = App::path('View');
  1015. $corePaths = array_merge(App::core('View'), App::core('Console/Templates/skel/View'));
  1016. if (!empty($plugin)) {
  1017. $count = count($viewPaths);
  1018. for ($i = 0; $i < $count; $i++) {
  1019. if (!in_array($viewPaths[$i], $corePaths)) {
  1020. $paths[] = $viewPaths[$i] . 'Plugin' . DS . $plugin . DS;
  1021. }
  1022. }
  1023. $paths = array_merge($paths, App::path('View', $plugin));
  1024. }
  1025. $paths = array_unique(array_merge($paths, $viewPaths));
  1026. if (!empty($this->theme)) {
  1027. $theme = Inflector::camelize($this->theme);
  1028. $themePaths = array();
  1029. foreach ($paths as $path) {
  1030. if (strpos($path, DS . 'Plugin' . DS) === false) {
  1031. if ($plugin) {
  1032. $themePaths[] = $path . 'Themed' . DS . $theme . DS . 'Plugin' . DS . $plugin . DS;
  1033. }
  1034. $themePaths[] = $path . 'Themed' . DS . $theme . DS;
  1035. }
  1036. }
  1037. $paths = array_merge($themePaths, $paths);
  1038. }
  1039. $paths = array_merge($paths, $corePaths);
  1040. if ($plugin !== null) {
  1041. return $paths;
  1042. }
  1043. return $this->_paths = $paths;
  1044. }
  1045. /**
  1046. * Checks if an element is cached and returns the cached data if present
  1047. *
  1048. * @param string $name Element name
  1049. * @param string $data Data
  1050. * @param array $options Element options
  1051. * @return string|null
  1052. */
  1053. protected function _elementCache($name, $data, $options) {
  1054. $plugin = null;
  1055. list($plugin, $name) = $this->pluginSplit($name);
  1056. $underscored = null;
  1057. if ($plugin) {
  1058. $underscored = Inflector::underscore($plugin);
  1059. }
  1060. $keys = array_merge(array($underscored, $name), array_keys($options), array_keys($data));
  1061. $this->elementCacheSettings = array(
  1062. 'config' => $this->elementCache,
  1063. 'key' => implode('_', $keys)
  1064. );
  1065. if (is_array($options['cache'])) {
  1066. $defaults = array(
  1067. 'config' => $this->elementCache,
  1068. 'key' => $this->elementCacheSettings['key']
  1069. );
  1070. $this->elementCacheSettings = array_merge($defaults, $options['cache']);
  1071. }
  1072. $this->elementCacheSettings['key'] = 'element_' . $this->elementCacheSettings['key'];
  1073. return Cache::read($this->elementCacheSettings['key'], $this->elementCacheSettings['config']);
  1074. }
  1075. /**
  1076. * Renders an element and fires the before and afterRender callbacks for it
  1077. * and writes to the cache if a cache is used
  1078. *
  1079. * @param string $file Element file path
  1080. * @param array $data Data to render
  1081. * @param array $options Element options
  1082. * @return string
  1083. */
  1084. protected function _renderElement($file, $data, $options) {
  1085. if (!$this->_helpersLoaded) {
  1086. $this->loadHelpers();
  1087. }
  1088. if ($options['callbacks']) {
  1089. $this->getEventManager()->dispatch(new CakeEvent('View.beforeRender', $this, array($file)));
  1090. }
  1091. $current = $this->_current;
  1092. $restore = $this->_currentType;
  1093. $this->_currentType = self::TYPE_ELEMENT;
  1094. $element = $this->_render($file, array_merge($this->viewVars, $data));
  1095. $this->_currentType = $restore;
  1096. $this->_current = $current;
  1097. if ($options['callbacks']) {
  1098. $this->getEventManager()->dispatch(new CakeEvent('View.afterRender', $this, array($file, $element)));
  1099. }
  1100. if (isset($options['cache'])) {
  1101. Cache::write($this->elementCacheSettings['key'], $element, $this->elementCacheSettings['config']);
  1102. }
  1103. return $element;
  1104. }
  1105. }