View.php 29 KB

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