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