Subversion Repositories SmartDukaan

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
13532 anikendra 1
<?php
2
/**
3
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
4
 * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
5
 *
6
 * Licensed under The MIT License
7
 * For full copyright and license information, please see the LICENSE.txt
8
 * Redistributions of files must retain the above copyright notice.
9
 *
10
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
11
 * @link          http://cakephp.org CakePHP(tm) Project
12
 * @package       Cake.View
13
 * @since         CakePHP(tm) v 0.2.9
14
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
15
 */
16
 
17
App::uses('Router', 'Routing');
18
App::uses('Hash', 'Utility');
19
 
20
/**
21
 * Abstract base class for all other Helpers in CakePHP.
22
 * Provides common methods and features.
23
 *
24
 * @package       Cake.View
25
 */
26
class Helper extends Object {
27
 
28
/**
29
 * Settings for this helper.
30
 *
31
 * @var array
32
 */
33
	public $settings = array();
34
 
35
/**
36
 * List of helpers used by this helper
37
 *
38
 * @var array
39
 */
40
	public $helpers = array();
41
 
42
/**
43
 * A helper lookup table used to lazy load helper objects.
44
 *
45
 * @var array
46
 */
47
	protected $_helperMap = array();
48
 
49
/**
50
 * The current theme name if any.
51
 *
52
 * @var string
53
 */
54
	public $theme = null;
55
 
56
/**
57
 * Request object
58
 *
59
 * @var CakeRequest
60
 */
61
	public $request = null;
62
 
63
/**
64
 * Plugin path
65
 *
66
 * @var string
67
 */
68
	public $plugin = null;
69
 
70
/**
71
 * Holds the fields array('field_name' => array('type' => 'string', 'length' => 100),
72
 * primaryKey and validates array('field_name')
73
 *
74
 * @var array
75
 */
76
	public $fieldset = array();
77
 
78
/**
79
 * Holds tag templates.
80
 *
81
 * @var array
82
 */
83
	public $tags = array();
84
 
85
/**
86
 * Holds the content to be cleaned.
87
 *
88
 * @var mixed
89
 */
90
	protected $_tainted = null;
91
 
92
/**
93
 * Holds the cleaned content.
94
 *
95
 * @var mixed
96
 */
97
	protected $_cleaned = null;
98
 
99
/**
100
 * The View instance this helper is attached to
101
 *
102
 * @var View
103
 */
104
	protected $_View;
105
 
106
/**
107
 * A list of strings that should be treated as suffixes, or
108
 * sub inputs for a parent input. This is used for date/time
109
 * inputs primarily.
110
 *
111
 * @var array
112
 */
113
	protected $_fieldSuffixes = array(
114
		'year', 'month', 'day', 'hour', 'min', 'second', 'meridian'
115
	);
116
 
117
/**
118
 * The name of the current model entities are in scope of.
119
 *
120
 * @see Helper::setEntity()
121
 * @var string
122
 */
123
	protected $_modelScope;
124
 
125
/**
126
 * The name of the current model association entities are in scope of.
127
 *
128
 * @see Helper::setEntity()
129
 * @var string
130
 */
131
	protected $_association;
132
 
133
/**
134
 * The dot separated list of elements the current field entity is for.
135
 *
136
 * @see Helper::setEntity()
137
 * @var string
138
 */
139
	protected $_entityPath;
140
 
141
/**
142
 * Minimized attributes
143
 *
144
 * @var array
145
 */
146
	protected $_minimizedAttributes = array(
147
		'compact', 'checked', 'declare', 'readonly', 'disabled', 'selected',
148
		'defer', 'ismap', 'nohref', 'noshade', 'nowrap', 'multiple', 'noresize',
149
		'autoplay', 'controls', 'loop', 'muted', 'required', 'novalidate', 'formnovalidate'
150
	);
151
 
152
/**
153
 * Format to attribute
154
 *
155
 * @var string
156
 */
157
	protected $_attributeFormat = '%s="%s"';
158
 
159
/**
160
 * Format to attribute
161
 *
162
 * @var string
163
 */
164
	protected $_minimizedAttributeFormat = '%s="%s"';
165
 
166
/**
167
 * Default Constructor
168
 *
169
 * @param View $View The View this helper is being attached to.
170
 * @param array $settings Configuration settings for the helper.
171
 */
172
	public function __construct(View $View, $settings = array()) {
173
		$this->_View = $View;
174
		$this->request = $View->request;
175
		if ($settings) {
176
			$this->settings = Hash::merge($this->settings, $settings);
177
		}
178
		if (!empty($this->helpers)) {
179
			$this->_helperMap = ObjectCollection::normalizeObjectArray($this->helpers);
180
		}
181
	}
182
 
183
/**
184
 * Provide non fatal errors on missing method calls.
185
 *
186
 * @param string $method Method to invoke
187
 * @param array $params Array of params for the method.
188
 * @return void
189
 */
190
	public function __call($method, $params) {
191
		trigger_error(__d('cake_dev', 'Method %1$s::%2$s does not exist', get_class($this), $method), E_USER_WARNING);
192
	}
193
 
194
/**
195
 * Lazy loads helpers. Provides access to deprecated request properties as well.
196
 *
197
 * @param string $name Name of the property being accessed.
198
 * @return mixed Helper or property found at $name
199
 * @deprecated Accessing request properties through this method is deprecated and will be removed in 3.0.
200
 */
201
	public function __get($name) {
202
		if (isset($this->_helperMap[$name]) && !isset($this->{$name})) {
203
			$settings = array_merge((array)$this->_helperMap[$name]['settings'], array('enabled' => false));
204
			$this->{$name} = $this->_View->loadHelper($this->_helperMap[$name]['class'], $settings);
205
		}
206
		if (isset($this->{$name})) {
207
			return $this->{$name};
208
		}
209
		switch ($name) {
210
			case 'base':
211
			case 'here':
212
			case 'webroot':
213
			case 'data':
214
				return $this->request->{$name};
215
			case 'action':
216
				return isset($this->request->params['action']) ? $this->request->params['action'] : '';
217
			case 'params':
218
				return $this->request;
219
		}
220
	}
221
 
222
/**
223
 * Provides backwards compatibility access for setting values to the request object.
224
 *
225
 * @param string $name Name of the property being accessed.
226
 * @param mixed $value
227
 * @return void
228
 * @deprecated This method will be removed in 3.0
229
 */
230
	public function __set($name, $value) {
231
		switch ($name) {
232
			case 'base':
233
			case 'here':
234
			case 'webroot':
235
			case 'data':
236
				$this->request->{$name} = $value;
237
				return;
238
			case 'action':
239
				$this->request->params['action'] = $value;
240
				return;
241
		}
242
		$this->{$name} = $value;
243
	}
244
 
245
/**
246
 * Finds URL for specified action.
247
 *
248
 * Returns a URL pointing at the provided parameters.
249
 *
250
 * @param string|array $url Either a relative string url like `/products/view/23` or
251
 *    an array of URL parameters. Using an array for URLs will allow you to leverage
252
 *    the reverse routing features of CakePHP.
253
 * @param boolean $full If true, the full base URL will be prepended to the result
254
 * @return string Full translated URL with base path.
255
 * @link http://book.cakephp.org/2.0/en/views/helpers.html
256
 */
257
	public function url($url = null, $full = false) {
258
		return h(Router::url($url, $full));
259
	}
260
 
261
/**
262
 * Checks if a file exists when theme is used, if no file is found default location is returned
263
 *
264
 * @param string $file The file to create a webroot path to.
265
 * @return string Web accessible path to file.
266
 */
267
	public function webroot($file) {
268
		$asset = explode('?', $file);
269
		$asset[1] = isset($asset[1]) ? '?' . $asset[1] : null;
270
		$webPath = "{$this->request->webroot}" . $asset[0];
271
		$file = $asset[0];
272
 
273
		if (!empty($this->theme)) {
274
			$file = trim($file, '/');
275
			$theme = $this->theme . '/';
276
 
277
			if (DS === '\\') {
278
				$file = str_replace('/', '\\', $file);
279
			}
280
 
281
			if (file_exists(Configure::read('App.www_root') . 'theme' . DS . $this->theme . DS . $file)) {
282
				$webPath = "{$this->request->webroot}theme/" . $theme . $asset[0];
283
			} else {
284
				$themePath = App::themePath($this->theme);
285
				$path = $themePath . 'webroot' . DS . $file;
286
				if (file_exists($path)) {
287
					$webPath = "{$this->request->webroot}theme/" . $theme . $asset[0];
288
				}
289
			}
290
		}
291
		if (strpos($webPath, '//') !== false) {
292
			return str_replace('//', '/', $webPath . $asset[1]);
293
		}
294
		return $webPath . $asset[1];
295
	}
296
 
297
/**
298
 * Generate URL for given asset file. Depending on options passed provides full URL with domain name.
299
 * Also calls Helper::assetTimestamp() to add timestamp to local files
300
 *
301
 * @param string|array Path string or URL array
302
 * @param array $options Options array. Possible keys:
303
 *   `fullBase` Return full URL with domain name
304
 *   `pathPrefix` Path prefix for relative URLs
305
 *   `ext` Asset extension to append
306
 *   `plugin` False value will prevent parsing path as a plugin
307
 * @return string Generated URL
308
 */
309
	public function assetUrl($path, $options = array()) {
310
		if (is_array($path)) {
311
			return $this->url($path, !empty($options['fullBase']));
312
		}
313
		if (strpos($path, '://') !== false) {
314
			return $path;
315
		}
316
		if (!array_key_exists('plugin', $options) || $options['plugin'] !== false) {
317
			list($plugin, $path) = $this->_View->pluginSplit($path, false);
318
		}
319
		if (!empty($options['pathPrefix']) && $path[0] !== '/') {
320
			$path = $options['pathPrefix'] . $path;
321
		}
322
		if (
323
			!empty($options['ext']) &&
324
			strpos($path, '?') === false &&
325
			substr($path, -strlen($options['ext'])) !== $options['ext']
326
		) {
327
			$path .= $options['ext'];
328
		}
329
		if (preg_match('|^([a-z0-9]+:)?//|', $path)) {
330
			return $path;
331
		}
332
		if (isset($plugin)) {
333
			$path = Inflector::underscore($plugin) . '/' . $path;
334
		}
335
		$path = $this->_encodeUrl($this->assetTimestamp($this->webroot($path)));
336
 
337
		if (!empty($options['fullBase'])) {
338
			$path = rtrim(Router::fullBaseUrl(), '/') . '/' . ltrim($path, '/');
339
		}
340
		return $path;
341
	}
342
 
343
/**
344
 * Encodes a URL for use in HTML attributes.
345
 *
346
 * @param string $url The URL to encode.
347
 * @return string The URL encoded for both URL & HTML contexts.
348
 */
349
	protected function _encodeUrl($url) {
350
		$path = parse_url($url, PHP_URL_PATH);
351
		$parts = array_map('rawurldecode', explode('/', $path));
352
		$parts = array_map('rawurlencode', $parts);
353
		$encoded = implode('/', $parts);
354
		return h(str_replace($path, $encoded, $url));
355
	}
356
 
357
/**
358
 * Adds a timestamp to a file based resource based on the value of `Asset.timestamp` in
359
 * Configure. If Asset.timestamp is true and debug > 0, or Asset.timestamp === 'force'
360
 * a timestamp will be added.
361
 *
362
 * @param string $path The file path to timestamp, the path must be inside WWW_ROOT
363
 * @return string Path with a timestamp added, or not.
364
 */
365
	public function assetTimestamp($path) {
366
		$stamp = Configure::read('Asset.timestamp');
367
		$timestampEnabled = $stamp === 'force' || ($stamp === true && Configure::read('debug') > 0);
368
		if ($timestampEnabled && strpos($path, '?') === false) {
369
			$filepath = preg_replace(
370
				'/^' . preg_quote($this->request->webroot, '/') . '/',
371
				'',
372
				urldecode($path)
373
			);
374
			$webrootPath = WWW_ROOT . str_replace('/', DS, $filepath);
375
			if (file_exists($webrootPath)) {
376
				//@codingStandardsIgnoreStart
377
				return $path . '?' . @filemtime($webrootPath);
378
				//@codingStandardsIgnoreEnd
379
			}
380
			$segments = explode('/', ltrim($filepath, '/'));
381
			if ($segments[0] === 'theme') {
382
				$theme = $segments[1];
383
				unset($segments[0], $segments[1]);
384
				$themePath = App::themePath($theme) . 'webroot' . DS . implode(DS, $segments);
385
				//@codingStandardsIgnoreStart
386
				return $path . '?' . @filemtime($themePath);
387
				//@codingStandardsIgnoreEnd
388
			} else {
389
				$plugin = Inflector::camelize($segments[0]);
390
				if (CakePlugin::loaded($plugin)) {
391
					unset($segments[0]);
392
					$pluginPath = CakePlugin::path($plugin) . 'webroot' . DS . implode(DS, $segments);
393
					//@codingStandardsIgnoreStart
394
					return $path . '?' . @filemtime($pluginPath);
395
					//@codingStandardsIgnoreEnd
396
				}
397
			}
398
		}
399
		return $path;
400
	}
401
 
402
/**
403
 * Used to remove harmful tags from content. Removes a number of well known XSS attacks
404
 * from content. However, is not guaranteed to remove all possibilities. Escaping
405
 * content is the best way to prevent all possible attacks.
406
 *
407
 * @param string|array $output Either an array of strings to clean or a single string to clean.
408
 * @return string|array cleaned content for output
409
 * @deprecated This method will be removed in 3.0
410
 */
411
	public function clean($output) {
412
		$this->_reset();
413
		if (empty($output)) {
414
			return null;
415
		}
416
		if (is_array($output)) {
417
			foreach ($output as $key => $value) {
418
				$return[$key] = $this->clean($value);
419
			}
420
			return $return;
421
		}
422
		$this->_tainted = $output;
423
		$this->_clean();
424
		return $this->_cleaned;
425
	}
426
 
427
/**
428
 * Returns a space-delimited string with items of the $options array. If a key
429
 * of $options array happens to be one of those listed in `Helper::$_minimizedAttributes`
430
 *
431
 * And its value is one of:
432
 *
433
 * - '1' (string)
434
 * - 1 (integer)
435
 * - true (boolean)
436
 * - 'true' (string)
437
 *
438
 * Then the value will be reset to be identical with key's name.
439
 * If the value is not one of these 3, the parameter is not output.
440
 *
441
 * 'escape' is a special option in that it controls the conversion of
442
 *  attributes to their html-entity encoded equivalents. Set to false to disable html-encoding.
443
 *
444
 * If value for any option key is set to `null` or `false`, that option will be excluded from output.
445
 *
446
 * @param array $options Array of options.
447
 * @param array $exclude Array of options to be excluded, the options here will not be part of the return.
448
 * @param string $insertBefore String to be inserted before options.
449
 * @param string $insertAfter String to be inserted after options.
450
 * @return string Composed attributes.
451
 * @deprecated This method will be moved to HtmlHelper in 3.0
452
 */
453
	protected function _parseAttributes($options, $exclude = null, $insertBefore = ' ', $insertAfter = null) {
454
		if (!is_string($options)) {
455
			$options = (array)$options + array('escape' => true);
456
 
457
			if (!is_array($exclude)) {
458
				$exclude = array();
459
			}
460
 
461
			$exclude = array('escape' => true) + array_flip($exclude);
462
			$escape = $options['escape'];
463
			$attributes = array();
464
 
465
			foreach ($options as $key => $value) {
466
				if (!isset($exclude[$key]) && $value !== false && $value !== null) {
467
					$attributes[] = $this->_formatAttribute($key, $value, $escape);
468
				}
469
			}
470
			$out = implode(' ', $attributes);
471
		} else {
472
			$out = $options;
473
		}
474
		return $out ? $insertBefore . $out . $insertAfter : '';
475
	}
476
 
477
/**
478
 * Formats an individual attribute, and returns the string value of the composed attribute.
479
 * Works with minimized attributes that have the same value as their name such as 'disabled' and 'checked'
480
 *
481
 * @param string $key The name of the attribute to create
482
 * @param string $value The value of the attribute to create.
483
 * @param boolean $escape Define if the value must be escaped
484
 * @return string The composed attribute.
485
 * @deprecated This method will be moved to HtmlHelper in 3.0
486
 */
487
	protected function _formatAttribute($key, $value, $escape = true) {
488
		if (is_array($value)) {
489
			$value = implode(' ', $value);
490
		}
491
		if (is_numeric($key)) {
492
			return sprintf($this->_minimizedAttributeFormat, $value, $value);
493
		}
494
		$truthy = array(1, '1', true, 'true', $key);
495
		$isMinimized = in_array($key, $this->_minimizedAttributes);
496
		if ($isMinimized && in_array($value, $truthy, true)) {
497
			return sprintf($this->_minimizedAttributeFormat, $key, $key);
498
		}
499
		if ($isMinimized) {
500
			return '';
501
		}
502
		return sprintf($this->_attributeFormat, $key, ($escape ? h($value) : $value));
503
	}
504
 
505
/**
506
 * Returns a string to be used as onclick handler for confirm dialogs.
507
 *
508
 * @param string $message Message to be displayed
509
 * @param string $okCode Code to be executed after user chose 'OK'
510
 * @param string $cancelCode Code to be executed after user chose 'Cancel'
511
 * @param array $options Array of options
512
 * @return string onclick JS code
513
 */
514
	protected function _confirm($message, $okCode, $cancelCode = '', $options = array()) {
515
		$message = json_encode($message);
516
		$confirm = "if (confirm({$message})) { {$okCode} } {$cancelCode}";
517
		if (isset($options['escape']) && $options['escape'] === false) {
518
			$confirm = h($confirm);
519
		}
520
		return $confirm;
521
	}
522
 
523
/**
524
 * Sets this helper's model and field properties to the dot-separated value-pair in $entity.
525
 *
526
 * @param string $entity A field name, like "ModelName.fieldName" or "ModelName.ID.fieldName"
527
 * @param boolean $setScope Sets the view scope to the model specified in $tagValue
528
 * @return void
529
 */
530
	public function setEntity($entity, $setScope = false) {
531
		if ($entity === null) {
532
			$this->_modelScope = false;
533
		}
534
		if ($setScope === true) {
535
			$this->_modelScope = $entity;
536
		}
537
		$parts = array_values(Hash::filter(explode('.', $entity)));
538
		if (empty($parts)) {
539
			return;
540
		}
541
		$count = count($parts);
542
		$lastPart = isset($parts[$count - 1]) ? $parts[$count - 1] : null;
543
 
544
		// Either 'body' or 'date.month' type inputs.
545
		if (
546
			($count === 1 && $this->_modelScope && !$setScope) ||
547
			(
548
				$count === 2 &&
549
				in_array($lastPart, $this->_fieldSuffixes) &&
550
				$this->_modelScope &&
551
				$parts[0] !== $this->_modelScope
552
			)
553
		) {
554
			$entity = $this->_modelScope . '.' . $entity;
555
		}
556
 
557
		// 0.name, 0.created.month style inputs. Excludes inputs with the modelScope in them.
558
		if (
559
			$count >= 2 &&
560
			is_numeric($parts[0]) &&
561
			!is_numeric($parts[1]) &&
562
			$this->_modelScope &&
563
			strpos($entity, $this->_modelScope) === false
564
		) {
565
			$entity = $this->_modelScope . '.' . $entity;
566
		}
567
 
568
		$this->_association = null;
569
 
570
		$isHabtm = (
571
			isset($this->fieldset[$this->_modelScope]['fields'][$parts[0]]['type']) &&
572
			$this->fieldset[$this->_modelScope]['fields'][$parts[0]]['type'] === 'multiple'
573
		);
574
 
575
		// habtm models are special
576
		if ($count === 1 && $isHabtm) {
577
			$this->_association = $parts[0];
578
			$entity = $parts[0] . '.' . $parts[0];
579
		} else {
580
			// check for associated model.
581
			$reversed = array_reverse($parts);
582
			foreach ($reversed as $i => $part) {
583
				if ($i > 0 && preg_match('/^[A-Z]/', $part)) {
584
					$this->_association = $part;
585
					break;
586
				}
587
			}
588
		}
589
		$this->_entityPath = $entity;
590
	}
591
 
592
/**
593
 * Returns the entity reference of the current context as an array of identity parts
594
 *
595
 * @return array An array containing the identity elements of an entity
596
 */
597
	public function entity() {
598
		return explode('.', $this->_entityPath);
599
	}
600
 
601
/**
602
 * Gets the currently-used model of the rendering context.
603
 *
604
 * @return string
605
 */
606
	public function model() {
607
		if ($this->_association) {
608
			return $this->_association;
609
		}
610
		return $this->_modelScope;
611
	}
612
 
613
/**
614
 * Gets the currently-used model field of the rendering context.
615
 * Strips off field suffixes such as year, month, day, hour, min, meridian
616
 * when the current entity is longer than 2 elements.
617
 *
618
 * @return string
619
 */
620
	public function field() {
621
		$entity = $this->entity();
622
		$count = count($entity);
623
		$last = $entity[$count - 1];
624
		if ($count > 2 && in_array($last, $this->_fieldSuffixes)) {
625
			$last = isset($entity[$count - 2]) ? $entity[$count - 2] : null;
626
		}
627
		return $last;
628
	}
629
 
630
/**
631
 * Generates a DOM ID for the selected element, if one is not set.
632
 * Uses the current View::entity() settings to generate a CamelCased id attribute.
633
 *
634
 * @param array|string $options Either an array of html attributes to add $id into, or a string
635
 *   with a view entity path to get a domId for.
636
 * @param string $id The name of the 'id' attribute.
637
 * @return mixed If $options was an array, an array will be returned with $id set. If a string
638
 *   was supplied, a string will be returned.
639
 */
640
	public function domId($options = null, $id = 'id') {
641
		if (is_array($options) && array_key_exists($id, $options) && $options[$id] === null) {
642
			unset($options[$id]);
643
			return $options;
644
		} elseif (!is_array($options) && $options !== null) {
645
			$this->setEntity($options);
646
			return $this->domId();
647
		}
648
 
649
		$entity = $this->entity();
650
		$model = array_shift($entity);
651
		$dom = $model . implode('', array_map(array('Inflector', 'camelize'), $entity));
652
 
653
		if (is_array($options) && !array_key_exists($id, $options)) {
654
			$options[$id] = $dom;
655
		} elseif ($options === null) {
656
			return $dom;
657
		}
658
		return $options;
659
	}
660
 
661
/**
662
 * Gets the input field name for the current tag. Creates input name attributes
663
 * using CakePHP's data[Model][field] formatting.
664
 *
665
 * @param array|string $options If an array, should be an array of attributes that $key needs to be added to.
666
 *   If a string or null, will be used as the View entity.
667
 * @param string $field
668
 * @param string $key The name of the attribute to be set, defaults to 'name'
669
 * @return mixed If an array was given for $options, an array with $key set will be returned.
670
 *   If a string was supplied a string will be returned.
671
 */
672
	protected function _name($options = array(), $field = null, $key = 'name') {
673
		if ($options === null) {
674
			$options = array();
675
		} elseif (is_string($options)) {
676
			$field = $options;
677
			$options = 0;
678
		}
679
 
680
		if (!empty($field)) {
681
			$this->setEntity($field);
682
		}
683
 
684
		if (is_array($options) && array_key_exists($key, $options)) {
685
			return $options;
686
		}
687
 
688
		switch ($field) {
689
			case '_method':
690
				$name = $field;
691
				break;
692
			default:
693
				$name = 'data[' . implode('][', $this->entity()) . ']';
694
		}
695
 
696
		if (is_array($options)) {
697
			$options[$key] = $name;
698
			return $options;
699
		}
700
		return $name;
701
	}
702
 
703
/**
704
 * Gets the data for the current tag
705
 *
706
 * @param array|string $options If an array, should be an array of attributes that $key needs to be added to.
707
 *   If a string or null, will be used as the View entity.
708
 * @param string $field
709
 * @param string $key The name of the attribute to be set, defaults to 'value'
710
 * @return mixed If an array was given for $options, an array with $key set will be returned.
711
 *   If a string was supplied a string will be returned.
712
 */
713
	public function value($options = array(), $field = null, $key = 'value') {
714
		if ($options === null) {
715
			$options = array();
716
		} elseif (is_string($options)) {
717
			$field = $options;
718
			$options = 0;
719
		}
720
 
721
		if (is_array($options) && isset($options[$key])) {
722
			return $options;
723
		}
724
 
725
		if (!empty($field)) {
726
			$this->setEntity($field);
727
		}
728
		$result = null;
729
		$data = $this->request->data;
730
 
731
		$entity = $this->entity();
732
		if (!empty($data) && is_array($data) && !empty($entity)) {
733
			$result = Hash::get($data, implode('.', $entity));
734
		}
735
 
736
		$habtmKey = $this->field();
737
		if (empty($result) && isset($data[$habtmKey][$habtmKey]) && is_array($data[$habtmKey])) {
738
			$result = $data[$habtmKey][$habtmKey];
739
		} elseif (empty($result) && isset($data[$habtmKey]) && is_array($data[$habtmKey])) {
740
			if (ClassRegistry::isKeySet($habtmKey)) {
741
				$model = ClassRegistry::getObject($habtmKey);
742
				$result = $this->_selectedArray($data[$habtmKey], $model->primaryKey);
743
			}
744
		}
745
 
746
		if (is_array($options)) {
747
			if ($result === null && isset($options['default'])) {
748
				$result = $options['default'];
749
			}
750
			unset($options['default']);
751
		}
752
 
753
		if (is_array($options)) {
754
			$options[$key] = $result;
755
			return $options;
756
		}
757
		return $result;
758
	}
759
 
760
/**
761
 * Sets the defaults for an input tag. Will set the
762
 * name, value, and id attributes for an array of html attributes.
763
 *
764
 * @param string $field The field name to initialize.
765
 * @param array $options Array of options to use while initializing an input field.
766
 * @return array Array options for the form input.
767
 */
768
	protected function _initInputField($field, $options = array()) {
769
		if ($field !== null) {
770
			$this->setEntity($field);
771
		}
772
		$options = (array)$options;
773
		$options = $this->_name($options);
774
		$options = $this->value($options);
775
		$options = $this->domId($options);
776
		return $options;
777
	}
778
 
779
/**
780
 * Adds the given class to the element options
781
 *
782
 * @param array $options Array options/attributes to add a class to
783
 * @param string $class The class name being added.
784
 * @param string $key the key to use for class.
785
 * @return array Array of options with $key set.
786
 */
787
	public function addClass($options = array(), $class = null, $key = 'class') {
788
		if (isset($options[$key]) && trim($options[$key])) {
789
			$options[$key] .= ' ' . $class;
790
		} else {
791
			$options[$key] = $class;
792
		}
793
		return $options;
794
	}
795
 
796
/**
797
 * Returns a string generated by a helper method
798
 *
799
 * This method can be overridden in subclasses to do generalized output post-processing
800
 *
801
 * @param string $str String to be output.
802
 * @return string
803
 * @deprecated This method will be removed in future versions.
804
 */
805
	public function output($str) {
806
		return $str;
807
	}
808
 
809
/**
810
 * Before render callback. beforeRender is called before the view file is rendered.
811
 *
812
 * Overridden in subclasses.
813
 *
814
 * @param string $viewFile The view file that is going to be rendered
815
 * @return void
816
 */
817
	public function beforeRender($viewFile) {
818
	}
819
 
820
/**
821
 * After render callback. afterRender is called after the view file is rendered
822
 * but before the layout has been rendered.
823
 *
824
 * Overridden in subclasses.
825
 *
826
 * @param string $viewFile The view file that was rendered.
827
 * @return void
828
 */
829
	public function afterRender($viewFile) {
830
	}
831
 
832
/**
833
 * Before layout callback. beforeLayout is called before the layout is rendered.
834
 *
835
 * Overridden in subclasses.
836
 *
837
 * @param string $layoutFile The layout about to be rendered.
838
 * @return void
839
 */
840
	public function beforeLayout($layoutFile) {
841
	}
842
 
843
/**
844
 * After layout callback. afterLayout is called after the layout has rendered.
845
 *
846
 * Overridden in subclasses.
847
 *
848
 * @param string $layoutFile The layout file that was rendered.
849
 * @return void
850
 */
851
	public function afterLayout($layoutFile) {
852
	}
853
 
854
/**
855
 * Before render file callback.
856
 * Called before any view fragment is rendered.
857
 *
858
 * Overridden in subclasses.
859
 *
860
 * @param string $viewFile The file about to be rendered.
861
 * @return void
862
 */
863
	public function beforeRenderFile($viewFile) {
864
	}
865
 
866
/**
867
 * After render file callback.
868
 * Called after any view fragment is rendered.
869
 *
870
 * Overridden in subclasses.
871
 *
872
 * @param string $viewFile The file just be rendered.
873
 * @param string $content The content that was rendered.
874
 * @return void
875
 */
876
	public function afterRenderFile($viewFile, $content) {
877
	}
878
 
879
/**
880
 * Transforms a recordset from a hasAndBelongsToMany association to a list of selected
881
 * options for a multiple select element
882
 *
883
 * @param string|array $data
884
 * @param string $key
885
 * @return array
886
 */
887
	protected function _selectedArray($data, $key = 'id') {
888
		if (!is_array($data)) {
889
			$model = $data;
890
			if (!empty($this->request->data[$model][$model])) {
891
				return $this->request->data[$model][$model];
892
			}
893
			if (!empty($this->request->data[$model])) {
894
				$data = $this->request->data[$model];
895
			}
896
		}
897
		$array = array();
898
		if (!empty($data)) {
899
			foreach ($data as $row) {
900
				if (isset($row[$key])) {
901
					$array[$row[$key]] = $row[$key];
902
				}
903
			}
904
		}
905
		return empty($array) ? null : $array;
906
	}
907
 
908
/**
909
 * Resets the vars used by Helper::clean() to null
910
 *
911
 * @return void
912
 */
913
	protected function _reset() {
914
		$this->_tainted = null;
915
		$this->_cleaned = null;
916
	}
917
 
918
/**
919
 * Removes harmful content from output
920
 *
921
 * @return void
922
 */
923
	protected function _clean() {
924
		if (get_magic_quotes_gpc()) {
925
			$this->_cleaned = stripslashes($this->_tainted);
926
		} else {
927
			$this->_cleaned = $this->_tainted;
928
		}
929
 
930
		$this->_cleaned = str_replace(array("&amp;", "&lt;", "&gt;"), array("&amp;amp;", "&amp;lt;", "&amp;gt;"), $this->_cleaned);
931
		$this->_cleaned = preg_replace('#(&\#*\w+)[\x00-\x20]+;#u', "$1;", $this->_cleaned);
932
		$this->_cleaned = preg_replace('#(&\#x*)([0-9A-F]+);*#iu', "$1$2;", $this->_cleaned);
933
		$this->_cleaned = html_entity_decode($this->_cleaned, ENT_COMPAT, "UTF-8");
934
		$this->_cleaned = preg_replace('#(<[^>]+[\x00-\x20\"\'\/])(on|xmlns)[^>]*>#iUu', "$1>", $this->_cleaned);
935
		$this->_cleaned = preg_replace('#([a-z]*)[\x00-\x20]*=[\x00-\x20]*([\`\'\"]*)[\\x00-\x20]*j[\x00-\x20]*a[\x00-\x20]*v[\x00-\x20]*a[\x00-\x20]*s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:#iUu', '$1=$2nojavascript...', $this->_cleaned);
936
		$this->_cleaned = preg_replace('#([a-z]*)[\x00-\x20]*=([\'\"]*)[\x00-\x20]*v[\x00-\x20]*b[\x00-\x20]*s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:#iUu', '$1=$2novbscript...', $this->_cleaned);
937
		$this->_cleaned = preg_replace('#([a-z]*)[\x00-\x20]*=*([\'\"]*)[\x00-\x20]*-moz-binding[\x00-\x20]*:#iUu', '$1=$2nomozbinding...', $this->_cleaned);
938
		$this->_cleaned = preg_replace('#([a-z]*)[\x00-\x20]*=([\'\"]*)[\x00-\x20]*data[\x00-\x20]*:#Uu', '$1=$2nodata...', $this->_cleaned);
939
		$this->_cleaned = preg_replace('#(<[^>]+)style[\x00-\x20]*=[\x00-\x20]*([\`\'\"]*).*expression[\x00-\x20]*\([^>]*>#iU', "$1>", $this->_cleaned);
940
		$this->_cleaned = preg_replace('#(<[^>]+)style[\x00-\x20]*=[\x00-\x20]*([\`\'\"]*).*behaviour[\x00-\x20]*\([^>]*>#iU', "$1>", $this->_cleaned);
941
		$this->_cleaned = preg_replace('#(<[^>]+)style[\x00-\x20]*=[\x00-\x20]*([\`\'\"]*).*s[\x00-\x20]*c[\x00-\x20]*r[\x00-\x20]*i[\x00-\x20]*p[\x00-\x20]*t[\x00-\x20]*:*[^>]*>#iUu', "$1>", $this->_cleaned);
942
		$this->_cleaned = preg_replace('#</*\w+:\w[^>]*>#i', "", $this->_cleaned);
943
		do {
944
			$oldstring = $this->_cleaned;
945
			$this->_cleaned = preg_replace('#</*(applet|meta|xml|blink|link|style|script|embed|object|iframe|frame|frameset|ilayer|layer|bgsound|title|base)[^>]*>#i', "", $this->_cleaned);
946
		} while ($oldstring !== $this->_cleaned);
947
		$this->_cleaned = str_replace(array("&amp;", "&lt;", "&gt;"), array("&amp;amp;", "&amp;lt;", "&amp;gt;"), $this->_cleaned);
948
	}
949
 
950
}