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