Subversion Repositories SmartDukaan

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
13532 anikendra 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 Name of controller
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 A single name as a string or a list of names as an array.
98
 */
99
	public $helpers = array();
100
 
101
/**
102
 * Path to View.
103
 *
104
 * @var string Path to View
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 Path to Layout
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 boolean
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 boolean
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
 * The names of views and their parents used with View::extend();
256
 *
257
 * @var array
258
 */
259
	protected $_parents = array();
260
 
261
/**
262
 * The currently rendering view file. Used for resolving parent files.
263
 *
264
 * @var string
265
 */
266
	protected $_current = null;
267
 
268
/**
269
 * Currently rendering an element. Used for finding parent fragments
270
 * for elements.
271
 *
272
 * @var string
273
 */
274
	protected $_currentType = '';
275
 
276
/**
277
 * Content stack, used for nested templates that all use View::extend();
278
 *
279
 * @var array
280
 */
281
	protected $_stack = array();
282
 
283
/**
284
 * Instance of the CakeEventManager this View object is using
285
 * to dispatch inner events. Usually the manager is shared with
286
 * the controller, so it it possible to register view events in
287
 * the controller layer.
288
 *
289
 * @var CakeEventManager
290
 */
291
	protected $_eventManager = null;
292
 
293
/**
294
 * Whether the event manager was already configured for this object
295
 *
296
 * @var boolean
297
 */
298
	protected $_eventManagerConfigured = false;
299
 
300
/**
301
 * Constant for view file type 'view'
302
 */
303
	const TYPE_VIEW = 'view';
304
 
305
/**
306
 * Constant for view file type 'element'
307
 */
308
	const TYPE_ELEMENT = 'element';
309
 
310
/**
311
 * Constant for view file type 'layout'
312
 */
313
	const TYPE_LAYOUT = 'layout';
314
 
315
/**
316
 * Constructor
317
 *
318
 * @param Controller $controller A controller object to pull View::_passedVars from.
319
 */
320
	public function __construct(Controller $controller = null) {
321
		if (is_object($controller)) {
322
			$count = count($this->_passedVars);
323
			for ($j = 0; $j < $count; $j++) {
324
				$var = $this->_passedVars[$j];
325
				$this->{$var} = $controller->{$var};
326
			}
327
			$this->_eventManager = $controller->getEventManager();
328
		}
329
		if (empty($this->request) && !($this->request = Router::getRequest(true))) {
330
			$this->request = new CakeRequest(null, false);
331
			$this->request->base = '';
332
			$this->request->here = $this->request->webroot = '/';
333
		}
334
		if (is_object($controller) && isset($controller->response)) {
335
			$this->response = $controller->response;
336
		} else {
337
			$this->response = new CakeResponse();
338
		}
339
		$this->Helpers = new HelperCollection($this);
340
		$this->Blocks = new ViewBlock();
341
		$this->loadHelpers();
342
		parent::__construct();
343
	}
344
 
345
/**
346
 * Returns the CakeEventManager manager instance that is handling any callbacks.
347
 * You can use this instance to register any new listeners or callbacks to the
348
 * controller events, or create your own events and trigger them at will.
349
 *
350
 * @return CakeEventManager
351
 */
352
	public function getEventManager() {
353
		if (empty($this->_eventManager)) {
354
			$this->_eventManager = new CakeEventManager();
355
		}
356
		if (!$this->_eventManagerConfigured) {
357
			$this->_eventManager->attach($this->Helpers);
358
			$this->_eventManagerConfigured = true;
359
		}
360
		return $this->_eventManager;
361
	}
362
 
363
/**
364
 * Renders a piece of PHP with provided parameters and returns HTML, XML, or any other string.
365
 *
366
 * This realizes the concept of Elements, (or "partial layouts") and the $params array is used to send
367
 * data to be used in the element. Elements can be cached improving performance by using the `cache` option.
368
 *
369
 * @param string $name Name of template file in the/app/View/Elements/ folder,
370
 *   or `MyPlugin.template` to use the template element from MyPlugin. If the element
371
 *   is not found in the plugin, the normal view path cascade will be searched.
372
 * @param array $data Array of data to be made available to the rendered view (i.e. the Element)
373
 * @param array $options Array of options. Possible keys are:
374
 * - `cache` - Can either be `true`, to enable caching using the config in View::$elementCache. Or an array
375
 *   If an array, the following keys can be used:
376
 *   - `config` - Used to store the cached element in a custom cache configuration.
377
 *   - `key` - Used to define the key used in the Cache::write(). It will be prefixed with `element_`
378
 * - `plugin` - Load an element from a specific plugin. This option is deprecated, see below.
379
 * - `callbacks` - Set to true to fire beforeRender and afterRender helper callbacks for this element.
380
 *   Defaults to false.
381
 * - `ignoreMissing` - Used to allow missing elements. Set to true to not trigger notices.
382
 * @return string Rendered Element
383
 * @deprecated The `$options['plugin']` is deprecated and will be removed in CakePHP 3.0. Use
384
 *   `Plugin.element_name` instead.
385
 */
386
	public function element($name, $data = array(), $options = array()) {
387
		$file = $plugin = null;
388
 
389
		if (isset($options['plugin'])) {
390
			$name = Inflector::camelize($options['plugin']) . '.' . $name;
391
		}
392
 
393
		if (!isset($options['callbacks'])) {
394
			$options['callbacks'] = false;
395
		}
396
 
397
		if (isset($options['cache'])) {
398
			$contents = $this->_elementCache($name, $data, $options);
399
			if ($contents !== false) {
400
				return $contents;
401
			}
402
		}
403
 
404
		$file = $this->_getElementFilename($name);
405
		if ($file) {
406
			return $this->_renderElement($file, $data, $options);
407
		}
408
 
409
		if (empty($options['ignoreMissing'])) {
410
			list ($plugin, $name) = pluginSplit($name, true);
411
			$name = str_replace('/', DS, $name);
412
			$file = $plugin . 'Elements' . DS . $name . $this->ext;
413
			trigger_error(__d('cake_dev', 'Element Not Found: %s', $file), E_USER_NOTICE);
414
		}
415
	}
416
 
417
/**
418
 * Checks if an element exists
419
 *
420
 * @param string $name Name of template file in the /app/View/Elements/ folder,
421
 *   or `MyPlugin.template` to check the template element from MyPlugin. If the element
422
 *   is not found in the plugin, the normal view path cascade will be searched.
423
 * @return boolean Success
424
 */
425
	public function elementExists($name) {
426
		return (bool)$this->_getElementFilename($name);
427
	}
428
 
429
/**
430
 * Renders view for given view file and layout.
431
 *
432
 * Render triggers helper callbacks, which are fired before and after the view are rendered,
433
 * as well as before and after the layout. The helper callbacks are called:
434
 *
435
 * - `beforeRender`
436
 * - `afterRender`
437
 * - `beforeLayout`
438
 * - `afterLayout`
439
 *
440
 * If View::$autoRender is false and no `$layout` is provided, the view will be returned bare.
441
 *
442
 * View and layout names can point to plugin views/layouts. Using the `Plugin.view` syntax
443
 * a plugin view/layout can be used instead of the app ones. If the chosen plugin is not found
444
 * the view will be located along the regular view path cascade.
445
 *
446
 * @param string $view Name of view file to use
447
 * @param string $layout Layout to use.
448
 * @return string Rendered Element
449
 * @throws CakeException If there is an error in the view.
450
 */
451
	public function render($view = null, $layout = null) {
452
		if ($this->hasRendered) {
453
			return true;
454
		}
455
		$this->Blocks->set('content', '');
456
 
457
		if ($view !== false && $viewFileName = $this->_getViewFileName($view)) {
458
			$this->_currentType = self::TYPE_VIEW;
459
			$this->getEventManager()->dispatch(new CakeEvent('View.beforeRender', $this, array($viewFileName)));
460
			$this->Blocks->set('content', $this->_render($viewFileName));
461
			$this->getEventManager()->dispatch(new CakeEvent('View.afterRender', $this, array($viewFileName)));
462
		}
463
 
464
		if ($layout === null) {
465
			$layout = $this->layout;
466
		}
467
		if ($layout && $this->autoLayout) {
468
			$this->Blocks->set('content', $this->renderLayout('', $layout));
469
		}
470
		$this->hasRendered = true;
471
		return $this->Blocks->get('content');
472
	}
473
 
474
/**
475
 * Renders a layout. Returns output from _render(). Returns false on error.
476
 * Several variables are created for use in layout.
477
 *
478
 * - `title_for_layout` - A backwards compatible place holder, you should set this value if you want more control.
479
 * - `content_for_layout` - contains rendered view file
480
 * - `scripts_for_layout` - Contains content added with addScript() as well as any content in
481
 *   the 'meta', 'css', and 'script' blocks. They are appended in that order.
482
 *
483
 * Deprecated features:
484
 *
485
 * - `$scripts_for_layout` is deprecated and will be removed in CakePHP 3.0.
486
 *   Use the block features instead. `meta`, `css` and `script` will be populated
487
 *   by the matching methods on HtmlHelper.
488
 * - `$title_for_layout` is deprecated and will be removed in CakePHP 3.0
489
 * - `$content_for_layout` is deprecated and will be removed in CakePHP 3.0.
490
 *   Use the `content` block instead.
491
 *
492
 * @param string $content Content to render in a view, wrapped by the surrounding layout.
493
 * @param string $layout Layout name
494
 * @return mixed Rendered output, or false on error
495
 * @throws CakeException if there is an error in the view.
496
 */
497
	public function renderLayout($content, $layout = null) {
498
		$layoutFileName = $this->_getLayoutFileName($layout);
499
		if (empty($layoutFileName)) {
500
			return $this->Blocks->get('content');
501
		}
502
 
503
		if (empty($content)) {
504
			$content = $this->Blocks->get('content');
505
		} else {
506
			$this->Blocks->set('content', $content);
507
		}
508
		$this->getEventManager()->dispatch(new CakeEvent('View.beforeLayout', $this, array($layoutFileName)));
509
 
510
		$scripts = implode("\n\t", $this->_scripts);
511
		$scripts .= $this->Blocks->get('meta') . $this->Blocks->get('css') . $this->Blocks->get('script');
512
 
513
		$this->viewVars = array_merge($this->viewVars, array(
514
			'content_for_layout' => $content,
515
			'scripts_for_layout' => $scripts,
516
		));
517
 
518
		if (!isset($this->viewVars['title_for_layout'])) {
519
			$this->viewVars['title_for_layout'] = Inflector::humanize($this->viewPath);
520
		}
521
 
522
		$this->_currentType = self::TYPE_LAYOUT;
523
		$this->Blocks->set('content', $this->_render($layoutFileName));
524
 
525
		$this->getEventManager()->dispatch(new CakeEvent('View.afterLayout', $this, array($layoutFileName)));
526
		return $this->Blocks->get('content');
527
	}
528
 
529
/**
530
 * Render cached view. Works in concert with CacheHelper and Dispatcher to
531
 * render cached view files.
532
 *
533
 * @param string $filename the cache file to include
534
 * @param string $timeStart the page render start time
535
 * @return boolean Success of rendering the cached file.
536
 */
537
	public function renderCache($filename, $timeStart) {
538
		$response = $this->response;
539
		ob_start();
540
		include $filename;
541
 
542
		$type = $response->mapType($response->type());
543
		if (Configure::read('debug') > 0 && $type === 'html') {
544
			echo "<!-- Cached Render Time: " . round(microtime(true) - $timeStart, 4) . "s -->";
545
		}
546
		$out = ob_get_clean();
547
 
548
		if (preg_match('/^<!--cachetime:(\\d+)-->/', $out, $match)) {
549
			if (time() >= $match['1']) {
550
				//@codingStandardsIgnoreStart
551
				@unlink($filename);
552
				//@codingStandardsIgnoreEnd
553
				unset($out);
554
				return false;
555
			}
556
			return substr($out, strlen($match[0]));
557
		}
558
	}
559
 
560
/**
561
 * Returns a list of variables available in the current View context
562
 *
563
 * @return array Array of the set view variable names.
564
 */
565
	public function getVars() {
566
		return array_keys($this->viewVars);
567
	}
568
 
569
/**
570
 * Returns the contents of the given View variable(s)
571
 *
572
 * @param string $var The view var you want the contents of.
573
 * @return mixed The content of the named var if its set, otherwise null.
574
 * @deprecated Will be removed in 3.0. Use View::get() instead.
575
 */
576
	public function getVar($var) {
577
		return $this->get($var);
578
	}
579
 
580
/**
581
 * Returns the contents of the given View variable or a block.
582
 * Blocks are checked before view variables.
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
 */
587
	public function get($var) {
588
		if (!isset($this->viewVars[$var])) {
589
			return null;
590
		}
591
		return $this->viewVars[$var];
592
	}
593
 
594
/**
595
 * Get the names of all the existing blocks.
596
 *
597
 * @return array An array containing the blocks.
598
 * @see ViewBlock::keys()
599
 */
600
	public function blocks() {
601
		return $this->Blocks->keys();
602
	}
603
 
604
/**
605
 * Start capturing output for a 'block'
606
 *
607
 * @param string $name The name of the block to capture for.
608
 * @return void
609
 * @see ViewBlock::start()
610
 */
611
	public function start($name) {
612
		$this->Blocks->start($name);
613
	}
614
 
615
/**
616
 * Start capturing output for a 'block' if it has no content
617
 *
618
 * @param string $name The name of the block to capture for.
619
 * @return void
620
 * @see ViewBlock::startIfEmpty()
621
 */
622
	public function startIfEmpty($name) {
623
		$this->Blocks->startIfEmpty($name);
624
	}
625
 
626
/**
627
 * Append to an existing or new block. Appending to a new
628
 * block will create the block.
629
 *
630
 * @param string $name Name of the block
631
 * @param mixed $value The content for the block.
632
 * @return void
633
 * @see ViewBlock::concat()
634
 */
635
	public function append($name, $value = null) {
636
		$this->Blocks->concat($name, $value);
637
	}
638
 
639
/**
640
 * Prepend to an existing or new block. Prepending to a new
641
 * block will create the block.
642
 *
643
 * @param string $name Name of the block
644
 * @param mixed $value The content for the block.
645
 * @return void
646
 * @see ViewBlock::concat()
647
 */
648
	public function prepend($name, $value = null) {
649
		$this->Blocks->concat($name, $value, ViewBlock::PREPEND);
650
	}
651
 
652
/**
653
 * Set the content for a block. This will overwrite any
654
 * existing content.
655
 *
656
 * @param string $name Name of the block
657
 * @param mixed $value The content for the block.
658
 * @return void
659
 * @see ViewBlock::set()
660
 */
661
	public function assign($name, $value) {
662
		$this->Blocks->set($name, $value);
663
	}
664
 
665
/**
666
 * Fetch the content for a block. If a block is
667
 * empty or undefined '' will be returned.
668
 *
669
 * @param string $name Name of the block
670
 * @param string $default Default text
671
 * @return string $default The block content or $default if the block does not exist.
672
 * @see ViewBlock::get()
673
 */
674
	public function fetch($name, $default = '') {
675
		return $this->Blocks->get($name, $default);
676
	}
677
 
678
/**
679
 * End a capturing block. The compliment to View::start()
680
 *
681
 * @return void
682
 * @see ViewBlock::end()
683
 */
684
	public function end() {
685
		$this->Blocks->end();
686
	}
687
 
688
/**
689
 * Provides view or element extension/inheritance. Views can extends a
690
 * parent view and populate blocks in the parent template.
691
 *
692
 * @param string $name The view or element to 'extend' the current one with.
693
 * @return void
694
 * @throws LogicException when you extend a view with itself or make extend loops.
695
 * @throws LogicException when you extend an element which doesn't exist
696
 */
697
	public function extend($name) {
698
		if ($name[0] === '/' || $this->_currentType === self::TYPE_VIEW) {
699
			$parent = $this->_getViewFileName($name);
700
		} else {
701
			switch ($this->_currentType) {
702
				case self::TYPE_ELEMENT:
703
					$parent = $this->_getElementFileName($name);
704
					if (!$parent) {
705
						list($plugin, $name) = $this->pluginSplit($name);
706
						$paths = $this->_paths($plugin);
707
						$defaultPath = $paths[0] . 'Elements' . DS;
708
						throw new LogicException(__d(
709
							'cake_dev',
710
							'You cannot extend an element which does not exist (%s).',
711
							$defaultPath . $name . $this->ext
712
						));
713
					}
714
					break;
715
				case self::TYPE_LAYOUT:
716
					$parent = $this->_getLayoutFileName($name);
717
					break;
718
				default:
719
					$parent = $this->_getViewFileName($name);
720
			}
721
		}
722
 
723
		if ($parent == $this->_current) {
724
			throw new LogicException(__d('cake_dev', 'You cannot have views extend themselves.'));
725
		}
726
		if (isset($this->_parents[$parent]) && $this->_parents[$parent] == $this->_current) {
727
			throw new LogicException(__d('cake_dev', 'You cannot have views extend in a loop.'));
728
		}
729
		$this->_parents[$this->_current] = $parent;
730
	}
731
 
732
/**
733
 * Adds a script block or other element to be inserted in $scripts_for_layout in
734
 * the `<head />` of a document layout
735
 *
736
 * @param string $name Either the key name for the script, or the script content. Name can be used to
737
 *   update/replace a script element.
738
 * @param string $content The content of the script being added, optional.
739
 * @return void
740
 * @deprecated Will be removed in 3.0. Superseded by blocks functionality.
741
 * @see View::start()
742
 */
743
	public function addScript($name, $content = null) {
744
		if (empty($content)) {
745
			if (!in_array($name, array_values($this->_scripts))) {
746
				$this->_scripts[] = $name;
747
			}
748
		} else {
749
			$this->_scripts[$name] = $content;
750
		}
751
	}
752
 
753
/**
754
 * Generates a unique, non-random DOM ID for an object, based on the object type and the target URL.
755
 *
756
 * @param string $object Type of object, i.e. 'form' or 'link'
757
 * @param string $url The object's target URL
758
 * @return string
759
 */
760
	public function uuid($object, $url) {
761
		$c = 1;
762
		$url = Router::url($url);
763
		$hash = $object . substr(md5($object . $url), 0, 10);
764
		while (in_array($hash, $this->uuids)) {
765
			$hash = $object . substr(md5($object . $url . $c), 0, 10);
766
			$c++;
767
		}
768
		$this->uuids[] = $hash;
769
		return $hash;
770
	}
771
 
772
/**
773
 * Allows a template or element to set a variable that will be available in
774
 * a layout or other element. Analogous to Controller::set().
775
 *
776
 * @param string|array $one A string or an array of data.
777
 * @param string|array $two Value in case $one is a string (which then works as the key).
778
 *    Unused if $one is an associative array, otherwise serves as the values to $one's keys.
779
 * @return void
780
 */
781
	public function set($one, $two = null) {
782
		$data = null;
783
		if (is_array($one)) {
784
			if (is_array($two)) {
785
				$data = array_combine($one, $two);
786
			} else {
787
				$data = $one;
788
			}
789
		} else {
790
			$data = array($one => $two);
791
		}
792
		if (!$data) {
793
			return false;
794
		}
795
		$this->viewVars = $data + $this->viewVars;
796
	}
797
 
798
/**
799
 * Magic accessor for helpers. Provides access to attributes that were deprecated.
800
 *
801
 * @param string $name Name of the attribute to get.
802
 * @return mixed
803
 */
804
	public function __get($name) {
805
		switch ($name) {
806
			case 'base':
807
			case 'here':
808
			case 'webroot':
809
			case 'data':
810
				return $this->request->{$name};
811
			case 'action':
812
				return $this->request->params['action'];
813
			case 'params':
814
				return $this->request;
815
			case 'output':
816
				return $this->Blocks->get('content');
817
		}
818
		if (isset($this->Helpers->{$name})) {
819
			$this->{$name} = $this->Helpers->{$name};
820
			return $this->Helpers->{$name};
821
		}
822
		return $this->{$name};
823
	}
824
 
825
/**
826
 * Magic accessor for deprecated attributes.
827
 *
828
 * @param string $name Name of the attribute to set.
829
 * @param mixed $value Value of the attribute to set.
830
 * @return mixed
831
 */
832
	public function __set($name, $value) {
833
		switch ($name) {
834
			case 'output':
835
				return $this->Blocks->set('content', $value);
836
			default:
837
				$this->{$name} = $value;
838
		}
839
	}
840
 
841
/**
842
 * Magic isset check for deprecated attributes.
843
 *
844
 * @param string $name Name of the attribute to check.
845
 * @return boolean
846
 */
847
	public function __isset($name) {
848
		if (isset($this->{$name})) {
849
			return true;
850
		}
851
		$magicGet = array('base', 'here', 'webroot', 'data', 'action', 'params', 'output');
852
		if (in_array($name, $magicGet)) {
853
			return $this->__get($name) !== null;
854
		}
855
		return false;
856
	}
857
 
858
/**
859
 * Interact with the HelperCollection to load all the helpers.
860
 *
861
 * @return void
862
 */
863
	public function loadHelpers() {
864
		$helpers = HelperCollection::normalizeObjectArray($this->helpers);
865
		foreach ($helpers as $properties) {
866
			list(, $class) = pluginSplit($properties['class']);
867
			$this->{$class} = $this->Helpers->load($properties['class'], $properties['settings']);
868
		}
869
	}
870
 
871
/**
872
 * Renders and returns output for given view filename with its
873
 * array of data. Handles parent/extended views.
874
 *
875
 * @param string $viewFile Filename of the view
876
 * @param array $data Data to include in rendered view. If empty the current View::$viewVars will be used.
877
 * @return string Rendered output
878
 * @throws CakeException when a block is left open.
879
 */
880
	protected function _render($viewFile, $data = array()) {
881
		if (empty($data)) {
882
			$data = $this->viewVars;
883
		}
884
		$this->_current = $viewFile;
885
		$initialBlocks = count($this->Blocks->unclosed());
886
 
887
		$eventManager = $this->getEventManager();
888
		$beforeEvent = new CakeEvent('View.beforeRenderFile', $this, array($viewFile));
889
 
890
		$eventManager->dispatch($beforeEvent);
891
		$content = $this->_evaluate($viewFile, $data);
892
 
893
		$afterEvent = new CakeEvent('View.afterRenderFile', $this, array($viewFile, $content));
894
 
895
		$afterEvent->modParams = 1;
896
		$eventManager->dispatch($afterEvent);
897
		$content = $afterEvent->data[1];
898
 
899
		if (isset($this->_parents[$viewFile])) {
900
			$this->_stack[] = $this->fetch('content');
901
			$this->assign('content', $content);
902
 
903
			$content = $this->_render($this->_parents[$viewFile]);
904
			$this->assign('content', array_pop($this->_stack));
905
		}
906
 
907
		$remainingBlocks = count($this->Blocks->unclosed());
908
 
909
		if ($initialBlocks !== $remainingBlocks) {
910
			throw new CakeException(__d('cake_dev', 'The "%s" block was left open. Blocks are not allowed to cross files.', $this->Blocks->active()));
911
		}
912
 
913
		return $content;
914
	}
915
 
916
/**
917
 * Sandbox method to evaluate a template / view script in.
918
 *
919
 * @param string $viewFn Filename of the view
920
 * @param array $dataForView Data to include in rendered view.
921
 *    If empty the current View::$viewVars will be used.
922
 * @return string Rendered output
923
 */
924
	protected function _evaluate($viewFile, $dataForView) {
925
		$this->__viewFile = $viewFile;
926
		extract($dataForView);
927
		ob_start();
928
 
929
		include $this->__viewFile;
930
 
931
		unset($this->__viewFile);
932
		return ob_get_clean();
933
	}
934
 
935
/**
936
 * Loads a helper. Delegates to the `HelperCollection::load()` to load the helper
937
 *
938
 * @param string $helperName Name of the helper to load.
939
 * @param array $settings Settings for the helper
940
 * @return Helper a constructed helper object.
941
 * @see HelperCollection::load()
942
 */
943
	public function loadHelper($helperName, $settings = array()) {
944
		return $this->Helpers->load($helperName, $settings);
945
	}
946
 
947
/**
948
 * Returns filename of given action's template file (.ctp) as a string.
949
 * CamelCased action names will be under_scored! This means that you can have
950
 * LongActionNames that refer to long_action_names.ctp views.
951
 *
952
 * @param string $name Controller action to find template filename for
953
 * @return string Template filename
954
 * @throws MissingViewException when a view file could not be found.
955
 */
956
	protected function _getViewFileName($name = null) {
957
		$subDir = null;
958
 
959
		if ($this->subDir !== null) {
960
			$subDir = $this->subDir . DS;
961
		}
962
 
963
		if ($name === null) {
964
			$name = $this->view;
965
		}
966
		$name = str_replace('/', DS, $name);
967
		list($plugin, $name) = $this->pluginSplit($name);
968
 
969
		if (strpos($name, DS) === false && $name[0] !== '.') {
970
			$name = $this->viewPath . DS . $subDir . Inflector::underscore($name);
971
		} elseif (strpos($name, DS) !== false) {
972
			if ($name[0] === DS || $name[1] === ':') {
973
				if (is_file($name)) {
974
					return $name;
975
				}
976
				$name = trim($name, DS);
977
			} elseif ($name[0] === '.') {
978
				$name = substr($name, 3);
979
			} elseif (!$plugin || $this->viewPath !== $this->name) {
980
				$name = $this->viewPath . DS . $subDir . $name;
981
			}
982
		}
983
		$paths = $this->_paths($plugin);
984
		$exts = $this->_getExtensions();
985
		foreach ($exts as $ext) {
986
			foreach ($paths as $path) {
987
				if (file_exists($path . $name . $ext)) {
988
					return $path . $name . $ext;
989
				}
990
			}
991
		}
992
		$defaultPath = $paths[0];
993
 
994
		if ($this->plugin) {
995
			$pluginPaths = App::path('plugins');
996
			foreach ($paths as $path) {
997
				if (strpos($path, $pluginPaths[0]) === 0) {
998
					$defaultPath = $path;
999
					break;
1000
				}
1001
			}
1002
		}
1003
		throw new MissingViewException(array('file' => $defaultPath . $name . $this->ext));
1004
	}
1005
 
1006
/**
1007
 * Splits a dot syntax plugin name into its plugin and filename.
1008
 * If $name does not have a dot, then index 0 will be null.
1009
 * It checks if the plugin is loaded, else filename will stay unchanged for filenames containing dot
1010
 *
1011
 * @param string $name The name you want to plugin split.
1012
 * @param boolean $fallback If true uses the plugin set in the current CakeRequest when parsed plugin is not loaded
1013
 * @return array Array with 2 indexes. 0 => plugin name, 1 => filename
1014
 */
1015
	public function pluginSplit($name, $fallback = true) {
1016
		$plugin = null;
1017
		list($first, $second) = pluginSplit($name);
1018
		if (CakePlugin::loaded($first) === true) {
1019
			$name = $second;
1020
			$plugin = $first;
1021
		}
1022
		if (isset($this->plugin) && !$plugin && $fallback) {
1023
			$plugin = $this->plugin;
1024
		}
1025
		return array($plugin, $name);
1026
	}
1027
 
1028
/**
1029
 * Returns layout filename for this template as a string.
1030
 *
1031
 * @param string $name The name of the layout to find.
1032
 * @return string Filename for layout file (.ctp).
1033
 * @throws MissingLayoutException when a layout cannot be located
1034
 */
1035
	protected function _getLayoutFileName($name = null) {
1036
		if ($name === null) {
1037
			$name = $this->layout;
1038
		}
1039
		$subDir = null;
1040
 
1041
		if ($this->layoutPath !== null) {
1042
			$subDir = $this->layoutPath . DS;
1043
		}
1044
		list($plugin, $name) = $this->pluginSplit($name);
1045
		$paths = $this->_paths($plugin);
1046
		$file = 'Layouts' . DS . $subDir . $name;
1047
 
1048
		$exts = $this->_getExtensions();
1049
		foreach ($exts as $ext) {
1050
			foreach ($paths as $path) {
1051
				if (file_exists($path . $file . $ext)) {
1052
					return $path . $file . $ext;
1053
				}
1054
			}
1055
		}
1056
		throw new MissingLayoutException(array('file' => $paths[0] . $file . $this->ext));
1057
	}
1058
 
1059
/**
1060
 * Get the extensions that view files can use.
1061
 *
1062
 * @return array Array of extensions view files use.
1063
 */
1064
	protected function _getExtensions() {
1065
		$exts = array($this->ext);
1066
		if ($this->ext !== '.ctp') {
1067
			$exts[] = '.ctp';
1068
		}
1069
		return $exts;
1070
	}
1071
 
1072
/**
1073
 * Finds an element filename, returns false on failure.
1074
 *
1075
 * @param string $name The name of the element to find.
1076
 * @return mixed Either a string to the element filename or false when one can't be found.
1077
 */
1078
	protected function _getElementFileName($name) {
1079
		list($plugin, $name) = $this->pluginSplit($name);
1080
 
1081
		$paths = $this->_paths($plugin);
1082
		$exts = $this->_getExtensions();
1083
		foreach ($exts as $ext) {
1084
			foreach ($paths as $path) {
1085
				if (file_exists($path . 'Elements' . DS . $name . $ext)) {
1086
					return $path . 'Elements' . DS . $name . $ext;
1087
				}
1088
			}
1089
		}
1090
		return false;
1091
	}
1092
 
1093
/**
1094
 * Return all possible paths to find view files in order
1095
 *
1096
 * @param string $plugin Optional plugin name to scan for view files.
1097
 * @param boolean $cached Set to false to force a refresh of view paths. Default true.
1098
 * @return array paths
1099
 */
1100
	protected function _paths($plugin = null, $cached = true) {
1101
		if ($plugin === null && $cached === true && !empty($this->_paths)) {
1102
			return $this->_paths;
1103
		}
1104
		$paths = array();
1105
		$viewPaths = App::path('View');
1106
		$corePaths = array_merge(App::core('View'), App::core('Console/Templates/skel/View'));
1107
 
1108
		if (!empty($plugin)) {
1109
			$count = count($viewPaths);
1110
			for ($i = 0; $i < $count; $i++) {
1111
				if (!in_array($viewPaths[$i], $corePaths)) {
1112
					$paths[] = $viewPaths[$i] . 'Plugin' . DS . $plugin . DS;
1113
				}
1114
			}
1115
			$paths = array_merge($paths, App::path('View', $plugin));
1116
		}
1117
 
1118
		$paths = array_unique(array_merge($paths, $viewPaths));
1119
		if (!empty($this->theme)) {
1120
			$theme = Inflector::camelize($this->theme);
1121
			$themePaths = array();
1122
			foreach ($paths as $path) {
1123
				if (strpos($path, DS . 'Plugin' . DS) === false) {
1124
					if ($plugin) {
1125
						$themePaths[] = $path . 'Themed' . DS . $theme . DS . 'Plugin' . DS . $plugin . DS;
1126
					}
1127
					$themePaths[] = $path . 'Themed' . DS . $theme . DS;
1128
				}
1129
			}
1130
			$paths = array_merge($themePaths, $paths);
1131
		}
1132
		$paths = array_merge($paths, $corePaths);
1133
		if ($plugin !== null) {
1134
			return $paths;
1135
		}
1136
		return $this->_paths = $paths;
1137
	}
1138
 
1139
/**
1140
 * Checks if an element is cached and returns the cached data if present
1141
 *
1142
 * @param string $name Element name
1143
 * @param string $data Data
1144
 * @param array $options Element options
1145
 * @return string|null
1146
 */
1147
	protected function _elementCache($name, $data, $options) {
1148
		$plugin = null;
1149
		list($plugin, $name) = $this->pluginSplit($name);
1150
 
1151
		$underscored = null;
1152
		if ($plugin) {
1153
			$underscored = Inflector::underscore($plugin);
1154
		}
1155
		$keys = array_merge(array($underscored, $name), array_keys($options), array_keys($data));
1156
		$this->elementCacheSettings = array(
1157
			'config' => $this->elementCache,
1158
			'key' => implode('_', $keys)
1159
		);
1160
		if (is_array($options['cache'])) {
1161
			$defaults = array(
1162
				'config' => $this->elementCache,
1163
				'key' => $this->elementCacheSettings['key']
1164
			);
1165
			$this->elementCacheSettings = array_merge($defaults, $options['cache']);
1166
		}
1167
		$this->elementCacheSettings['key'] = 'element_' . $this->elementCacheSettings['key'];
1168
		return Cache::read($this->elementCacheSettings['key'], $this->elementCacheSettings['config']);
1169
	}
1170
 
1171
/**
1172
 * Renders an element and fires the before and afterRender callbacks for it
1173
 * and writes to the cache if a cache is used
1174
 *
1175
 * @param string $file Element file path
1176
 * @param array $data Data to render
1177
 * @param array $options Element options
1178
 * @return string
1179
 */
1180
	protected function _renderElement($file, $data, $options) {
1181
		if ($options['callbacks']) {
1182
			$this->getEventManager()->dispatch(new CakeEvent('View.beforeRender', $this, array($file)));
1183
		}
1184
 
1185
		$current = $this->_current;
1186
		$restore = $this->_currentType;
1187
 
1188
		$this->_currentType = self::TYPE_ELEMENT;
1189
		$element = $this->_render($file, array_merge($this->viewVars, $data));
1190
 
1191
		$this->_currentType = $restore;
1192
		$this->_current = $current;
1193
 
1194
		if ($options['callbacks']) {
1195
			$this->getEventManager()->dispatch(new CakeEvent('View.afterRender', $this, array($file, $element)));
1196
		}
1197
		if (isset($options['cache'])) {
1198
			Cache::write($this->elementCacheSettings['key'], $element, $this->elementCacheSettings['config']);
1199
		}
1200
		return $element;
1201
	}
1202
}