Subversion Repositories SmartDukaan

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
15403 manish.sha 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
App::uses('Inflector', 'Utility');
20
 
21
/**
22
 * Abstract base class for all other Helpers in CakePHP.
23
 * Provides common methods and features.
24
 *
25
 * @package       Cake.View
26
 */
27
class Helper extends Object {
28
 
29
/**
30
 * Settings for this helper.
31
 *
32
 * @var array
33
 */
34
	public $settings = array();
35
 
36
/**
37
 * List of helpers used by this helper
38
 *
39
 * @var array
40
 */
41
	public $helpers = array();
42
 
43
/**
44
 * A helper lookup table used to lazy load helper objects.
45
 *
46
 * @var array
47
 */
48
	protected $_helperMap = array();
49
 
50
/**
51
 * The current theme name if any.
52
 *
53
 * @var string
54
 */
55
	public $theme = null;
56
 
57
/**
58
 * Request object
59
 *
60
 * @var CakeRequest
61
 */
62
	public $request = null;
63
 
64
/**
65
 * Plugin path
66
 *
67
 * @var string
68
 */
69
	public $plugin = null;
70
 
71
/**
72
 * Holds the fields array('field_name' => array('type' => 'string', 'length' => 100),
73
 * primaryKey and validates array('field_name')
74
 *
75
 * @var array
76
 */
77
	public $fieldset = array();
78
 
79
/**
80
 * Holds tag templates.
81
 *
82
 * @var array
83
 */
84
	public $tags = array();
85
 
86
/**
87
 * Holds the content to be cleaned.
88
 *
89
 * @var mixed
90
 */
91
	protected $_tainted = null;
92
 
93
/**
94
 * Holds the cleaned content.
95
 *
96
 * @var mixed
97
 */
98
	protected $_cleaned = null;
99
 
100
/**
101
 * The View instance this helper is attached to
102
 *
103
 * @var View
104
 */
105
	protected $_View;
106
 
107
/**
108
 * A list of strings that should be treated as suffixes, or
109
 * sub inputs for a parent input. This is used for date/time
110
 * inputs primarily.
111
 *
112
 * @var array
113
 */
114
	protected $_fieldSuffixes = array(
115
		'year', 'month', 'day', 'hour', 'min', 'second', 'meridian'
116
	);
117
 
118
/**
119
 * The name of the current model entities are in scope of.
120
 *
121
 * @see Helper::setEntity()
122
 * @var string
123
 */
124
	protected $_modelScope;
125
 
126
/**
127
 * The name of the current model association entities are in scope of.
128
 *
129
 * @see Helper::setEntity()
130
 * @var string
131
 */
132
	protected $_association;
133
 
134
/**
135
 * The dot separated list of elements the current field entity is for.
136
 *
137
 * @see Helper::setEntity()
138
 * @var string
139
 */
140
	protected $_entityPath;
141
 
142
/**
143
 * Minimized attributes
144
 *
145
 * @var array
146
 */
147
	protected $_minimizedAttributes = array(
148
		'compact', 'checked', 'declare', 'readonly', 'disabled', 'selected',
149
		'defer', 'ismap', 'nohref', 'noshade', 'nowrap', 'multiple', 'noresize',
150
		'autoplay', 'controls', 'loop', 'muted', 'required', 'novalidate', 'formnovalidate'
151
	);
152
 
153
/**
154
 * Format to attribute
155
 *
156
 * @var string
157
 */
158
	protected $_attributeFormat = '%s="%s"';
159
 
160
/**
161
 * Format to attribute
162
 *
163
 * @var string
164
 */
165
	protected $_minimizedAttributeFormat = '%s="%s"';
166
 
167
/**
168
 * Default Constructor
169
 *
170
 * @param View $View The View this helper is being attached to.
171
 * @param array $settings Configuration settings for the helper.
172
 */
173
	public function __construct(View $View, $settings = array()) {
174
		$this->_View = $View;
175
		$this->request = $View->request;
176
		if ($settings) {
177
			$this->settings = Hash::merge($this->settings, $settings);
178
		}
179
		if (!empty($this->helpers)) {
180
			$this->_helperMap = ObjectCollection::normalizeObjectArray($this->helpers);
181
		}
182
	}
183
 
184
/**
185
 * Provide non fatal errors on missing method calls.
186
 *
187
 * @param string $method Method to invoke
188
 * @param array $params Array of params for the method.
189
 * @return void
190
 */
191
	public function __call($method, $params) {
192
		trigger_error(__d('cake_dev', 'Method %1$s::%2$s does not exist', get_class($this), $method), E_USER_WARNING);
193
	}
194
 
195
/**
196
 * Lazy loads helpers. Provides access to deprecated request properties as well.
197
 *
198
 * @param string $name Name of the property being accessed.
199
 * @return mixed Helper or property found at $name
200
 * @deprecated 3.0.0 Accessing request properties through this method is deprecated and will be removed in 3.0.
201
 */
202
	public function __get($name) {
203
		if (isset($this->_helperMap[$name]) && !isset($this->{$name})) {
204
			$settings = array('enabled' => false) + (array)$this->_helperMap[$name]['settings'];
205
			$this->{$name} = $this->_View->loadHelper($this->_helperMap[$name]['class'], $settings);
206
		}
207
		if (isset($this->{$name})) {
208
			return $this->{$name};
209
		}
210
		switch ($name) {
211
			case 'base':
212
			case 'here':
213
			case 'webroot':
214
			case 'data':
215
				return $this->request->{$name};
216
			case 'action':
217
				return isset($this->request->params['action']) ? $this->request->params['action'] : '';
218
			case 'params':
219
				return $this->request;
220
		}
221
	}
222
 
223
/**
224
 * Provides backwards compatibility access for setting values to the request object.
225
 *
226
 * @param string $name Name of the property being accessed.
227
 * @param mixed $value Value to set.
228
 * @return void
229
 * @deprecated 3.0.0 This method will be removed in 3.0
230
 */
231
	public function __set($name, $value) {
232
		switch ($name) {
233
			case 'base':
234
			case 'here':
235
			case 'webroot':
236
			case 'data':
237
				$this->request->{$name} = $value;
238
				return;
239
			case 'action':
240
				$this->request->params['action'] = $value;
241
				return;
242
		}
243
		$this->{$name} = $value;
244
	}
245
 
246
/**
247
 * Finds URL for specified action.
248
 *
249
 * Returns a URL pointing at the provided parameters.
250
 *
251
 * @param string|array $url Either a relative string url like `/products/view/23` or
252
 *    an array of URL parameters. Using an array for URLs will allow you to leverage
253
 *    the reverse routing features of CakePHP.
254
 * @param bool $full If true, the full base URL will be prepended to the result
255
 * @return string Full translated URL with base path.
256
 * @link http://book.cakephp.org/2.0/en/views/helpers.html
257
 */
258
	public function url($url = null, $full = false) {
259
		return h(Router::url($url, $full));
260
	}
261
 
262
/**
263
 * Checks if a file exists when theme is used, if no file is found default location is returned
264
 *
265
 * @param string $file The file to create a webroot path to.
266
 * @return string Web accessible path to file.
267
 */
268
	public function webroot($file) {
269
		$asset = explode('?', $file);
270
		$asset[1] = isset($asset[1]) ? '?' . $asset[1] : null;
271
		$webPath = "{$this->request->webroot}" . $asset[0];
272
		$file = $asset[0];
273
 
274
		if (!empty($this->theme)) {
275
			$file = trim($file, '/');
276
			$theme = $this->theme . '/';
277
 
278
			if (DS === '\\') {
279
				$file = str_replace('/', '\\', $file);
280
			}
281
 
282
			if (file_exists(Configure::read('App.www_root') . 'theme' . DS . $this->theme . DS . $file)) {
283
				$webPath = "{$this->request->webroot}theme/" . $theme . $asset[0];
284
			} else {
285
				$themePath = App::themePath($this->theme);
286
				$path = $themePath . 'webroot' . DS . $file;
287
				if (file_exists($path)) {
288
					$webPath = "{$this->request->webroot}theme/" . $theme . $asset[0];
289
				}
290
			}
291
		}
292
		if (strpos($webPath, '//') !== false) {
293
			return str_replace('//', '/', $webPath . $asset[1]);
294
		}
295
		return $webPath . $asset[1];
296
	}
297
 
298
/**
299
 * Generate URL for given asset file. Depending on options passed provides full URL with domain name.
300
 * Also calls Helper::assetTimestamp() to add timestamp to local files
301
 *
302
 * @param string|array $path Path string or URL array
303
 * @param array $options Options array. Possible keys:
304
 *   `fullBase` Return full URL with domain name
305
 *   `pathPrefix` Path prefix for relative URLs
306
 *   `ext` Asset extension to append
307
 *   `plugin` False value will prevent parsing path as a plugin
308
 * @return string Generated URL
309
 */
310
	public function assetUrl($path, $options = array()) {
311
		if (is_array($path)) {
312
			return $this->url($path, !empty($options['fullBase']));
313
		}
314
		if (strpos($path, '://') !== false) {
315
			return $path;
316
		}
317
		if (!array_key_exists('plugin', $options) || $options['plugin'] !== false) {
318
			list($plugin, $path) = $this->_View->pluginSplit($path, false);
319
		}
320
		if (!empty($options['pathPrefix']) && $path[0] !== '/') {
321
			$path = $options['pathPrefix'] . $path;
322
		}
323
		if (!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|null Cleaned content for output
409
 * @deprecated 3.0.0 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 3.0.0 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 bool $escape Define if the value must be escaped
484
 * @return string The composed attribute.
485
 * @deprecated 3.0.0 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 bool $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 (($count === 1 && $this->_modelScope && !$setScope) ||
546
			(
547
				$count === 2 &&
548
				in_array($lastPart, $this->_fieldSuffixes) &&
549
				$this->_modelScope &&
550
				$parts[0] !== $this->_modelScope
551
			)
552
		) {
553
			$entity = $this->_modelScope . '.' . $entity;
554
		}
555
 
556
		// 0.name, 0.created.month style inputs. Excludes inputs with the modelScope in them.
557
		if ($count >= 2 &&
558
			is_numeric($parts[0]) &&
559
			!is_numeric($parts[1]) &&
560
			$this->_modelScope &&
561
			strpos($entity, $this->_modelScope) === false
562
		) {
563
			$entity = $this->_modelScope . '.' . $entity;
564
		}
565
 
566
		$this->_association = null;
567
 
568
		$isHabtm = (
569
			isset($this->fieldset[$this->_modelScope]['fields'][$parts[0]]['type']) &&
570
			$this->fieldset[$this->_modelScope]['fields'][$parts[0]]['type'] === 'multiple'
571
		);
572
 
573
		// habtm models are special
574
		if ($count === 1 && $isHabtm) {
575
			$this->_association = $parts[0];
576
			$entity = $parts[0] . '.' . $parts[0];
577
		} else {
578
			// check for associated model.
579
			$reversed = array_reverse($parts);
580
			foreach ($reversed as $i => $part) {
581
				if ($i > 0 && preg_match('/^[A-Z]/', $part)) {
582
					$this->_association = $part;
583
					break;
584
				}
585
			}
586
		}
587
		$this->_entityPath = $entity;
588
	}
589
 
590
/**
591
 * Returns the entity reference of the current context as an array of identity parts
592
 *
593
 * @return array An array containing the identity elements of an entity
594
 */
595
	public function entity() {
596
		return explode('.', $this->_entityPath);
597
	}
598
 
599
/**
600
 * Gets the currently-used model of the rendering context.
601
 *
602
 * @return string
603
 */
604
	public function model() {
605
		if ($this->_association) {
606
			return $this->_association;
607
		}
608
		return $this->_modelScope;
609
	}
610
 
611
/**
612
 * Gets the currently-used model field of the rendering context.
613
 * Strips off field suffixes such as year, month, day, hour, min, meridian
614
 * when the current entity is longer than 2 elements.
615
 *
616
 * @return string
617
 */
618
	public function field() {
619
		$entity = $this->entity();
620
		$count = count($entity);
621
		$last = $entity[$count - 1];
622
		if ($count > 2 && in_array($last, $this->_fieldSuffixes)) {
623
			$last = isset($entity[$count - 2]) ? $entity[$count - 2] : null;
624
		}
625
		return $last;
626
	}
627
 
628
/**
629
 * Generates a DOM ID for the selected element, if one is not set.
630
 * Uses the current View::entity() settings to generate a CamelCased id attribute.
631
 *
632
 * @param array|string $options Either an array of html attributes to add $id into, or a string
633
 *   with a view entity path to get a domId for.
634
 * @param string $id The name of the 'id' attribute.
635
 * @return mixed If $options was an array, an array will be returned with $id set. If a string
636
 *   was supplied, a string will be returned.
637
 */
638
	public function domId($options = null, $id = 'id') {
639
		if (is_array($options) && array_key_exists($id, $options) && $options[$id] === null) {
640
			unset($options[$id]);
641
			return $options;
642
		} elseif (!is_array($options) && $options !== null) {
643
			$this->setEntity($options);
644
			return $this->domId();
645
		}
646
 
647
		$entity = $this->entity();
648
		$model = array_shift($entity);
649
		$dom = $model . implode('', array_map(array('Inflector', 'camelize'), $entity));
650
 
651
		if (is_array($options) && !array_key_exists($id, $options)) {
652
			$options[$id] = $dom;
653
		} elseif ($options === null) {
654
			return $dom;
655
		}
656
		return $options;
657
	}
658
 
659
/**
660
 * Gets the input field name for the current tag. Creates input name attributes
661
 * using CakePHP's data[Model][field] formatting.
662
 *
663
 * @param array|string $options If an array, should be an array of attributes that $key needs to be added to.
664
 *   If a string or null, will be used as the View entity.
665
 * @param string $field Field name.
666
 * @param string $key The name of the attribute to be set, defaults to 'name'
667
 * @return mixed If an array was given for $options, an array with $key set will be returned.
668
 *   If a string was supplied a string will be returned.
669
 */
670
	protected function _name($options = array(), $field = null, $key = 'name') {
671
		if ($options === null) {
672
			$options = array();
673
		} elseif (is_string($options)) {
674
			$field = $options;
675
			$options = 0;
676
		}
677
 
678
		if (!empty($field)) {
679
			$this->setEntity($field);
680
		}
681
 
682
		if (is_array($options) && array_key_exists($key, $options)) {
683
			return $options;
684
		}
685
 
686
		switch ($field) {
687
			case '_method':
688
				$name = $field;
689
				break;
690
			default:
691
				$name = 'data[' . implode('][', $this->entity()) . ']';
692
		}
693
 
694
		if (is_array($options)) {
695
			$options[$key] = $name;
696
			return $options;
697
		}
698
		return $name;
699
	}
700
 
701
/**
702
 * Gets the data for the current tag
703
 *
704
 * @param array|string $options If an array, should be an array of attributes that $key needs to be added to.
705
 *   If a string or null, will be used as the View entity.
706
 * @param string $field Field name.
707
 * @param string $key The name of the attribute to be set, defaults to 'value'
708
 * @return mixed If an array was given for $options, an array with $key set will be returned.
709
 *   If a string was supplied a string will be returned.
710
 */
711
	public function value($options = array(), $field = null, $key = 'value') {
712
		if ($options === null) {
713
			$options = array();
714
		} elseif (is_string($options)) {
715
			$field = $options;
716
			$options = 0;
717
		}
718
 
719
		if (is_array($options) && isset($options[$key])) {
720
			return $options;
721
		}
722
 
723
		if (!empty($field)) {
724
			$this->setEntity($field);
725
		}
726
		$result = null;
727
		$data = $this->request->data;
728
 
729
		$entity = $this->entity();
730
		if (!empty($data) && is_array($data) && !empty($entity)) {
731
			$result = Hash::get($data, implode('.', $entity));
732
		}
733
 
734
		$habtmKey = $this->field();
735
		if (empty($result) && isset($data[$habtmKey][$habtmKey]) && is_array($data[$habtmKey])) {
736
			$result = $data[$habtmKey][$habtmKey];
737
		} elseif (empty($result) && isset($data[$habtmKey]) && is_array($data[$habtmKey])) {
738
			if (ClassRegistry::isKeySet($habtmKey)) {
739
				$model = ClassRegistry::getObject($habtmKey);
740
				$result = $this->_selectedArray($data[$habtmKey], $model->primaryKey);
741
			}
742
		}
743
 
744
		if (is_array($options)) {
745
			if ($result === null && isset($options['default'])) {
746
				$result = $options['default'];
747
			}
748
			unset($options['default']);
749
		}
750
 
751
		if (is_array($options)) {
752
			$options[$key] = $result;
753
			return $options;
754
		}
755
		return $result;
756
	}
757
 
758
/**
759
 * Sets the defaults for an input tag. Will set the
760
 * name, value, and id attributes for an array of html attributes.
761
 *
762
 * @param string $field The field name to initialize.
763
 * @param array $options Array of options to use while initializing an input field.
764
 * @return array Array options for the form input.
765
 */
766
	protected function _initInputField($field, $options = array()) {
767
		if ($field !== null) {
768
			$this->setEntity($field);
769
		}
770
		$options = (array)$options;
771
		$options = $this->_name($options);
772
		$options = $this->value($options);
773
		$options = $this->domId($options);
774
		return $options;
775
	}
776
 
777
/**
778
 * Adds the given class to the element options
779
 *
780
 * @param array $options Array options/attributes to add a class to
781
 * @param string $class The class name being added.
782
 * @param string $key the key to use for class.
783
 * @return array Array of options with $key set.
784
 */
785
	public function addClass($options = array(), $class = null, $key = 'class') {
786
		if (isset($options[$key]) && trim($options[$key])) {
787
			$options[$key] .= ' ' . $class;
788
		} else {
789
			$options[$key] = $class;
790
		}
791
		return $options;
792
	}
793
 
794
/**
795
 * Returns a string generated by a helper method
796
 *
797
 * This method can be overridden in subclasses to do generalized output post-processing
798
 *
799
 * @param string $str String to be output.
800
 * @return string
801
 * @deprecated 3.0.0 This method will be removed in future versions.
802
 */
803
	public function output($str) {
804
		return $str;
805
	}
806
 
807
/**
808
 * Before render callback. beforeRender is called before the view file is rendered.
809
 *
810
 * Overridden in subclasses.
811
 *
812
 * @param string $viewFile The view file that is going to be rendered
813
 * @return void
814
 */
815
	public function beforeRender($viewFile) {
816
	}
817
 
818
/**
819
 * After render callback. afterRender is called after the view file is rendered
820
 * but before the layout has been rendered.
821
 *
822
 * Overridden in subclasses.
823
 *
824
 * @param string $viewFile The view file that was rendered.
825
 * @return void
826
 */
827
	public function afterRender($viewFile) {
828
	}
829
 
830
/**
831
 * Before layout callback. beforeLayout is called before the layout is rendered.
832
 *
833
 * Overridden in subclasses.
834
 *
835
 * @param string $layoutFile The layout about to be rendered.
836
 * @return void
837
 */
838
	public function beforeLayout($layoutFile) {
839
	}
840
 
841
/**
842
 * After layout callback. afterLayout is called after the layout has rendered.
843
 *
844
 * Overridden in subclasses.
845
 *
846
 * @param string $layoutFile The layout file that was rendered.
847
 * @return void
848
 */
849
	public function afterLayout($layoutFile) {
850
	}
851
 
852
/**
853
 * Before render file callback.
854
 * Called before any view fragment is rendered.
855
 *
856
 * Overridden in subclasses.
857
 *
858
 * @param string $viewFile The file about to be rendered.
859
 * @return void
860
 */
861
	public function beforeRenderFile($viewFile) {
862
	}
863
 
864
/**
865
 * After render file callback.
866
 * Called after any view fragment is rendered.
867
 *
868
 * Overridden in subclasses.
869
 *
870
 * @param string $viewFile The file just be rendered.
871
 * @param string $content The content that was rendered.
872
 * @return void
873
 */
874
	public function afterRenderFile($viewFile, $content) {
875
	}
876
 
877
/**
878
 * Transforms a recordset from a hasAndBelongsToMany association to a list of selected
879
 * options for a multiple select element
880
 *
881
 * @param string|array $data Data array or model name.
882
 * @param string $key Field name.
883
 * @return array
884
 */
885
	protected function _selectedArray($data, $key = 'id') {
886
		if (!is_array($data)) {
887
			$model = $data;
888
			if (!empty($this->request->data[$model][$model])) {
889
				return $this->request->data[$model][$model];
890
			}
891
			if (!empty($this->request->data[$model])) {
892
				$data = $this->request->data[$model];
893
			}
894
		}
895
		$array = array();
896
		if (!empty($data)) {
897
			foreach ($data as $row) {
898
				if (isset($row[$key])) {
899
					$array[$row[$key]] = $row[$key];
900
				}
901
			}
902
		}
903
		return empty($array) ? null : $array;
904
	}
905
 
906
/**
907
 * Resets the vars used by Helper::clean() to null
908
 *
909
 * @return void
910
 */
911
	protected function _reset() {
912
		$this->_tainted = null;
913
		$this->_cleaned = null;
914
	}
915
 
916
/**
917
 * Removes harmful content from output
918
 *
919
 * @return void
920
 */
921
	protected function _clean() {
922
		if (get_magic_quotes_gpc()) {
923
			$this->_cleaned = stripslashes($this->_tainted);
924
		} else {
925
			$this->_cleaned = $this->_tainted;
926
		}
927
 
928
		$this->_cleaned = str_replace(array("&amp;", "&lt;", "&gt;"), array("&amp;amp;", "&amp;lt;", "&amp;gt;"), $this->_cleaned);
929
		$this->_cleaned = preg_replace('#(&\#*\w+)[\x00-\x20]+;#u', "$1;", $this->_cleaned);
930
		$this->_cleaned = preg_replace('#(&\#x*)([0-9A-F]+);*#iu', "$1$2;", $this->_cleaned);
931
		$this->_cleaned = html_entity_decode($this->_cleaned, ENT_COMPAT, "UTF-8");
932
		$this->_cleaned = preg_replace('#(<[^>]+[\x00-\x20\"\'\/])(on|xmlns)[^>]*>#iUu', "$1>", $this->_cleaned);
933
		$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);
934
		$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);
935
		$this->_cleaned = preg_replace('#([a-z]*)[\x00-\x20]*=*([\'\"]*)[\x00-\x20]*-moz-binding[\x00-\x20]*:#iUu', '$1=$2nomozbinding...', $this->_cleaned);
936
		$this->_cleaned = preg_replace('#([a-z]*)[\x00-\x20]*=([\'\"]*)[\x00-\x20]*data[\x00-\x20]*:#Uu', '$1=$2nodata...', $this->_cleaned);
937
		$this->_cleaned = preg_replace('#(<[^>]+)style[\x00-\x20]*=[\x00-\x20]*([\`\'\"]*).*expression[\x00-\x20]*\([^>]*>#iU', "$1>", $this->_cleaned);
938
		$this->_cleaned = preg_replace('#(<[^>]+)style[\x00-\x20]*=[\x00-\x20]*([\`\'\"]*).*behaviour[\x00-\x20]*\([^>]*>#iU', "$1>", $this->_cleaned);
939
		$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);
940
		$this->_cleaned = preg_replace('#</*\w+:\w[^>]*>#i', "", $this->_cleaned);
941
		do {
942
			$oldstring = $this->_cleaned;
943
			$this->_cleaned = preg_replace('#</*(applet|meta|xml|blink|link|style|script|embed|object|iframe|frame|frameset|ilayer|layer|bgsound|title|base)[^>]*>#i', "", $this->_cleaned);
944
		} while ($oldstring !== $this->_cleaned);
945
		$this->_cleaned = str_replace(array("&amp;", "&lt;", "&gt;"), array("&amp;amp;", "&amp;lt;", "&amp;gt;"), $this->_cleaned);
946
	}
947
 
948
}