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: $this->_currentType = self::TYPE_ELEMENT;
419: $element = $this->_render($file, array_merge($this->viewVars, $data));
420:
421: if ($callbacks) {
422: $this->getEventManager()->dispatch(new CakeEvent('View.afterRender', $this, array($file, $element)));
423: }
424: if (isset($options['cache'])) {
425: Cache::write($key, $element, $caching['config']);
426: }
427: return $element;
428: }
429: $file = 'Elements' . DS . $name . $this->ext;
430:
431: if (Configure::read('debug') > 0) {
432: return __d('cake_dev', 'Element Not Found: %s', $file);
433: }
434: }
435:
436: /**
437: * Renders view for given view file and layout.
438: *
439: * Render triggers helper callbacks, which are fired before and after the view are rendered,
440: * as well as before and after the layout. The helper callbacks are called:
441: *
442: * - `beforeRender`
443: * - `afterRender`
444: * - `beforeLayout`
445: * - `afterLayout`
446: *
447: * If View::$autoRender is false and no `$layout` is provided, the view will be returned bare.
448: *
449: * View and layout names can point to plugin views/layouts. Using the `Plugin.view` syntax
450: * a plugin view/layout can be used instead of the app ones. If the chosen plugin is not found
451: * the view will be located along the regular view path cascade.
452: *
453: * @param string $view Name of view file to use
454: * @param string $layout Layout to use.
455: * @return string Rendered Element
456: * @throws CakeException if there is an error in the view.
457: */
458: public function render($view = null, $layout = null) {
459: if ($this->hasRendered) {
460: return true;
461: }
462: if (!$this->_helpersLoaded) {
463: $this->loadHelpers();
464: }
465: $this->Blocks->set('content', '');
466:
467: if ($view !== false && $viewFileName = $this->_getViewFileName($view)) {
468: $this->_currentType = self::TYPE_VIEW;
469: $this->getEventManager()->dispatch(new CakeEvent('View.beforeRender', $this, array($viewFileName)));
470: $this->Blocks->set('content', $this->_render($viewFileName));
471: $this->getEventManager()->dispatch(new CakeEvent('View.afterRender', $this, array($viewFileName)));
472: }
473:
474: if ($layout === null) {
475: $layout = $this->layout;
476: }
477: if ($layout && $this->autoLayout) {
478: $this->Blocks->set('content', $this->renderLayout('', $layout));
479: }
480: $this->hasRendered = true;
481: return $this->Blocks->get('content');
482: }
483:
484: /**
485: * Renders a layout. Returns output from _render(). Returns false on error.
486: * Several variables are created for use in layout.
487: *
488: * - `title_for_layout` - A backwards compatible place holder, you should set this value if you want more control.
489: * - `content_for_layout` - contains rendered view file
490: * - `scripts_for_layout` - Contains content added with addScript() as well as any content in
491: * the 'meta', 'css', and 'script' blocks. They are appended in that order.
492: *
493: * Deprecated features:
494: *
495: * - `$scripts_for_layout` is deprecated and will be removed in CakePHP 3.0.
496: * Use the block features instead. `meta`, `css` and `script` will be populated
497: * by the matching methods on HtmlHelper.
498: * - `$title_for_layout` is deprecated and will be removed in CakePHP 3.0
499: * - `$content_for_layout` is deprecated and will be removed in CakePHP 3.0.
500: * Use the `content` block instead.
501: *
502: * @param string $content Content to render in a view, wrapped by the surrounding layout.
503: * @param string $layout Layout name
504: * @return mixed Rendered output, or false on error
505: * @throws CakeException if there is an error in the view.
506: */
507: public function renderLayout($content, $layout = null) {
508: $layoutFileName = $this->_getLayoutFileName($layout);
509: if (empty($layoutFileName)) {
510: return $this->Blocks->get('content');
511: }
512:
513: if (!$this->_helpersLoaded) {
514: $this->loadHelpers();
515: }
516: if (empty($content)) {
517: $content = $this->Blocks->get('content');
518: }
519: $this->getEventManager()->dispatch(new CakeEvent('View.beforeLayout', $this, array($layoutFileName)));
520:
521: $scripts = implode("\n\t", $this->_scripts);
522: $scripts .= $this->Blocks->get('meta') . $this->Blocks->get('css') . $this->Blocks->get('script');
523:
524: $this->viewVars = array_merge($this->viewVars, array(
525: 'content_for_layout' => $content,
526: 'scripts_for_layout' => $scripts,
527: ));
528:
529: if (!isset($this->viewVars['title_for_layout'])) {
530: $this->viewVars['title_for_layout'] = Inflector::humanize($this->viewPath);
531: }
532:
533: $this->_currentType = self::TYPE_LAYOUT;
534: $this->Blocks->set('content', $this->_render($layoutFileName));
535:
536: $this->getEventManager()->dispatch(new CakeEvent('View.afterLayout', $this, array($layoutFileName)));
537: return $this->Blocks->get('content');
538: }
539:
540: /**
541: * Render cached view. Works in concert with CacheHelper and Dispatcher to
542: * render cached view files.
543: *
544: * @param string $filename the cache file to include
545: * @param string $timeStart the page render start time
546: * @return boolean Success of rendering the cached file.
547: */
548: public function renderCache($filename, $timeStart) {
549: ob_start();
550: include ($filename);
551:
552: if (Configure::read('debug') > 0 && $this->layout != 'xml') {
553: echo "<!-- Cached Render Time: " . round(microtime(true) - $timeStart, 4) . "s -->";
554: }
555: $out = ob_get_clean();
556:
557: if (preg_match('/^<!--cachetime:(\\d+)-->/', $out, $match)) {
558: if (time() >= $match['1']) {
559: @unlink($filename);
560: unset ($out);
561: return false;
562: } else {
563: if ($this->layout === 'xml') {
564: header('Content-type: text/xml');
565: }
566: $commentLength = strlen('<!--cachetime:' . $match['1'] . '-->');
567: echo substr($out, $commentLength);
568: return true;
569: }
570: }
571: }
572:
573: /**
574: * Returns a list of variables available in the current View context
575: *
576: * @return array Array of the set view variable names.
577: */
578: public function getVars() {
579: return array_keys($this->viewVars);
580: }
581:
582: /**
583: * Returns the contents of the given View variable(s)
584: *
585: * @param string $var The view var you want the contents of.
586: * @return mixed The content of the named var if its set, otherwise null.
587: * @deprecated Will be removed in 3.0 Use View::get() instead.
588: */
589: public function getVar($var) {
590: return $this->get($var);
591: }
592:
593: /**
594: * Returns the contents of the given View variable or a block.
595: * Blocks are checked before view variables.
596: *
597: * @param string $var The view var you want the contents of.
598: * @return mixed The content of the named var if its set, otherwise null.
599: */
600: public function get($var) {
601: if (!isset($this->viewVars[$var])) {
602: return null;
603: }
604: return $this->viewVars[$var];
605: }
606:
607: /**
608: * Get the names of all the existing blocks.
609: *
610: * @return array An array containing the blocks.
611: * @see ViewBlock::keys()
612: */
613: public function blocks() {
614: return $this->Blocks->keys();
615: }
616:
617: /**
618: * Start capturing output for a 'block'
619: *
620: * @param string $name The name of the block to capture for.
621: * @return void
622: * @see ViewBlock::start()
623: */
624: public function start($name) {
625: return $this->Blocks->start($name);
626: }
627:
628: /**
629: * Append to an existing or new block. Appending to a new
630: * block will create the block.
631: *
632: * @param string $name Name of the block
633: * @param string $value The content for the block.
634: * @return void
635: * @throws CakeException when you use non-string values.
636: * @see ViewBlock::append()
637: */
638: public function append($name, $value = null) {
639: return $this->Blocks->append($name, $value);
640: }
641:
642: /**
643: * Set the content for a block. This will overwrite any
644: * existing content.
645: *
646: * @param string $name Name of the block
647: * @param string $value The content for the block.
648: * @return void
649: * @throws CakeException when you use non-string values.
650: * @see ViewBlock::assign()
651: */
652: public function assign($name, $value) {
653: return $this->Blocks->set($name, $value);
654: }
655:
656: /**
657: * Fetch the content for a block. If a block is
658: * empty or undefined '' will be returned.
659: *
660: * @param string $name Name of the block
661: * @return The block content or '' if the block does not exist.
662: * @see ViewBlock::fetch()
663: */
664: public function fetch($name) {
665: return $this->Blocks->get($name);
666: }
667:
668: /**
669: * End a capturing block. The compliment to View::start()
670: *
671: * @return void
672: * @see ViewBlock::start()
673: */
674: public function end() {
675: return $this->Blocks->end();
676: }
677:
678: /**
679: * Provides view or element extension/inheritance. Views can extends a
680: * parent view and populate blocks in the parent template.
681: *
682: * @param string $name The view or element to 'extend' the current one with.
683: * @return void
684: * @throws LogicException when you extend a view with itself or make extend loops.
685: * @throws LogicException when you extend an element which doesn't exist
686: */
687: public function extend($name) {
688: if ($name[0] === '/' || $this->_currentType === self::TYPE_VIEW) {
689: $parent = $this->_getViewFileName($name);
690: } else {
691: switch ($this->_currentType) {
692: case self::TYPE_ELEMENT:
693: $parent = $this->_getElementFileName($name);
694: if (!$parent) {
695: list($plugin, $name) = $this->pluginSplit($name);
696: $paths = $this->_paths($plugin);
697: $defaultPath = $paths[0] . 'Elements' . DS;
698: throw new LogicException(__d(
699: 'cake_dev',
700: 'You cannot extend an element which does not exist (%s).',
701: $defaultPath . $name . $this->ext
702: ));
703: }
704: break;
705: case self::TYPE_LAYOUT:
706: $parent = $this->_getLayoutFileName($name);
707: break;
708: default:
709: $parent = $this->_getViewFileName($name);
710: }
711: }
712:
713: if ($parent == $this->_current) {
714: throw new LogicException(__d('cake_dev', 'You cannot have views extend themselves.'));
715: }
716: if (isset($this->_parents[$parent]) && $this->_parents[$parent] == $this->_current) {
717: throw new LogicException(__d('cake_dev', 'You cannot have views extend in a loop.'));
718: }
719: $this->_parents[$this->_current] = $parent;
720: }
721:
722: /**
723: * Adds a script block or other element to be inserted in $scripts_for_layout in
724: * the `<head />` of a document layout
725: *
726: * @param string $name Either the key name for the script, or the script content. Name can be used to
727: * update/replace a script element.
728: * @param string $content The content of the script being added, optional.
729: * @return void
730: * @deprecated Will be removed in 3.0. Supersceeded by blocks functionality.
731: * @see View::start()
732: */
733: public function addScript($name, $content = null) {
734: if (empty($content)) {
735: if (!in_array($name, array_values($this->_scripts))) {
736: $this->_scripts[] = $name;
737: }
738: } else {
739: $this->_scripts[$name] = $content;
740: }
741: }
742:
743: /**
744: * Generates a unique, non-random DOM ID for an object, based on the object type and the target URL.
745: *
746: * @param string $object Type of object, i.e. 'form' or 'link'
747: * @param string $url The object's target URL
748: * @return string
749: */
750: public function uuid($object, $url) {
751: $c = 1;
752: $url = Router::url($url);
753: $hash = $object . substr(md5($object . $url), 0, 10);
754: while (in_array($hash, $this->uuids)) {
755: $hash = $object . substr(md5($object . $url . $c), 0, 10);
756: $c++;
757: }
758: $this->uuids[] = $hash;
759: return $hash;
760: }
761:
762: /**
763: * Allows a template or element to set a variable that will be available in
764: * a layout or other element. Analogous to Controller::set().
765: *
766: * @param mixed $one A string or an array of data.
767: * @param mixed $two Value in case $one is a string (which then works as the key).
768: * Unused if $one is an associative array, otherwise serves as the values to $one's keys.
769: * @return void
770: */
771: public function set($one, $two = null) {
772: $data = null;
773: if (is_array($one)) {
774: if (is_array($two)) {
775: $data = array_combine($one, $two);
776: } else {
777: $data = $one;
778: }
779: } else {
780: $data = array($one => $two);
781: }
782: if ($data == null) {
783: return false;
784: }
785: $this->viewVars = $data + $this->viewVars;
786: }
787:
788: /**
789: * Magic accessor for helpers. Provides access to attributes that were deprecated.
790: *
791: * @param string $name Name of the attribute to get.
792: * @return mixed
793: */
794: public function __get($name) {
795: if (isset($this->Helpers->{$name})) {
796: return $this->Helpers->{$name};
797: }
798: switch ($name) {
799: case 'base':
800: case 'here':
801: case 'webroot':
802: case 'data':
803: return $this->request->{$name};
804: case 'action':
805: return $this->request->params['action'];
806: case 'params':
807: return $this->request;
808: case 'output':
809: return $this->Blocks->get('content');
810: default:
811: return $this->{$name};
812: }
813: }
814:
815: /**
816: * Magic accessor for deprecated attributes.
817: *
818: * @param string $name Name of the attribute to set.
819: * @param string $value Value of the attribute to set.
820: * @return mixed
821: */
822: public function __set($name, $value) {
823: switch ($name) {
824: case 'output':
825: return $this->Blocks->set('content', $value);
826: default:
827: $this->{$name} = $value;
828: }
829: }
830:
831: /**
832: * Magic isset check for deprecated attributes.
833: *
834: * @param string $name Name of the attribute to check.
835: * @return boolean
836: */
837: public function __isset($name) {
838: if (isset($this->{$name})) {
839: return true;
840: }
841: $magicGet = array('base', 'here', 'webroot', 'data', 'action', 'params', 'output');
842: if (in_array($name, $magicGet)) {
843: return $this->__get($name) !== null;
844: }
845: return false;
846: }
847:
848: /**
849: * Interact with the HelperCollection to load all the helpers.
850: *
851: * @return void
852: */
853: public function loadHelpers() {
854: $helpers = HelperCollection::normalizeObjectArray($this->helpers);
855: foreach ($helpers as $name => $properties) {
856: list($plugin, $class) = pluginSplit($properties['class']);
857: $this->{$class} = $this->Helpers->load($properties['class'], $properties['settings']);
858: }
859: $this->_helpersLoaded = true;
860: }
861:
862: /**
863: * Renders and returns output for given view filename with its
864: * array of data. Handles parent/extended views.
865: *
866: * @param string $viewFile Filename of the view
867: * @param array $data Data to include in rendered view. If empty the current View::$viewVars will be used.
868: * @return string Rendered output
869: * @throws CakeException when a block is left open.
870: */
871: protected function _render($viewFile, $data = array()) {
872: if (empty($data)) {
873: $data = $this->viewVars;
874: }
875: $this->_current = $viewFile;
876: $initialBlocks = count($this->Blocks->unclosed());
877:
878: $this->getEventManager()->dispatch(new CakeEvent('View.beforeRenderFile', $this, array($viewFile)));
879: $content = $this->_evaluate($viewFile, $data);
880: $afterEvent = new CakeEvent('View.afterRenderFile', $this, array($viewFile, $content));
881: //TODO: For BC puporses, set extra info in the event object. Remove when appropriate
882: $afterEvent->modParams = 1;
883: $this->getEventManager()->dispatch($afterEvent);
884: $content = $afterEvent->data[1];
885:
886: if (isset($this->_parents[$viewFile])) {
887: $this->_stack[] = $this->fetch('content');
888: $this->assign('content', $content);
889:
890: $content = $this->_render($this->_parents[$viewFile]);
891: $this->assign('content', array_pop($this->_stack));
892: }
893:
894: $remainingBlocks = count($this->Blocks->unclosed());
895:
896: if ($initialBlocks !== $remainingBlocks) {
897: throw new CakeException(__d('cake_dev', 'The "%s" block was left open. Blocks are not allowed to cross files.', $this->Blocks->active()));
898: }
899:
900: return $content;
901: }
902:
903: /**
904: * Sandbox method to evaluate a template / view script in.
905: *
906: * @param string $___viewFn Filename of the view
907: * @param array $___dataForView Data to include in rendered view.
908: * If empty the current View::$viewVars will be used.
909: * @return string Rendered output
910: */
911: protected function _evaluate($___viewFn, $___dataForView) {
912: extract($___dataForView, EXTR_SKIP);
913: ob_start();
914:
915: include $___viewFn;
916:
917: return ob_get_clean();
918: }
919:
920: /**
921: * Loads a helper. Delegates to the `HelperCollection::load()` to load the helper
922: *
923: * @param string $helperName Name of the helper to load.
924: * @param array $settings Settings for the helper
925: * @return Helper a constructed helper object.
926: * @see HelperCollection::load()
927: */
928: public function loadHelper($helperName, $settings = array()) {
929: return $this->Helpers->load($helperName, $settings);
930: }
931:
932: /**
933: * Returns filename of given action's template file (.ctp) as a string.
934: * CamelCased action names will be under_scored! This means that you can have
935: * LongActionNames that refer to long_action_names.ctp views.
936: *
937: * @param string $name Controller action to find template filename for
938: * @return string Template filename
939: * @throws MissingViewException when a view file could not be found.
940: */
941: protected function _getViewFileName($name = null) {
942: $subDir = null;
943:
944: if (!is_null($this->subDir)) {
945: $subDir = $this->subDir . DS;
946: }
947:
948: if ($name === null) {
949: $name = $this->view;
950: }
951: $name = str_replace('/', DS, $name);
952: list($plugin, $name) = $this->pluginSplit($name);
953:
954: if (strpos($name, DS) === false && $name[0] !== '.') {
955: $name = $this->viewPath . DS . $subDir . Inflector::underscore($name);
956: } elseif (strpos($name, DS) !== false) {
957: if ($name[0] === DS || $name[1] === ':') {
958: if (is_file($name)) {
959: return $name;
960: }
961: $name = trim($name, DS);
962: } elseif ($name[0] === '.') {
963: $name = substr($name, 3);
964: } elseif (!$plugin || $this->viewPath !== $this->name) {
965: $name = $this->viewPath . DS . $subDir . $name;
966: }
967: }
968: $paths = $this->_paths($plugin);
969: $exts = $this->_getExtensions();
970: foreach ($exts as $ext) {
971: foreach ($paths as $path) {
972: if (file_exists($path . $name . $ext)) {
973: return $path . $name . $ext;
974: }
975: }
976: }
977: $defaultPath = $paths[0];
978:
979: if ($this->plugin) {
980: $pluginPaths = App::path('plugins');
981: foreach ($paths as $path) {
982: if (strpos($path, $pluginPaths[0]) === 0) {
983: $defaultPath = $path;
984: break;
985: }
986: }
987: }
988: throw new MissingViewException(array('file' => $defaultPath . $name . $this->ext));
989: }
990:
991: /**
992: * Splits a dot syntax plugin name into its plugin and filename.
993: * If $name does not have a dot, then index 0 will be null.
994: * It checks if the plugin is loaded, else filename will stay unchanged for filenames containing dot
995: *
996: * @param string $name The name you want to plugin split.
997: * @param boolean $fallback If true uses the plugin set in the current CakeRequest when parsed plugin is not loaded
998: * @return array Array with 2 indexes. 0 => plugin name, 1 => filename
999: */
1000: public function pluginSplit($name, $fallback = true) {
1001: $plugin = null;
1002: list($first, $second) = pluginSplit($name);
1003: if (CakePlugin::loaded($first) === true) {
1004: $name = $second;
1005: $plugin = $first;
1006: }
1007: if (isset($this->plugin) && !$plugin && $fallback) {
1008: $plugin = $this->plugin;
1009: }
1010: return array($plugin, $name);
1011: }
1012:
1013: /**
1014: * Returns layout filename for this template as a string.
1015: *
1016: * @param string $name The name of the layout to find.
1017: * @return string Filename for layout file (.ctp).
1018: * @throws MissingLayoutException when a layout cannot be located
1019: */
1020: protected function _getLayoutFileName($name = null) {
1021: if ($name === null) {
1022: $name = $this->layout;
1023: }
1024: $subDir = null;
1025:
1026: if (!is_null($this->layoutPath)) {
1027: $subDir = $this->layoutPath . DS;
1028: }
1029: list($plugin, $name) = $this->pluginSplit($name);
1030: $paths = $this->_paths($plugin);
1031: $file = 'Layouts' . DS . $subDir . $name;
1032:
1033: $exts = $this->_getExtensions();
1034: foreach ($exts as $ext) {
1035: foreach ($paths as $path) {
1036: if (file_exists($path . $file . $ext)) {
1037: return $path . $file . $ext;
1038: }
1039: }
1040: }
1041: throw new MissingLayoutException(array('file' => $paths[0] . $file . $this->ext));
1042: }
1043:
1044: /**
1045: * Get the extensions that view files can use.
1046: *
1047: * @return array Array of extensions view files use.
1048: */
1049: protected function _getExtensions() {
1050: $exts = array($this->ext);
1051: if ($this->ext !== '.ctp') {
1052: array_push($exts, '.ctp');
1053: }
1054: return $exts;
1055: }
1056:
1057: /**
1058: * Finds an element filename, returns false on failure.
1059: *
1060: * @param string $name The name of the element to find.
1061: * @return mixed Either a string to the element filename or false when one can't be found.
1062: */
1063: protected function _getElementFileName($name) {
1064: list($plugin, $name) = $this->pluginSplit($name);
1065:
1066: $paths = $this->_paths($plugin);
1067: $exts = $this->_getExtensions();
1068: foreach ($exts as $ext) {
1069: foreach ($paths as $path) {
1070: if (file_exists($path . 'Elements' . DS . $name . $ext)) {
1071: return $path . 'Elements' . DS . $name . $ext;
1072: }
1073: }
1074: }
1075: return false;
1076: }
1077:
1078: /**
1079: * Return all possible paths to find view files in order
1080: *
1081: * @param string $plugin Optional plugin name to scan for view files.
1082: * @param boolean $cached Set to true to force a refresh of view paths.
1083: * @return array paths
1084: */
1085: protected function _paths($plugin = null, $cached = true) {
1086: if ($plugin === null && $cached === true && !empty($this->_paths)) {
1087: return $this->_paths;
1088: }
1089: $paths = array();
1090: $viewPaths = App::path('View');
1091: $corePaths = array_merge(App::core('View'), App::core('Console/Templates/skel/View'));
1092:
1093: if (!empty($plugin)) {
1094: $count = count($viewPaths);
1095: for ($i = 0; $i < $count; $i++) {
1096: if (!in_array($viewPaths[$i], $corePaths)) {
1097: $paths[] = $viewPaths[$i] . 'Plugin' . DS . $plugin . DS;
1098: }
1099: }
1100: $paths = array_merge($paths, App::path('View', $plugin));
1101: }
1102:
1103: $paths = array_unique(array_merge($paths, $viewPaths));
1104: if (!empty($this->theme)) {
1105: $themePaths = array();
1106: foreach ($paths as $path) {
1107: if (strpos($path, DS . 'Plugin' . DS) === false) {
1108: if ($plugin) {
1109: $themePaths[] = $path . 'Themed' . DS . $this->theme . DS . 'Plugin' . DS . $plugin . DS;
1110: }
1111: $themePaths[] = $path . 'Themed' . DS . $this->theme . DS;
1112: }
1113: }
1114: $paths = array_merge($themePaths, $paths);
1115: }
1116: $paths = array_merge($paths, $corePaths);
1117: if ($plugin !== null) {
1118: return $paths;
1119: }
1120: return $this->_paths = $paths;
1121: }
1122:
1123: }
1124: