View.php 27 KB

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