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.Helper
13
 * @since         CakePHP(tm) v 0.10.0.1076
14
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
15
 */
16
 
17
App::uses('ClassRegistry', 'Utility');
18
App::uses('AppHelper', 'View/Helper');
19
App::uses('Hash', 'Utility');
20
App::uses('Inflector', 'Utility');
21
 
22
/**
23
 * Form helper library.
24
 *
25
 * Automatic generation of HTML FORMs from given data.
26
 *
27
 * @package       Cake.View.Helper
28
 * @property      HtmlHelper $Html
29
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html
30
 */
31
class FormHelper extends AppHelper {
32
 
33
/**
34
 * Other helpers used by FormHelper
35
 *
36
 * @var array
37
 */
38
	public $helpers = array('Html');
39
 
40
/**
41
 * Options used by DateTime fields
42
 *
43
 * @var array
44
 */
45
	protected $_options = array(
46
		'day' => array(), 'minute' => array(), 'hour' => array(),
47
		'month' => array(), 'year' => array(), 'meridian' => array()
48
	);
49
 
50
/**
51
 * List of fields created, used with secure forms.
52
 *
53
 * @var array
54
 */
55
	public $fields = array();
56
 
57
/**
58
 * Constant used internally to skip the securing process,
59
 * and neither add the field to the hash or to the unlocked fields.
60
 *
61
 * @var string
62
 */
63
	const SECURE_SKIP = 'skip';
64
 
65
/**
66
 * Defines the type of form being created. Set by FormHelper::create().
67
 *
68
 * @var string
69
 */
70
	public $requestType = null;
71
 
72
/**
73
 * The default model being used for the current form.
74
 *
75
 * @var string
76
 */
77
	public $defaultModel = null;
78
 
79
/**
80
 * Persistent default options used by input(). Set by FormHelper::create().
81
 *
82
 * @var array
83
 */
84
	protected $_inputDefaults = array();
85
 
86
/**
87
 * An array of field names that have been excluded from
88
 * the Token hash used by SecurityComponent's validatePost method
89
 *
90
 * @see FormHelper::_secure()
91
 * @see SecurityComponent::validatePost()
92
 * @var array
93
 */
94
	protected $_unlockedFields = array();
95
 
96
/**
97
 * Holds the model references already loaded by this helper
98
 * product of trying to inspect them out of field names
99
 *
100
 * @var array
101
 */
102
	protected $_models = array();
103
 
104
/**
105
 * Holds all the validation errors for models loaded and inspected
106
 * it can also be set manually to be able to display custom error messages
107
 * in the any of the input fields generated by this helper
108
 *
109
 * @var array
110
 */
111
	public $validationErrors = array();
112
 
113
/**
114
 * Holds already used DOM ID suffixes to avoid collisions with multiple form field elements.
115
 *
116
 * @var array
117
 */
118
	protected $_domIdSuffixes = array();
119
 
120
/**
121
 * The action attribute value of the last created form.
122
 * Used to make form/request specific hashes for SecurityComponent.
123
 *
124
 * @var string
125
 */
126
	protected $_lastAction = '';
127
 
128
/**
129
 * Copies the validationErrors variable from the View object into this instance
130
 *
131
 * @param View $View The View this helper is being attached to.
132
 * @param array $settings Configuration settings for the helper.
133
 */
134
	public function __construct(View $View, $settings = array()) {
135
		parent::__construct($View, $settings);
136
		$this->validationErrors =& $View->validationErrors;
137
	}
138
 
139
/**
140
 * Guess the location for a model based on its name and tries to create a new instance
141
 * or get an already created instance of the model
142
 *
143
 * @param string $model Model name.
144
 * @return Model|null Model instance
145
 */
146
	protected function _getModel($model) {
147
		$object = null;
148
		if (!$model || $model === 'Model') {
149
			return $object;
150
		}
151
 
152
		if (array_key_exists($model, $this->_models)) {
153
			return $this->_models[$model];
154
		}
155
 
156
		if (ClassRegistry::isKeySet($model)) {
157
			$object = ClassRegistry::getObject($model);
158
		} elseif (isset($this->request->params['models'][$model])) {
159
			$plugin = $this->request->params['models'][$model]['plugin'];
160
			$plugin .= ($plugin) ? '.' : null;
161
			$object = ClassRegistry::init(array(
162
				'class' => $plugin . $this->request->params['models'][$model]['className'],
163
				'alias' => $model
164
			));
165
		} elseif (ClassRegistry::isKeySet($this->defaultModel)) {
166
			$defaultObject = ClassRegistry::getObject($this->defaultModel);
167
			if ($defaultObject && in_array($model, array_keys($defaultObject->getAssociated()), true) && isset($defaultObject->{$model})) {
168
				$object = $defaultObject->{$model};
169
			}
170
		} else {
171
			$object = ClassRegistry::init($model, true);
172
		}
173
 
174
		$this->_models[$model] = $object;
175
		if (!$object) {
176
			return null;
177
		}
178
 
179
		$this->fieldset[$model] = array('fields' => null, 'key' => $object->primaryKey, 'validates' => null);
180
		return $object;
181
	}
182
 
183
/**
184
 * Inspects the model properties to extract information from them.
185
 * Currently it can extract information from the the fields, the primary key and required fields
186
 *
187
 * The $key parameter accepts the following list of values:
188
 *
189
 * - key: Returns the name of the primary key for the model
190
 * - fields: Returns the model schema
191
 * - validates: returns the list of fields that are required
192
 * - errors: returns the list of validation errors
193
 *
194
 * If the $field parameter is passed if will return the information for that sole field.
195
 *
196
 * `$this->_introspectModel('Post', 'fields', 'title');` will return the schema information for title column
197
 *
198
 * @param string $model name of the model to extract information from
199
 * @param string $key name of the special information key to obtain (key, fields, validates, errors)
200
 * @param string $field name of the model field to get information from
201
 * @return mixed information extracted for the special key and field in a model
202
 */
203
	protected function _introspectModel($model, $key, $field = null) {
204
		$object = $this->_getModel($model);
205
		if (!$object) {
206
			return;
207
		}
208
 
209
		if ($key === 'key') {
210
			return $this->fieldset[$model]['key'] = $object->primaryKey;
211
		}
212
 
213
		if ($key === 'fields') {
214
			if (!isset($this->fieldset[$model]['fields'])) {
215
				$this->fieldset[$model]['fields'] = $object->schema();
216
				foreach ($object->hasAndBelongsToMany as $alias => $assocData) {
217
					$this->fieldset[$object->alias]['fields'][$alias] = array('type' => 'multiple');
218
				}
219
			}
220
			if ($field === null || $field === false) {
221
				return $this->fieldset[$model]['fields'];
222
			} elseif (isset($this->fieldset[$model]['fields'][$field])) {
223
				return $this->fieldset[$model]['fields'][$field];
224
			}
225
			return isset($object->hasAndBelongsToMany[$field]) ? array('type' => 'multiple') : null;
226
		}
227
 
228
		if ($key === 'errors' && !isset($this->validationErrors[$model])) {
229
			$this->validationErrors[$model] =& $object->validationErrors;
230
			return $this->validationErrors[$model];
231
		} elseif ($key === 'errors' && isset($this->validationErrors[$model])) {
232
			return $this->validationErrors[$model];
233
		}
234
 
235
		if ($key === 'validates' && !isset($this->fieldset[$model]['validates'])) {
236
			$validates = array();
237
			foreach (iterator_to_array($object->validator(), true) as $validateField => $validateProperties) {
238
				if ($this->_isRequiredField($validateProperties)) {
239
					$validates[$validateField] = true;
240
				}
241
			}
242
			$this->fieldset[$model]['validates'] = $validates;
243
		}
244
 
245
		if ($key === 'validates') {
246
			if (empty($field)) {
247
				return $this->fieldset[$model]['validates'];
248
			}
249
			return isset($this->fieldset[$model]['validates'][$field]) ?
250
				$this->fieldset[$model]['validates'] : null;
251
		}
252
	}
253
 
254
/**
255
 * Returns if a field is required to be filled based on validation properties from the validating object.
256
 *
257
 * @param CakeValidationSet $validationRules Validation rules set.
258
 * @return bool true if field is required to be filled, false otherwise
259
 */
260
	protected function _isRequiredField($validationRules) {
261
		if (empty($validationRules) || count($validationRules) === 0) {
262
			return false;
263
		}
264
 
265
		$isUpdate = $this->requestType === 'put';
266
		foreach ($validationRules as $rule) {
267
			$rule->isUpdate($isUpdate);
268
			if ($rule->skip()) {
269
				continue;
270
			}
271
 
272
			return !$rule->allowEmpty;
273
		}
274
		return false;
275
	}
276
 
277
/**
278
 * Returns false if given form field described by the current entity has no errors.
279
 * Otherwise it returns the validation message
280
 *
281
 * @return mixed Either false when there are no errors, or an array of error
282
 *    strings. An error string could be ''.
283
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::tagIsInvalid
284
 */
285
	public function tagIsInvalid() {
286
		$entity = $this->entity();
287
		$model = array_shift($entity);
288
 
289
		// 0.Model.field. Fudge entity path
290
		if (empty($model) || is_numeric($model)) {
291
			array_splice($entity, 1, 0, $model);
292
			$model = array_shift($entity);
293
		}
294
 
295
		$errors = array();
296
		if (!empty($entity) && isset($this->validationErrors[$model])) {
297
			$errors = $this->validationErrors[$model];
298
		}
299
		if (!empty($entity) && empty($errors)) {
300
			$errors = $this->_introspectModel($model, 'errors');
301
		}
302
		if (empty($errors)) {
303
			return false;
304
		}
305
		$errors = Hash::get($errors, implode('.', $entity));
306
		return $errors === null ? false : $errors;
307
	}
308
 
309
/**
310
 * Returns an HTML FORM element.
311
 *
312
 * ### Options:
313
 *
314
 * - `type` Form method defaults to POST
315
 * - `action`  The controller action the form submits to, (optional).
316
 * - `url`  The URL the form submits to. Can be a string or a URL array. If you use 'url'
317
 *    you should leave 'action' undefined.
318
 * - `default`  Allows for the creation of Ajax forms. Set this to false to prevent the default event handler.
319
 *   Will create an onsubmit attribute if it doesn't not exist. If it does, default action suppression
320
 *   will be appended.
321
 * - `onsubmit` Used in conjunction with 'default' to create ajax forms.
322
 * - `inputDefaults` set the default $options for FormHelper::input(). Any options that would
323
 *   be set when using FormHelper::input() can be set here. Options set with `inputDefaults`
324
 *   can be overridden when calling input()
325
 * - `encoding` Set the accept-charset encoding for the form. Defaults to `Configure::read('App.encoding')`
326
 *
327
 * @param mixed $model The model name for which the form is being defined. Should
328
 *   include the plugin name for plugin models. e.g. `ContactManager.Contact`.
329
 *   If an array is passed and $options argument is empty, the array will be used as options.
330
 *   If `false` no model is used.
331
 * @param array $options An array of html attributes and options.
332
 * @return string A formatted opening FORM tag.
333
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#options-for-create
334
 */
335
	public function create($model = null, $options = array()) {
336
		$created = $id = false;
337
		$append = '';
338
 
339
		if (is_array($model) && empty($options)) {
340
			$options = $model;
341
			$model = null;
342
		}
343
 
344
		if (empty($model) && $model !== false && !empty($this->request->params['models'])) {
345
			$model = key($this->request->params['models']);
346
		} elseif (empty($model) && empty($this->request->params['models'])) {
347
			$model = false;
348
		}
349
		$this->defaultModel = $model;
350
 
351
		$key = null;
352
		if ($model !== false) {
353
			list($plugin, $model) = pluginSplit($model, true);
354
			$key = $this->_introspectModel($plugin . $model, 'key');
355
			$this->setEntity($model, true);
356
		}
357
 
358
		if ($model !== false && $key) {
359
			$recordExists = (
360
				isset($this->request->data[$model]) &&
361
				!empty($this->request->data[$model][$key]) &&
362
				!is_array($this->request->data[$model][$key])
363
			);
364
 
365
			if ($recordExists) {
366
				$created = true;
367
				$id = $this->request->data[$model][$key];
368
			}
369
		}
370
 
371
		$options += array(
372
			'type' => ($created && empty($options['action'])) ? 'put' : 'post',
373
			'action' => null,
374
			'url' => null,
375
			'default' => true,
376
			'encoding' => strtolower(Configure::read('App.encoding')),
377
			'inputDefaults' => array()
378
		);
379
		$this->inputDefaults($options['inputDefaults']);
380
		unset($options['inputDefaults']);
381
 
382
		if (!isset($options['id'])) {
383
			$domId = isset($options['action']) ? $options['action'] : $this->request['action'];
384
			$options['id'] = $this->domId($domId . 'Form');
385
		}
386
 
387
		if ($options['action'] === null && $options['url'] === null) {
388
			$options['action'] = $this->request->here(false);
389
		} elseif (empty($options['url']) || is_array($options['url'])) {
390
			if (empty($options['url']['controller'])) {
391
				if (!empty($model)) {
392
					$options['url']['controller'] = Inflector::underscore(Inflector::pluralize($model));
393
				} elseif (!empty($this->request->params['controller'])) {
394
					$options['url']['controller'] = Inflector::underscore($this->request->params['controller']);
395
				}
396
			}
397
			if (empty($options['action'])) {
398
				$options['action'] = $this->request->params['action'];
399
			}
400
 
401
			$plugin = null;
402
			if ($this->plugin) {
403
				$plugin = Inflector::underscore($this->plugin);
404
			}
405
			$actionDefaults = array(
406
				'plugin' => $plugin,
407
				'controller' => $this->_View->viewPath,
408
				'action' => $options['action'],
409
			);
410
			$options['action'] = array_merge($actionDefaults, (array)$options['url']);
411
			if (!isset($options['action'][0]) && !empty($id)) {
412
				$options['action'][0] = $id;
413
			}
414
		} elseif (is_string($options['url'])) {
415
			$options['action'] = $options['url'];
416
		}
417
		unset($options['url']);
418
 
419
		switch (strtolower($options['type'])) {
420
			case 'get':
421
				$htmlAttributes['method'] = 'get';
422
				break;
423
			case 'file':
424
				$htmlAttributes['enctype'] = 'multipart/form-data';
425
				$options['type'] = ($created) ? 'put' : 'post';
426
			case 'post':
427
			case 'put':
428
			case 'delete':
429
				$append .= $this->hidden('_method', array(
430
					'name' => '_method', 'value' => strtoupper($options['type']), 'id' => null,
431
					'secure' => self::SECURE_SKIP
432
				));
433
			default:
434
				$htmlAttributes['method'] = 'post';
435
		}
436
		$this->requestType = strtolower($options['type']);
437
 
438
		$action = $this->url($options['action']);
439
		$this->_lastAction($options['action']);
440
		unset($options['type'], $options['action']);
441
 
442
		if (!$options['default']) {
443
			if (!isset($options['onsubmit'])) {
444
				$options['onsubmit'] = '';
445
			}
446
			$htmlAttributes['onsubmit'] = $options['onsubmit'] . 'event.returnValue = false; return false;';
447
		}
448
		unset($options['default']);
449
 
450
		if (!empty($options['encoding'])) {
451
			$htmlAttributes['accept-charset'] = $options['encoding'];
452
			unset($options['encoding']);
453
		}
454
 
455
		$htmlAttributes = array_merge($options, $htmlAttributes);
456
 
457
		$this->fields = array();
458
		if ($this->requestType !== 'get') {
459
			$append .= $this->_csrfField();
460
		}
461
 
462
		if (!empty($append)) {
463
			$append = $this->Html->useTag('hiddenblock', $append);
464
		}
465
 
466
		if ($model !== false) {
467
			$this->setEntity($model, true);
468
			$this->_introspectModel($model, 'fields');
469
		}
470
 
471
		return $this->Html->useTag('form', $action, $htmlAttributes) . $append;
472
	}
473
 
474
/**
475
 * Return a CSRF input if the _Token is present.
476
 * Used to secure forms in conjunction with SecurityComponent
477
 *
478
 * @return string
479
 */
480
	protected function _csrfField() {
481
		if (empty($this->request->params['_Token'])) {
482
			return '';
483
		}
484
		if (!empty($this->request['_Token']['unlockedFields'])) {
485
			foreach ((array)$this->request['_Token']['unlockedFields'] as $unlocked) {
486
				$this->_unlockedFields[] = $unlocked;
487
			}
488
		}
489
		return $this->hidden('_Token.key', array(
490
			'value' => $this->request->params['_Token']['key'], 'id' => 'Token' . mt_rand(),
491
			'secure' => self::SECURE_SKIP
492
		));
493
	}
494
 
495
/**
496
 * Closes an HTML form, cleans up values set by FormHelper::create(), and writes hidden
497
 * input fields where appropriate.
498
 *
499
 * If $options is set a form submit button will be created. Options can be either a string or an array.
500
 *
501
 * ```
502
 * array usage:
503
 *
504
 * array('label' => 'save'); value="save"
505
 * array('label' => 'save', 'name' => 'Whatever'); value="save" name="Whatever"
506
 * array('name' => 'Whatever'); value="Submit" name="Whatever"
507
 * array('label' => 'save', 'name' => 'Whatever', 'div' => 'good') <div class="good"> value="save" name="Whatever"
508
 * array('label' => 'save', 'name' => 'Whatever', 'div' => array('class' => 'good')); <div class="good"> value="save" name="Whatever"
509
 * ```
510
 *
511
 * If $secureAttributes is set, these html attributes will be merged into the hidden input tags generated for the
512
 * Security Component. This is especially useful to set HTML5 attributes like 'form'
513
 *
514
 * @param string|array $options as a string will use $options as the value of button,
515
 * @param array $secureAttributes will be passed as html attributes into the hidden input elements generated for the
516
 *   Security Component.
517
 * @return string a closing FORM tag optional submit button.
518
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#closing-the-form
519
 */
520
	public function end($options = null, $secureAttributes = array()) {
521
		$out = null;
522
		$submit = null;
523
 
524
		if ($options !== null) {
525
			$submitOptions = array();
526
			if (is_string($options)) {
527
				$submit = $options;
528
			} else {
529
				if (isset($options['label'])) {
530
					$submit = $options['label'];
531
					unset($options['label']);
532
				}
533
				$submitOptions = $options;
534
			}
535
			$out .= $this->submit($submit, $submitOptions);
536
		}
537
		if ($this->requestType !== 'get' &&
538
			isset($this->request['_Token']) &&
539
			!empty($this->request['_Token'])
540
		) {
541
			$out .= $this->secure($this->fields, $secureAttributes);
542
			$this->fields = array();
543
		}
544
		$this->setEntity(null);
545
		$out .= $this->Html->useTag('formend');
546
 
547
		$this->_View->modelScope = false;
548
		$this->requestType = null;
549
		return $out;
550
	}
551
 
552
/**
553
 * Generates a hidden field with a security hash based on the fields used in
554
 * the form.
555
 *
556
 * If $secureAttributes is set, these html attributes will be merged into
557
 * the hidden input tags generated for the Security Component. This is
558
 * especially useful to set HTML5 attributes like 'form'.
559
 *
560
 * @param array|null $fields If set specifies the list of fields to use when
561
 *    generating the hash, else $this->fields is being used.
562
 * @param array $secureAttributes will be passed as html attributes into the hidden
563
 *    input elements generated for the Security Component.
564
 * @return string A hidden input field with a security hash
565
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::secure
566
 */
567
	public function secure($fields = array(), $secureAttributes = array()) {
568
		if (!isset($this->request['_Token']) || empty($this->request['_Token'])) {
569
			return;
570
		}
571
		$locked = array();
572
		$unlockedFields = $this->_unlockedFields;
573
 
574
		foreach ($fields as $key => $value) {
575
			if (!is_int($key)) {
576
				$locked[$key] = $value;
577
				unset($fields[$key]);
578
			}
579
		}
580
 
581
		sort($unlockedFields, SORT_STRING);
582
		sort($fields, SORT_STRING);
583
		ksort($locked, SORT_STRING);
584
		$fields += $locked;
585
 
586
		$locked = implode(array_keys($locked), '|');
587
		$unlocked = implode($unlockedFields, '|');
588
		$hashParts = array(
589
			$this->_lastAction,
590
			serialize($fields),
591
			$unlocked,
592
			Configure::read('Security.salt')
593
		);
594
		$fields = Security::hash(implode('', $hashParts), 'sha1');
595
 
596
		$tokenFields = array_merge($secureAttributes, array(
597
			'value' => urlencode($fields . ':' . $locked),
598
			'id' => 'TokenFields' . mt_rand(),
599
		));
600
		$out = $this->hidden('_Token.fields', $tokenFields);
601
		$tokenUnlocked = array_merge($secureAttributes, array(
602
			'value' => urlencode($unlocked),
603
			'id' => 'TokenUnlocked' . mt_rand(),
604
		));
605
		$out .= $this->hidden('_Token.unlocked', $tokenUnlocked);
606
		return $this->Html->useTag('hiddenblock', $out);
607
	}
608
 
609
/**
610
 * Add to or get the list of fields that are currently unlocked.
611
 * Unlocked fields are not included in the field hash used by SecurityComponent
612
 * unlocking a field once its been added to the list of secured fields will remove
613
 * it from the list of fields.
614
 *
615
 * @param string $name The dot separated name for the field.
616
 * @return mixed Either null, or the list of fields.
617
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::unlockField
618
 */
619
	public function unlockField($name = null) {
620
		if ($name === null) {
621
			return $this->_unlockedFields;
622
		}
623
		if (!in_array($name, $this->_unlockedFields)) {
624
			$this->_unlockedFields[] = $name;
625
		}
626
		$index = array_search($name, $this->fields);
627
		if ($index !== false) {
628
			unset($this->fields[$index]);
629
		}
630
		unset($this->fields[$name]);
631
	}
632
 
633
/**
634
 * Determine which fields of a form should be used for hash.
635
 * Populates $this->fields
636
 *
637
 * @param bool $lock Whether this field should be part of the validation
638
 *     or excluded as part of the unlockedFields.
639
 * @param string|array $field Reference to field to be secured. Should be dot separated to indicate nesting.
640
 * @param mixed $value Field value, if value should not be tampered with.
641
 * @return void
642
 */
643
	protected function _secure($lock, $field = null, $value = null) {
644
		if (!$field) {
645
			$field = $this->entity();
646
		} elseif (is_string($field)) {
647
			$field = Hash::filter(explode('.', $field));
648
		}
649
 
650
		foreach ($this->_unlockedFields as $unlockField) {
651
			$unlockParts = explode('.', $unlockField);
652
			if (array_values(array_intersect($field, $unlockParts)) === $unlockParts) {
653
				return;
654
			}
655
		}
656
 
657
		$field = implode('.', $field);
658
		$field = preg_replace('/(\.\d+)+$/', '', $field);
659
 
660
		if ($lock) {
661
			if (!in_array($field, $this->fields)) {
662
				if ($value !== null) {
663
					return $this->fields[$field] = $value;
664
				}
665
				$this->fields[] = $field;
666
			}
667
		} else {
668
			$this->unlockField($field);
669
		}
670
	}
671
 
672
/**
673
 * Returns true if there is an error for the given field, otherwise false
674
 *
675
 * @param string $field This should be "Modelname.fieldname"
676
 * @return bool If there are errors this method returns true, else false.
677
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::isFieldError
678
 */
679
	public function isFieldError($field) {
680
		$this->setEntity($field);
681
		return (bool)$this->tagIsInvalid();
682
	}
683
 
684
/**
685
 * Returns a formatted error message for given FORM field, NULL if no errors.
686
 *
687
 * ### Options:
688
 *
689
 * - `escape` boolean - Whether or not to html escape the contents of the error.
690
 * - `wrap` mixed - Whether or not the error message should be wrapped in a div. If a
691
 *   string, will be used as the HTML tag to use.
692
 * - `class` string - The class name for the error message
693
 *
694
 * @param string $field A field name, like "Modelname.fieldname"
695
 * @param string|array $text Error message as string or array of messages.
696
 *   If array contains `attributes` key it will be used as options for error container
697
 * @param array $options Rendering options for <div /> wrapper tag
698
 * @return string|null If there are errors this method returns an error message, otherwise null.
699
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::error
700
 */
701
	public function error($field, $text = null, $options = array()) {
702
		$defaults = array('wrap' => true, 'class' => 'error-message', 'escape' => true);
703
		$options += $defaults;
704
		$this->setEntity($field);
705
 
706
		$error = $this->tagIsInvalid();
707
		if ($error === false) {
708
			return null;
709
		}
710
		if (is_array($text)) {
711
			if (isset($text['attributes']) && is_array($text['attributes'])) {
712
				$options = array_merge($options, $text['attributes']);
713
				unset($text['attributes']);
714
			}
715
			$tmp = array();
716
			foreach ($error as &$e) {
717
				if (isset($text[$e])) {
718
					$tmp[] = $text[$e];
719
				} else {
720
					$tmp[] = $e;
721
				}
722
			}
723
			$text = $tmp;
724
		}
725
 
726
		if ($text !== null) {
727
			$error = $text;
728
		}
729
		if (is_array($error)) {
730
			foreach ($error as &$e) {
731
				if (is_numeric($e)) {
732
					$e = __d('cake', 'Error in field %s', Inflector::humanize($this->field()));
733
				}
734
			}
735
		}
736
		if ($options['escape']) {
737
			$error = h($error);
738
			unset($options['escape']);
739
		}
740
		if (is_array($error)) {
741
			if (count($error) > 1) {
742
				$listParams = array();
743
				if (isset($options['listOptions'])) {
744
					if (is_string($options['listOptions'])) {
745
						$listParams[] = $options['listOptions'];
746
					} else {
747
						if (isset($options['listOptions']['itemOptions'])) {
748
							$listParams[] = $options['listOptions']['itemOptions'];
749
							unset($options['listOptions']['itemOptions']);
750
						} else {
751
							$listParams[] = array();
752
						}
753
						if (isset($options['listOptions']['tag'])) {
754
							$listParams[] = $options['listOptions']['tag'];
755
							unset($options['listOptions']['tag']);
756
						}
757
						array_unshift($listParams, $options['listOptions']);
758
					}
759
					unset($options['listOptions']);
760
				}
761
				array_unshift($listParams, $error);
762
				$error = call_user_func_array(array($this->Html, 'nestedList'), $listParams);
763
			} else {
764
				$error = array_pop($error);
765
			}
766
		}
767
		if ($options['wrap']) {
768
			$tag = is_string($options['wrap']) ? $options['wrap'] : 'div';
769
			unset($options['wrap']);
770
			return $this->Html->tag($tag, $error, $options);
771
		}
772
		return $error;
773
	}
774
 
775
/**
776
 * Returns a formatted LABEL element for HTML FORMs. Will automatically generate
777
 * a `for` attribute if one is not provided.
778
 *
779
 * ### Options
780
 *
781
 * - `for` - Set the for attribute, if its not defined the for attribute
782
 *   will be generated from the $fieldName parameter using
783
 *   FormHelper::domId().
784
 *
785
 * Examples:
786
 *
787
 * The text and for attribute are generated off of the fieldname
788
 *
789
 * ```
790
 * echo $this->Form->label('Post.published');
791
 * <label for="PostPublished">Published</label>
792
 * ```
793
 *
794
 * Custom text:
795
 *
796
 * ```
797
 * echo $this->Form->label('Post.published', 'Publish');
798
 * <label for="PostPublished">Publish</label>
799
 * ```
800
 *
801
 * Custom class name:
802
 *
803
 * ```
804
 * echo $this->Form->label('Post.published', 'Publish', 'required');
805
 * <label for="PostPublished" class="required">Publish</label>
806
 * ```
807
 *
808
 * Custom attributes:
809
 *
810
 * ```
811
 * echo $this->Form->label('Post.published', 'Publish', array(
812
 *		'for' => 'post-publish'
813
 * ));
814
 * <label for="post-publish">Publish</label>
815
 * ```
816
 *
817
 * @param string $fieldName This should be "Modelname.fieldname"
818
 * @param string $text Text that will appear in the label field. If
819
 *   $text is left undefined the text will be inflected from the
820
 *   fieldName.
821
 * @param array|string $options An array of HTML attributes, or a string, to be used as a class name.
822
 * @return string The formatted LABEL element
823
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::label
824
 */
825
	public function label($fieldName = null, $text = null, $options = array()) {
826
		if ($fieldName === null) {
827
			$fieldName = implode('.', $this->entity());
828
		}
829
 
830
		if ($text === null) {
831
			if (strpos($fieldName, '.') !== false) {
832
				$fieldElements = explode('.', $fieldName);
833
				$text = array_pop($fieldElements);
834
			} else {
835
				$text = $fieldName;
836
			}
837
			if (substr($text, -3) === '_id') {
838
				$text = substr($text, 0, -3);
839
			}
840
			$text = __(Inflector::humanize(Inflector::underscore($text)));
841
		}
842
 
843
		if (is_string($options)) {
844
			$options = array('class' => $options);
845
		}
846
 
847
		if (isset($options['for'])) {
848
			$labelFor = $options['for'];
849
			unset($options['for']);
850
		} else {
851
			$labelFor = $this->domId($fieldName);
852
		}
853
 
854
		return $this->Html->useTag('label', $labelFor, $options, $text);
855
	}
856
 
857
/**
858
 * Generate a set of inputs for `$fields`. If $fields is null the fields of current model
859
 * will be used.
860
 *
861
 * You can customize individual inputs through `$fields`.
862
 * ```
863
 *	$this->Form->inputs(array(
864
 *		'name' => array('label' => 'custom label')
865
 *	));
866
 * ```
867
 *
868
 * In addition to controller fields output, `$fields` can be used to control legend
869
 * and fieldset rendering.
870
 * `$this->Form->inputs('My legend');` Would generate an input set with a custom legend.
871
 * Passing `fieldset` and `legend` key in `$fields` array has been deprecated since 2.3,
872
 * for more fine grained control use the `fieldset` and `legend` keys in `$options` param.
873
 *
874
 * @param array $fields An array of fields to generate inputs for, or null.
875
 * @param array $blacklist A simple array of fields to not create inputs for.
876
 * @param array $options Options array. Valid keys are:
877
 * - `fieldset` Set to false to disable the fieldset. If a string is supplied it will be used as
878
 *    the class name for the fieldset element.
879
 * - `legend` Set to false to disable the legend for the generated input set. Or supply a string
880
 *    to customize the legend text.
881
 * @return string Completed form inputs.
882
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::inputs
883
 */
884
	public function inputs($fields = null, $blacklist = null, $options = array()) {
885
		$fieldset = $legend = true;
886
		$modelFields = array();
887
		$model = $this->model();
888
		if ($model) {
889
			$modelFields = array_keys((array)$this->_introspectModel($model, 'fields'));
890
		}
891
		if (is_array($fields)) {
892
			if (array_key_exists('legend', $fields) && !in_array('legend', $modelFields)) {
893
				$legend = $fields['legend'];
894
				unset($fields['legend']);
895
			}
896
 
897
			if (isset($fields['fieldset']) && !in_array('fieldset', $modelFields)) {
898
				$fieldset = $fields['fieldset'];
899
				unset($fields['fieldset']);
900
			}
901
		} elseif ($fields !== null) {
902
			$fieldset = $legend = $fields;
903
			if (!is_bool($fieldset)) {
904
				$fieldset = true;
905
			}
906
			$fields = array();
907
		}
908
 
909
		if (isset($options['legend'])) {
910
			$legend = $options['legend'];
911
		}
912
		if (isset($options['fieldset'])) {
913
			$fieldset = $options['fieldset'];
914
		}
915
 
916
		if (empty($fields)) {
917
			$fields = $modelFields;
918
		}
919
 
920
		if ($legend === true) {
921
			$actionName = __d('cake', 'New %s');
922
			$isEdit = (
923
				strpos($this->request->params['action'], 'update') !== false ||
924
				strpos($this->request->params['action'], 'edit') !== false
925
			);
926
			if ($isEdit) {
927
				$actionName = __d('cake', 'Edit %s');
928
			}
929
			$modelName = Inflector::humanize(Inflector::underscore($model));
930
			$legend = sprintf($actionName, __($modelName));
931
		}
932
 
933
		$out = null;
934
		foreach ($fields as $name => $options) {
935
			if (is_numeric($name) && !is_array($options)) {
936
				$name = $options;
937
				$options = array();
938
			}
939
			$entity = explode('.', $name);
940
			$blacklisted = (
941
				is_array($blacklist) &&
942
				(in_array($name, $blacklist) || in_array(end($entity), $blacklist))
943
			);
944
			if ($blacklisted) {
945
				continue;
946
			}
947
			$out .= $this->input($name, $options);
948
		}
949
 
950
		if (is_string($fieldset)) {
951
			$fieldsetClass = sprintf(' class="%s"', $fieldset);
952
		} else {
953
			$fieldsetClass = '';
954
		}
955
 
956
		if ($fieldset) {
957
			if ($legend) {
958
				$out = $this->Html->useTag('legend', $legend) . $out;
959
			}
960
			$out = $this->Html->useTag('fieldset', $fieldsetClass, $out);
961
		}
962
		return $out;
963
	}
964
 
965
/**
966
 * Generates a form input element complete with label and wrapper div
967
 *
968
 * ### Options
969
 *
970
 * See each field type method for more information. Any options that are part of
971
 * $attributes or $options for the different **type** methods can be included in `$options` for input().i
972
 * Additionally, any unknown keys that are not in the list below, or part of the selected type's options
973
 * will be treated as a regular html attribute for the generated input.
974
 *
975
 * - `type` - Force the type of widget you want. e.g. `type => 'select'`
976
 * - `label` - Either a string label, or an array of options for the label. See FormHelper::label().
977
 * - `div` - Either `false` to disable the div, or an array of options for the div.
978
 *	See HtmlHelper::div() for more options.
979
 * - `options` - For widgets that take options e.g. radio, select.
980
 * - `error` - Control the error message that is produced. Set to `false` to disable any kind of error reporting (field
981
 *    error and error messages).
982
 * - `errorMessage` - Boolean to control rendering error messages (field error will still occur).
983
 * - `empty` - String or boolean to enable empty select box options.
984
 * - `before` - Content to place before the label + input.
985
 * - `after` - Content to place after the label + input.
986
 * - `between` - Content to place between the label + input.
987
 * - `format` - Format template for element order. Any element that is not in the array, will not be in the output.
988
 *	- Default input format order: array('before', 'label', 'between', 'input', 'after', 'error')
989
 *	- Default checkbox format order: array('before', 'input', 'between', 'label', 'after', 'error')
990
 *	- Hidden input will not be formatted
991
 *	- Radio buttons cannot have the order of input and label elements controlled with these settings.
992
 *
993
 * @param string $fieldName This should be "Modelname.fieldname"
994
 * @param array $options Each type of input takes different options.
995
 * @return string Completed form widget.
996
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#creating-form-elements
997
 */
998
	public function input($fieldName, $options = array()) {
999
		$this->setEntity($fieldName);
1000
		$options = $this->_parseOptions($options);
1001
 
1002
		$divOptions = $this->_divOptions($options);
1003
		unset($options['div']);
1004
 
1005
		if ($options['type'] === 'radio' && isset($options['options'])) {
1006
			$radioOptions = (array)$options['options'];
1007
			unset($options['options']);
1008
		}
1009
 
1010
		$label = $this->_getLabel($fieldName, $options);
1011
		if ($options['type'] !== 'radio') {
1012
			unset($options['label']);
1013
		}
1014
 
1015
		$error = $this->_extractOption('error', $options, null);
1016
		unset($options['error']);
1017
 
1018
		$errorMessage = $this->_extractOption('errorMessage', $options, true);
1019
		unset($options['errorMessage']);
1020
 
1021
		$selected = $this->_extractOption('selected', $options, null);
1022
		unset($options['selected']);
1023
 
1024
		if ($options['type'] === 'datetime' || $options['type'] === 'date' || $options['type'] === 'time') {
1025
			$dateFormat = $this->_extractOption('dateFormat', $options, 'MDY');
1026
			$timeFormat = $this->_extractOption('timeFormat', $options, 12);
1027
			unset($options['dateFormat'], $options['timeFormat']);
1028
		}
1029
 
1030
		$type = $options['type'];
1031
		$out = array('before' => $options['before'], 'label' => $label, 'between' => $options['between'], 'after' => $options['after']);
1032
		$format = $this->_getFormat($options);
1033
 
1034
		unset($options['type'], $options['before'], $options['between'], $options['after'], $options['format']);
1035
 
1036
		$out['error'] = null;
1037
		if ($type !== 'hidden' && $error !== false) {
1038
			$errMsg = $this->error($fieldName, $error);
1039
			if ($errMsg) {
1040
				$divOptions = $this->addClass($divOptions, 'error');
1041
				if ($errorMessage) {
1042
					$out['error'] = $errMsg;
1043
				}
1044
			}
1045
		}
1046
 
1047
		if ($type === 'radio' && isset($out['between'])) {
1048
			$options['between'] = $out['between'];
1049
			$out['between'] = null;
1050
		}
1051
		$out['input'] = $this->_getInput(compact('type', 'fieldName', 'options', 'radioOptions', 'selected', 'dateFormat', 'timeFormat'));
1052
 
1053
		$output = '';
1054
		foreach ($format as $element) {
1055
			$output .= $out[$element];
1056
		}
1057
 
1058
		if (!empty($divOptions['tag'])) {
1059
			$tag = $divOptions['tag'];
1060
			unset($divOptions['tag']);
1061
			$output = $this->Html->tag($tag, $output, $divOptions);
1062
		}
1063
		return $output;
1064
	}
1065
 
1066
/**
1067
 * Generates an input element
1068
 *
1069
 * @param array $args The options for the input element
1070
 * @return string The generated input element
1071
 */
1072
	protected function _getInput($args) {
1073
		extract($args);
1074
		switch ($type) {
1075
			case 'hidden':
1076
				return $this->hidden($fieldName, $options);
1077
			case 'checkbox':
1078
				return $this->checkbox($fieldName, $options);
1079
			case 'radio':
1080
				return $this->radio($fieldName, $radioOptions, $options);
1081
			case 'file':
1082
				return $this->file($fieldName, $options);
1083
			case 'select':
1084
				$options += array('options' => array(), 'value' => $selected);
1085
				$list = $options['options'];
1086
				unset($options['options']);
1087
				return $this->select($fieldName, $list, $options);
1088
			case 'time':
1089
				$options['value'] = $selected;
1090
				return $this->dateTime($fieldName, null, $timeFormat, $options);
1091
			case 'date':
1092
				$options['value'] = $selected;
1093
				return $this->dateTime($fieldName, $dateFormat, null, $options);
1094
			case 'datetime':
1095
				$options['value'] = $selected;
1096
				return $this->dateTime($fieldName, $dateFormat, $timeFormat, $options);
1097
			case 'textarea':
1098
				return $this->textarea($fieldName, $options + array('cols' => '30', 'rows' => '6'));
1099
			case 'url':
1100
				return $this->text($fieldName, array('type' => 'url') + $options);
1101
			default:
1102
				return $this->{$type}($fieldName, $options);
1103
		}
1104
	}
1105
 
1106
/**
1107
 * Generates input options array
1108
 *
1109
 * @param array $options Options list.
1110
 * @return array Options
1111
 */
1112
	protected function _parseOptions($options) {
1113
		$options = array_merge(
1114
			array('before' => null, 'between' => null, 'after' => null, 'format' => null),
1115
			$this->_inputDefaults,
1116
			$options
1117
		);
1118
 
1119
		if (!isset($options['type'])) {
1120
			$options = $this->_magicOptions($options);
1121
		}
1122
 
1123
		if (in_array($options['type'], array('radio', 'select'))) {
1124
			$options = $this->_optionsOptions($options);
1125
		}
1126
 
1127
		$options = $this->_maxLength($options);
1128
 
1129
		if (isset($options['rows']) || isset($options['cols'])) {
1130
			$options['type'] = 'textarea';
1131
		}
1132
 
1133
		if ($options['type'] === 'datetime' || $options['type'] === 'date' || $options['type'] === 'time' || $options['type'] === 'select') {
1134
			$options += array('empty' => false);
1135
		}
1136
		return $options;
1137
	}
1138
 
1139
/**
1140
 * Generates list of options for multiple select
1141
 *
1142
 * @param array $options Options list.
1143
 * @return array
1144
 */
1145
	protected function _optionsOptions($options) {
1146
		if (isset($options['options'])) {
1147
			return $options;
1148
		}
1149
		$varName = Inflector::variable(
1150
			Inflector::pluralize(preg_replace('/_id$/', '', $this->field()))
1151
		);
1152
		$varOptions = $this->_View->get($varName);
1153
		if (!is_array($varOptions)) {
1154
			return $options;
1155
		}
1156
		if ($options['type'] !== 'radio') {
1157
			$options['type'] = 'select';
1158
		}
1159
		$options['options'] = $varOptions;
1160
		return $options;
1161
	}
1162
 
1163
/**
1164
 * Magically set option type and corresponding options
1165
 *
1166
 * @param array $options Options list.
1167
 * @return array
1168
 */
1169
	protected function _magicOptions($options) {
1170
		$modelKey = $this->model();
1171
		$fieldKey = $this->field();
1172
		$options['type'] = 'text';
1173
		if (isset($options['options'])) {
1174
			$options['type'] = 'select';
1175
		} elseif (in_array($fieldKey, array('psword', 'passwd', 'password'))) {
1176
			$options['type'] = 'password';
1177
		} elseif (in_array($fieldKey, array('tel', 'telephone', 'phone'))) {
1178
			$options['type'] = 'tel';
1179
		} elseif ($fieldKey === 'email') {
1180
			$options['type'] = 'email';
1181
		} elseif (isset($options['checked'])) {
1182
			$options['type'] = 'checkbox';
1183
		} elseif ($fieldDef = $this->_introspectModel($modelKey, 'fields', $fieldKey)) {
1184
			$type = $fieldDef['type'];
1185
			$primaryKey = $this->fieldset[$modelKey]['key'];
1186
			$map = array(
1187
				'string' => 'text', 'datetime' => 'datetime',
1188
				'boolean' => 'checkbox', 'timestamp' => 'datetime',
1189
				'text' => 'textarea', 'time' => 'time',
1190
				'date' => 'date', 'float' => 'number',
1191
				'integer' => 'number', 'decimal' => 'number',
1192
				'binary' => 'file'
1193
			);
1194
 
1195
			if (isset($this->map[$type])) {
1196
				$options['type'] = $this->map[$type];
1197
			} elseif (isset($map[$type])) {
1198
				$options['type'] = $map[$type];
1199
			}
1200
			if ($fieldKey === $primaryKey) {
1201
				$options['type'] = 'hidden';
1202
			}
1203
			if ($options['type'] === 'number' &&
1204
				!isset($options['step'])
1205
			) {
1206
				if ($type === 'decimal') {
1207
					$decimalPlaces = substr($fieldDef['length'], strpos($fieldDef['length'], ',') + 1);
1208
					$options['step'] = sprintf('%.' . $decimalPlaces . 'F', pow(10, -1 * $decimalPlaces));
1209
				} elseif ($type === 'float') {
1210
					$options['step'] = 'any';
1211
				}
1212
			}
1213
		}
1214
 
1215
		if (preg_match('/_id$/', $fieldKey) && $options['type'] !== 'hidden') {
1216
			$options['type'] = 'select';
1217
		}
1218
 
1219
		if ($modelKey === $fieldKey) {
1220
			$options['type'] = 'select';
1221
			if (!isset($options['multiple'])) {
1222
				$options['multiple'] = 'multiple';
1223
			}
1224
		}
1225
		if (in_array($options['type'], array('text', 'number'))) {
1226
			$options = $this->_optionsOptions($options);
1227
		}
1228
		if ($options['type'] === 'select' && array_key_exists('step', $options)) {
1229
			unset($options['step']);
1230
		}
1231
 
1232
		return $options;
1233
	}
1234
 
1235
/**
1236
 * Generate format options
1237
 *
1238
 * @param array $options Options list.
1239
 * @return array
1240
 */
1241
	protected function _getFormat($options) {
1242
		if ($options['type'] === 'hidden') {
1243
			return array('input');
1244
		}
1245
		if (is_array($options['format']) && in_array('input', $options['format'])) {
1246
			return $options['format'];
1247
		}
1248
		if ($options['type'] === 'checkbox') {
1249
			return array('before', 'input', 'between', 'label', 'after', 'error');
1250
		}
1251
		return array('before', 'label', 'between', 'input', 'after', 'error');
1252
	}
1253
 
1254
/**
1255
 * Generate label for input
1256
 *
1257
 * @param string $fieldName Field name.
1258
 * @param array $options Options list.
1259
 * @return bool|string false or Generated label element
1260
 */
1261
	protected function _getLabel($fieldName, $options) {
1262
		if ($options['type'] === 'radio') {
1263
			return false;
1264
		}
1265
 
1266
		$label = null;
1267
		if (isset($options['label'])) {
1268
			$label = $options['label'];
1269
		}
1270
 
1271
		if ($label === false) {
1272
			return false;
1273
		}
1274
		return $this->_inputLabel($fieldName, $label, $options);
1275
	}
1276
 
1277
/**
1278
 * Calculates maxlength option
1279
 *
1280
 * @param array $options Options list.
1281
 * @return array
1282
 */
1283
	protected function _maxLength($options) {
1284
		$fieldDef = $this->_introspectModel($this->model(), 'fields', $this->field());
1285
		$autoLength = (
1286
			!array_key_exists('maxlength', $options) &&
1287
			isset($fieldDef['length']) &&
1288
			is_scalar($fieldDef['length']) &&
1289
			$fieldDef['length'] < 1000000 &&
1290
			$fieldDef['type'] !== 'decimal' &&
1291
			$options['type'] !== 'select'
1292
		);
1293
		if ($autoLength &&
1294
			in_array($options['type'], array('text', 'textarea', 'email', 'tel', 'url', 'search'))
1295
		) {
1296
			$options['maxlength'] = (int)$fieldDef['length'];
1297
		}
1298
		return $options;
1299
	}
1300
 
1301
/**
1302
 * Generate div options for input
1303
 *
1304
 * @param array $options Options list.
1305
 * @return array
1306
 */
1307
	protected function _divOptions($options) {
1308
		if ($options['type'] === 'hidden') {
1309
			return array();
1310
		}
1311
		$div = $this->_extractOption('div', $options, true);
1312
		if (!$div) {
1313
			return array();
1314
		}
1315
 
1316
		$divOptions = array('class' => 'input');
1317
		$divOptions = $this->addClass($divOptions, $options['type']);
1318
		if (is_string($div)) {
1319
			$divOptions['class'] = $div;
1320
		} elseif (is_array($div)) {
1321
			$divOptions = array_merge($divOptions, $div);
1322
		}
1323
		if ($this->_extractOption('required', $options) !== false &&
1324
			$this->_introspectModel($this->model(), 'validates', $this->field())
1325
		) {
1326
			$divOptions = $this->addClass($divOptions, 'required');
1327
		}
1328
		if (!isset($divOptions['tag'])) {
1329
			$divOptions['tag'] = 'div';
1330
		}
1331
		return $divOptions;
1332
	}
1333
 
1334
/**
1335
 * Extracts a single option from an options array.
1336
 *
1337
 * @param string $name The name of the option to pull out.
1338
 * @param array $options The array of options you want to extract.
1339
 * @param mixed $default The default option value
1340
 * @return mixed the contents of the option or default
1341
 */
1342
	protected function _extractOption($name, $options, $default = null) {
1343
		if (array_key_exists($name, $options)) {
1344
			return $options[$name];
1345
		}
1346
		return $default;
1347
	}
1348
 
1349
/**
1350
 * Generate a label for an input() call.
1351
 *
1352
 * $options can contain a hash of id overrides. These overrides will be
1353
 * used instead of the generated values if present.
1354
 *
1355
 * @param string $fieldName Field name.
1356
 * @param string|array $label Label text or array with text and options.
1357
 * @param array $options Options for the label element. 'NONE' option is
1358
 *   deprecated and will be removed in 3.0
1359
 * @return string Generated label element
1360
 */
1361
	protected function _inputLabel($fieldName, $label, $options) {
1362
		$labelAttributes = $this->domId(array(), 'for');
1363
		$idKey = null;
1364
		if ($options['type'] === 'date' || $options['type'] === 'datetime') {
1365
			$firstInput = 'M';
1366
			if (array_key_exists('dateFormat', $options) &&
1367
				($options['dateFormat'] === null || $options['dateFormat'] === 'NONE')
1368
			) {
1369
				$firstInput = 'H';
1370
			} elseif (!empty($options['dateFormat'])) {
1371
				$firstInput = substr($options['dateFormat'], 0, 1);
1372
			}
1373
			switch ($firstInput) {
1374
				case 'D':
1375
					$idKey = 'day';
1376
					$labelAttributes['for'] .= 'Day';
1377
					break;
1378
				case 'Y':
1379
					$idKey = 'year';
1380
					$labelAttributes['for'] .= 'Year';
1381
					break;
1382
				case 'M':
1383
					$idKey = 'month';
1384
					$labelAttributes['for'] .= 'Month';
1385
					break;
1386
				case 'H':
1387
					$idKey = 'hour';
1388
					$labelAttributes['for'] .= 'Hour';
1389
			}
1390
		}
1391
		if ($options['type'] === 'time') {
1392
			$labelAttributes['for'] .= 'Hour';
1393
			$idKey = 'hour';
1394
		}
1395
		if (isset($idKey) && isset($options['id']) && isset($options['id'][$idKey])) {
1396
			$labelAttributes['for'] = $options['id'][$idKey];
1397
		}
1398
 
1399
		if (is_array($label)) {
1400
			$labelText = null;
1401
			if (isset($label['text'])) {
1402
				$labelText = $label['text'];
1403
				unset($label['text']);
1404
			}
1405
			$labelAttributes = array_merge($labelAttributes, $label);
1406
		} else {
1407
			$labelText = $label;
1408
		}
1409
 
1410
		if (isset($options['id']) && is_string($options['id'])) {
1411
			$labelAttributes = array_merge($labelAttributes, array('for' => $options['id']));
1412
		}
1413
		return $this->label($fieldName, $labelText, $labelAttributes);
1414
	}
1415
 
1416
/**
1417
 * Creates a checkbox input widget.
1418
 *
1419
 * ### Options:
1420
 *
1421
 * - `value` - the value of the checkbox
1422
 * - `checked` - boolean indicate that this checkbox is checked.
1423
 * - `hiddenField` - boolean to indicate if you want the results of checkbox() to include
1424
 *    a hidden input with a value of ''.
1425
 * - `disabled` - create a disabled input.
1426
 * - `default` - Set the default value for the checkbox. This allows you to start checkboxes
1427
 *    as checked, without having to check the POST data. A matching POST data value, will overwrite
1428
 *    the default value.
1429
 *
1430
 * @param string $fieldName Name of a field, like this "Modelname.fieldname"
1431
 * @param array $options Array of HTML attributes.
1432
 * @return string An HTML text input element.
1433
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#options-for-select-checkbox-and-radio-inputs
1434
 */
1435
	public function checkbox($fieldName, $options = array()) {
1436
		$valueOptions = array();
1437
		if (isset($options['default'])) {
1438
			$valueOptions['default'] = $options['default'];
1439
			unset($options['default']);
1440
		}
1441
 
1442
		$options += array('value' => 1, 'required' => false);
1443
		$options = $this->_initInputField($fieldName, $options) + array('hiddenField' => true);
1444
		$value = current($this->value($valueOptions));
1445
		$output = '';
1446
 
1447
		if ((!isset($options['checked']) && !empty($value) && $value == $options['value']) ||
1448
			!empty($options['checked'])
1449
		) {
1450
			$options['checked'] = 'checked';
1451
		}
1452
		if ($options['hiddenField']) {
1453
			$hiddenOptions = array(
1454
				'id' => $options['id'] . '_',
1455
				'name' => $options['name'],
1456
				'value' => ($options['hiddenField'] !== true ? $options['hiddenField'] : '0'),
1457
				'form' => isset($options['form']) ? $options['form'] : null,
1458
				'secure' => false,
1459
			);
1460
			if (isset($options['disabled']) && $options['disabled']) {
1461
				$hiddenOptions['disabled'] = 'disabled';
1462
			}
1463
			$output = $this->hidden($fieldName, $hiddenOptions);
1464
		}
1465
		unset($options['hiddenField']);
1466
 
1467
		return $output . $this->Html->useTag('checkbox', $options['name'], array_diff_key($options, array('name' => null)));
1468
	}
1469
 
1470
/**
1471
 * Creates a set of radio widgets. Will create a legend and fieldset
1472
 * by default. Use $options to control this
1473
 *
1474
 * ### Attributes:
1475
 *
1476
 * - `separator` - define the string in between the radio buttons
1477
 * - `between` - the string between legend and input set or array of strings to insert
1478
 *    strings between each input block
1479
 * - `legend` - control whether or not the widget set has a fieldset & legend
1480
 * - `value` - indicate a value that is should be checked
1481
 * - `label` - boolean to indicate whether or not labels for widgets show be displayed
1482
 * - `hiddenField` - boolean to indicate if you want the results of radio() to include
1483
 *    a hidden input with a value of ''. This is useful for creating radio sets that non-continuous
1484
 * - `disabled` - Set to `true` or `disabled` to disable all the radio buttons.
1485
 * - `empty` - Set to `true` to create an input with the value '' as the first option. When `true`
1486
 *   the radio label will be 'empty'. Set this option to a string to control the label value.
1487
 *
1488
 * @param string $fieldName Name of a field, like this "Modelname.fieldname"
1489
 * @param array $options Radio button options array.
1490
 * @param array $attributes Array of HTML attributes, and special attributes above.
1491
 * @return string Completed radio widget set.
1492
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#options-for-select-checkbox-and-radio-inputs
1493
 */
1494
	public function radio($fieldName, $options = array(), $attributes = array()) {
1495
		$attributes['options'] = $options;
1496
		$attributes = $this->_initInputField($fieldName, $attributes);
1497
		unset($attributes['options']);
1498
 
1499
		$showEmpty = $this->_extractOption('empty', $attributes);
1500
		if ($showEmpty) {
1501
			$showEmpty = ($showEmpty === true) ? __d('cake', 'empty') : $showEmpty;
1502
			$options = array('' => $showEmpty) + $options;
1503
		}
1504
		unset($attributes['empty']);
1505
 
1506
		$legend = false;
1507
		if (isset($attributes['legend'])) {
1508
			$legend = $attributes['legend'];
1509
			unset($attributes['legend']);
1510
		} elseif (count($options) > 1) {
1511
			$legend = __(Inflector::humanize($this->field()));
1512
		}
1513
 
1514
		$label = true;
1515
		if (isset($attributes['label'])) {
1516
			$label = $attributes['label'];
1517
			unset($attributes['label']);
1518
		}
1519
 
1520
		$separator = null;
1521
		if (isset($attributes['separator'])) {
1522
			$separator = $attributes['separator'];
1523
			unset($attributes['separator']);
1524
		}
1525
 
1526
		$between = null;
1527
		if (isset($attributes['between'])) {
1528
			$between = $attributes['between'];
1529
			unset($attributes['between']);
1530
		}
1531
 
1532
		$value = null;
1533
		if (isset($attributes['value'])) {
1534
			$value = $attributes['value'];
1535
		} else {
1536
			$value = $this->value($fieldName);
1537
		}
1538
 
1539
		$disabled = array();
1540
		if (isset($attributes['disabled'])) {
1541
			$disabled = $attributes['disabled'];
1542
		}
1543
 
1544
		$out = array();
1545
 
1546
		$hiddenField = isset($attributes['hiddenField']) ? $attributes['hiddenField'] : true;
1547
		unset($attributes['hiddenField']);
1548
 
1549
		if (isset($value) && is_bool($value)) {
1550
			$value = $value ? 1 : 0;
1551
		}
1552
 
1553
		$this->_domIdSuffixes = array();
1554
		foreach ($options as $optValue => $optTitle) {
1555
			$optionsHere = array('value' => $optValue, 'disabled' => false);
1556
 
1557
			if (isset($value) && strval($optValue) === strval($value)) {
1558
				$optionsHere['checked'] = 'checked';
1559
			}
1560
			$isNumeric = is_numeric($optValue);
1561
			if ($disabled && (!is_array($disabled) || in_array((string)$optValue, $disabled, !$isNumeric))) {
1562
				$optionsHere['disabled'] = true;
1563
			}
1564
			$tagName = $attributes['id'] . $this->domIdSuffix($optValue);
1565
 
1566
			if ($label) {
1567
				$labelOpts = is_array($label) ? $label : array();
1568
				$labelOpts += array('for' => $tagName);
1569
				$optTitle = $this->label($tagName, $optTitle, $labelOpts);
1570
			}
1571
 
1572
			if (is_array($between)) {
1573
				$optTitle .= array_shift($between);
1574
			}
1575
			$allOptions = array_merge($attributes, $optionsHere);
1576
			$out[] = $this->Html->useTag('radio', $attributes['name'], $tagName,
1577
				array_diff_key($allOptions, array('name' => null, 'type' => null, 'id' => null)),
1578
				$optTitle
1579
			);
1580
		}
1581
		$hidden = null;
1582
 
1583
		if ($hiddenField) {
1584
			if (!isset($value) || $value === '') {
1585
				$hidden = $this->hidden($fieldName, array(
1586
					'form' => isset($attributes['form']) ? $attributes['form'] : null,
1587
					'id' => $attributes['id'] . '_',
1588
					'value' => '',
1589
					'name' => $attributes['name']
1590
				));
1591
			}
1592
		}
1593
		$out = $hidden . implode($separator, $out);
1594
 
1595
		if (is_array($between)) {
1596
			$between = '';
1597
		}
1598
		if ($legend) {
1599
			$out = $this->Html->useTag('fieldset', '', $this->Html->useTag('legend', $legend) . $between . $out);
1600
		}
1601
		return $out;
1602
	}
1603
 
1604
/**
1605
 * Missing method handler - implements various simple input types. Is used to create inputs
1606
 * of various types. e.g. `$this->Form->text();` will create `<input type="text" />` while
1607
 * `$this->Form->range();` will create `<input type="range" />`
1608
 *
1609
 * ### Usage
1610
 *
1611
 * `$this->Form->search('User.query', array('value' => 'test'));`
1612
 *
1613
 * Will make an input like:
1614
 *
1615
 * `<input type="search" id="UserQuery" name="data[User][query]" value="test" />`
1616
 *
1617
 * The first argument to an input type should always be the fieldname, in `Model.field` format.
1618
 * The second argument should always be an array of attributes for the input.
1619
 *
1620
 * @param string $method Method name / input type to make.
1621
 * @param array $params Parameters for the method call
1622
 * @return string Formatted input method.
1623
 * @throws CakeException When there are no params for the method call.
1624
 */
1625
	public function __call($method, $params) {
1626
		$options = array();
1627
		if (empty($params)) {
1628
			throw new CakeException(__d('cake_dev', 'Missing field name for FormHelper::%s', $method));
1629
		}
1630
		if (isset($params[1])) {
1631
			$options = $params[1];
1632
		}
1633
		if (!isset($options['type'])) {
1634
			$options['type'] = $method;
1635
		}
1636
		$options = $this->_initInputField($params[0], $options);
1637
		return $this->Html->useTag('input', $options['name'], array_diff_key($options, array('name' => null)));
1638
	}
1639
 
1640
/**
1641
 * Creates a textarea widget.
1642
 *
1643
 * ### Options:
1644
 *
1645
 * - `escape` - Whether or not the contents of the textarea should be escaped. Defaults to true.
1646
 *
1647
 * @param string $fieldName Name of a field, in the form "Modelname.fieldname"
1648
 * @param array $options Array of HTML attributes, and special options above.
1649
 * @return string A generated HTML text input element
1650
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::textarea
1651
 */
1652
	public function textarea($fieldName, $options = array()) {
1653
		$options = $this->_initInputField($fieldName, $options);
1654
		$value = null;
1655
 
1656
		if (array_key_exists('value', $options)) {
1657
			$value = $options['value'];
1658
			if (!array_key_exists('escape', $options) || $options['escape'] !== false) {
1659
				$value = h($value);
1660
			}
1661
			unset($options['value']);
1662
		}
1663
		return $this->Html->useTag('textarea', $options['name'], array_diff_key($options, array('type' => null, 'name' => null)), $value);
1664
	}
1665
 
1666
/**
1667
 * Creates a hidden input field.
1668
 *
1669
 * @param string $fieldName Name of a field, in the form of "Modelname.fieldname"
1670
 * @param array $options Array of HTML attributes.
1671
 * @return string A generated hidden input
1672
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::hidden
1673
 */
1674
	public function hidden($fieldName, $options = array()) {
1675
		$options += array('required' => false, 'secure' => true);
1676
 
1677
		$secure = $options['secure'];
1678
		unset($options['secure']);
1679
 
1680
		$options = $this->_initInputField($fieldName, array_merge(
1681
			$options, array('secure' => self::SECURE_SKIP)
1682
		));
1683
 
1684
		if ($secure === true) {
1685
			$this->_secure(true, null, '' . $options['value']);
1686
		}
1687
 
1688
		return $this->Html->useTag('hidden', $options['name'], array_diff_key($options, array('name' => null)));
1689
	}
1690
 
1691
/**
1692
 * Creates file input widget.
1693
 *
1694
 * @param string $fieldName Name of a field, in the form "Modelname.fieldname"
1695
 * @param array $options Array of HTML attributes.
1696
 * @return string A generated file input.
1697
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::file
1698
 */
1699
	public function file($fieldName, $options = array()) {
1700
		$options += array('secure' => true);
1701
		$secure = $options['secure'];
1702
		$options['secure'] = self::SECURE_SKIP;
1703
 
1704
		$options = $this->_initInputField($fieldName, $options);
1705
		$field = $this->entity();
1706
 
1707
		foreach (array('name', 'type', 'tmp_name', 'error', 'size') as $suffix) {
1708
			$this->_secure($secure, array_merge($field, array($suffix)));
1709
		}
1710
 
1711
		$exclude = array('name' => null, 'value' => null);
1712
		return $this->Html->useTag('file', $options['name'], array_diff_key($options, $exclude));
1713
	}
1714
 
1715
/**
1716
 * Creates a `<button>` tag. The type attribute defaults to `type="submit"`
1717
 * You can change it to a different value by using `$options['type']`.
1718
 *
1719
 * ### Options:
1720
 *
1721
 * - `escape` - HTML entity encode the $title of the button. Defaults to false.
1722
 *
1723
 * @param string $title The button's caption. Not automatically HTML encoded
1724
 * @param array $options Array of options and HTML attributes.
1725
 * @return string A HTML button tag.
1726
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::button
1727
 */
1728
	public function button($title, $options = array()) {
1729
		$options += array('type' => 'submit', 'escape' => false, 'secure' => false);
1730
		if ($options['escape']) {
1731
			$title = h($title);
1732
		}
1733
		if (isset($options['name'])) {
1734
			$name = str_replace(array('[', ']'), array('.', ''), $options['name']);
1735
			$this->_secure($options['secure'], $name);
1736
		}
1737
		return $this->Html->useTag('button', $options, $title);
1738
	}
1739
 
1740
/**
1741
 * Create a `<button>` tag with a surrounding `<form>` that submits via POST.
1742
 *
1743
 * This method creates a `<form>` element. So do not use this method in an already opened form.
1744
 * Instead use FormHelper::submit() or FormHelper::button() to create buttons inside opened forms.
1745
 *
1746
 * ### Options:
1747
 *
1748
 * - `data` - Array with key/value to pass in input hidden
1749
 * - Other options is the same of button method.
1750
 *
1751
 * @param string $title The button's caption. Not automatically HTML encoded
1752
 * @param string|array $url URL as string or array
1753
 * @param array $options Array of options and HTML attributes.
1754
 * @return string A HTML button tag.
1755
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::postButton
1756
 */
1757
	public function postButton($title, $url, $options = array()) {
1758
		$out = $this->create(false, array('id' => false, 'url' => $url));
1759
		if (isset($options['data']) && is_array($options['data'])) {
1760
			foreach (Hash::flatten($options['data']) as $key => $value) {
1761
				$out .= $this->hidden($key, array('value' => $value, 'id' => false));
1762
			}
1763
			unset($options['data']);
1764
		}
1765
		$out .= $this->button($title, $options);
1766
		$out .= $this->end();
1767
		return $out;
1768
	}
1769
 
1770
/**
1771
 * Creates an HTML link, but access the URL using the method you specify (defaults to POST).
1772
 * Requires javascript to be enabled in browser.
1773
 *
1774
 * This method creates a `<form>` element. So do not use this method inside an existing form.
1775
 * Instead you should add a submit button using FormHelper::submit()
1776
 *
1777
 * ### Options:
1778
 *
1779
 * - `data` - Array with key/value to pass in input hidden
1780
 * - `method` - Request method to use. Set to 'delete' to simulate HTTP/1.1 DELETE request. Defaults to 'post'.
1781
 * - `confirm` - Can be used instead of $confirmMessage.
1782
 * - `inline` - Whether or not the associated form tag should be output inline.
1783
 *   Set to false to have the form tag appended to the 'postLink' view block.
1784
 *   Defaults to true.
1785
 * - `block` - Choose a custom block to append the form tag to. Using this option
1786
 *   will override the inline option.
1787
 * - Other options are the same of HtmlHelper::link() method.
1788
 * - The option `onclick` will be replaced.
1789
 *
1790
 * @param string $title The content to be wrapped by <a> tags.
1791
 * @param string|array $url Cake-relative URL or array of URL parameters, or external URL (starts with http://)
1792
 * @param array $options Array of HTML attributes.
1793
 * @param bool|string $confirmMessage JavaScript confirmation message. This
1794
 *   argument is deprecated as of 2.6. Use `confirm` key in $options instead.
1795
 * @return string An `<a />` element.
1796
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::postLink
1797
 */
1798
	public function postLink($title, $url = null, $options = array(), $confirmMessage = false) {
1799
		$options = (array)$options + array('inline' => true, 'block' => null);
1800
		if (!$options['inline'] && empty($options['block'])) {
1801
			$options['block'] = __FUNCTION__;
1802
		}
1803
		unset($options['inline']);
1804
 
1805
		$requestMethod = 'POST';
1806
		if (!empty($options['method'])) {
1807
			$requestMethod = strtoupper($options['method']);
1808
			unset($options['method']);
1809
		}
1810
		if (!empty($options['confirm'])) {
1811
			$confirmMessage = $options['confirm'];
1812
			unset($options['confirm']);
1813
		}
1814
 
1815
		$formName = str_replace('.', '', uniqid('post_', true));
1816
		$formUrl = $this->url($url);
1817
		$formOptions = array(
1818
			'name' => $formName,
1819
			'id' => $formName,
1820
			'style' => 'display:none;',
1821
			'method' => 'post',
1822
		);
1823
		if (isset($options['target'])) {
1824
			$formOptions['target'] = $options['target'];
1825
			unset($options['target']);
1826
		}
1827
 
1828
		$this->_lastAction($url);
1829
 
1830
		$out = $this->Html->useTag('form', $formUrl, $formOptions);
1831
		$out .= $this->Html->useTag('hidden', '_method', array(
1832
			'value' => $requestMethod
1833
		));
1834
		$out .= $this->_csrfField();
1835
 
1836
		$fields = array();
1837
		if (isset($options['data']) && is_array($options['data'])) {
1838
			foreach (Hash::flatten($options['data']) as $key => $value) {
1839
				$fields[$key] = $value;
1840
				$out .= $this->hidden($key, array('value' => $value, 'id' => false));
1841
			}
1842
			unset($options['data']);
1843
		}
1844
		$out .= $this->secure($fields);
1845
		$out .= $this->Html->useTag('formend');
1846
 
1847
		if ($options['block']) {
1848
			$this->_View->append($options['block'], $out);
1849
			$out = '';
1850
		}
1851
		unset($options['block']);
1852
 
1853
		$url = '#';
1854
		$onClick = 'document.' . $formName . '.submit();';
1855
		if ($confirmMessage) {
1856
			$options['onclick'] = $this->_confirm($confirmMessage, $onClick, '', $options);
1857
		} else {
1858
			$options['onclick'] = $onClick . ' ';
1859
		}
1860
		$options['onclick'] .= 'event.returnValue = false; return false;';
1861
 
1862
		$out .= $this->Html->link($title, $url, $options);
1863
		return $out;
1864
	}
1865
 
1866
/**
1867
 * Creates a submit button element. This method will generate `<input />` elements that
1868
 * can be used to submit, and reset forms by using $options. image submits can be created by supplying an
1869
 * image path for $caption.
1870
 *
1871
 * ### Options
1872
 *
1873
 * - `div` - Include a wrapping div?  Defaults to true. Accepts sub options similar to
1874
 *   FormHelper::input().
1875
 * - `before` - Content to include before the input.
1876
 * - `after` - Content to include after the input.
1877
 * - `type` - Set to 'reset' for reset inputs. Defaults to 'submit'
1878
 * - Other attributes will be assigned to the input element.
1879
 *
1880
 * ### Options
1881
 *
1882
 * - `div` - Include a wrapping div?  Defaults to true. Accepts sub options similar to
1883
 *   FormHelper::input().
1884
 * - Other attributes will be assigned to the input element.
1885
 *
1886
 * @param string $caption The label appearing on the button OR if string contains :// or the
1887
 *  extension .jpg, .jpe, .jpeg, .gif, .png use an image if the extension
1888
 *  exists, AND the first character is /, image is relative to webroot,
1889
 *  OR if the first character is not /, image is relative to webroot/img.
1890
 * @param array $options Array of options. See above.
1891
 * @return string A HTML submit button
1892
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::submit
1893
 */
1894
	public function submit($caption = null, $options = array()) {
1895
		if (!is_string($caption) && empty($caption)) {
1896
			$caption = __d('cake', 'Submit');
1897
		}
1898
		$out = null;
1899
		$div = true;
1900
 
1901
		if (isset($options['div'])) {
1902
			$div = $options['div'];
1903
			unset($options['div']);
1904
		}
1905
		$options += array('type' => 'submit', 'before' => null, 'after' => null, 'secure' => false);
1906
		$divOptions = array('tag' => 'div');
1907
 
1908
		if ($div === true) {
1909
			$divOptions['class'] = 'submit';
1910
		} elseif ($div === false) {
1911
			unset($divOptions);
1912
		} elseif (is_string($div)) {
1913
			$divOptions['class'] = $div;
1914
		} elseif (is_array($div)) {
1915
			$divOptions = array_merge(array('class' => 'submit', 'tag' => 'div'), $div);
1916
		}
1917
 
1918
		if (isset($options['name'])) {
1919
			$name = str_replace(array('[', ']'), array('.', ''), $options['name']);
1920
			$this->_secure($options['secure'], $name);
1921
		}
1922
		unset($options['secure']);
1923
 
1924
		$before = $options['before'];
1925
		$after = $options['after'];
1926
		unset($options['before'], $options['after']);
1927
 
1928
		$isUrl = strpos($caption, '://') !== false;
1929
		$isImage = preg_match('/\.(jpg|jpe|jpeg|gif|png|ico)$/', $caption);
1930
 
1931
		if ($isUrl || $isImage) {
1932
			$unlockFields = array('x', 'y');
1933
			if (isset($options['name'])) {
1934
				$unlockFields = array(
1935
					$options['name'] . '_x', $options['name'] . '_y'
1936
				);
1937
			}
1938
			foreach ($unlockFields as $ignore) {
1939
				$this->unlockField($ignore);
1940
			}
1941
		}
1942
 
1943
		if ($isUrl) {
1944
			unset($options['type']);
1945
			$tag = $this->Html->useTag('submitimage', $caption, $options);
1946
		} elseif ($isImage) {
1947
			unset($options['type']);
1948
			if ($caption{0} !== '/') {
1949
				$url = $this->webroot(Configure::read('App.imageBaseUrl') . $caption);
1950
			} else {
1951
				$url = $this->webroot(trim($caption, '/'));
1952
			}
1953
			$url = $this->assetTimestamp($url);
1954
			$tag = $this->Html->useTag('submitimage', $url, $options);
1955
		} else {
1956
			$options['value'] = $caption;
1957
			$tag = $this->Html->useTag('submit', $options);
1958
		}
1959
		$out = $before . $tag . $after;
1960
 
1961
		if (isset($divOptions)) {
1962
			$tag = $divOptions['tag'];
1963
			unset($divOptions['tag']);
1964
			$out = $this->Html->tag($tag, $out, $divOptions);
1965
		}
1966
		return $out;
1967
	}
1968
 
1969
/**
1970
 * Returns a formatted SELECT element.
1971
 *
1972
 * ### Attributes:
1973
 *
1974
 * - `showParents` - If included in the array and set to true, an additional option element
1975
 *   will be added for the parent of each option group. You can set an option with the same name
1976
 *   and it's key will be used for the value of the option.
1977
 * - `multiple` - show a multiple select box. If set to 'checkbox' multiple checkboxes will be
1978
 *   created instead.
1979
 * - `empty` - If true, the empty select option is shown. If a string,
1980
 *   that string is displayed as the empty element.
1981
 * - `escape` - If true contents of options will be HTML entity encoded. Defaults to true.
1982
 * - `value` The selected value of the input.
1983
 * - `class` - When using multiple = checkbox the class name to apply to the divs. Defaults to 'checkbox'.
1984
 * - `disabled` - Control the disabled attribute. When creating a select box, set to true to disable the
1985
 *   select box. When creating checkboxes, `true` will disable all checkboxes. You can also set disabled
1986
 *   to a list of values you want to disable when creating checkboxes.
1987
 *
1988
 * ### Using options
1989
 *
1990
 * A simple array will create normal options:
1991
 *
1992
 * ```
1993
 * $options = array(1 => 'one', 2 => 'two);
1994
 * $this->Form->select('Model.field', $options));
1995
 * ```
1996
 *
1997
 * While a nested options array will create optgroups with options inside them.
1998
 * ```
1999
 * $options = array(
2000
 *  1 => 'bill',
2001
 *  'fred' => array(
2002
 *     2 => 'fred',
2003
 *     3 => 'fred jr.'
2004
 *  )
2005
 * );
2006
 * $this->Form->select('Model.field', $options);
2007
 * ```
2008
 *
2009
 * In the above `2 => 'fred'` will not generate an option element. You should enable the `showParents`
2010
 * attribute to show the fred option.
2011
 *
2012
 * If you have multiple options that need to have the same value attribute, you can
2013
 * use an array of arrays to express this:
2014
 *
2015
 * ```
2016
 * $options = array(
2017
 *  array('name' => 'United states', 'value' => 'USA'),
2018
 *  array('name' => 'USA', 'value' => 'USA'),
2019
 * );
2020
 * ```
2021
 *
2022
 * @param string $fieldName Name attribute of the SELECT
2023
 * @param array $options Array of the OPTION elements (as 'value'=>'Text' pairs) to be used in the
2024
 *	SELECT element
2025
 * @param array $attributes The HTML attributes of the select element.
2026
 * @return string Formatted SELECT element
2027
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#options-for-select-checkbox-and-radio-inputs
2028
 */
2029
	public function select($fieldName, $options = array(), $attributes = array()) {
2030
		$select = array();
2031
		$style = null;
2032
		$tag = null;
2033
		$attributes += array(
2034
			'class' => null,
2035
			'escape' => true,
2036
			'secure' => true,
2037
			'empty' => '',
2038
			'showParents' => false,
2039
			'hiddenField' => true,
2040
			'disabled' => false
2041
		);
2042
 
2043
		$escapeOptions = $this->_extractOption('escape', $attributes);
2044
		$secure = $this->_extractOption('secure', $attributes);
2045
		$showEmpty = $this->_extractOption('empty', $attributes);
2046
		$showParents = $this->_extractOption('showParents', $attributes);
2047
		$hiddenField = $this->_extractOption('hiddenField', $attributes);
2048
		unset($attributes['escape'], $attributes['secure'], $attributes['empty'], $attributes['showParents'], $attributes['hiddenField']);
2049
		$id = $this->_extractOption('id', $attributes);
2050
 
2051
		$attributes = $this->_initInputField($fieldName, array_merge(
2052
			(array)$attributes, array('secure' => self::SECURE_SKIP)
2053
		));
2054
 
2055
		if (is_string($options) && isset($this->_options[$options])) {
2056
			$options = $this->_generateOptions($options);
2057
		} elseif (!is_array($options)) {
2058
			$options = array();
2059
		}
2060
		if (isset($attributes['type'])) {
2061
			unset($attributes['type']);
2062
		}
2063
 
2064
		if (!empty($attributes['multiple'])) {
2065
			$style = ($attributes['multiple'] === 'checkbox') ? 'checkbox' : null;
2066
			$template = ($style) ? 'checkboxmultiplestart' : 'selectmultiplestart';
2067
			$tag = $template;
2068
			if ($hiddenField) {
2069
				$hiddenAttributes = array(
2070
					'value' => '',
2071
					'id' => $attributes['id'] . ($style ? '' : '_'),
2072
					'secure' => false,
2073
					'form' => isset($attributes['form']) ? $attributes['form'] : null,
2074
					'name' => $attributes['name'],
2075
					'disabled' => $attributes['disabled'] === true || $attributes['disabled'] === 'disabled'
2076
				);
2077
				$select[] = $this->hidden(null, $hiddenAttributes);
2078
			}
2079
		} else {
2080
			$tag = 'selectstart';
2081
		}
2082
 
2083
		if ($tag === 'checkboxmultiplestart') {
2084
			unset($attributes['required']);
2085
		}
2086
 
2087
		if (!empty($tag) || isset($template)) {
2088
			$hasOptions = (count($options) > 0 || $showEmpty);
2089
			// Secure the field if there are options, or its a multi select.
2090
			// Single selects with no options don't submit, but multiselects do.
2091
			if ((!isset($secure) || $secure) &&
2092
				empty($attributes['disabled']) &&
2093
				(!empty($attributes['multiple']) || $hasOptions)
2094
			) {
2095
				$this->_secure(true, $this->_secureFieldName($attributes));
2096
			}
2097
			$filter = array('name' => null, 'value' => null);
2098
			if (is_array($attributes['disabled'])) {
2099
				$filter['disabled'] = null;
2100
			}
2101
			$select[] = $this->Html->useTag($tag, $attributes['name'], array_diff_key($attributes, $filter));
2102
		}
2103
		$emptyMulti = (
2104
			$showEmpty !== null && $showEmpty !== false && !(
2105
				empty($showEmpty) && (isset($attributes) &&
2106
				array_key_exists('multiple', $attributes))
2107
			)
2108
		);
2109
 
2110
		if ($emptyMulti) {
2111
			$showEmpty = ($showEmpty === true) ? '' : $showEmpty;
2112
			$options = array('' => $showEmpty) + $options;
2113
		}
2114
 
2115
		if (!$id) {
2116
			$attributes['id'] = Inflector::camelize($attributes['id']);
2117
		}
2118
 
2119
		$select = array_merge($select, $this->_selectOptions(
2120
			array_reverse($options, true),
2121
			array(),
2122
			$showParents,
2123
			array(
2124
				'escape' => $escapeOptions,
2125
				'style' => $style,
2126
				'name' => $attributes['name'],
2127
				'value' => $attributes['value'],
2128
				'class' => $attributes['class'],
2129
				'id' => $attributes['id'],
2130
				'disabled' => $attributes['disabled'],
2131
			)
2132
		));
2133
 
2134
		$template = ($style === 'checkbox') ? 'checkboxmultipleend' : 'selectend';
2135
		$select[] = $this->Html->useTag($template);
2136
		return implode("\n", $select);
2137
	}
2138
 
2139
/**
2140
 * Generates a valid DOM ID suffix from a string.
2141
 * Also avoids collisions when multiple values are coverted to the same suffix by
2142
 * appending a numeric value.
2143
 *
2144
 * For pre-HTML5 IDs only characters like a-z 0-9 - _ are valid. HTML5 doesn't have that
2145
 * limitation, but to avoid layout issues it still filters out some sensitive chars.
2146
 *
2147
 * @param string $value The value that should be transferred into a DOM ID suffix.
2148
 * @param string $type Doctype to use. Defaults to html4.
2149
 * @return string DOM ID
2150
 */
2151
	public function domIdSuffix($value, $type = 'html4') {
2152
		if ($type === 'html5') {
2153
			$value = str_replace(array('@', '<', '>', ' ', '"', '\''), '_', $value);
2154
		} else {
2155
			$value = Inflector::camelize(Inflector::slug($value));
2156
		}
2157
		$value = Inflector::camelize($value);
2158
		$count = 1;
2159
		$suffix = $value;
2160
		while (in_array($suffix, $this->_domIdSuffixes)) {
2161
			$suffix = $value . $count++;
2162
		}
2163
		$this->_domIdSuffixes[] = $suffix;
2164
		return $suffix;
2165
	}
2166
 
2167
/**
2168
 * Returns a SELECT element for days.
2169
 *
2170
 * ### Attributes:
2171
 *
2172
 * - `empty` - If true, the empty select option is shown. If a string,
2173
 *   that string is displayed as the empty element.
2174
 * - `value` The selected value of the input.
2175
 *
2176
 * @param string $fieldName Prefix name for the SELECT element
2177
 * @param array $attributes HTML attributes for the select element
2178
 * @return string A generated day select box.
2179
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::day
2180
 */
2181
	public function day($fieldName = null, $attributes = array()) {
2182
		$attributes += array('empty' => true, 'value' => null);
2183
		$attributes = $this->_dateTimeSelected('day', $fieldName, $attributes);
2184
 
2185
		if (strlen($attributes['value']) > 2) {
2186
			$date = date_create($attributes['value']);
2187
			$attributes['value'] = null;
2188
			if ($date) {
2189
				$attributes['value'] = $date->format('d');
2190
			}
2191
		} elseif ($attributes['value'] === false) {
2192
			$attributes['value'] = null;
2193
		}
2194
		return $this->select($fieldName . ".day", $this->_generateOptions('day'), $attributes);
2195
	}
2196
 
2197
/**
2198
 * Returns a SELECT element for years
2199
 *
2200
 * ### Attributes:
2201
 *
2202
 * - `empty` - If true, the empty select option is shown. If a string,
2203
 *   that string is displayed as the empty element.
2204
 * - `orderYear` - Ordering of year values in select options.
2205
 *   Possible values 'asc', 'desc'. Default 'desc'
2206
 * - `value` The selected value of the input.
2207
 *
2208
 * @param string $fieldName Prefix name for the SELECT element
2209
 * @param int $minYear First year in sequence
2210
 * @param int $maxYear Last year in sequence
2211
 * @param array $attributes Attribute array for the select elements.
2212
 * @return string Completed year select input
2213
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::year
2214
 */
2215
	public function year($fieldName, $minYear = null, $maxYear = null, $attributes = array()) {
2216
		if (is_array($minYear)) {
2217
			$attributes = $minYear;
2218
			$minYear = null;
2219
		}
2220
 
2221
		$attributes += array('empty' => true, 'value' => null);
2222
		if ((empty($attributes['value']) || $attributes['value'] === true) && $value = $this->value($fieldName)) {
2223
			if (is_array($value)) {
2224
				$year = null;
2225
				extract($value);
2226
				$attributes['value'] = $year;
2227
			} else {
2228
				if (empty($value)) {
2229
					if (!$attributes['empty'] && !$maxYear) {
2230
						$attributes['value'] = 'now';
2231
 
2232
					} elseif (!$attributes['empty'] && $maxYear && !$attributes['value']) {
2233
						$attributes['value'] = $maxYear;
2234
					}
2235
				} else {
2236
					$attributes['value'] = $value;
2237
				}
2238
			}
2239
		}
2240
 
2241
		if (strlen($attributes['value']) > 4 || $attributes['value'] === 'now') {
2242
			$date = date_create($attributes['value']);
2243
			$attributes['value'] = null;
2244
			if ($date) {
2245
				$attributes['value'] = $date->format('Y');
2246
			}
2247
		} elseif ($attributes['value'] === false) {
2248
			$attributes['value'] = null;
2249
		}
2250
		$yearOptions = array('value' => $attributes['value'], 'min' => $minYear, 'max' => $maxYear, 'order' => 'desc');
2251
		if (isset($attributes['orderYear'])) {
2252
			$yearOptions['order'] = $attributes['orderYear'];
2253
			unset($attributes['orderYear']);
2254
		}
2255
		return $this->select(
2256
			$fieldName . '.year', $this->_generateOptions('year', $yearOptions),
2257
			$attributes
2258
		);
2259
	}
2260
 
2261
/**
2262
 * Returns a SELECT element for months.
2263
 *
2264
 * ### Attributes:
2265
 *
2266
 * - `monthNames` - If false, 2 digit numbers will be used instead of text.
2267
 *   If an array, the given array will be used.
2268
 * - `empty` - If true, the empty select option is shown. If a string,
2269
 *   that string is displayed as the empty element.
2270
 * - `value` The selected value of the input.
2271
 *
2272
 * @param string $fieldName Prefix name for the SELECT element
2273
 * @param array $attributes Attributes for the select element
2274
 * @return string A generated month select dropdown.
2275
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::month
2276
 */
2277
	public function month($fieldName, $attributes = array()) {
2278
		$attributes += array('empty' => true, 'value' => null);
2279
		$attributes = $this->_dateTimeSelected('month', $fieldName, $attributes);
2280
 
2281
		if (strlen($attributes['value']) > 2) {
2282
			$date = date_create($attributes['value']);
2283
			$attributes['value'] = null;
2284
			if ($date) {
2285
				$attributes['value'] = $date->format('m');
2286
			}
2287
		} elseif ($attributes['value'] === false) {
2288
			$attributes['value'] = null;
2289
		}
2290
		$defaults = array('monthNames' => true);
2291
		$attributes = array_merge($defaults, (array)$attributes);
2292
		$monthNames = $attributes['monthNames'];
2293
		unset($attributes['monthNames']);
2294
 
2295
		return $this->select(
2296
			$fieldName . ".month",
2297
			$this->_generateOptions('month', array('monthNames' => $monthNames)),
2298
			$attributes
2299
		);
2300
	}
2301
 
2302
/**
2303
 * Returns a SELECT element for hours.
2304
 *
2305
 * ### Attributes:
2306
 *
2307
 * - `empty` - If true, the empty select option is shown. If a string,
2308
 *   that string is displayed as the empty element.
2309
 * - `value` The selected value of the input.
2310
 *
2311
 * @param string $fieldName Prefix name for the SELECT element
2312
 * @param bool $format24Hours True for 24 hours format
2313
 * @param array $attributes List of HTML attributes
2314
 * @return string Completed hour select input
2315
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::hour
2316
 */
2317
	public function hour($fieldName, $format24Hours = false, $attributes = array()) {
2318
		if (is_array($format24Hours)) {
2319
			$attributes = $format24Hours;
2320
			$format24Hours = false;
2321
		}
2322
 
2323
		$attributes += array('empty' => true, 'value' => null);
2324
		$attributes = $this->_dateTimeSelected('hour', $fieldName, $attributes);
2325
 
2326
		if (strlen($attributes['value']) > 2) {
2327
			try {
2328
				$date = new DateTime($attributes['value']);
2329
				if ($format24Hours) {
2330
					$attributes['value'] = $date->format('H');
2331
				} else {
2332
					$attributes['value'] = $date->format('g');
2333
				}
2334
			} catch (Exception $e) {
2335
				$attributes['value'] = null;
2336
			}
2337
		} elseif ($attributes['value'] === false) {
2338
			$attributes['value'] = null;
2339
		}
2340
 
2341
		if ($attributes['value'] > 12 && !$format24Hours) {
2342
			$attributes['value'] -= 12;
2343
		}
2344
		if (($attributes['value'] === 0 || $attributes['value'] === '00') && !$format24Hours) {
2345
			$attributes['value'] = 12;
2346
		}
2347
 
2348
		return $this->select(
2349
			$fieldName . ".hour",
2350
			$this->_generateOptions($format24Hours ? 'hour24' : 'hour'),
2351
			$attributes
2352
		);
2353
	}
2354
 
2355
/**
2356
 * Returns a SELECT element for minutes.
2357
 *
2358
 * ### Attributes:
2359
 *
2360
 * - `empty` - If true, the empty select option is shown. If a string,
2361
 *   that string is displayed as the empty element.
2362
 * - `value` The selected value of the input.
2363
 *
2364
 * @param string $fieldName Prefix name for the SELECT element
2365
 * @param array $attributes Array of Attributes
2366
 * @return string Completed minute select input.
2367
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::minute
2368
 */
2369
	public function minute($fieldName, $attributes = array()) {
2370
		$attributes += array('empty' => true, 'value' => null);
2371
		$attributes = $this->_dateTimeSelected('min', $fieldName, $attributes);
2372
 
2373
		if (strlen($attributes['value']) > 2) {
2374
			$date = date_create($attributes['value']);
2375
			$attributes['value'] = null;
2376
			if ($date) {
2377
				$attributes['value'] = $date->format('i');
2378
			}
2379
		} elseif ($attributes['value'] === false) {
2380
			$attributes['value'] = null;
2381
		}
2382
		$minuteOptions = array();
2383
 
2384
		if (isset($attributes['interval'])) {
2385
			$minuteOptions['interval'] = $attributes['interval'];
2386
			unset($attributes['interval']);
2387
		}
2388
		return $this->select(
2389
			$fieldName . ".min", $this->_generateOptions('minute', $minuteOptions),
2390
			$attributes
2391
		);
2392
	}
2393
 
2394
/**
2395
 * Selects values for dateTime selects.
2396
 *
2397
 * @param string $select Name of element field. ex. 'day'
2398
 * @param string $fieldName Name of fieldName being generated ex. Model.created
2399
 * @param array $attributes Array of attributes, must contain 'empty' key.
2400
 * @return array Attributes array with currently selected value.
2401
 */
2402
	protected function _dateTimeSelected($select, $fieldName, $attributes) {
2403
		if ((empty($attributes['value']) || $attributes['value'] === true) && $value = $this->value($fieldName)) {
2404
			if (is_array($value)) {
2405
				$attributes['value'] = isset($value[$select]) ? $value[$select] : null;
2406
			} else {
2407
				if (empty($value)) {
2408
					if (!$attributes['empty']) {
2409
						$attributes['value'] = 'now';
2410
					}
2411
				} else {
2412
					$attributes['value'] = $value;
2413
				}
2414
			}
2415
		}
2416
		return $attributes;
2417
	}
2418
 
2419
/**
2420
 * Returns a SELECT element for AM or PM.
2421
 *
2422
 * ### Attributes:
2423
 *
2424
 * - `empty` - If true, the empty select option is shown. If a string,
2425
 *   that string is displayed as the empty element.
2426
 * - `value` The selected value of the input.
2427
 *
2428
 * @param string $fieldName Prefix name for the SELECT element
2429
 * @param array $attributes Array of Attributes
2430
 * @return string Completed meridian select input
2431
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::meridian
2432
 */
2433
	public function meridian($fieldName, $attributes = array()) {
2434
		$attributes += array('empty' => true, 'value' => null);
2435
		if ((empty($attributes['value']) || $attributes['value'] === true) && $value = $this->value($fieldName)) {
2436
			if (is_array($value)) {
2437
				$meridian = null;
2438
				extract($value);
2439
				$attributes['value'] = $meridian;
2440
			} else {
2441
				if (empty($value)) {
2442
					if (!$attributes['empty']) {
2443
						$attributes['value'] = date('a');
2444
					}
2445
				} else {
2446
					$date = date_create($attributes['value']);
2447
					$attributes['value'] = null;
2448
					if ($date) {
2449
						$attributes['value'] = $date->format('a');
2450
					}
2451
				}
2452
			}
2453
		}
2454
 
2455
		if ($attributes['value'] === false) {
2456
			$attributes['value'] = null;
2457
		}
2458
		return $this->select(
2459
			$fieldName . ".meridian", $this->_generateOptions('meridian'),
2460
			$attributes
2461
		);
2462
	}
2463
 
2464
/**
2465
 * Returns a set of SELECT elements for a full datetime setup: day, month and year, and then time.
2466
 *
2467
 * ### Attributes:
2468
 *
2469
 * - `monthNames` If false, 2 digit numbers will be used instead of text.
2470
 *   If an array, the given array will be used.
2471
 * - `minYear` The lowest year to use in the year select
2472
 * - `maxYear` The maximum year to use in the year select
2473
 * - `interval` The interval for the minutes select. Defaults to 1
2474
 * - `separator` The contents of the string between select elements. Defaults to '-'
2475
 * - `empty` - If true, the empty select option is shown. If a string,
2476
 *   that string is displayed as the empty element.
2477
 * - `round` - Set to `up` or `down` if you want to force rounding in either direction. Defaults to null.
2478
 * - `value` | `default` The default value to be used by the input. A value in `$this->data`
2479
 *   matching the field name will override this value. If no default is provided `time()` will be used.
2480
 *
2481
 * @param string $fieldName Prefix name for the SELECT element
2482
 * @param string $dateFormat DMY, MDY, YMD, or null to not generate date inputs.
2483
 * @param string $timeFormat 12, 24, or null to not generate time inputs.
2484
 * @param array $attributes Array of Attributes
2485
 * @return string Generated set of select boxes for the date and time formats chosen.
2486
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::dateTime
2487
 */
2488
	public function dateTime($fieldName, $dateFormat = 'DMY', $timeFormat = '12', $attributes = array()) {
2489
		$attributes += array('empty' => true, 'value' => null);
2490
		$year = $month = $day = $hour = $min = $meridian = null;
2491
 
2492
		if (empty($attributes['value'])) {
2493
			$attributes = $this->value($attributes, $fieldName);
2494
		}
2495
 
2496
		if ($attributes['value'] === null && $attributes['empty'] != true) {
2497
			$attributes['value'] = time();
2498
			if (!empty($attributes['maxYear']) && $attributes['maxYear'] < date('Y')) {
2499
				$attributes['value'] = strtotime(date($attributes['maxYear'] . '-m-d'));
2500
			}
2501
		}
2502
 
2503
		if (!empty($attributes['value'])) {
2504
			list($year, $month, $day, $hour, $min, $meridian) = $this->_getDateTimeValue(
2505
				$attributes['value'],
2506
				$timeFormat
2507
			);
2508
		}
2509
 
2510
		$defaults = array(
2511
			'minYear' => null, 'maxYear' => null, 'separator' => '-',
2512
			'interval' => 1, 'monthNames' => true, 'round' => null
2513
		);
2514
		$attributes = array_merge($defaults, (array)$attributes);
2515
		if (isset($attributes['minuteInterval'])) {
2516
			$attributes['interval'] = $attributes['minuteInterval'];
2517
			unset($attributes['minuteInterval']);
2518
		}
2519
		$minYear = $attributes['minYear'];
2520
		$maxYear = $attributes['maxYear'];
2521
		$separator = $attributes['separator'];
2522
		$interval = $attributes['interval'];
2523
		$monthNames = $attributes['monthNames'];
2524
		$round = $attributes['round'];
2525
		$attributes = array_diff_key($attributes, $defaults);
2526
 
2527
		if (!empty($interval) && $interval > 1 && !empty($min)) {
2528
			$current = new DateTime();
2529
			if ($year !== null) {
2530
				$current->setDate($year, $month, $day);
2531
			}
2532
			if ($hour !== null) {
2533
				$current->setTime($hour, $min);
2534
			}
2535
			$changeValue = $min * (1 / $interval);
2536
			switch ($round) {
2537
				case 'up':
2538
					$changeValue = ceil($changeValue);
2539
					break;
2540
				case 'down':
2541
					$changeValue = floor($changeValue);
2542
					break;
2543
				default:
2544
					$changeValue = round($changeValue);
2545
			}
2546
			$change = ($changeValue * $interval) - $min;
2547
			$current->modify($change > 0 ? "+$change minutes" : "$change minutes");
2548
			$format = ($timeFormat == 12) ? 'Y m d h i a' : 'Y m d H i a';
2549
			$newTime = explode(' ', $current->format($format));
2550
			list($year, $month, $day, $hour, $min, $meridian) = $newTime;
2551
		}
2552
 
2553
		$keys = array('Day', 'Month', 'Year', 'Hour', 'Minute', 'Meridian');
2554
		$attrs = array_fill_keys($keys, $attributes);
2555
 
2556
		$hasId = isset($attributes['id']);
2557
		if ($hasId && is_array($attributes['id'])) {
2558
			// check for missing ones and build selectAttr for each element
2559
			$attributes['id'] += array(
2560
				'month' => '',
2561
				'year' => '',
2562
				'day' => '',
2563
				'hour' => '',
2564
				'minute' => '',
2565
				'meridian' => ''
2566
			);
2567
			foreach ($keys as $key) {
2568
				$attrs[$key]['id'] = $attributes['id'][strtolower($key)];
2569
			}
2570
		}
2571
		if ($hasId && is_string($attributes['id'])) {
2572
			// build out an array version
2573
			foreach ($keys as $key) {
2574
				$attrs[$key]['id'] = $attributes['id'] . $key;
2575
			}
2576
		}
2577
 
2578
		if (is_array($attributes['empty'])) {
2579
			$attributes['empty'] += array(
2580
				'month' => true,
2581
				'year' => true,
2582
				'day' => true,
2583
				'hour' => true,
2584
				'minute' => true,
2585
				'meridian' => true
2586
			);
2587
			foreach ($keys as $key) {
2588
				$attrs[$key]['empty'] = $attributes['empty'][strtolower($key)];
2589
			}
2590
		}
2591
 
2592
		$selects = array();
2593
		foreach (preg_split('//', $dateFormat, -1, PREG_SPLIT_NO_EMPTY) as $char) {
2594
			switch ($char) {
2595
				case 'Y':
2596
					$attrs['Year']['value'] = $year;
2597
					$selects[] = $this->year(
2598
						$fieldName, $minYear, $maxYear, $attrs['Year']
2599
					);
2600
					break;
2601
				case 'M':
2602
					$attrs['Month']['value'] = $month;
2603
					$attrs['Month']['monthNames'] = $monthNames;
2604
					$selects[] = $this->month($fieldName, $attrs['Month']);
2605
					break;
2606
				case 'D':
2607
					$attrs['Day']['value'] = $day;
2608
					$selects[] = $this->day($fieldName, $attrs['Day']);
2609
					break;
2610
			}
2611
		}
2612
		$opt = implode($separator, $selects);
2613
 
2614
		$attrs['Minute']['interval'] = $interval;
2615
		switch ($timeFormat) {
2616
			case '24':
2617
				$attrs['Hour']['value'] = $hour;
2618
				$attrs['Minute']['value'] = $min;
2619
				$opt .= $this->hour($fieldName, true, $attrs['Hour']) . ':' .
2620
				$this->minute($fieldName, $attrs['Minute']);
2621
				break;
2622
			case '12':
2623
				$attrs['Hour']['value'] = $hour;
2624
				$attrs['Minute']['value'] = $min;
2625
				$attrs['Meridian']['value'] = $meridian;
2626
				$opt .= $this->hour($fieldName, false, $attrs['Hour']) . ':' .
2627
				$this->minute($fieldName, $attrs['Minute']) . ' ' .
2628
				$this->meridian($fieldName, $attrs['Meridian']);
2629
				break;
2630
		}
2631
		return $opt;
2632
	}
2633
 
2634
/**
2635
 * Parse the value for a datetime selected value
2636
 *
2637
 * @param string|array $value The selected value.
2638
 * @param int $timeFormat The time format
2639
 * @return array Array of selected value.
2640
 */
2641
	protected function _getDateTimeValue($value, $timeFormat) {
2642
		$year = $month = $day = $hour = $min = $meridian = null;
2643
		if (is_array($value)) {
2644
			extract($value);
2645
			if ($meridian === 'pm') {
2646
				$hour += 12;
2647
			}
2648
			return array($year, $month, $day, $hour, $min, $meridian);
2649
		}
2650
 
2651
		if (is_numeric($value)) {
2652
			$value = strftime('%Y-%m-%d %H:%M:%S', $value);
2653
		}
2654
		$meridian = 'am';
2655
		$pos = strpos($value, '-');
2656
		if ($pos !== false) {
2657
			$date = explode('-', $value);
2658
			$days = explode(' ', $date[2]);
2659
			$day = $days[0];
2660
			$month = $date[1];
2661
			$year = $date[0];
2662
		} else {
2663
			$days[1] = $value;
2664
		}
2665
 
2666
		if (!empty($timeFormat)) {
2667
			$time = explode(':', $days[1]);
2668
 
2669
			if ($time[0] >= 12) {
2670
				$meridian = 'pm';
2671
			}
2672
			$hour = $min = null;
2673
			if (isset($time[1])) {
2674
				$hour = $time[0];
2675
				$min = $time[1];
2676
			}
2677
		}
2678
		return array($year, $month, $day, $hour, $min, $meridian);
2679
	}
2680
 
2681
/**
2682
 * Gets the input field name for the current tag
2683
 *
2684
 * @param array $options Options list.
2685
 * @param string $field Field name.
2686
 * @param string $key Key name.
2687
 * @return array
2688
 */
2689
	protected function _name($options = array(), $field = null, $key = 'name') {
2690
		if ($this->requestType === 'get') {
2691
			if ($options === null) {
2692
				$options = array();
2693
			} elseif (is_string($options)) {
2694
				$field = $options;
2695
				$options = 0;
2696
			}
2697
 
2698
			if (!empty($field)) {
2699
				$this->setEntity($field);
2700
			}
2701
 
2702
			if (is_array($options) && isset($options[$key])) {
2703
				return $options;
2704
			}
2705
 
2706
			$entity = $this->entity();
2707
			$model = $this->model();
2708
			$name = $model === $entity[0] && isset($entity[1]) ? $entity[1] : $entity[0];
2709
			$last = $entity[count($entity) - 1];
2710
			if (in_array($last, $this->_fieldSuffixes)) {
2711
				$name .= '[' . $last . ']';
2712
			}
2713
 
2714
			if (is_array($options)) {
2715
				$options[$key] = $name;
2716
				return $options;
2717
			}
2718
			return $name;
2719
		}
2720
		return parent::_name($options, $field, $key);
2721
	}
2722
 
2723
/**
2724
 * Returns an array of formatted OPTION/OPTGROUP elements
2725
 *
2726
 * @param array $elements Elements to format.
2727
 * @param array $parents Parents for OPTGROUP.
2728
 * @param bool $showParents Whether to show parents.
2729
 * @param array $attributes HTML attributes.
2730
 * @return array
2731
 */
2732
	protected function _selectOptions($elements = array(), $parents = array(), $showParents = null, $attributes = array()) {
2733
		$select = array();
2734
		$attributes = array_merge(
2735
			array('escape' => true, 'style' => null, 'value' => null, 'class' => null),
2736
			$attributes
2737
		);
2738
		$selectedIsEmpty = ($attributes['value'] === '' || $attributes['value'] === null);
2739
		$selectedIsArray = is_array($attributes['value']);
2740
 
2741
		$this->_domIdSuffixes = array();
2742
		foreach ($elements as $name => $title) {
2743
			$htmlOptions = array();
2744
			if (is_array($title) && (!isset($title['name']) || !isset($title['value']))) {
2745
				if (!empty($name)) {
2746
					if ($attributes['style'] === 'checkbox') {
2747
						$select[] = $this->Html->useTag('fieldsetend');
2748
					} else {
2749
						$select[] = $this->Html->useTag('optiongroupend');
2750
					}
2751
					$parents[] = $name;
2752
				}
2753
				$select = array_merge($select, $this->_selectOptions(
2754
					$title, $parents, $showParents, $attributes
2755
				));
2756
 
2757
				if (!empty($name)) {
2758
					$name = $attributes['escape'] ? h($name) : $name;
2759
					if ($attributes['style'] === 'checkbox') {
2760
						$select[] = $this->Html->useTag('fieldsetstart', $name);
2761
					} else {
2762
						$select[] = $this->Html->useTag('optiongroup', $name, '');
2763
					}
2764
				}
2765
				$name = null;
2766
			} elseif (is_array($title)) {
2767
				$htmlOptions = $title;
2768
				$name = $title['value'];
2769
				$title = $title['name'];
2770
				unset($htmlOptions['name'], $htmlOptions['value']);
2771
			}
2772
 
2773
			if ($name !== null) {
2774
				$isNumeric = is_numeric($name);
2775
				if ((!$selectedIsArray && !$selectedIsEmpty && (string)$attributes['value'] == (string)$name) ||
2776
					($selectedIsArray && in_array((string)$name, $attributes['value'], !$isNumeric))
2777
				) {
2778
					if ($attributes['style'] === 'checkbox') {
2779
						$htmlOptions['checked'] = true;
2780
					} else {
2781
						$htmlOptions['selected'] = 'selected';
2782
					}
2783
				}
2784
 
2785
				if ($showParents || (!in_array($title, $parents))) {
2786
					$title = ($attributes['escape']) ? h($title) : $title;
2787
 
2788
					$hasDisabled = !empty($attributes['disabled']);
2789
					if ($hasDisabled) {
2790
						$disabledIsArray = is_array($attributes['disabled']);
2791
						if ($disabledIsArray) {
2792
							$disabledIsNumeric = is_numeric($name);
2793
						}
2794
					}
2795
					if ($hasDisabled &&
2796
						$disabledIsArray &&
2797
						in_array((string)$name, $attributes['disabled'], !$disabledIsNumeric)
2798
					) {
2799
						$htmlOptions['disabled'] = 'disabled';
2800
					}
2801
					if ($hasDisabled && !$disabledIsArray && $attributes['style'] === 'checkbox') {
2802
						$htmlOptions['disabled'] = $attributes['disabled'] === true ? 'disabled' : $attributes['disabled'];
2803
					}
2804
 
2805
					if ($attributes['style'] === 'checkbox') {
2806
						$htmlOptions['value'] = $name;
2807
 
2808
						$tagName = $attributes['id'] . $this->domIdSuffix($name);
2809
						$htmlOptions['id'] = $tagName;
2810
						$label = array('for' => $tagName);
2811
 
2812
						if (isset($htmlOptions['checked']) && $htmlOptions['checked'] === true) {
2813
							$label['class'] = 'selected';
2814
						}
2815
 
2816
						$name = $attributes['name'];
2817
 
2818
						if (empty($attributes['class'])) {
2819
							$attributes['class'] = 'checkbox';
2820
						} elseif ($attributes['class'] === 'form-error') {
2821
							$attributes['class'] = 'checkbox ' . $attributes['class'];
2822
						}
2823
						$label = $this->label(null, $title, $label);
2824
						$item = $this->Html->useTag('checkboxmultiple', $name, $htmlOptions);
2825
						$select[] = $this->Html->div($attributes['class'], $item . $label);
2826
					} else {
2827
						if ($attributes['escape']) {
2828
							$name = h($name);
2829
						}
2830
						$select[] = $this->Html->useTag('selectoption', $name, $htmlOptions, $title);
2831
					}
2832
				}
2833
			}
2834
		}
2835
 
2836
		return array_reverse($select, true);
2837
	}
2838
 
2839
/**
2840
 * Generates option lists for common <select /> menus
2841
 *
2842
 * @param string $name List type name.
2843
 * @param array $options Options list.
2844
 * @return array
2845
 */
2846
	protected function _generateOptions($name, $options = array()) {
2847
		if (!empty($this->options[$name])) {
2848
			return $this->options[$name];
2849
		}
2850
		$data = array();
2851
 
2852
		switch ($name) {
2853
			case 'minute':
2854
				if (isset($options['interval'])) {
2855
					$interval = $options['interval'];
2856
				} else {
2857
					$interval = 1;
2858
				}
2859
				$i = 0;
2860
				while ($i < 60) {
2861
					$data[sprintf('%02d', $i)] = sprintf('%02d', $i);
2862
					$i += $interval;
2863
				}
2864
				break;
2865
			case 'hour':
2866
				for ($i = 1; $i <= 12; $i++) {
2867
					$data[sprintf('%02d', $i)] = $i;
2868
				}
2869
				break;
2870
			case 'hour24':
2871
				for ($i = 0; $i <= 23; $i++) {
2872
					$data[sprintf('%02d', $i)] = $i;
2873
				}
2874
				break;
2875
			case 'meridian':
2876
				$data = array('am' => 'am', 'pm' => 'pm');
2877
				break;
2878
			case 'day':
2879
				for ($i = 1; $i <= 31; $i++) {
2880
					$data[sprintf('%02d', $i)] = $i;
2881
				}
2882
				break;
2883
			case 'month':
2884
				if ($options['monthNames'] === true) {
2885
					$data['01'] = __d('cake', 'January');
2886
					$data['02'] = __d('cake', 'February');
2887
					$data['03'] = __d('cake', 'March');
2888
					$data['04'] = __d('cake', 'April');
2889
					$data['05'] = __d('cake', 'May');
2890
					$data['06'] = __d('cake', 'June');
2891
					$data['07'] = __d('cake', 'July');
2892
					$data['08'] = __d('cake', 'August');
2893
					$data['09'] = __d('cake', 'September');
2894
					$data['10'] = __d('cake', 'October');
2895
					$data['11'] = __d('cake', 'November');
2896
					$data['12'] = __d('cake', 'December');
2897
				} elseif (is_array($options['monthNames'])) {
2898
					$data = $options['monthNames'];
2899
				} else {
2900
					for ($m = 1; $m <= 12; $m++) {
2901
						$data[sprintf("%02s", $m)] = strftime("%m", mktime(1, 1, 1, $m, 1, 1999));
2902
					}
2903
				}
2904
				break;
2905
			case 'year':
2906
				$current = (int)date('Y');
2907
 
2908
				$min = !isset($options['min']) ? $current - 20 : (int)$options['min'];
2909
				$max = !isset($options['max']) ? $current + 20 : (int)$options['max'];
2910
 
2911
				if ($min > $max) {
2912
					list($min, $max) = array($max, $min);
2913
				}
2914
				if (!empty($options['value']) &&
2915
					(int)$options['value'] < $min &&
2916
					(int)$options['value'] > 0
2917
				) {
2918
					$min = (int)$options['value'];
2919
				} elseif (!empty($options['value']) && (int)$options['value'] > $max) {
2920
					$max = (int)$options['value'];
2921
				}
2922
 
2923
				for ($i = $min; $i <= $max; $i++) {
2924
					$data[$i] = $i;
2925
				}
2926
				if ($options['order'] !== 'asc') {
2927
					$data = array_reverse($data, true);
2928
				}
2929
				break;
2930
		}
2931
		$this->_options[$name] = $data;
2932
		return $this->_options[$name];
2933
	}
2934
 
2935
/**
2936
 * Sets field defaults and adds field to form security input hash.
2937
 * Will also add a 'form-error' class if the field contains validation errors.
2938
 *
2939
 * ### Options
2940
 *
2941
 * - `secure` - boolean whether or not the field should be added to the security fields.
2942
 *   Disabling the field using the `disabled` option, will also omit the field from being
2943
 *   part of the hashed key.
2944
 *
2945
 * This method will convert a numerically indexed 'disabled' into an associative
2946
 * value. FormHelper's internals expect associative options.
2947
 *
2948
 * @param string $field Name of the field to initialize options for.
2949
 * @param array $options Array of options to append options into.
2950
 * @return array Array of options for the input.
2951
 */
2952
	protected function _initInputField($field, $options = array()) {
2953
		if (isset($options['secure'])) {
2954
			$secure = $options['secure'];
2955
			unset($options['secure']);
2956
		} else {
2957
			$secure = (isset($this->request['_Token']) && !empty($this->request['_Token']));
2958
		}
2959
 
2960
		$disabledIndex = array_search('disabled', $options, true);
2961
		if (is_int($disabledIndex)) {
2962
			unset($options[$disabledIndex]);
2963
			$options['disabled'] = true;
2964
		}
2965
 
2966
		$result = parent::_initInputField($field, $options);
2967
		if ($this->tagIsInvalid() !== false) {
2968
			$result = $this->addClass($result, 'form-error');
2969
		}
2970
 
2971
		$isDisabled = false;
2972
		if (isset($result['disabled'])) {
2973
			$isDisabled = (
2974
				$result['disabled'] === true ||
2975
				$result['disabled'] === 'disabled' ||
2976
				(is_array($result['disabled']) &&
2977
					!empty($result['options']) &&
2978
					array_diff($result['options'], $result['disabled']) === array()
2979
				)
2980
			);
2981
		}
2982
		if ($isDisabled) {
2983
			return $result;
2984
		}
2985
 
2986
		if (!isset($result['required']) &&
2987
			$this->_introspectModel($this->model(), 'validates', $this->field())
2988
		) {
2989
			$result['required'] = true;
2990
		}
2991
 
2992
		if ($secure === self::SECURE_SKIP) {
2993
			return $result;
2994
		}
2995
 
2996
		$this->_secure($secure, $this->_secureFieldName($options));
2997
		return $result;
2998
	}
2999
 
3000
/**
3001
 * Get the field name for use with _secure().
3002
 *
3003
 * Parses the name attribute to create a dot separated name value for use
3004
 * in secured field hash.
3005
 *
3006
 * @param array $options An array of options possibly containing a name key.
3007
 * @return string|null
3008
 */
3009
	protected function _secureFieldName($options) {
3010
		if (isset($options['name'])) {
3011
			preg_match_all('/\[(.*?)\]/', $options['name'], $matches);
3012
			if (isset($matches[1])) {
3013
				return $matches[1];
3014
			}
3015
		}
3016
		return null;
3017
	}
3018
 
3019
/**
3020
 * Sets the last created form action.
3021
 *
3022
 * @param string|array $url URL.
3023
 * @return void
3024
 */
3025
	protected function _lastAction($url) {
3026
		$action = Router::url($url, true);
3027
		$query = parse_url($action, PHP_URL_QUERY);
3028
		$query = $query ? '?' . $query : '';
3029
		$this->_lastAction = parse_url($action, PHP_URL_PATH) . $query;
3030
	}
3031
 
3032
/**
3033
 * Set/Get inputDefaults for form elements
3034
 *
3035
 * @param array $defaults New default values
3036
 * @param bool $merge Merge with current defaults
3037
 * @return array inputDefaults
3038
 */
3039
	public function inputDefaults($defaults = null, $merge = false) {
3040
		if ($defaults !== null) {
3041
			if ($merge) {
3042
				$this->_inputDefaults = array_merge($this->_inputDefaults, (array)$defaults);
3043
			} else {
3044
				$this->_inputDefaults = (array)$defaults;
3045
			}
3046
		}
3047
		return $this->_inputDefaults;
3048
	}
3049
 
3050
}