Subversion Repositories SmartDukaan

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
12345 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
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
 * @throws CakeException If there is an error in the view.
462
 */
463
	public function render($view = null, $layout = null) {
464
		if ($this->hasRendered) {
465
			return;
466
		}
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
 *   Use the `title` block instead.
501
 * - `$content_for_layout` is deprecated and will be removed in CakePHP 3.0.
502
 *   Use the `content` block instead.
503
 *
504
 * @param string $content Content to render in a view, wrapped by the surrounding layout.
505
 * @param string $layout Layout name
506
 * @return mixed Rendered output, or false on error
507
 * @throws CakeException if there is an error in the view.
508
 */
509
	public function renderLayout($content, $layout = null) {
510
		$layoutFileName = $this->_getLayoutFileName($layout);
511
		if (empty($layoutFileName)) {
512
			return $this->Blocks->get('content');
513
		}
514
 
515
		if (empty($content)) {
516
			$content = $this->Blocks->get('content');
517
		} else {
518
			$this->Blocks->set('content', $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
		$title = $this->Blocks->get('title');
531
		if ($title === '') {
532
			if (isset($this->viewVars['title_for_layout'])) {
533
				$title = $this->viewVars['title_for_layout'];
534
			} else {
535
				$title = Inflector::humanize($this->viewPath);
536
			}
537
		}
538
		$this->viewVars['title_for_layout'] = $title;
539
		$this->Blocks->set('title', $title);
540
 
541
		$this->_currentType = self::TYPE_LAYOUT;
542
		$this->Blocks->set('content', $this->_render($layoutFileName));
543
 
544
		$this->getEventManager()->dispatch(new CakeEvent('View.afterLayout', $this, array($layoutFileName)));
545
		return $this->Blocks->get('content');
546
	}
547
 
548
/**
549
 * Render cached view. Works in concert with CacheHelper and Dispatcher to
550
 * render cached view files.
551
 *
552
 * @param string $filename the cache file to include
553
 * @param string $timeStart the page render start time
554
 * @return bool Success of rendering the cached file.
555
 */
556
	public function renderCache($filename, $timeStart) {
557
		$response = $this->response;
558
		ob_start();
559
		include $filename;
560
 
561
		$type = $response->mapType($response->type());
562
		if (Configure::read('debug') > 0 && $type === 'html') {
563
			echo "<!-- Cached Render Time: " . round(microtime(true) - $timeStart, 4) . "s -->";
564
		}
565
		$out = ob_get_clean();
566
 
567
		if (preg_match('/^<!--cachetime:(\\d+)-->/', $out, $match)) {
568
			if (time() >= $match['1']) {
569
				//@codingStandardsIgnoreStart
570
				@unlink($filename);
571
				//@codingStandardsIgnoreEnd
572
				unset($out);
573
				return false;
574
			}
575
			return substr($out, strlen($match[0]));
576
		}
577
	}
578
 
579
/**
580
 * Returns a list of variables available in the current View context
581
 *
582
 * @return array Array of the set view variable names.
583
 */
584
	public function getVars() {
585
		return array_keys($this->viewVars);
586
	}
587
 
588
/**
589
 * Returns the contents of the given View variable(s)
590
 *
591
 * @param string $var The view var you want the contents of.
592
 * @return mixed The content of the named var if its set, otherwise null.
593
 * @deprecated Will be removed in 3.0. Use View::get() instead.
594
 */
595
	public function getVar($var) {
596
		return $this->get($var);
597
	}
598
 
599
/**
600
 * Returns the contents of the given View variable.
601
 *
602
 * @param string $var The view var you want the contents of.
603
 * @param mixed $default The default/fallback content of $var.
604
 * @return mixed The content of the named var if its set, otherwise $default.
605
 */
606
	public function get($var, $default = null) {
607
		if (!isset($this->viewVars[$var])) {
608
			return $default;
609
		}
610
		return $this->viewVars[$var];
611
	}
612
 
613
/**
614
 * Get the names of all the existing blocks.
615
 *
616
 * @return array An array containing the blocks.
617
 * @see ViewBlock::keys()
618
 */
619
	public function blocks() {
620
		return $this->Blocks->keys();
621
	}
622
 
623
/**
624
 * Start capturing output for a 'block'
625
 *
626
 * @param string $name The name of the block to capture for.
627
 * @return void
628
 * @see ViewBlock::start()
629
 */
630
	public function start($name) {
631
		$this->Blocks->start($name);
632
	}
633
 
634
/**
635
 * Start capturing output for a 'block' if it has no content
636
 *
637
 * @param string $name The name of the block to capture for.
638
 * @return void
639
 * @see ViewBlock::startIfEmpty()
640
 */
641
	public function startIfEmpty($name) {
642
		$this->Blocks->startIfEmpty($name);
643
	}
644
 
645
/**
646
 * Append to an existing or new block. Appending to a new
647
 * block will create the block.
648
 *
649
 * @param string $name Name of the block
650
 * @param mixed $value The content for the block.
651
 * @return void
652
 * @see ViewBlock::concat()
653
 */
654
	public function append($name, $value = null) {
655
		$this->Blocks->concat($name, $value);
656
	}
657
 
658
/**
659
 * Prepend to an existing or new block. Prepending to a new
660
 * block will create the block.
661
 *
662
 * @param string $name Name of the block
663
 * @param mixed $value The content for the block.
664
 * @return void
665
 * @see ViewBlock::concat()
666
 */
667
	public function prepend($name, $value = null) {
668
		$this->Blocks->concat($name, $value, ViewBlock::PREPEND);
669
	}
670
 
671
/**
672
 * Set the content for a block. This will overwrite any
673
 * existing content.
674
 *
675
 * @param string $name Name of the block
676
 * @param mixed $value The content for the block.
677
 * @return void
678
 * @see ViewBlock::set()
679
 */
680
	public function assign($name, $value) {
681
		$this->Blocks->set($name, $value);
682
	}
683
 
684
/**
685
 * Fetch the content for a block. If a block is
686
 * empty or undefined '' will be returned.
687
 *
688
 * @param string $name Name of the block
689
 * @param string $default Default text
690
 * @return string default The block content or $default if the block does not exist.
691
 * @see ViewBlock::get()
692
 */
693
	public function fetch($name, $default = '') {
694
		return $this->Blocks->get($name, $default);
695
	}
696
 
697
/**
698
 * End a capturing block. The compliment to View::start()
699
 *
700
 * @return void
701
 * @see ViewBlock::end()
702
 */
703
	public function end() {
704
		$this->Blocks->end();
705
	}
706
 
707
/**
708
 * Provides view or element extension/inheritance. Views can extends a
709
 * parent view and populate blocks in the parent template.
710
 *
711
 * @param string $name The view or element to 'extend' the current one with.
712
 * @return void
713
 * @throws LogicException when you extend a view with itself or make extend loops.
714
 * @throws LogicException when you extend an element which doesn't exist
715
 */
716
	public function extend($name) {
717
		if ($name[0] === '/' || $this->_currentType === self::TYPE_VIEW) {
718
			$parent = $this->_getViewFileName($name);
719
		} else {
720
			switch ($this->_currentType) {
721
				case self::TYPE_ELEMENT:
722
					$parent = $this->_getElementFileName($name);
723
					if (!$parent) {
724
						list($plugin, $name) = $this->pluginSplit($name);
725
						$paths = $this->_paths($plugin);
726
						$defaultPath = $paths[0] . 'Elements' . DS;
727
						throw new LogicException(__d(
728
							'cake_dev',
729
							'You cannot extend an element which does not exist (%s).',
730
							$defaultPath . $name . $this->ext
731
						));
732
					}
733
					break;
734
				case self::TYPE_LAYOUT:
735
					$parent = $this->_getLayoutFileName($name);
736
					break;
737
				default:
738
					$parent = $this->_getViewFileName($name);
739
			}
740
		}
741
 
742
		if ($parent == $this->_current) {
743
			throw new LogicException(__d('cake_dev', 'You cannot have views extend themselves.'));
744
		}
745
		if (isset($this->_parents[$parent]) && $this->_parents[$parent] == $this->_current) {
746
			throw new LogicException(__d('cake_dev', 'You cannot have views extend in a loop.'));
747
		}
748
		$this->_parents[$this->_current] = $parent;
749
	}
750
 
751
/**
752
 * Adds a script block or other element to be inserted in $scripts_for_layout in
753
 * the `<head />` of a document layout
754
 *
755
 * @param string $name Either the key name for the script, or the script content. Name can be used to
756
 *   update/replace a script element.
757
 * @param string $content The content of the script being added, optional.
758
 * @return void
759
 * @deprecated Will be removed in 3.0. Superseded by blocks functionality.
760
 * @see View::start()
761
 */
762
	public function addScript($name, $content = null) {
763
		if (empty($content)) {
764
			if (!in_array($name, array_values($this->_scripts))) {
765
				$this->_scripts[] = $name;
766
			}
767
		} else {
768
			$this->_scripts[$name] = $content;
769
		}
770
	}
771
 
772
/**
773
 * Generates a unique, non-random DOM ID for an object, based on the object type and the target URL.
774
 *
775
 * @param string $object Type of object, i.e. 'form' or 'link'
776
 * @param string $url The object's target URL
777
 * @return string
778
 */
779
	public function uuid($object, $url) {
780
		$c = 1;
781
		$url = Router::url($url);
782
		$hash = $object . substr(md5($object . $url), 0, 10);
783
		while (in_array($hash, $this->uuids)) {
784
			$hash = $object . substr(md5($object . $url . $c), 0, 10);
785
			$c++;
786
		}
787
		$this->uuids[] = $hash;
788
		return $hash;
789
	}
790
 
791
/**
792
 * Allows a template or element to set a variable that will be available in
793
 * a layout or other element. Analogous to Controller::set().
794
 *
795
 * @param string|array $one A string or an array of data.
796
 * @param string|array $two Value in case $one is a string (which then works as the key).
797
 *    Unused if $one is an associative array, otherwise serves as the values to $one's keys.
798
 * @return void
799
 */
800
	public function set($one, $two = null) {
801
		$data = null;
802
		if (is_array($one)) {
803
			if (is_array($two)) {
804
				$data = array_combine($one, $two);
805
			} else {
806
				$data = $one;
807
			}
808
		} else {
809
			$data = array($one => $two);
810
		}
811
		if (!$data) {
812
			return false;
813
		}
814
		$this->viewVars = $data + $this->viewVars;
815
	}
816
 
817
/**
818
 * Magic accessor for helpers. Provides access to attributes that were deprecated.
819
 *
820
 * @param string $name Name of the attribute to get.
821
 * @return mixed
822
 */
823
	public function __get($name) {
824
		switch ($name) {
825
			case 'base':
826
			case 'here':
827
			case 'webroot':
828
			case 'data':
829
				return $this->request->{$name};
830
			case 'action':
831
				return $this->request->params['action'];
832
			case 'params':
833
				return $this->request;
834
			case 'output':
835
				return $this->Blocks->get('content');
836
		}
837
		if (isset($this->Helpers->{$name})) {
838
			$this->{$name} = $this->Helpers->{$name};
839
			return $this->Helpers->{$name};
840
		}
841
		return $this->{$name};
842
	}
843
 
844
/**
845
 * Magic accessor for deprecated attributes.
846
 *
847
 * @param string $name Name of the attribute to set.
848
 * @param mixed $value Value of the attribute to set.
849
 * @return mixed
850
 */
851
	public function __set($name, $value) {
852
		switch ($name) {
853
			case 'output':
854
				return $this->Blocks->set('content', $value);
855
			default:
856
				$this->{$name} = $value;
857
		}
858
	}
859
 
860
/**
861
 * Magic isset check for deprecated attributes.
862
 *
863
 * @param string $name Name of the attribute to check.
864
 * @return bool
865
 */
866
	public function __isset($name) {
867
		if (isset($this->{$name})) {
868
			return true;
869
		}
870
		$magicGet = array('base', 'here', 'webroot', 'data', 'action', 'params', 'output');
871
		if (in_array($name, $magicGet)) {
872
			return $this->__get($name) !== null;
873
		}
874
		return false;
875
	}
876
 
877
/**
878
 * Interact with the HelperCollection to load all the helpers.
879
 *
880
 * @return void
881
 */
882
	public function loadHelpers() {
883
		$helpers = HelperCollection::normalizeObjectArray($this->helpers);
884
		foreach ($helpers as $properties) {
885
			list(, $class) = pluginSplit($properties['class']);
886
			$this->{$class} = $this->Helpers->load($properties['class'], $properties['settings']);
887
		}
888
	}
889
 
890
/**
891
 * Renders and returns output for given view filename with its
892
 * array of data. Handles parent/extended views.
893
 *
894
 * @param string $viewFile Filename of the view
895
 * @param array $data Data to include in rendered view. If empty the current View::$viewVars will be used.
896
 * @return string Rendered output
897
 * @throws CakeException when a block is left open.
898
 */
899
	protected function _render($viewFile, $data = array()) {
900
		if (empty($data)) {
901
			$data = $this->viewVars;
902
		}
903
		$this->_current = $viewFile;
904
		$initialBlocks = count($this->Blocks->unclosed());
905
 
906
		$eventManager = $this->getEventManager();
907
		$beforeEvent = new CakeEvent('View.beforeRenderFile', $this, array($viewFile));
908
 
909
		$eventManager->dispatch($beforeEvent);
910
		$content = $this->_evaluate($viewFile, $data);
911
 
912
		$afterEvent = new CakeEvent('View.afterRenderFile', $this, array($viewFile, $content));
913
 
914
		$afterEvent->modParams = 1;
915
		$eventManager->dispatch($afterEvent);
916
		$content = $afterEvent->data[1];
917
 
918
		if (isset($this->_parents[$viewFile])) {
919
			$this->_stack[] = $this->fetch('content');
920
			$this->assign('content', $content);
921
 
922
			$content = $this->_render($this->_parents[$viewFile]);
923
			$this->assign('content', array_pop($this->_stack));
924
		}
925
 
926
		$remainingBlocks = count($this->Blocks->unclosed());
927
 
928
		if ($initialBlocks !== $remainingBlocks) {
929
			throw new CakeException(__d('cake_dev', 'The "%s" block was left open. Blocks are not allowed to cross files.', $this->Blocks->active()));
930
		}
931
 
932
		return $content;
933
	}
934
 
935
/**
936
 * Sandbox method to evaluate a template / view script in.
937
 *
938
 * @param string $viewFile Filename of the view
939
 * @param array $dataForView Data to include in rendered view.
940
 *    If empty the current View::$viewVars will be used.
941
 * @return string Rendered output
942
 */
943
	protected function _evaluate($viewFile, $dataForView) {
944
		$this->__viewFile = $viewFile;
945
		extract($dataForView);
946
		ob_start();
947
 
948
		include $this->__viewFile;
949
 
950
		unset($this->__viewFile);
951
		return ob_get_clean();
952
	}
953
 
954
/**
955
 * Loads a helper. Delegates to the `HelperCollection::load()` to load the helper
956
 *
957
 * @param string $helperName Name of the helper to load.
958
 * @param array $settings Settings for the helper
959
 * @return Helper a constructed helper object.
960
 * @see HelperCollection::load()
961
 */
962
	public function loadHelper($helperName, $settings = array()) {
963
		return $this->Helpers->load($helperName, $settings);
964
	}
965
 
966
/**
967
 * Returns filename of given action's template file (.ctp) as a string.
968
 * CamelCased action names will be under_scored! This means that you can have
969
 * LongActionNames that refer to long_action_names.ctp views.
970
 *
971
 * @param string $name Controller action to find template filename for
972
 * @return string Template filename
973
 * @throws MissingViewException when a view file could not be found.
974
 */
975
	protected function _getViewFileName($name = null) {
976
		$subDir = null;
977
 
978
		if ($this->subDir !== null) {
979
			$subDir = $this->subDir . DS;
980
		}
981
 
982
		if ($name === null) {
983
			$name = $this->view;
984
		}
985
		$name = str_replace('/', DS, $name);
986
		list($plugin, $name) = $this->pluginSplit($name);
987
 
988
		if (strpos($name, DS) === false && $name[0] !== '.') {
989
			$name = $this->viewPath . DS . $subDir . Inflector::underscore($name);
990
		} elseif (strpos($name, DS) !== false) {
991
			if ($name[0] === DS || $name[1] === ':') {
992
				if (is_file($name)) {
993
					return $name;
994
				}
995
				$name = trim($name, DS);
996
			} elseif ($name[0] === '.') {
997
				$name = substr($name, 3);
998
			} elseif (!$plugin || $this->viewPath !== $this->name) {
999
				$name = $this->viewPath . DS . $subDir . $name;
1000
			}
1001
		}
1002
		$paths = $this->_paths($plugin);
1003
		$exts = $this->_getExtensions();
1004
		foreach ($exts as $ext) {
1005
			foreach ($paths as $path) {
1006
				if (file_exists($path . $name . $ext)) {
1007
					return $path . $name . $ext;
1008
				}
1009
			}
1010
		}
1011
		$defaultPath = $paths[0];
1012
 
1013
		if ($this->plugin) {
1014
			$pluginPaths = App::path('plugins');
1015
			foreach ($paths as $path) {
1016
				if (strpos($path, $pluginPaths[0]) === 0) {
1017
					$defaultPath = $path;
1018
					break;
1019
				}
1020
			}
1021
		}
1022
		throw new MissingViewException(array('file' => $defaultPath . $name . $this->ext));
1023
	}
1024
 
1025
/**
1026
 * Splits a dot syntax plugin name into its plugin and filename.
1027
 * If $name does not have a dot, then index 0 will be null.
1028
 * It checks if the plugin is loaded, else filename will stay unchanged for filenames containing dot
1029
 *
1030
 * @param string $name The name you want to plugin split.
1031
 * @param bool $fallback If true uses the plugin set in the current CakeRequest when parsed plugin is not loaded
1032
 * @return array Array with 2 indexes. 0 => plugin name, 1 => filename
1033
 */
1034
	public function pluginSplit($name, $fallback = true) {
1035
		$plugin = null;
1036
		list($first, $second) = pluginSplit($name);
1037
		if (CakePlugin::loaded($first) === true) {
1038
			$name = $second;
1039
			$plugin = $first;
1040
		}
1041
		if (isset($this->plugin) && !$plugin && $fallback) {
1042
			$plugin = $this->plugin;
1043
		}
1044
		return array($plugin, $name);
1045
	}
1046
 
1047
/**
1048
 * Returns layout filename for this template as a string.
1049
 *
1050
 * @param string $name The name of the layout to find.
1051
 * @return string Filename for layout file (.ctp).
1052
 * @throws MissingLayoutException when a layout cannot be located
1053
 */
1054
	protected function _getLayoutFileName($name = null) {
1055
		if ($name === null) {
1056
			$name = $this->layout;
1057
		}
1058
		$subDir = null;
1059
 
1060
		if ($this->layoutPath !== null) {
1061
			$subDir = $this->layoutPath . DS;
1062
		}
1063
		list($plugin, $name) = $this->pluginSplit($name);
1064
		$paths = $this->_paths($plugin);
1065
		$file = 'Layouts' . DS . $subDir . $name;
1066
 
1067
		$exts = $this->_getExtensions();
1068
		foreach ($exts as $ext) {
1069
			foreach ($paths as $path) {
1070
				if (file_exists($path . $file . $ext)) {
1071
					return $path . $file . $ext;
1072
				}
1073
			}
1074
		}
1075
		throw new MissingLayoutException(array('file' => $paths[0] . $file . $this->ext));
1076
	}
1077
 
1078
/**
1079
 * Get the extensions that view files can use.
1080
 *
1081
 * @return array Array of extensions view files use.
1082
 */
1083
	protected function _getExtensions() {
1084
		$exts = array($this->ext);
1085
		if ($this->ext !== '.ctp') {
1086
			$exts[] = '.ctp';
1087
		}
1088
		return $exts;
1089
	}
1090
 
1091
/**
1092
 * Finds an element filename, returns false on failure.
1093
 *
1094
 * @param string $name The name of the element to find.
1095
 * @return mixed Either a string to the element filename or false when one can't be found.
1096
 */
1097
	protected function _getElementFileName($name) {
1098
		list($plugin, $name) = $this->pluginSplit($name);
1099
 
1100
		$paths = $this->_paths($plugin);
1101
		$exts = $this->_getExtensions();
1102
		foreach ($exts as $ext) {
1103
			foreach ($paths as $path) {
1104
				if (file_exists($path . 'Elements' . DS . $name . $ext)) {
1105
					return $path . 'Elements' . DS . $name . $ext;
1106
				}
1107
			}
1108
		}
1109
		return false;
1110
	}
1111
 
1112
/**
1113
 * Return all possible paths to find view files in order
1114
 *
1115
 * @param string $plugin Optional plugin name to scan for view files.
1116
 * @param bool $cached Set to false to force a refresh of view paths. Default true.
1117
 * @return array paths
1118
 */
1119
	protected function _paths($plugin = null, $cached = true) {
1120
		if ($cached === true) {
1121
			if ($plugin === null && !empty($this->_paths)) {
1122
				return $this->_paths;
1123
			}
1124
			if ($plugin !== null && isset($this->_pathsForPlugin[$plugin])) {
1125
				return $this->_pathsForPlugin[$plugin];
1126
			}
1127
		}
1128
		$paths = array();
1129
		$viewPaths = App::path('View');
1130
		$corePaths = array_merge(App::core('View'), App::core('Console/Templates/skel/View'));
1131
 
1132
		if (!empty($plugin)) {
1133
			$count = count($viewPaths);
1134
			for ($i = 0; $i < $count; $i++) {
1135
				if (!in_array($viewPaths[$i], $corePaths)) {
1136
					$paths[] = $viewPaths[$i] . 'Plugin' . DS . $plugin . DS;
1137
				}
1138
			}
1139
			$paths = array_merge($paths, App::path('View', $plugin));
1140
		}
1141
 
1142
		$paths = array_unique(array_merge($paths, $viewPaths));
1143
		if (!empty($this->theme)) {
1144
			$theme = Inflector::camelize($this->theme);
1145
			$themePaths = array();
1146
			foreach ($paths as $path) {
1147
				if (strpos($path, DS . 'Plugin' . DS) === false) {
1148
					if ($plugin) {
1149
						$themePaths[] = $path . 'Themed' . DS . $theme . DS . 'Plugin' . DS . $plugin . DS;
1150
					}
1151
					$themePaths[] = $path . 'Themed' . DS . $theme . DS;
1152
				}
1153
			}
1154
			$paths = array_merge($themePaths, $paths);
1155
		}
1156
		$paths = array_merge($paths, $corePaths);
1157
		if ($plugin !== null) {
1158
			return $this->_pathsForPlugin[$plugin] = $paths;
1159
		}
1160
		return $this->_paths = $paths;
1161
	}
1162
 
1163
/**
1164
 * Checks if an element is cached and returns the cached data if present
1165
 *
1166
 * @param string $name Element name
1167
 * @param string $data Data
1168
 * @param array $options Element options
1169
 * @return string|null
1170
 */
1171
	protected function _elementCache($name, $data, $options) {
1172
		$plugin = null;
1173
		list($plugin, $name) = $this->pluginSplit($name);
1174
 
1175
		$underscored = null;
1176
		if ($plugin) {
1177
			$underscored = Inflector::underscore($plugin);
1178
		}
1179
		$keys = array_merge(array($underscored, $name), array_keys($options), array_keys($data));
1180
		$this->elementCacheSettings = array(
1181
			'config' => $this->elementCache,
1182
			'key' => implode('_', $keys)
1183
		);
1184
		if (is_array($options['cache'])) {
1185
			$defaults = array(
1186
				'config' => $this->elementCache,
1187
				'key' => $this->elementCacheSettings['key']
1188
			);
1189
			$this->elementCacheSettings = array_merge($defaults, $options['cache']);
1190
		}
1191
		$this->elementCacheSettings['key'] = 'element_' . $this->elementCacheSettings['key'];
1192
		return Cache::read($this->elementCacheSettings['key'], $this->elementCacheSettings['config']);
1193
	}
1194
 
1195
/**
1196
 * Renders an element and fires the before and afterRender callbacks for it
1197
 * and writes to the cache if a cache is used
1198
 *
1199
 * @param string $file Element file path
1200
 * @param array $data Data to render
1201
 * @param array $options Element options
1202
 * @return string
1203
 */
1204
	protected function _renderElement($file, $data, $options) {
1205
		if ($options['callbacks']) {
1206
			$this->getEventManager()->dispatch(new CakeEvent('View.beforeRender', $this, array($file)));
1207
		}
1208
 
1209
		$current = $this->_current;
1210
		$restore = $this->_currentType;
1211
 
1212
		$this->_currentType = self::TYPE_ELEMENT;
1213
		$element = $this->_render($file, array_merge($this->viewVars, $data));
1214
 
1215
		$this->_currentType = $restore;
1216
		$this->_current = $current;
1217
 
1218
		if ($options['callbacks']) {
1219
			$this->getEventManager()->dispatch(new CakeEvent('View.afterRender', $this, array($file, $element)));
1220
		}
1221
		if (isset($options['cache'])) {
1222
			Cache::write($this->elementCacheSettings['key'], $element, $this->elementCacheSettings['config']);
1223
		}
1224
		return $element;
1225
	}
1226
}