View.php 26 KB

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