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