View.php 33 KB

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