PageRenderTime 54ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/Cake/View/View.php

https://bitbucket.org/praveen_excell/opshop
PHP | 1130 lines | 523 code | 106 blank | 501 comment | 98 complexity | 66277388d596bca0dffe6c82c00882c1 MD5 | raw file
Possible License(s): GPL-2.0, AGPL-1.0, LGPL-2.1
  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. * List of variables to collect from the associated controller.
  199. *
  200. * @var array
  201. */
  202. protected $_passedVars = array(
  203. 'viewVars', 'autoLayout', 'ext', 'helpers', 'view', 'layout', 'name', 'theme',
  204. 'layoutPath', 'viewPath', 'request', 'plugin', 'passedArgs', 'cacheAction'
  205. );
  206. /**
  207. * Scripts (and/or other <head /> tags) for the layout.
  208. *
  209. * @var array
  210. */
  211. protected $_scripts = array();
  212. /**
  213. * Holds an array of paths.
  214. *
  215. * @var array
  216. */
  217. protected $_paths = array();
  218. /**
  219. * Indicate that helpers have been loaded.
  220. *
  221. * @var boolean
  222. */
  223. protected $_helpersLoaded = false;
  224. /**
  225. * The names of views and their parents used with View::extend();
  226. *
  227. * @var array
  228. */
  229. protected $_parents = array();
  230. /**
  231. * The currently rendering view file. Used for resolving parent files.
  232. *
  233. * @var string
  234. */
  235. protected $_current = null;
  236. /**
  237. * Currently rendering an element. Used for finding parent fragments
  238. * for elements.
  239. *
  240. * @var string
  241. */
  242. protected $_currentType = '';
  243. /**
  244. * Content stack, used for nested templates that all use View::extend();
  245. *
  246. * @var array
  247. */
  248. protected $_stack = array();
  249. /**
  250. * Instance of the CakeEventManager this View object is using
  251. * to dispatch inner events. Usually the manager is shared with
  252. * the controller, so it it possible to register view events in
  253. * the controller layer.
  254. *
  255. * @var CakeEventManager
  256. */
  257. protected $_eventManager = null;
  258. /**
  259. * Whether the event manager was already configured for this object
  260. *
  261. * @var boolean
  262. */
  263. protected $_eventManagerConfigured = false;
  264. const TYPE_VIEW = 'view';
  265. const TYPE_ELEMENT = 'element';
  266. const TYPE_LAYOUT = 'layout';
  267. /**
  268. * Constructor
  269. *
  270. * @param Controller $controller A controller object to pull View::_passedVars from.
  271. */
  272. public function __construct(Controller $controller = null) {
  273. if (is_object($controller)) {
  274. $count = count($this->_passedVars);
  275. for ($j = 0; $j < $count; $j++) {
  276. $var = $this->_passedVars[$j];
  277. $this->{$var} = $controller->{$var};
  278. }
  279. $this->_eventManager = $controller->getEventManager();
  280. }
  281. if (empty($this->request) && !($this->request = Router::getRequest(true))) {
  282. $this->request = new CakeRequest(null, false);
  283. $this->request->base = '';
  284. $this->request->here = $this->request->webroot = '/';
  285. }
  286. if (is_object($controller) && isset($controller->response)) {
  287. $this->response = $controller->response;
  288. } else {
  289. $this->response = new CakeResponse(array('charset' => Configure::read('App.encoding')));
  290. }
  291. $this->Helpers = new HelperCollection($this);
  292. $this->Blocks = new ViewBlock();
  293. parent::__construct();
  294. }
  295. /**
  296. * Returns the CakeEventManager manager instance that is handling any callbacks.
  297. * You can use this instance to register any new listeners or callbacks to the
  298. * controller events, or create your own events and trigger them at will.
  299. *
  300. * @return CakeEventManager
  301. */
  302. public function getEventManager() {
  303. if (empty($this->_eventManager)) {
  304. $this->_eventManager = new CakeEventManager();
  305. }
  306. if (!$this->_eventManagerConfigured) {
  307. $this->_eventManager->attach($this->Helpers);
  308. $this->_eventManagerConfigured = true;
  309. }
  310. return $this->_eventManager;
  311. }
  312. /**
  313. * Renders a piece of PHP with provided parameters and returns HTML, XML, or any other string.
  314. *
  315. * This realizes the concept of Elements, (or "partial layouts") and the $params array is used to send
  316. * data to be used in the element. Elements can be cached improving performance by using the `cache` option.
  317. *
  318. * @param string $name Name of template file in the/app/View/Elements/ folder,
  319. * or `MyPlugin.template` to use the template element from MyPlugin. If the element
  320. * is not found in the plugin, the normal view path cascade will be searched.
  321. * @param array $data Array of data to be made available to the rendered view (i.e. the Element)
  322. * @param array $options Array of options. Possible keys are:
  323. * - `cache` - Can either be `true`, to enable caching using the config in View::$elementCache. Or an array
  324. * If an array, the following keys can be used:
  325. * - `config` - Used to store the cached element in a custom cache configuration.
  326. * - `key` - Used to define the key used in the Cache::write(). It will be prefixed with `element_`
  327. * - `plugin` - Load an element from a specific plugin. This option is deprecated, see below.
  328. * - `callbacks` - Set to true to fire beforeRender and afterRender helper callbacks for this element.
  329. * Defaults to false.
  330. * @return string Rendered Element
  331. * @deprecated The `$options['plugin']` is deprecated and will be removed in CakePHP 3.0. Use
  332. * `Plugin.element_name` instead.
  333. */
  334. public function element($name, $data = array(), $options = array()) {
  335. $file = $plugin = $key = null;
  336. $callbacks = false;
  337. if (isset($options['plugin'])) {
  338. $name = Inflector::camelize($options['plugin']) . '.' . $name;
  339. }
  340. if (isset($options['callbacks'])) {
  341. $callbacks = $options['callbacks'];
  342. }
  343. if (isset($options['cache'])) {
  344. $underscored = null;
  345. if ($plugin) {
  346. $underscored = Inflector::underscore($plugin);
  347. }
  348. $keys = array_merge(array($underscored, $name), array_keys($options), array_keys($data));
  349. $caching = array(
  350. 'config' => $this->elementCache,
  351. 'key' => implode('_', $keys)
  352. );
  353. if (is_array($options['cache'])) {
  354. $defaults = array(
  355. 'config' => $this->elementCache,
  356. 'key' => $caching['key']
  357. );
  358. $caching = array_merge($defaults, $options['cache']);
  359. }
  360. $key = 'element_' . $caching['key'];
  361. $contents = Cache::read($key, $caching['config']);
  362. if ($contents !== false) {
  363. return $contents;
  364. }
  365. }
  366. $file = $this->_getElementFilename($name);
  367. if ($file) {
  368. if (!$this->_helpersLoaded) {
  369. $this->loadHelpers();
  370. }
  371. if ($callbacks) {
  372. $this->getEventManager()->dispatch(new CakeEvent('View.beforeRender', $this, array($file)));
  373. }
  374. $current = $this->_current;
  375. $restore = $this->_currentType;
  376. $this->_currentType = self::TYPE_ELEMENT;
  377. $element = $this->_render($file, array_merge($this->viewVars, $data));
  378. $this->_currentType = $restore;
  379. $this->_current = $current;
  380. if ($callbacks) {
  381. $this->getEventManager()->dispatch(new CakeEvent('View.afterRender', $this, array($file, $element)));
  382. }
  383. if (isset($options['cache'])) {
  384. Cache::write($key, $element, $caching['config']);
  385. }
  386. return $element;
  387. }
  388. $file = 'Elements' . DS . $name . $this->ext;
  389. if (Configure::read('debug') > 0) {
  390. return __d('cake_dev', 'Element Not Found: %s', $file);
  391. }
  392. }
  393. /**
  394. * Renders view for given view file and layout.
  395. *
  396. * Render triggers helper callbacks, which are fired before and after the view are rendered,
  397. * as well as before and after the layout. The helper callbacks are called:
  398. *
  399. * - `beforeRender`
  400. * - `afterRender`
  401. * - `beforeLayout`
  402. * - `afterLayout`
  403. *
  404. * If View::$autoRender is false and no `$layout` is provided, the view will be returned bare.
  405. *
  406. * View and layout names can point to plugin views/layouts. Using the `Plugin.view` syntax
  407. * a plugin view/layout can be used instead of the app ones. If the chosen plugin is not found
  408. * the view will be located along the regular view path cascade.
  409. *
  410. * @param string $view Name of view file to use
  411. * @param string $layout Layout to use.
  412. * @return string Rendered Element
  413. * @throws CakeException if there is an error in the view.
  414. */
  415. public function render($view = null, $layout = null) {
  416. if ($this->hasRendered) {
  417. return true;
  418. }
  419. if (!$this->_helpersLoaded) {
  420. $this->loadHelpers();
  421. }
  422. $this->Blocks->set('content', '');
  423. if ($view !== false && $viewFileName = $this->_getViewFileName($view)) {
  424. $this->_currentType = self::TYPE_VIEW;
  425. $this->getEventManager()->dispatch(new CakeEvent('View.beforeRender', $this, array($viewFileName)));
  426. $this->Blocks->set('content', $this->_render($viewFileName));
  427. $this->getEventManager()->dispatch(new CakeEvent('View.afterRender', $this, array($viewFileName)));
  428. }
  429. if ($layout === null) {
  430. $layout = $this->layout;
  431. }
  432. if ($layout && $this->autoLayout) {
  433. $this->Blocks->set('content', $this->renderLayout('', $layout));
  434. }
  435. $this->hasRendered = true;
  436. return $this->Blocks->get('content');
  437. }
  438. /**
  439. * Renders a layout. Returns output from _render(). Returns false on error.
  440. * Several variables are created for use in layout.
  441. *
  442. * - `title_for_layout` - A backwards compatible place holder, you should set this value if you want more control.
  443. * - `content_for_layout` - contains rendered view file
  444. * - `scripts_for_layout` - Contains content added with addScript() as well as any content in
  445. * the 'meta', 'css', and 'script' blocks. They are appended in that order.
  446. *
  447. * Deprecated features:
  448. *
  449. * - `$scripts_for_layout` is deprecated and will be removed in CakePHP 3.0.
  450. * Use the block features instead. `meta`, `css` and `script` will be populated
  451. * by the matching methods on HtmlHelper.
  452. * - `$title_for_layout` is deprecated and will be removed in CakePHP 3.0
  453. * - `$content_for_layout` is deprecated and will be removed in CakePHP 3.0.
  454. * Use the `content` block instead.
  455. *
  456. * @param string $content Content to render in a view, wrapped by the surrounding layout.
  457. * @param string $layout Layout name
  458. * @return mixed Rendered output, or false on error
  459. * @throws CakeException if there is an error in the view.
  460. */
  461. public function renderLayout($content, $layout = null) {
  462. $layoutFileName = $this->_getLayoutFileName($layout);
  463. if (empty($layoutFileName)) {
  464. return $this->Blocks->get('content');
  465. }
  466. if (!$this->_helpersLoaded) {
  467. $this->loadHelpers();
  468. }
  469. if (empty($content)) {
  470. $content = $this->Blocks->get('content');
  471. }
  472. $this->getEventManager()->dispatch(new CakeEvent('View.beforeLayout', $this, array($layoutFileName)));
  473. $scripts = implode("\n\t", $this->_scripts);
  474. $scripts .= $this->Blocks->get('meta') . $this->Blocks->get('css') . $this->Blocks->get('script');
  475. $this->viewVars = array_merge($this->viewVars, array(
  476. 'content_for_layout' => $content,
  477. 'scripts_for_layout' => $scripts,
  478. ));
  479. if (!isset($this->viewVars['title_for_layout'])) {
  480. $this->viewVars['title_for_layout'] = Inflector::humanize($this->viewPath);
  481. }
  482. $this->_currentType = self::TYPE_LAYOUT;
  483. $this->Blocks->set('content', $this->_render($layoutFileName));
  484. $this->getEventManager()->dispatch(new CakeEvent('View.afterLayout', $this, array($layoutFileName)));
  485. return $this->Blocks->get('content');
  486. }
  487. /**
  488. * Render cached view. Works in concert with CacheHelper and Dispatcher to
  489. * render cached view files.
  490. *
  491. * @param string $filename the cache file to include
  492. * @param string $timeStart the page render start time
  493. * @return boolean Success of rendering the cached file.
  494. */
  495. public function renderCache($filename, $timeStart) {
  496. ob_start();
  497. include ($filename);
  498. if (Configure::read('debug') > 0 && $this->layout != 'xml') {
  499. echo "<!-- Cached Render Time: " . round(microtime(true) - $timeStart, 4) . "s -->";
  500. }
  501. $out = ob_get_clean();
  502. if (preg_match('/^<!--cachetime:(\\d+)-->/', $out, $match)) {
  503. if (time() >= $match['1']) {
  504. @unlink($filename);
  505. unset ($out);
  506. return false;
  507. } else {
  508. if ($this->layout === 'xml') {
  509. header('Content-type: text/xml');
  510. }
  511. $commentLength = strlen('<!--cachetime:' . $match['1'] . '-->');
  512. return substr($out, $commentLength);
  513. }
  514. }
  515. }
  516. /**
  517. * Returns a list of variables available in the current View context
  518. *
  519. * @return array Array of the set view variable names.
  520. */
  521. public function getVars() {
  522. return array_keys($this->viewVars);
  523. }
  524. /**
  525. * Returns the contents of the given View variable(s)
  526. *
  527. * @param string $var The view var you want the contents of.
  528. * @return mixed The content of the named var if its set, otherwise null.
  529. * @deprecated Will be removed in 3.0 Use View::get() instead.
  530. */
  531. public function getVar($var) {
  532. return $this->get($var);
  533. }
  534. /**
  535. * Returns the contents of the given View variable or a block.
  536. * Blocks are checked before view variables.
  537. *
  538. * @param string $var The view var you want the contents of.
  539. * @return mixed The content of the named var if its set, otherwise null.
  540. */
  541. public function get($var) {
  542. if (!isset($this->viewVars[$var])) {
  543. return null;
  544. }
  545. return $this->viewVars[$var];
  546. }
  547. /**
  548. * Get the names of all the existing blocks.
  549. *
  550. * @return array An array containing the blocks.
  551. * @see ViewBlock::keys()
  552. */
  553. public function blocks() {
  554. return $this->Blocks->keys();
  555. }
  556. /**
  557. * Start capturing output for a 'block'
  558. *
  559. * @param string $name The name of the block to capture for.
  560. * @return void
  561. * @see ViewBlock::start()
  562. */
  563. public function start($name) {
  564. return $this->Blocks->start($name);
  565. }
  566. /**
  567. * Append to an existing or new block. Appending to a new
  568. * block will create the block.
  569. *
  570. * @param string $name Name of the block
  571. * @param string $value The content for the block.
  572. * @return void
  573. * @throws CakeException when you use non-string values.
  574. * @see ViewBlock::append()
  575. */
  576. public function append($name, $value = null) {
  577. return $this->Blocks->append($name, $value);
  578. }
  579. /**
  580. * Set the content for a block. This will overwrite any
  581. * existing content.
  582. *
  583. * @param string $name Name of the block
  584. * @param string $value The content for the block.
  585. * @return void
  586. * @throws CakeException when you use non-string values.
  587. * @see ViewBlock::set()
  588. */
  589. public function assign($name, $value) {
  590. return $this->Blocks->set($name, $value);
  591. }
  592. /**
  593. * Fetch the content for a block. If a block is
  594. * empty or undefined '' will be returned.
  595. *
  596. * @param string $name Name of the block
  597. * @return The block content or '' if the block does not exist.
  598. * @see ViewBlock::get()
  599. */
  600. public function fetch($name) {
  601. return $this->Blocks->get($name);
  602. }
  603. /**
  604. * End a capturing block. The compliment to View::start()
  605. *
  606. * @return void
  607. * @see ViewBlock::end()
  608. */
  609. public function end() {
  610. return $this->Blocks->end();
  611. }
  612. /**
  613. * Provides view or element extension/inheritance. Views can extends a
  614. * parent view and populate blocks in the parent template.
  615. *
  616. * @param string $name The view or element to 'extend' the current one with.
  617. * @return void
  618. * @throws LogicException when you extend a view with itself or make extend loops.
  619. * @throws LogicException when you extend an element which doesn't exist
  620. */
  621. public function extend($name) {
  622. if ($name[0] === '/' || $this->_currentType === self::TYPE_VIEW) {
  623. $parent = $this->_getViewFileName($name);
  624. } else {
  625. switch ($this->_currentType) {
  626. case self::TYPE_ELEMENT:
  627. $parent = $this->_getElementFileName($name);
  628. if (!$parent) {
  629. list($plugin, $name) = $this->pluginSplit($name);
  630. $paths = $this->_paths($plugin);
  631. $defaultPath = $paths[0] . 'Elements' . DS;
  632. throw new LogicException(__d(
  633. 'cake_dev',
  634. 'You cannot extend an element which does not exist (%s).',
  635. $defaultPath . $name . $this->ext
  636. ));
  637. }
  638. break;
  639. case self::TYPE_LAYOUT:
  640. $parent = $this->_getLayoutFileName($name);
  641. break;
  642. default:
  643. $parent = $this->_getViewFileName($name);
  644. }
  645. }
  646. if ($parent == $this->_current) {
  647. throw new LogicException(__d('cake_dev', 'You cannot have views extend themselves.'));
  648. }
  649. if (isset($this->_parents[$parent]) && $this->_parents[$parent] == $this->_current) {
  650. throw new LogicException(__d('cake_dev', 'You cannot have views extend in a loop.'));
  651. }
  652. $this->_parents[$this->_current] = $parent;
  653. }
  654. /**
  655. * Adds a script block or other element to be inserted in $scripts_for_layout in
  656. * the `<head />` of a document layout
  657. *
  658. * @param string $name Either the key name for the script, or the script content. Name can be used to
  659. * update/replace a script element.
  660. * @param string $content The content of the script being added, optional.
  661. * @return void
  662. * @deprecated Will be removed in 3.0. Supersceeded by blocks functionality.
  663. * @see View::start()
  664. */
  665. public function addScript($name, $content = null) {
  666. if (empty($content)) {
  667. if (!in_array($name, array_values($this->_scripts))) {
  668. $this->_scripts[] = $name;
  669. }
  670. } else {
  671. $this->_scripts[$name] = $content;
  672. }
  673. }
  674. /**
  675. * Generates a unique, non-random DOM ID for an object, based on the object type and the target URL.
  676. *
  677. * @param string $object Type of object, i.e. 'form' or 'link'
  678. * @param string $url The object's target URL
  679. * @return string
  680. */
  681. public function uuid($object, $url) {
  682. $c = 1;
  683. $url = Router::url($url);
  684. $hash = $object . substr(md5($object . $url), 0, 10);
  685. while (in_array($hash, $this->uuids)) {
  686. $hash = $object . substr(md5($object . $url . $c), 0, 10);
  687. $c++;
  688. }
  689. $this->uuids[] = $hash;
  690. return $hash;
  691. }
  692. /**
  693. * Allows a template or element to set a variable that will be available in
  694. * a layout or other element. Analogous to Controller::set().
  695. *
  696. * @param string|array $one A string or an array of data.
  697. * @param string|array $two Value in case $one is a string (which then works as the key).
  698. * Unused if $one is an associative array, otherwise serves as the values to $one's keys.
  699. * @return void
  700. */
  701. public function set($one, $two = null) {
  702. $data = null;
  703. if (is_array($one)) {
  704. if (is_array($two)) {
  705. $data = array_combine($one, $two);
  706. } else {
  707. $data = $one;
  708. }
  709. } else {
  710. $data = array($one => $two);
  711. }
  712. if ($data == null) {
  713. return false;
  714. }
  715. $this->viewVars = $data + $this->viewVars;
  716. }
  717. /**
  718. * Magic accessor for helpers. Provides access to attributes that were deprecated.
  719. *
  720. * @param string $name Name of the attribute to get.
  721. * @return mixed
  722. */
  723. public function __get($name) {
  724. switch ($name) {
  725. case 'base':
  726. case 'here':
  727. case 'webroot':
  728. case 'data':
  729. return $this->request->{$name};
  730. case 'action':
  731. return $this->request->params['action'];
  732. case 'params':
  733. return $this->request;
  734. case 'output':
  735. return $this->Blocks->get('content');
  736. }
  737. if (isset($this->Helpers->{$name})) {
  738. $this->{$name} = $this->Helpers->{$name};
  739. return $this->Helpers->{$name};
  740. }
  741. return $this->{$name};
  742. }
  743. /**
  744. * Magic accessor for deprecated attributes.
  745. *
  746. * @param string $name Name of the attribute to set.
  747. * @param string $value Value of the attribute to set.
  748. * @return mixed
  749. */
  750. public function __set($name, $value) {
  751. switch ($name) {
  752. case 'output':
  753. return $this->Blocks->set('content', $value);
  754. default:
  755. $this->{$name} = $value;
  756. }
  757. }
  758. /**
  759. * Magic isset check for deprecated attributes.
  760. *
  761. * @param string $name Name of the attribute to check.
  762. * @return boolean
  763. */
  764. public function __isset($name) {
  765. if (isset($this->{$name})) {
  766. return true;
  767. }
  768. $magicGet = array('base', 'here', 'webroot', 'data', 'action', 'params', 'output');
  769. if (in_array($name, $magicGet)) {
  770. return $this->__get($name) !== null;
  771. }
  772. return false;
  773. }
  774. /**
  775. * Interact with the HelperCollection to load all the helpers.
  776. *
  777. * @return void
  778. */
  779. public function loadHelpers() {
  780. $helpers = HelperCollection::normalizeObjectArray($this->helpers);
  781. foreach ($helpers as $properties) {
  782. list($plugin, $class) = pluginSplit($properties['class']);
  783. $this->{$class} = $this->Helpers->load($properties['class'], $properties['settings']);
  784. }
  785. $this->_helpersLoaded = true;
  786. }
  787. /**
  788. * Renders and returns output for given view filename with its
  789. * array of data. Handles parent/extended views.
  790. *
  791. * @param string $viewFile Filename of the view
  792. * @param array $data Data to include in rendered view. If empty the current View::$viewVars will be used.
  793. * @return string Rendered output
  794. * @throws CakeException when a block is left open.
  795. */
  796. protected function _render($viewFile, $data = array()) {
  797. if (empty($data)) {
  798. $data = $this->viewVars;
  799. }
  800. $this->_current = $viewFile;
  801. $initialBlocks = count($this->Blocks->unclosed());
  802. $this->getEventManager()->dispatch(new CakeEvent('View.beforeRenderFile', $this, array($viewFile)));
  803. $content = $this->_evaluate($viewFile, $data);
  804. $afterEvent = new CakeEvent('View.afterRenderFile', $this, array($viewFile, $content));
  805. //TODO: For BC puporses, set extra info in the event object. Remove when appropriate
  806. $afterEvent->modParams = 1;
  807. $this->getEventManager()->dispatch($afterEvent);
  808. $content = $afterEvent->data[1];
  809. if (isset($this->_parents[$viewFile])) {
  810. $this->_stack[] = $this->fetch('content');
  811. $this->assign('content', $content);
  812. $content = $this->_render($this->_parents[$viewFile]);
  813. $this->assign('content', array_pop($this->_stack));
  814. }
  815. $remainingBlocks = count($this->Blocks->unclosed());
  816. if ($initialBlocks !== $remainingBlocks) {
  817. throw new CakeException(__d('cake_dev', 'The "%s" block was left open. Blocks are not allowed to cross files.', $this->Blocks->active()));
  818. }
  819. return $content;
  820. }
  821. /**
  822. * Sandbox method to evaluate a template / view script in.
  823. *
  824. * @param string $viewFn Filename of the view
  825. * @param array $dataForView Data to include in rendered view.
  826. * If empty the current View::$viewVars will be used.
  827. * @return string Rendered output
  828. */
  829. protected function _evaluate($viewFile, $dataForView) {
  830. $this->__viewFile = $viewFile;
  831. extract($dataForView);
  832. ob_start();
  833. include $this->__viewFile;
  834. unset($this->__viewFile);
  835. return ob_get_clean();
  836. }
  837. /**
  838. * Loads a helper. Delegates to the `HelperCollection::load()` to load the helper
  839. *
  840. * @param string $helperName Name of the helper to load.
  841. * @param array $settings Settings for the helper
  842. * @return Helper a constructed helper object.
  843. * @see HelperCollection::load()
  844. */
  845. public function loadHelper($helperName, $settings = array()) {
  846. return $this->Helpers->load($helperName, $settings);
  847. }
  848. /**
  849. * Returns filename of given action's template file (.ctp) as a string.
  850. * CamelCased action names will be under_scored! This means that you can have
  851. * LongActionNames that refer to long_action_names.ctp views.
  852. *
  853. * @param string $name Controller action to find template filename for
  854. * @return string Template filename
  855. * @throws MissingViewException when a view file could not be found.
  856. */
  857. protected function _getViewFileName($name = null) {
  858. $subDir = null;
  859. if (!is_null($this->subDir)) {
  860. $subDir = $this->subDir . DS;
  861. }
  862. if ($name === null) {
  863. $name = $this->view;
  864. }
  865. $name = str_replace('/', DS, $name);
  866. list($plugin, $name) = $this->pluginSplit($name);
  867. if (strpos($name, DS) === false && $name[0] !== '.') {
  868. $name = $this->viewPath . DS . $subDir . Inflector::underscore($name);
  869. } elseif (strpos($name, DS) !== false) {
  870. if ($name[0] === DS || $name[1] === ':') {
  871. if (is_file($name)) {
  872. return $name;
  873. }
  874. $name = trim($name, DS);
  875. } elseif ($name[0] === '.') {
  876. $name = substr($name, 3);
  877. } elseif (!$plugin || $this->viewPath !== $this->name) {
  878. $name = $this->viewPath . DS . $subDir . $name;
  879. }
  880. }
  881. $paths = $this->_paths($plugin);
  882. $exts = $this->_getExtensions();
  883. foreach ($exts as $ext) {
  884. foreach ($paths as $path) {
  885. if (file_exists($path . $name . $ext)) {
  886. return $path . $name . $ext;
  887. }
  888. }
  889. }
  890. $defaultPath = $paths[0];
  891. if ($this->plugin) {
  892. $pluginPaths = App::path('plugins');
  893. foreach ($paths as $path) {
  894. if (strpos($path, $pluginPaths[0]) === 0) {
  895. $defaultPath = $path;
  896. break;
  897. }
  898. }
  899. }
  900. throw new MissingViewException(array('file' => $defaultPath . $name . $this->ext));
  901. }
  902. /**
  903. * Splits a dot syntax plugin name into its plugin and filename.
  904. * If $name does not have a dot, then index 0 will be null.
  905. * It checks if the plugin is loaded, else filename will stay unchanged for filenames containing dot
  906. *
  907. * @param string $name The name you want to plugin split.
  908. * @param boolean $fallback If true uses the plugin set in the current CakeRequest when parsed plugin is not loaded
  909. * @return array Array with 2 indexes. 0 => plugin name, 1 => filename
  910. */
  911. public function pluginSplit($name, $fallback = true) {
  912. $plugin = null;
  913. list($first, $second) = pluginSplit($name);
  914. if (CakePlugin::loaded($first) === true) {
  915. $name = $second;
  916. $plugin = $first;
  917. }
  918. if (isset($this->plugin) && !$plugin && $fallback) {
  919. $plugin = $this->plugin;
  920. }
  921. return array($plugin, $name);
  922. }
  923. /**
  924. * Returns layout filename for this template as a string.
  925. *
  926. * @param string $name The name of the layout to find.
  927. * @return string Filename for layout file (.ctp).
  928. * @throws MissingLayoutException when a layout cannot be located
  929. */
  930. protected function _getLayoutFileName($name = null) {
  931. if ($name === null) {
  932. $name = $this->layout;
  933. }
  934. $subDir = null;
  935. if (!is_null($this->layoutPath)) {
  936. $subDir = $this->layoutPath . DS;
  937. }
  938. list($plugin, $name) = $this->pluginSplit($name);
  939. $paths = $this->_paths($plugin);
  940. $file = 'Layouts' . DS . $subDir . $name;
  941. $exts = $this->_getExtensions();
  942. foreach ($exts as $ext) {
  943. foreach ($paths as $path) {
  944. if (file_exists($path . $file . $ext)) {
  945. return $path . $file . $ext;
  946. }
  947. }
  948. }
  949. throw new MissingLayoutException(array('file' => $paths[0] . $file . $this->ext));
  950. }
  951. /**
  952. * Get the extensions that view files can use.
  953. *
  954. * @return array Array of extensions view files use.
  955. */
  956. protected function _getExtensions() {
  957. $exts = array($this->ext);
  958. if ($this->ext !== '.ctp') {
  959. array_push($exts, '.ctp');
  960. }
  961. return $exts;
  962. }
  963. /**
  964. * Finds an element filename, returns false on failure.
  965. *
  966. * @param string $name The name of the element to find.
  967. * @return mixed Either a string to the element filename or false when one can't be found.
  968. */
  969. protected function _getElementFileName($name) {
  970. list($plugin, $name) = $this->pluginSplit($name);
  971. $paths = $this->_paths($plugin);
  972. $exts = $this->_getExtensions();
  973. foreach ($exts as $ext) {
  974. foreach ($paths as $path) {
  975. if (file_exists($path . 'Elements' . DS . $name . $ext)) {
  976. return $path . 'Elements' . DS . $name . $ext;
  977. }
  978. }
  979. }
  980. return false;
  981. }
  982. /**
  983. * Return all possible paths to find view files in order
  984. *
  985. * @param string $plugin Optional plugin name to scan for view files.
  986. * @param boolean $cached Set to true to force a refresh of view paths.
  987. * @return array paths
  988. */
  989. protected function _paths($plugin = null, $cached = true) {
  990. if ($plugin === null && $cached === true && !empty($this->_paths)) {
  991. return $this->_paths;
  992. }
  993. $paths = array();
  994. $viewPaths = App::path('View');
  995. $corePaths = array_merge(App::core('View'), App::core('Console/Templates/skel/View'));
  996. if (!empty($plugin)) {
  997. $count = count($viewPaths);
  998. for ($i = 0; $i < $count; $i++) {
  999. if (!in_array($viewPaths[$i], $corePaths)) {
  1000. $paths[] = $viewPaths[$i] . 'Plugin' . DS . $plugin . DS;
  1001. }
  1002. }
  1003. $paths = array_merge($paths, App::path('View', $plugin));
  1004. }
  1005. $paths = array_unique(array_merge($paths, $viewPaths));
  1006. if (!empty($this->theme)) {
  1007. $themePaths = array();
  1008. foreach ($paths as $path) {
  1009. if (strpos($path, DS . 'Plugin' . DS) === false) {
  1010. if ($plugin) {
  1011. $themePaths[] = $path . 'Themed' . DS . $this->theme . DS . 'Plugin' . DS . $plugin . DS;
  1012. }
  1013. $themePaths[] = $path . 'Themed' . DS . $this->theme . DS;
  1014. }
  1015. }
  1016. $paths = array_merge($themePaths, $paths);
  1017. }
  1018. $paths = array_merge($paths, $corePaths);
  1019. if ($plugin !== null) {
  1020. return $paths;
  1021. }
  1022. return $this->_paths = $paths;
  1023. }
  1024. }