View.php 32 KB

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