Subversion Repositories SmartDukaan

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
12345 anikendra 1
<?php
2
/**
3
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
4
 * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
5
 *
6
 * Licensed under The MIT License
7
 * For full copyright and license information, please see the LICENSE.txt
8
 * Redistributions of files must retain the above copyright notice.
9
 *
10
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
11
 * @link          http://cakephp.org CakePHP(tm) Project
12
 * @package       Cake.View.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 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 An 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 (empty($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 (
538
			$this->requestType !== 'get' &&
539
			isset($this->request['_Token']) &&
540
			!empty($this->request['_Token'])
541
		) {
542
			$out .= $this->secure($this->fields, $secureAttributes);
543
			$this->fields = array();
544
		}
545
		$this->setEntity(null);
546
		$out .= $this->Html->useTag('formend');
547
 
548
		$this->_View->modelScope = false;
549
		$this->requestType = null;
550
		return $out;
551
	}
552
 
553
/**
554
 * Generates a hidden field with a security hash based on the fields used in
555
 * the form.
556
 *
557
 * If $secureAttributes is set, these html attributes will be merged into
558
 * the hidden input tags generated for the Security Component. This is
559
 * especially useful to set HTML5 attributes like 'form'.
560
 *
561
 * @param array|null $fields If set specifies the list of fields to use when
562
 *    generating the hash, else $this->fields is being used.
563
 * @param array $secureAttributes will be passed as html attributes into the hidden
564
 *    input elements generated for the Security Component.
565
 * @return string A hidden input field with a security hash
566
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::secure
567
 */
568
	public function secure($fields = array(), $secureAttributes = array()) {
569
		if (!isset($this->request['_Token']) || empty($this->request['_Token'])) {
570
			return;
571
		}
572
		$locked = array();
573
		$unlockedFields = $this->_unlockedFields;
574
 
575
		foreach ($fields as $key => $value) {
576
			if (!is_int($key)) {
577
				$locked[$key] = $value;
578
				unset($fields[$key]);
579
			}
580
		}
581
 
582
		sort($unlockedFields, SORT_STRING);
583
		sort($fields, SORT_STRING);
584
		ksort($locked, SORT_STRING);
585
		$fields += $locked;
586
 
587
		$locked = implode(array_keys($locked), '|');
588
		$unlocked = implode($unlockedFields, '|');
589
		$hashParts = array(
590
			$this->_lastAction,
591
			serialize($fields),
592
			$unlocked,
593
			Configure::read('Security.salt')
594
		);
595
		$fields = Security::hash(implode('', $hashParts), 'sha1');
596
 
597
		$tokenFields = array_merge($secureAttributes, array(
598
			'value' => urlencode($fields . ':' . $locked),
599
			'id' => 'TokenFields' . mt_rand(),
600
		));
601
		$out = $this->hidden('_Token.fields', $tokenFields);
602
		$tokenUnlocked = array_merge($secureAttributes, array(
603
			'value' => urlencode($unlocked),
604
			'id' => 'TokenUnlocked' . mt_rand(),
605
		));
606
		$out .= $this->hidden('_Token.unlocked', $tokenUnlocked);
607
		return $this->Html->useTag('hiddenblock', $out);
608
	}
609
 
610
/**
611
 * Add to or get the list of fields that are currently unlocked.
612
 * Unlocked fields are not included in the field hash used by SecurityComponent
613
 * unlocking a field once its been added to the list of secured fields will remove
614
 * it from the list of fields.
615
 *
616
 * @param string $name The dot separated name for the field.
617
 * @return mixed Either null, or the list of fields.
618
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::unlockField
619
 */
620
	public function unlockField($name = null) {
621
		if ($name === null) {
622
			return $this->_unlockedFields;
623
		}
624
		if (!in_array($name, $this->_unlockedFields)) {
625
			$this->_unlockedFields[] = $name;
626
		}
627
		$index = array_search($name, $this->fields);
628
		if ($index !== false) {
629
			unset($this->fields[$index]);
630
		}
631
		unset($this->fields[$name]);
632
	}
633
 
634
/**
635
 * Determine which fields of a form should be used for hash.
636
 * Populates $this->fields
637
 *
638
 * @param bool $lock Whether this field should be part of the validation
639
 *     or excluded as part of the unlockedFields.
640
 * @param string|array $field Reference to field to be secured. Should be dot separated to indicate nesting.
641
 * @param mixed $value Field value, if value should not be tampered with.
642
 * @return void
643
 */
644
	protected function _secure($lock, $field = null, $value = null) {
645
		if (!$field) {
646
			$field = $this->entity();
647
		} elseif (is_string($field)) {
648
			$field = Hash::filter(explode('.', $field));
649
		}
650
 
651
		foreach ($this->_unlockedFields as $unlockField) {
652
			$unlockParts = explode('.', $unlockField);
653
			if (array_values(array_intersect($field, $unlockParts)) === $unlockParts) {
654
				return;
655
			}
656
		}
657
 
658
		$field = implode('.', $field);
659
		$field = preg_replace('/(\.\d+)+$/', '', $field);
660
 
661
		if ($lock) {
662
			if (!in_array($field, $this->fields)) {
663
				if ($value !== null) {
664
					return $this->fields[$field] = $value;
665
				}
666
				$this->fields[] = $field;
667
			}
668
		} else {
669
			$this->unlockField($field);
670
		}
671
	}
672
 
673
/**
674
 * Returns true if there is an error for the given field, otherwise false
675
 *
676
 * @param string $field This should be "Modelname.fieldname"
677
 * @return bool If there are errors this method returns true, else false.
678
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::isFieldError
679
 */
680
	public function isFieldError($field) {
681
		$this->setEntity($field);
682
		return (bool)$this->tagIsInvalid();
683
	}
684
 
685
/**
686
 * Returns a formatted error message for given FORM field, NULL if no errors.
687
 *
688
 * ### Options:
689
 *
690
 * - `escape` boolean - Whether or not to html escape the contents of the error.
691
 * - `wrap` mixed - Whether or not the error message should be wrapped in a div. If a
692
 *   string, will be used as the HTML tag to use.
693
 * - `class` string - The class name for the error message
694
 *
695
 * @param string $field A field name, like "Modelname.fieldname"
696
 * @param string|array $text Error message as string or array of messages.
697
 *   If array contains `attributes` key it will be used as options for error container
698
 * @param array $options Rendering options for <div /> wrapper tag
699
 * @return string If there are errors this method returns an error message, otherwise null.
700
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::error
701
 */
702
	public function error($field, $text = null, $options = array()) {
703
		$defaults = array('wrap' => true, 'class' => 'error-message', 'escape' => true);
704
		$options += $defaults;
705
		$this->setEntity($field);
706
 
707
		$error = $this->tagIsInvalid();
708
		if ($error === false) {
709
			return null;
710
		}
711
		if (is_array($text)) {
712
			if (isset($text['attributes']) && is_array($text['attributes'])) {
713
				$options = array_merge($options, $text['attributes']);
714
				unset($text['attributes']);
715
			}
716
			$tmp = array();
717
			foreach ($error as &$e) {
718
				if (isset($text[$e])) {
719
					$tmp[] = $text[$e];
720
				} else {
721
					$tmp[] = $e;
722
				}
723
			}
724
			$text = $tmp;
725
		}
726
 
727
		if ($text !== null) {
728
			$error = $text;
729
		}
730
		if (is_array($error)) {
731
			foreach ($error as &$e) {
732
				if (is_numeric($e)) {
733
					$e = __d('cake', 'Error in field %s', Inflector::humanize($this->field()));
734
				}
735
			}
736
		}
737
		if ($options['escape']) {
738
			$error = h($error);
739
			unset($options['escape']);
740
		}
741
		if (is_array($error)) {
742
			if (count($error) > 1) {
743
				$listParams = array();
744
				if (isset($options['listOptions'])) {
745
					if (is_string($options['listOptions'])) {
746
						$listParams[] = $options['listOptions'];
747
					} else {
748
						if (isset($options['listOptions']['itemOptions'])) {
749
							$listParams[] = $options['listOptions']['itemOptions'];
750
							unset($options['listOptions']['itemOptions']);
751
						} else {
752
							$listParams[] = array();
753
						}
754
						if (isset($options['listOptions']['tag'])) {
755
							$listParams[] = $options['listOptions']['tag'];
756
							unset($options['listOptions']['tag']);
757
						}
758
						array_unshift($listParams, $options['listOptions']);
759
					}
760
					unset($options['listOptions']);
761
				}
762
				array_unshift($listParams, $error);
763
				$error = call_user_func_array(array($this->Html, 'nestedList'), $listParams);
764
			} else {
765
				$error = array_pop($error);
766
			}
767
		}
768
		if ($options['wrap']) {
769
			$tag = is_string($options['wrap']) ? $options['wrap'] : 'div';
770
			unset($options['wrap']);
771
			return $this->Html->tag($tag, $error, $options);
772
		}
773
		return $error;
774
	}
775
 
776
/**
777
 * Returns a formatted LABEL element for HTML FORMs. Will automatically generate
778
 * a `for` attribute if one is not provided.
779
 *
780
 * ### Options
781
 *
782
 * - `for` - Set the for attribute, if its not defined the for attribute
783
 *   will be generated from the $fieldName parameter using
784
 *   FormHelper::domId().
785
 *
786
 * Examples:
787
 *
788
 * The text and for attribute are generated off of the fieldname
789
 *
790
 * {{{
791
 * echo $this->Form->label('Post.published');
792
 * <label for="PostPublished">Published</label>
793
 * }}}
794
 *
795
 * Custom text:
796
 *
797
 * {{{
798
 * echo $this->Form->label('Post.published', 'Publish');
799
 * <label for="PostPublished">Publish</label>
800
 * }}}
801
 *
802
 * Custom class name:
803
 *
804
 * {{{
805
 * echo $this->Form->label('Post.published', 'Publish', 'required');
806
 * <label for="PostPublished" class="required">Publish</label>
807
 * }}}
808
 *
809
 * Custom attributes:
810
 *
811
 * {{{
812
 * echo $this->Form->label('Post.published', 'Publish', array(
813
 *		'for' => 'post-publish'
814
 * ));
815
 * <label for="post-publish">Publish</label>
816
 * }}}
817
 *
818
 * @param string $fieldName This should be "Modelname.fieldname"
819
 * @param string $text Text that will appear in the label field. If
820
 *   $text is left undefined the text will be inflected from the
821
 *   fieldName.
822
 * @param array|string $options An array of HTML attributes, or a string, to be used as a class name.
823
 * @return string The formatted LABEL element
824
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::label
825
 */
826
	public function label($fieldName = null, $text = null, $options = array()) {
827
		if ($fieldName === null) {
828
			$fieldName = implode('.', $this->entity());
829
		}
830
 
831
		if ($text === null) {
832
			if (strpos($fieldName, '.') !== false) {
833
				$fieldElements = explode('.', $fieldName);
834
				$text = array_pop($fieldElements);
835
			} else {
836
				$text = $fieldName;
837
			}
838
			if (substr($text, -3) === '_id') {
839
				$text = substr($text, 0, -3);
840
			}
841
			$text = __(Inflector::humanize(Inflector::underscore($text)));
842
		}
843
 
844
		if (is_string($options)) {
845
			$options = array('class' => $options);
846
		}
847
 
848
		if (isset($options['for'])) {
849
			$labelFor = $options['for'];
850
			unset($options['for']);
851
		} else {
852
			$labelFor = $this->domId($fieldName);
853
		}
854
 
855
		return $this->Html->useTag('label', $labelFor, $options, $text);
856
	}
857
 
858
/**
859
 * Generate a set of inputs for `$fields`. If $fields is null the fields of current model
860
 * will be used.
861
 *
862
 * You can customize individual inputs through `$fields`.
863
 * {{{
864
 *	$this->Form->inputs(array(
865
 *		'name' => array('label' => 'custom label')
866
 *	));
867
 * }}}
868
 *
869
 * In addition to controller fields output, `$fields` can be used to control legend
870
 * and fieldset rendering.
871
 * `$this->Form->inputs('My legend');` Would generate an input set with a custom legend.
872
 * Passing `fieldset` and `legend` key in `$fields` array has been deprecated since 2.3,
873
 * for more fine grained control use the `fieldset` and `legend` keys in `$options` param.
874
 *
875
 * @param array $fields An array of fields to generate inputs for, or null.
876
 * @param array $blacklist A simple array of fields to not create inputs for.
877
 * @param array $options Options array. Valid keys are:
878
 * - `fieldset` Set to false to disable the fieldset. If a string is supplied it will be used as
879
 *    the class name for the fieldset element.
880
 * - `legend` Set to false to disable the legend for the generated input set. Or supply a string
881
 *    to customize the legend text.
882
 * @return string Completed form inputs.
883
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::inputs
884
 */
885
	public function inputs($fields = null, $blacklist = null, $options = array()) {
886
		$fieldset = $legend = true;
887
		$modelFields = array();
888
		$model = $this->model();
889
		if ($model) {
890
			$modelFields = array_keys((array)$this->_introspectModel($model, 'fields'));
891
		}
892
		if (is_array($fields)) {
893
			if (array_key_exists('legend', $fields) && !in_array('legend', $modelFields)) {
894
				$legend = $fields['legend'];
895
				unset($fields['legend']);
896
			}
897
 
898
			if (isset($fields['fieldset']) && !in_array('fieldset', $modelFields)) {
899
				$fieldset = $fields['fieldset'];
900
				unset($fields['fieldset']);
901
			}
902
		} elseif ($fields !== null) {
903
			$fieldset = $legend = $fields;
904
			if (!is_bool($fieldset)) {
905
				$fieldset = true;
906
			}
907
			$fields = array();
908
		}
909
 
910
		if (isset($options['legend'])) {
911
			$legend = $options['legend'];
912
		}
913
		if (isset($options['fieldset'])) {
914
			$fieldset = $options['fieldset'];
915
		}
916
 
917
		if (empty($fields)) {
918
			$fields = $modelFields;
919
		}
920
 
921
		if ($legend === true) {
922
			$actionName = __d('cake', 'New %s');
923
			$isEdit = (
924
				strpos($this->request->params['action'], 'update') !== false ||
925
				strpos($this->request->params['action'], 'edit') !== false
926
			);
927
			if ($isEdit) {
928
				$actionName = __d('cake', 'Edit %s');
929
			}
930
			$modelName = Inflector::humanize(Inflector::underscore($model));
931
			$legend = sprintf($actionName, __($modelName));
932
		}
933
 
934
		$out = null;
935
		foreach ($fields as $name => $options) {
936
			if (is_numeric($name) && !is_array($options)) {
937
				$name = $options;
938
				$options = array();
939
			}
940
			$entity = explode('.', $name);
941
			$blacklisted = (
942
				is_array($blacklist) &&
943
				(in_array($name, $blacklist) || in_array(end($entity), $blacklist))
944
			);
945
			if ($blacklisted) {
946
				continue;
947
			}
948
			$out .= $this->input($name, $options);
949
		}
950
 
951
		if (is_string($fieldset)) {
952
			$fieldsetClass = sprintf(' class="%s"', $fieldset);
953
		} else {
954
			$fieldsetClass = '';
955
		}
956
 
957
		if ($fieldset) {
958
			if ($legend) {
959
				$out = $this->Html->useTag('legend', $legend) . $out;
960
			}
961
			$out = $this->Html->useTag('fieldset', $fieldsetClass, $out);
962
		}
963
		return $out;
964
	}
965
 
966
/**
967
 * Generates a form input element complete with label and wrapper div
968
 *
969
 * ### Options
970
 *
971
 * See each field type method for more information. Any options that are part of
972
 * $attributes or $options for the different **type** methods can be included in `$options` for input().i
973
 * Additionally, any unknown keys that are not in the list below, or part of the selected type's options
974
 * will be treated as a regular html attribute for the generated input.
975
 *
976
 * - `type` - Force the type of widget you want. e.g. `type => 'select'`
977
 * - `label` - Either a string label, or an array of options for the label. See FormHelper::label().
978
 * - `div` - Either `false` to disable the div, or an array of options for the div.
979
 *	See HtmlHelper::div() for more options.
980
 * - `options` - For widgets that take options e.g. radio, select.
981
 * - `error` - Control the error message that is produced. Set to `false` to disable any kind of error reporting (field
982
 *    error and error messages).
983
 * - `errorMessage` - Boolean to control rendering error messages (field error will still occur).
984
 * - `empty` - String or boolean to enable empty select box options.
985
 * - `before` - Content to place before the label + input.
986
 * - `after` - Content to place after the label + input.
987
 * - `between` - Content to place between the label + input.
988
 * - `format` - Format template for element order. Any element that is not in the array, will not be in the output.
989
 *	- Default input format order: array('before', 'label', 'between', 'input', 'after', 'error')
990
 *	- Default checkbox format order: array('before', 'input', 'between', 'label', 'after', 'error')
991
 *	- Hidden input will not be formatted
992
 *	- Radio buttons cannot have the order of input and label elements controlled with these settings.
993
 *
994
 * @param string $fieldName This should be "Modelname.fieldname"
995
 * @param array $options Each type of input takes different options.
996
 * @return string Completed form widget.
997
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#creating-form-elements
998
 */
999
	public function input($fieldName, $options = array()) {
1000
		$this->setEntity($fieldName);
1001
		$options = $this->_parseOptions($options);
1002
 
1003
		$divOptions = $this->_divOptions($options);
1004
		unset($options['div']);
1005
 
1006
		if ($options['type'] === 'radio' && isset($options['options'])) {
1007
			$radioOptions = (array)$options['options'];
1008
			unset($options['options']);
1009
		}
1010
 
1011
		$label = $this->_getLabel($fieldName, $options);
1012
		if ($options['type'] !== 'radio') {
1013
			unset($options['label']);
1014
		}
1015
 
1016
		$error = $this->_extractOption('error', $options, null);
1017
		unset($options['error']);
1018
 
1019
		$errorMessage = $this->_extractOption('errorMessage', $options, true);
1020
		unset($options['errorMessage']);
1021
 
1022
		$selected = $this->_extractOption('selected', $options, null);
1023
		unset($options['selected']);
1024
 
1025
		if ($options['type'] === 'datetime' || $options['type'] === 'date' || $options['type'] === 'time') {
1026
			$dateFormat = $this->_extractOption('dateFormat', $options, 'MDY');
1027
			$timeFormat = $this->_extractOption('timeFormat', $options, 12);
1028
			unset($options['dateFormat'], $options['timeFormat']);
1029
		}
1030
 
1031
		$type = $options['type'];
1032
		$out = array('before' => $options['before'], 'label' => $label, 'between' => $options['between'], 'after' => $options['after']);
1033
		$format = $this->_getFormat($options);
1034
 
1035
		unset($options['type'], $options['before'], $options['between'], $options['after'], $options['format']);
1036
 
1037
		$out['error'] = null;
1038
		if ($type !== 'hidden' && $error !== false) {
1039
			$errMsg = $this->error($fieldName, $error);
1040
			if ($errMsg) {
1041
				$divOptions = $this->addClass($divOptions, 'error');
1042
				if ($errorMessage) {
1043
					$out['error'] = $errMsg;
1044
				}
1045
			}
1046
		}
1047
 
1048
		if ($type === 'radio' && isset($out['between'])) {
1049
			$options['between'] = $out['between'];
1050
			$out['between'] = null;
1051
		}
1052
		$out['input'] = $this->_getInput(compact('type', 'fieldName', 'options', 'radioOptions', 'selected', 'dateFormat', 'timeFormat'));
1053
 
1054
		$output = '';
1055
		foreach ($format as $element) {
1056
			$output .= $out[$element];
1057
		}
1058
 
1059
		if (!empty($divOptions['tag'])) {
1060
			$tag = $divOptions['tag'];
1061
			unset($divOptions['tag']);
1062
			$output = $this->Html->tag($tag, $output, $divOptions);
1063
		}
1064
		return $output;
1065
	}
1066
 
1067
/**
1068
 * Generates an input element
1069
 *
1070
 * @param array $args The options for the input element
1071
 * @return string The generated input element
1072
 */
1073
	protected function _getInput($args) {
1074
		extract($args);
1075
		switch ($type) {
1076
			case 'hidden':
1077
				return $this->hidden($fieldName, $options);
1078
			case 'checkbox':
1079
				return $this->checkbox($fieldName, $options);
1080
			case 'radio':
1081
				return $this->radio($fieldName, $radioOptions, $options);
1082
			case 'file':
1083
				return $this->file($fieldName, $options);
1084
			case 'select':
1085
				$options += array('options' => array(), 'value' => $selected);
1086
				$list = $options['options'];
1087
				unset($options['options']);
1088
				return $this->select($fieldName, $list, $options);
1089
			case 'time':
1090
				$options['value'] = $selected;
1091
				return $this->dateTime($fieldName, null, $timeFormat, $options);
1092
			case 'date':
1093
				$options['value'] = $selected;
1094
				return $this->dateTime($fieldName, $dateFormat, null, $options);
1095
			case 'datetime':
1096
				$options['value'] = $selected;
1097
				return $this->dateTime($fieldName, $dateFormat, $timeFormat, $options);
1098
			case 'textarea':
1099
				return $this->textarea($fieldName, $options + array('cols' => '30', 'rows' => '6'));
1100
			case 'url':
1101
				return $this->text($fieldName, array('type' => 'url') + $options);
1102
			default:
1103
				return $this->{$type}($fieldName, $options);
1104
		}
1105
	}
1106
 
1107
/**
1108
 * Generates input options array
1109
 *
1110
 * @param array $options Options list.
1111
 * @return array Options
1112
 */
1113
	protected function _parseOptions($options) {
1114
		$options = array_merge(
1115
			array('before' => null, 'between' => null, 'after' => null, 'format' => null),
1116
			$this->_inputDefaults,
1117
			$options
1118
		);
1119
 
1120
		if (!isset($options['type'])) {
1121
			$options = $this->_magicOptions($options);
1122
		}
1123
 
1124
		if (in_array($options['type'], array('radio', 'select'))) {
1125
			$options = $this->_optionsOptions($options);
1126
		}
1127
 
1128
		if (isset($options['rows']) || isset($options['cols'])) {
1129
			$options['type'] = 'textarea';
1130
		}
1131
 
1132
		if ($options['type'] === 'datetime' || $options['type'] === 'date' || $options['type'] === 'time' || $options['type'] === 'select') {
1133
			$options += array('empty' => false);
1134
		}
1135
		return $options;
1136
	}
1137
 
1138
/**
1139
 * Generates list of options for multiple select
1140
 *
1141
 * @param array $options Options list.
1142
 * @return array
1143
 */
1144
	protected function _optionsOptions($options) {
1145
		if (isset($options['options'])) {
1146
			return $options;
1147
		}
1148
		$varName = Inflector::variable(
1149
			Inflector::pluralize(preg_replace('/_id$/', '', $this->field()))
1150
		);
1151
		$varOptions = $this->_View->get($varName);
1152
		if (!is_array($varOptions)) {
1153
			return $options;
1154
		}
1155
		if ($options['type'] !== 'radio') {
1156
			$options['type'] = 'select';
1157
		}
1158
		$options['options'] = $varOptions;
1159
		return $options;
1160
	}
1161
 
1162
/**
1163
 * Magically set option type and corresponding options
1164
 *
1165
 * @param array $options Options list.
1166
 * @return array
1167
 */
1168
	protected function _magicOptions($options) {
1169
		$modelKey = $this->model();
1170
		$fieldKey = $this->field();
1171
		$options['type'] = 'text';
1172
		if (isset($options['options'])) {
1173
			$options['type'] = 'select';
1174
		} elseif (in_array($fieldKey, array('psword', 'passwd', 'password'))) {
1175
			$options['type'] = 'password';
1176
		} elseif (in_array($fieldKey, array('tel', 'telephone', 'phone'))) {
1177
			$options['type'] = 'tel';
1178
		} elseif ($fieldKey === 'email') {
1179
			$options['type'] = 'email';
1180
		} elseif (isset($options['checked'])) {
1181
			$options['type'] = 'checkbox';
1182
		} elseif ($fieldDef = $this->_introspectModel($modelKey, 'fields', $fieldKey)) {
1183
			$type = $fieldDef['type'];
1184
			$primaryKey = $this->fieldset[$modelKey]['key'];
1185
			$map = array(
1186
				'string' => 'text', 'datetime' => 'datetime',
1187
				'boolean' => 'checkbox', 'timestamp' => 'datetime',
1188
				'text' => 'textarea', 'time' => 'time',
1189
				'date' => 'date', 'float' => 'number',
1190
				'integer' => 'number', 'decimal' => 'number',
1191
				'binary' => 'file'
1192
			);
1193
 
1194
			if (isset($this->map[$type])) {
1195
				$options['type'] = $this->map[$type];
1196
			} elseif (isset($map[$type])) {
1197
				$options['type'] = $map[$type];
1198
			}
1199
			if ($fieldKey === $primaryKey) {
1200
				$options['type'] = 'hidden';
1201
			}
1202
			if (
1203
				$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
		$options = $this->_maxLength($options);
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
			$options['type'] !== 'select'
1290
		);
1291
		if ($autoLength &&
1292
			in_array($options['type'], array('text', 'email', 'tel', 'url', 'search'))
1293
		) {
1294
			$options['maxlength'] = $fieldDef['length'];
1295
		}
1296
		return $options;
1297
	}
1298
 
1299
/**
1300
 * Generate div options for input
1301
 *
1302
 * @param array $options Options list.
1303
 * @return array
1304
 */
1305
	protected function _divOptions($options) {
1306
		if ($options['type'] === 'hidden') {
1307
			return array();
1308
		}
1309
		$div = $this->_extractOption('div', $options, true);
1310
		if (!$div) {
1311
			return array();
1312
		}
1313
 
1314
		$divOptions = array('class' => 'input');
1315
		$divOptions = $this->addClass($divOptions, $options['type']);
1316
		if (is_string($div)) {
1317
			$divOptions['class'] = $div;
1318
		} elseif (is_array($div)) {
1319
			$divOptions = array_merge($divOptions, $div);
1320
		}
1321
		if (
1322
			$this->_extractOption('required', $options) !== false &&
1323
			$this->_introspectModel($this->model(), 'validates', $this->field())
1324
		) {
1325
			$divOptions = $this->addClass($divOptions, 'required');
1326
		}
1327
		if (!isset($divOptions['tag'])) {
1328
			$divOptions['tag'] = 'div';
1329
		}
1330
		return $divOptions;
1331
	}
1332
 
1333
/**
1334
 * Extracts a single option from an options array.
1335
 *
1336
 * @param string $name The name of the option to pull out.
1337
 * @param array $options The array of options you want to extract.
1338
 * @param mixed $default The default option value
1339
 * @return mixed the contents of the option or default
1340
 */
1341
	protected function _extractOption($name, $options, $default = null) {
1342
		if (array_key_exists($name, $options)) {
1343
			return $options[$name];
1344
		}
1345
		return $default;
1346
	}
1347
 
1348
/**
1349
 * Generate a label for an input() call.
1350
 *
1351
 * $options can contain a hash of id overrides. These overrides will be
1352
 * used instead of the generated values if present.
1353
 *
1354
 * @param string $fieldName Field name.
1355
 * @param string|array $label Label text or array with text and options.
1356
 * @param array $options Options for the label element. 'NONE' option is
1357
 *   deprecated and will be removed in 3.0
1358
 * @return string Generated label element
1359
 */
1360
	protected function _inputLabel($fieldName, $label, $options) {
1361
		$labelAttributes = $this->domId(array(), 'for');
1362
		$idKey = null;
1363
		if ($options['type'] === 'date' || $options['type'] === 'datetime') {
1364
			$firstInput = 'M';
1365
			if (
1366
				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 (
1448
			(!isset($options['checked']) && !empty($value) && $value == $options['value']) ||
1449
			!empty($options['checked'])
1450
		) {
1451
			$options['checked'] = 'checked';
1452
		}
1453
		if ($options['hiddenField']) {
1454
			$hiddenOptions = array(
1455
				'id' => $options['id'] . '_',
1456
				'name' => $options['name'],
1457
				'value' => ($options['hiddenField'] !== true ? $options['hiddenField'] : '0'),
1458
				'form' => isset($options['form']) ? $options['form'] : null,
1459
				'secure' => false,
1460
			);
1461
			if (isset($options['disabled']) && $options['disabled']) {
1462
				$hiddenOptions['disabled'] = 'disabled';
1463
			}
1464
			$output = $this->hidden($fieldName, $hiddenOptions);
1465
		}
1466
		unset($options['hiddenField']);
1467
 
1468
		return $output . $this->Html->useTag('checkbox', $options['name'], array_diff_key($options, array('name' => null)));
1469
	}
1470
 
1471
/**
1472
 * Creates a set of radio widgets. Will create a legend and fieldset
1473
 * by default. Use $options to control this
1474
 *
1475
 * ### Attributes:
1476
 *
1477
 * - `separator` - define the string in between the radio buttons
1478
 * - `between` - the string between legend and input set or array of strings to insert
1479
 *    strings between each input block
1480
 * - `legend` - control whether or not the widget set has a fieldset & legend
1481
 * - `value` - indicate a value that is should be checked
1482
 * - `label` - boolean to indicate whether or not labels for widgets show be displayed
1483
 * - `hiddenField` - boolean to indicate if you want the results of radio() to include
1484
 *    a hidden input with a value of ''. This is useful for creating radio sets that non-continuous
1485
 * - `disabled` - Set to `true` or `disabled` to disable all the radio buttons.
1486
 * - `empty` - Set to `true` to create a input with the value '' as the first option. When `true`
1487
 *   the radio label will be 'empty'. Set this option to a string to control the label value.
1488
 *
1489
 * @param string $fieldName Name of a field, like this "Modelname.fieldname"
1490
 * @param array $options Radio button options array.
1491
 * @param array $attributes Array of HTML attributes, and special attributes above.
1492
 * @return string Completed radio widget set.
1493
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#options-for-select-checkbox-and-radio-inputs
1494
 */
1495
	public function radio($fieldName, $options = array(), $attributes = array()) {
1496
		$attributes = $this->_initInputField($fieldName, $attributes);
1497
 
1498
		$showEmpty = $this->_extractOption('empty', $attributes);
1499
		if ($showEmpty) {
1500
			$showEmpty = ($showEmpty === true) ? __d('cake', 'empty') : $showEmpty;
1501
			$options = array('' => $showEmpty) + $options;
1502
		}
1503
		unset($attributes['empty']);
1504
 
1505
		$legend = false;
1506
		if (isset($attributes['legend'])) {
1507
			$legend = $attributes['legend'];
1508
			unset($attributes['legend']);
1509
		} elseif (count($options) > 1) {
1510
			$legend = __(Inflector::humanize($this->field()));
1511
		}
1512
 
1513
		$label = true;
1514
		if (isset($attributes['label'])) {
1515
			$label = $attributes['label'];
1516
			unset($attributes['label']);
1517
		}
1518
 
1519
		$separator = null;
1520
		if (isset($attributes['separator'])) {
1521
			$separator = $attributes['separator'];
1522
			unset($attributes['separator']);
1523
		}
1524
 
1525
		$between = null;
1526
		if (isset($attributes['between'])) {
1527
			$between = $attributes['between'];
1528
			unset($attributes['between']);
1529
		}
1530
 
1531
		$value = null;
1532
		if (isset($attributes['value'])) {
1533
			$value = $attributes['value'];
1534
		} else {
1535
			$value = $this->value($fieldName);
1536
		}
1537
 
1538
		$disabled = array();
1539
		if (isset($attributes['disabled'])) {
1540
			$disabled = $attributes['disabled'];
1541
		}
1542
 
1543
		$out = array();
1544
 
1545
		$hiddenField = isset($attributes['hiddenField']) ? $attributes['hiddenField'] : true;
1546
		unset($attributes['hiddenField']);
1547
 
1548
		if (isset($value) && is_bool($value)) {
1549
			$value = $value ? 1 : 0;
1550
		}
1551
 
1552
		$this->_domIdSuffixes = array();
1553
		foreach ($options as $optValue => $optTitle) {
1554
			$optionsHere = array('value' => $optValue, 'disabled' => false);
1555
 
1556
			if (isset($value) && strval($optValue) === strval($value)) {
1557
				$optionsHere['checked'] = 'checked';
1558
			}
1559
			$isNumeric = is_numeric($optValue);
1560
			if ($disabled && (!is_array($disabled) || in_array((string)$optValue, $disabled, !$isNumeric))) {
1561
				$optionsHere['disabled'] = true;
1562
			}
1563
			$tagName = $attributes['id'] . $this->domIdSuffix($optValue);
1564
 
1565
			if ($label) {
1566
				$labelOpts = is_array($label) ? $label : array();
1567
				$labelOpts += array('for' => $tagName);
1568
				$optTitle = $this->label($tagName, $optTitle, $labelOpts);
1569
			}
1570
 
1571
			if (is_array($between)) {
1572
				$optTitle .= array_shift($between);
1573
			}
1574
			$allOptions = array_merge($attributes, $optionsHere);
1575
			$out[] = $this->Html->useTag('radio', $attributes['name'], $tagName,
1576
				array_diff_key($allOptions, array('name' => null, 'type' => null, 'id' => null)),
1577
				$optTitle
1578
			);
1579
		}
1580
		$hidden = null;
1581
 
1582
		if ($hiddenField) {
1583
			if (!isset($value) || $value === '') {
1584
				$hidden = $this->hidden($fieldName, array(
1585
					'form' => isset($attributes['form']) ? $attributes['form'] : null,
1586
					'id' => $attributes['id'] . '_',
1587
					'value' => '',
1588
					'name' => $attributes['name']
1589
				));
1590
			}
1591
		}
1592
		$out = $hidden . implode($separator, $out);
1593
 
1594
		if (is_array($between)) {
1595
			$between = '';
1596
		}
1597
		if ($legend) {
1598
			$out = $this->Html->useTag('fieldset', '', $this->Html->useTag('legend', $legend) . $between . $out);
1599
		}
1600
		return $out;
1601
	}
1602
 
1603
/**
1604
 * Missing method handler - implements various simple input types. Is used to create inputs
1605
 * of various types. e.g. `$this->Form->text();` will create `<input type="text" />` while
1606
 * `$this->Form->range();` will create `<input type="range" />`
1607
 *
1608
 * ### Usage
1609
 *
1610
 * `$this->Form->search('User.query', array('value' => 'test'));`
1611
 *
1612
 * Will make an input like:
1613
 *
1614
 * `<input type="search" id="UserQuery" name="data[User][query]" value="test" />`
1615
 *
1616
 * The first argument to an input type should always be the fieldname, in `Model.field` format.
1617
 * The second argument should always be an array of attributes for the input.
1618
 *
1619
 * @param string $method Method name / input type to make.
1620
 * @param array $params Parameters for the method call
1621
 * @return string Formatted input method.
1622
 * @throws CakeException When there are no params for the method call.
1623
 */
1624
	public function __call($method, $params) {
1625
		$options = array();
1626
		if (empty($params)) {
1627
			throw new CakeException(__d('cake_dev', 'Missing field name for FormHelper::%s', $method));
1628
		}
1629
		if (isset($params[1])) {
1630
			$options = $params[1];
1631
		}
1632
		if (!isset($options['type'])) {
1633
			$options['type'] = $method;
1634
		}
1635
		$options = $this->_initInputField($params[0], $options);
1636
		return $this->Html->useTag('input', $options['name'], array_diff_key($options, array('name' => null)));
1637
	}
1638
 
1639
/**
1640
 * Creates a textarea widget.
1641
 *
1642
 * ### Options:
1643
 *
1644
 * - `escape` - Whether or not the contents of the textarea should be escaped. Defaults to true.
1645
 *
1646
 * @param string $fieldName Name of a field, in the form "Modelname.fieldname"
1647
 * @param array $options Array of HTML attributes, and special options above.
1648
 * @return string A generated HTML text input element
1649
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::textarea
1650
 */
1651
	public function textarea($fieldName, $options = array()) {
1652
		$options = $this->_initInputField($fieldName, $options);
1653
		$value = null;
1654
 
1655
		if (array_key_exists('value', $options)) {
1656
			$value = $options['value'];
1657
			if (!array_key_exists('escape', $options) || $options['escape'] !== false) {
1658
				$value = h($value);
1659
			}
1660
			unset($options['value']);
1661
		}
1662
		return $this->Html->useTag('textarea', $options['name'], array_diff_key($options, array('type' => null, 'name' => null)), $value);
1663
	}
1664
 
1665
/**
1666
 * Creates a hidden input field.
1667
 *
1668
 * @param string $fieldName Name of a field, in the form of "Modelname.fieldname"
1669
 * @param array $options Array of HTML attributes.
1670
 * @return string A generated hidden input
1671
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::hidden
1672
 */
1673
	public function hidden($fieldName, $options = array()) {
1674
		$options += array('required' => false, 'secure' => true);
1675
 
1676
		$secure = $options['secure'];
1677
		unset($options['secure']);
1678
 
1679
		$options = $this->_initInputField($fieldName, array_merge(
1680
			$options, array('secure' => self::SECURE_SKIP)
1681
		));
1682
 
1683
		if ($secure === true) {
1684
			$this->_secure(true, null, '' . $options['value']);
1685
		}
1686
 
1687
		return $this->Html->useTag('hidden', $options['name'], array_diff_key($options, array('name' => null)));
1688
	}
1689
 
1690
/**
1691
 * Creates file input widget.
1692
 *
1693
 * @param string $fieldName Name of a field, in the form "Modelname.fieldname"
1694
 * @param array $options Array of HTML attributes.
1695
 * @return string A generated file input.
1696
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::file
1697
 */
1698
	public function file($fieldName, $options = array()) {
1699
		$options += array('secure' => true);
1700
		$secure = $options['secure'];
1701
		$options['secure'] = self::SECURE_SKIP;
1702
 
1703
		$options = $this->_initInputField($fieldName, $options);
1704
		$field = $this->entity();
1705
 
1706
		foreach (array('name', 'type', 'tmp_name', 'error', 'size') as $suffix) {
1707
			$this->_secure($secure, array_merge($field, array($suffix)));
1708
		}
1709
 
1710
		$exclude = array('name' => null, 'value' => null);
1711
		return $this->Html->useTag('file', $options['name'], array_diff_key($options, $exclude));
1712
	}
1713
 
1714
/**
1715
 * Creates a `<button>` tag. The type attribute defaults to `type="submit"`
1716
 * You can change it to a different value by using `$options['type']`.
1717
 *
1718
 * ### Options:
1719
 *
1720
 * - `escape` - HTML entity encode the $title of the button. Defaults to false.
1721
 *
1722
 * @param string $title The button's caption. Not automatically HTML encoded
1723
 * @param array $options Array of options and HTML attributes.
1724
 * @return string A HTML button tag.
1725
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::button
1726
 */
1727
	public function button($title, $options = array()) {
1728
		$options += array('type' => 'submit', 'escape' => false, 'secure' => false);
1729
		if ($options['escape']) {
1730
			$title = h($title);
1731
		}
1732
		if (isset($options['name'])) {
1733
			$name = str_replace(array('[', ']'), array('.', ''), $options['name']);
1734
			$this->_secure($options['secure'], $name);
1735
		}
1736
		return $this->Html->useTag('button', $options, $title);
1737
	}
1738
 
1739
/**
1740
 * Create a `<button>` tag with a surrounding `<form>` that submits via POST.
1741
 *
1742
 * This method creates a `<form>` element. So do not use this method in an already opened form.
1743
 * Instead use FormHelper::submit() or FormHelper::button() to create buttons inside opened forms.
1744
 *
1745
 * ### Options:
1746
 *
1747
 * - `data` - Array with key/value to pass in input hidden
1748
 * - Other options is the same of button method.
1749
 *
1750
 * @param string $title The button's caption. Not automatically HTML encoded
1751
 * @param string|array $url URL as string or array
1752
 * @param array $options Array of options and HTML attributes.
1753
 * @return string A HTML button tag.
1754
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::postButton
1755
 */
1756
	public function postButton($title, $url, $options = array()) {
1757
		$out = $this->create(false, array('id' => false, 'url' => $url));
1758
		if (isset($options['data']) && is_array($options['data'])) {
1759
			foreach (Hash::flatten($options['data']) as $key => $value) {
1760
				$out .= $this->hidden($key, array('value' => $value, 'id' => false));
1761
			}
1762
			unset($options['data']);
1763
		}
1764
		$out .= $this->button($title, $options);
1765
		$out .= $this->end();
1766
		return $out;
1767
	}
1768
 
1769
/**
1770
 * Creates an HTML link, but access the URL using the method you specify (defaults to POST).
1771
 * Requires javascript to be enabled in browser.
1772
 *
1773
 * This method creates a `<form>` element. So do not use this method inside an existing form.
1774
 * Instead you should add a submit button using FormHelper::submit()
1775
 *
1776
 * ### Options:
1777
 *
1778
 * - `data` - Array with key/value to pass in input hidden
1779
 * - `method` - Request method to use. Set to 'delete' to simulate HTTP/1.1 DELETE request. Defaults to 'post'.
1780
 * - `confirm` - Can be used instead of $confirmMessage.
1781
 * - `inline` - Whether or not the associated form tag should be output inline.
1782
 *   Set to false to have the form tag appended to the 'postLink' view block.
1783
 *   Defaults to true.
1784
 * - `block` - Choose a custom block to append the form tag to. Using this option
1785
 *   will override the inline option.
1786
 * - Other options are the same of HtmlHelper::link() method.
1787
 * - The option `onclick` will be replaced.
1788
 *
1789
 * @param string $title The content to be wrapped by <a> tags.
1790
 * @param string|array $url Cake-relative URL or array of URL parameters, or external URL (starts with http://)
1791
 * @param array $options Array of HTML attributes.
1792
 * @param bool|string $confirmMessage JavaScript confirmation message.
1793
 * @return string An `<a />` element.
1794
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::postLink
1795
 */
1796
	public function postLink($title, $url = null, $options = array(), $confirmMessage = false) {
1797
		$options = (array)$options + array('inline' => true, 'block' => null);
1798
		if (!$options['inline'] && empty($options['block'])) {
1799
			$options['block'] = __FUNCTION__;
1800
		}
1801
		unset($options['inline']);
1802
 
1803
		$requestMethod = 'POST';
1804
		if (!empty($options['method'])) {
1805
			$requestMethod = strtoupper($options['method']);
1806
			unset($options['method']);
1807
		}
1808
		if (!empty($options['confirm'])) {
1809
			$confirmMessage = $options['confirm'];
1810
			unset($options['confirm']);
1811
		}
1812
 
1813
		$formName = str_replace('.', '', uniqid('post_', true));
1814
		$formUrl = $this->url($url);
1815
		$formOptions = array(
1816
			'name' => $formName,
1817
			'id' => $formName,
1818
			'style' => 'display:none;',
1819
			'method' => 'post',
1820
		);
1821
		if (isset($options['target'])) {
1822
			$formOptions['target'] = $options['target'];
1823
			unset($options['target']);
1824
		}
1825
 
1826
		$this->_lastAction($url);
1827
 
1828
		$out = $this->Html->useTag('form', $formUrl, $formOptions);
1829
		$out .= $this->Html->useTag('hidden', '_method', array(
1830
			'value' => $requestMethod
1831
		));
1832
		$out .= $this->_csrfField();
1833
 
1834
		$fields = array();
1835
		if (isset($options['data']) && is_array($options['data'])) {
1836
			foreach (Hash::flatten($options['data']) as $key => $value) {
1837
				$fields[$key] = $value;
1838
				$out .= $this->hidden($key, array('value' => $value, 'id' => false));
1839
			}
1840
			unset($options['data']);
1841
		}
1842
		$out .= $this->secure($fields);
1843
		$out .= $this->Html->useTag('formend');
1844
 
1845
		if ($options['block']) {
1846
			$this->_View->append($options['block'], $out);
1847
			$out = '';
1848
		}
1849
		unset($options['block']);
1850
 
1851
		$url = '#';
1852
		$onClick = 'document.' . $formName . '.submit();';
1853
		if ($confirmMessage) {
1854
			$options['onclick'] = $this->_confirm($confirmMessage, $onClick, '', $options);
1855
		} else {
1856
			$options['onclick'] = $onClick . ' ';
1857
		}
1858
		$options['onclick'] .= 'event.returnValue = false; return false;';
1859
 
1860
		$out .= $this->Html->link($title, $url, $options);
1861
		return $out;
1862
	}
1863
 
1864
/**
1865
 * Creates a submit button element. This method will generate `<input />` elements that
1866
 * can be used to submit, and reset forms by using $options. image submits can be created by supplying an
1867
 * image path for $caption.
1868
 *
1869
 * ### Options
1870
 *
1871
 * - `div` - Include a wrapping div?  Defaults to true. Accepts sub options similar to
1872
 *   FormHelper::input().
1873
 * - `before` - Content to include before the input.
1874
 * - `after` - Content to include after the input.
1875
 * - `type` - Set to 'reset' for reset inputs. Defaults to 'submit'
1876
 * - Other attributes will be assigned to the input element.
1877
 *
1878
 * ### Options
1879
 *
1880
 * - `div` - Include a wrapping div?  Defaults to true. Accepts sub options similar to
1881
 *   FormHelper::input().
1882
 * - Other attributes will be assigned to the input element.
1883
 *
1884
 * @param string $caption The label appearing on the button OR if string contains :// or the
1885
 *  extension .jpg, .jpe, .jpeg, .gif, .png use an image if the extension
1886
 *  exists, AND the first character is /, image is relative to webroot,
1887
 *  OR if the first character is not /, image is relative to webroot/img.
1888
 * @param array $options Array of options. See above.
1889
 * @return string A HTML submit button
1890
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::submit
1891
 */
1892
	public function submit($caption = null, $options = array()) {
1893
		if (!is_string($caption) && empty($caption)) {
1894
			$caption = __d('cake', 'Submit');
1895
		}
1896
		$out = null;
1897
		$div = true;
1898
 
1899
		if (isset($options['div'])) {
1900
			$div = $options['div'];
1901
			unset($options['div']);
1902
		}
1903
		$options += array('type' => 'submit', 'before' => null, 'after' => null, 'secure' => false);
1904
		$divOptions = array('tag' => 'div');
1905
 
1906
		if ($div === true) {
1907
			$divOptions['class'] = 'submit';
1908
		} elseif ($div === false) {
1909
			unset($divOptions);
1910
		} elseif (is_string($div)) {
1911
			$divOptions['class'] = $div;
1912
		} elseif (is_array($div)) {
1913
			$divOptions = array_merge(array('class' => 'submit', 'tag' => 'div'), $div);
1914
		}
1915
 
1916
		if (isset($options['name'])) {
1917
			$name = str_replace(array('[', ']'), array('.', ''), $options['name']);
1918
			$this->_secure($options['secure'], $name);
1919
		}
1920
		unset($options['secure']);
1921
 
1922
		$before = $options['before'];
1923
		$after = $options['after'];
1924
		unset($options['before'], $options['after']);
1925
 
1926
		$isUrl = strpos($caption, '://') !== false;
1927
		$isImage = preg_match('/\.(jpg|jpe|jpeg|gif|png|ico)$/', $caption);
1928
 
1929
		if ($isUrl || $isImage) {
1930
			$unlockFields = array('x', 'y');
1931
			if (isset($options['name'])) {
1932
				$unlockFields = array(
1933
					$options['name'] . '_x', $options['name'] . '_y'
1934
				);
1935
			}
1936
			foreach ($unlockFields as $ignore) {
1937
				$this->unlockField($ignore);
1938
			}
1939
		}
1940
 
1941
		if ($isUrl) {
1942
			unset($options['type']);
1943
			$tag = $this->Html->useTag('submitimage', $caption, $options);
1944
		} elseif ($isImage) {
1945
			unset($options['type']);
1946
			if ($caption{0} !== '/') {
1947
				$url = $this->webroot(Configure::read('App.imageBaseUrl') . $caption);
1948
			} else {
1949
				$url = $this->webroot(trim($caption, '/'));
1950
			}
1951
			$url = $this->assetTimestamp($url);
1952
			$tag = $this->Html->useTag('submitimage', $url, $options);
1953
		} else {
1954
			$options['value'] = $caption;
1955
			$tag = $this->Html->useTag('submit', $options);
1956
		}
1957
		$out = $before . $tag . $after;
1958
 
1959
		if (isset($divOptions)) {
1960
			$tag = $divOptions['tag'];
1961
			unset($divOptions['tag']);
1962
			$out = $this->Html->tag($tag, $out, $divOptions);
1963
		}
1964
		return $out;
1965
	}
1966
 
1967
/**
1968
 * Returns a formatted SELECT element.
1969
 *
1970
 * ### Attributes:
1971
 *
1972
 * - `showParents` - If included in the array and set to true, an additional option element
1973
 *   will be added for the parent of each option group. You can set an option with the same name
1974
 *   and it's key will be used for the value of the option.
1975
 * - `multiple` - show a multiple select box. If set to 'checkbox' multiple checkboxes will be
1976
 *   created instead.
1977
 * - `empty` - If true, the empty select option is shown. If a string,
1978
 *   that string is displayed as the empty element.
1979
 * - `escape` - If true contents of options will be HTML entity encoded. Defaults to true.
1980
 * - `value` The selected value of the input.
1981
 * - `class` - When using multiple = checkbox the class name to apply to the divs. Defaults to 'checkbox'.
1982
 * - `disabled` - Control the disabled attribute. When creating a select box, set to true to disable the
1983
 *   select box. When creating checkboxes, `true` will disable all checkboxes. You can also set disabled
1984
 *   to a list of values you want to disable when creating checkboxes.
1985
 *
1986
 * ### Using options
1987
 *
1988
 * A simple array will create normal options:
1989
 *
1990
 * {{{
1991
 * $options = array(1 => 'one', 2 => 'two);
1992
 * $this->Form->select('Model.field', $options));
1993
 * }}}
1994
 *
1995
 * While a nested options array will create optgroups with options inside them.
1996
 * {{{
1997
 * $options = array(
1998
 *  1 => 'bill',
1999
 *  'fred' => array(
2000
 *     2 => 'fred',
2001
 *     3 => 'fred jr.'
2002
 *  )
2003
 * );
2004
 * $this->Form->select('Model.field', $options);
2005
 * }}}
2006
 *
2007
 * In the above `2 => 'fred'` will not generate an option element. You should enable the `showParents`
2008
 * attribute to show the fred option.
2009
 *
2010
 * If you have multiple options that need to have the same value attribute, you can
2011
 * use an array of arrays to express this:
2012
 *
2013
 * {{{
2014
 * $options = array(
2015
 *  array('name' => 'United states', 'value' => 'USA'),
2016
 *  array('name' => 'USA', 'value' => 'USA'),
2017
 * );
2018
 * }}}
2019
 *
2020
 * @param string $fieldName Name attribute of the SELECT
2021
 * @param array $options Array of the OPTION elements (as 'value'=>'Text' pairs) to be used in the
2022
 *	SELECT element
2023
 * @param array $attributes The HTML attributes of the select element.
2024
 * @return string Formatted SELECT element
2025
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#options-for-select-checkbox-and-radio-inputs
2026
 */
2027
	public function select($fieldName, $options = array(), $attributes = array()) {
2028
		$select = array();
2029
		$style = null;
2030
		$tag = null;
2031
		$attributes += array(
2032
			'class' => null,
2033
			'escape' => true,
2034
			'secure' => true,
2035
			'empty' => '',
2036
			'showParents' => false,
2037
			'hiddenField' => true,
2038
			'disabled' => false
2039
		);
2040
 
2041
		$escapeOptions = $this->_extractOption('escape', $attributes);
2042
		$secure = $this->_extractOption('secure', $attributes);
2043
		$showEmpty = $this->_extractOption('empty', $attributes);
2044
		$showParents = $this->_extractOption('showParents', $attributes);
2045
		$hiddenField = $this->_extractOption('hiddenField', $attributes);
2046
		unset($attributes['escape'], $attributes['secure'], $attributes['empty'], $attributes['showParents'], $attributes['hiddenField']);
2047
		$id = $this->_extractOption('id', $attributes);
2048
 
2049
		$attributes = $this->_initInputField($fieldName, array_merge(
2050
			(array)$attributes, array('secure' => self::SECURE_SKIP)
2051
		));
2052
 
2053
		if (is_string($options) && isset($this->_options[$options])) {
2054
			$options = $this->_generateOptions($options);
2055
		} elseif (!is_array($options)) {
2056
			$options = array();
2057
		}
2058
		if (isset($attributes['type'])) {
2059
			unset($attributes['type']);
2060
		}
2061
 
2062
		if (!empty($attributes['multiple'])) {
2063
			$style = ($attributes['multiple'] === 'checkbox') ? 'checkbox' : null;
2064
			$template = ($style) ? 'checkboxmultiplestart' : 'selectmultiplestart';
2065
			$tag = $template;
2066
			if ($hiddenField) {
2067
				$hiddenAttributes = array(
2068
					'value' => '',
2069
					'id' => $attributes['id'] . ($style ? '' : '_'),
2070
					'secure' => false,
2071
					'form' => isset($attributes['form']) ? $attributes['form'] : null,
2072
					'name' => $attributes['name']
2073
				);
2074
				$select[] = $this->hidden(null, $hiddenAttributes);
2075
			}
2076
		} else {
2077
			$tag = 'selectstart';
2078
		}
2079
 
2080
		if ($tag === 'checkboxmultiplestart') {
2081
			unset($attributes['required']);
2082
		}
2083
 
2084
		if (!empty($tag) || isset($template)) {
2085
			$hasOptions = (count($options) > 0 || $showEmpty);
2086
			// Secure the field if there are options, or its a multi select.
2087
			// Single selects with no options don't submit, but multiselects do.
2088
			if (
2089
				(!isset($secure) || $secure) &&
2090
				empty($attributes['disabled']) &&
2091
				(!empty($attributes['multiple']) || $hasOptions)
2092
			) {
2093
				$this->_secure(true, $this->_secureFieldName($attributes));
2094
			}
2095
			$filter = array('name' => null, 'value' => null);
2096
			if (is_array($attributes['disabled'])) {
2097
				$filter['disabled'] = null;
2098
			}
2099
			$select[] = $this->Html->useTag($tag, $attributes['name'], array_diff_key($attributes, $filter));
2100
		}
2101
		$emptyMulti = (
2102
			$showEmpty !== null && $showEmpty !== false && !(
2103
				empty($showEmpty) && (isset($attributes) &&
2104
				array_key_exists('multiple', $attributes))
2105
			)
2106
		);
2107
 
2108
		if ($emptyMulti) {
2109
			$showEmpty = ($showEmpty === true) ? '' : $showEmpty;
2110
			$options = array('' => $showEmpty) + $options;
2111
		}
2112
 
2113
		if (!$id) {
2114
			$attributes['id'] = Inflector::camelize($attributes['id']);
2115
		}
2116
 
2117
		$select = array_merge($select, $this->_selectOptions(
2118
			array_reverse($options, true),
2119
			array(),
2120
			$showParents,
2121
			array(
2122
				'escape' => $escapeOptions,
2123
				'style' => $style,
2124
				'name' => $attributes['name'],
2125
				'value' => $attributes['value'],
2126
				'class' => $attributes['class'],
2127
				'id' => $attributes['id'],
2128
				'disabled' => $attributes['disabled'],
2129
			)
2130
		));
2131
 
2132
		$template = ($style === 'checkbox') ? 'checkboxmultipleend' : 'selectend';
2133
		$select[] = $this->Html->useTag($template);
2134
		return implode("\n", $select);
2135
	}
2136
 
2137
/**
2138
 * Generates a valid DOM ID suffix from a string.
2139
 * Also avoids collisions when multiple values are coverted to the same suffix by
2140
 * appending a numeric value.
2141
 *
2142
 * For pre-HTML5 IDs only characters like a-z 0-9 - _ are valid. HTML5 doesn't have that
2143
 * limitation, but to avoid layout issues it still filters out some sensitive chars.
2144
 *
2145
 * @param string $value The value that should be transferred into a DOM ID suffix.
2146
 * @param string $type Doctype to use. Defaults to html4.
2147
 * @return string DOM ID
2148
 */
2149
	public function domIdSuffix($value, $type = 'html4') {
2150
		if ($type === 'html5') {
2151
			$value = str_replace(array('@', '<', '>', ' ', '"', '\''), '_', $value);
2152
		} else {
2153
			$value = Inflector::camelize(Inflector::slug($value));
2154
		}
2155
		$value = Inflector::camelize($value);
2156
		$count = 1;
2157
		$suffix = $value;
2158
		while (in_array($suffix, $this->_domIdSuffixes)) {
2159
			$suffix = $value . $count++;
2160
		}
2161
		$this->_domIdSuffixes[] = $suffix;
2162
		return $suffix;
2163
	}
2164
 
2165
/**
2166
 * Returns a SELECT element for days.
2167
 *
2168
 * ### Attributes:
2169
 *
2170
 * - `empty` - If true, the empty select option is shown. If a string,
2171
 *   that string is displayed as the empty element.
2172
 * - `value` The selected value of the input.
2173
 *
2174
 * @param string $fieldName Prefix name for the SELECT element
2175
 * @param array $attributes HTML attributes for the select element
2176
 * @return string A generated day select box.
2177
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::day
2178
 */
2179
	public function day($fieldName = null, $attributes = array()) {
2180
		$attributes += array('empty' => true, 'value' => null);
2181
		$attributes = $this->_dateTimeSelected('day', $fieldName, $attributes);
2182
 
2183
		if (strlen($attributes['value']) > 2) {
2184
			$date = date_create($attributes['value']);
2185
			$attributes['value'] = null;
2186
			if ($date) {
2187
				$attributes['value'] = $date->format('d');
2188
			}
2189
		} elseif ($attributes['value'] === false) {
2190
			$attributes['value'] = null;
2191
		}
2192
		return $this->select($fieldName . ".day", $this->_generateOptions('day'), $attributes);
2193
	}
2194
 
2195
/**
2196
 * Returns a SELECT element for years
2197
 *
2198
 * ### Attributes:
2199
 *
2200
 * - `empty` - If true, the empty select option is shown. If a string,
2201
 *   that string is displayed as the empty element.
2202
 * - `orderYear` - Ordering of year values in select options.
2203
 *   Possible values 'asc', 'desc'. Default 'desc'
2204
 * - `value` The selected value of the input.
2205
 *
2206
 * @param string $fieldName Prefix name for the SELECT element
2207
 * @param int $minYear First year in sequence
2208
 * @param int $maxYear Last year in sequence
2209
 * @param array $attributes Attribute array for the select elements.
2210
 * @return string Completed year select input
2211
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::year
2212
 */
2213
	public function year($fieldName, $minYear = null, $maxYear = null, $attributes = array()) {
2214
		$attributes += array('empty' => true, 'value' => null);
2215
		if ((empty($attributes['value']) || $attributes['value'] === true) && $value = $this->value($fieldName)) {
2216
			if (is_array($value)) {
2217
				$year = null;
2218
				extract($value);
2219
				$attributes['value'] = $year;
2220
			} else {
2221
				if (empty($value)) {
2222
					if (!$attributes['empty'] && !$maxYear) {
2223
						$attributes['value'] = 'now';
2224
 
2225
					} elseif (!$attributes['empty'] && $maxYear && !$attributes['value']) {
2226
						$attributes['value'] = $maxYear;
2227
					}
2228
				} else {
2229
					$attributes['value'] = $value;
2230
				}
2231
			}
2232
		}
2233
 
2234
		if (strlen($attributes['value']) > 4 || $attributes['value'] === 'now') {
2235
			$date = date_create($attributes['value']);
2236
			$attributes['value'] = null;
2237
			if ($date) {
2238
				$attributes['value'] = $date->format('Y');
2239
			}
2240
		} elseif ($attributes['value'] === false) {
2241
			$attributes['value'] = null;
2242
		}
2243
		$yearOptions = array('value' => $attributes['value'], 'min' => $minYear, 'max' => $maxYear, 'order' => 'desc');
2244
		if (isset($attributes['orderYear'])) {
2245
			$yearOptions['order'] = $attributes['orderYear'];
2246
			unset($attributes['orderYear']);
2247
		}
2248
		return $this->select(
2249
			$fieldName . '.year', $this->_generateOptions('year', $yearOptions),
2250
			$attributes
2251
		);
2252
	}
2253
 
2254
/**
2255
 * Returns a SELECT element for months.
2256
 *
2257
 * ### Attributes:
2258
 *
2259
 * - `monthNames` - If false, 2 digit numbers will be used instead of text.
2260
 *   If a array, the given array will be used.
2261
 * - `empty` - If true, the empty select option is shown. If a string,
2262
 *   that string is displayed as the empty element.
2263
 * - `value` The selected value of the input.
2264
 *
2265
 * @param string $fieldName Prefix name for the SELECT element
2266
 * @param array $attributes Attributes for the select element
2267
 * @return string A generated month select dropdown.
2268
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::month
2269
 */
2270
	public function month($fieldName, $attributes = array()) {
2271
		$attributes += array('empty' => true, 'value' => null);
2272
		$attributes = $this->_dateTimeSelected('month', $fieldName, $attributes);
2273
 
2274
		if (strlen($attributes['value']) > 2) {
2275
			$date = date_create($attributes['value']);
2276
			$attributes['value'] = null;
2277
			if ($date) {
2278
				$attributes['value'] = $date->format('m');
2279
			}
2280
		} elseif ($attributes['value'] === false) {
2281
			$attributes['value'] = null;
2282
		}
2283
		$defaults = array('monthNames' => true);
2284
		$attributes = array_merge($defaults, (array)$attributes);
2285
		$monthNames = $attributes['monthNames'];
2286
		unset($attributes['monthNames']);
2287
 
2288
		return $this->select(
2289
			$fieldName . ".month",
2290
			$this->_generateOptions('month', array('monthNames' => $monthNames)),
2291
			$attributes
2292
		);
2293
	}
2294
 
2295
/**
2296
 * Returns a SELECT element for hours.
2297
 *
2298
 * ### Attributes:
2299
 *
2300
 * - `empty` - If true, the empty select option is shown. If a string,
2301
 *   that string is displayed as the empty element.
2302
 * - `value` The selected value of the input.
2303
 *
2304
 * @param string $fieldName Prefix name for the SELECT element
2305
 * @param bool $format24Hours True for 24 hours format
2306
 * @param array $attributes List of HTML attributes
2307
 * @return string Completed hour select input
2308
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::hour
2309
 */
2310
	public function hour($fieldName, $format24Hours = false, $attributes = array()) {
2311
		$attributes += array('empty' => true, 'value' => null);
2312
		$attributes = $this->_dateTimeSelected('hour', $fieldName, $attributes);
2313
 
2314
		if (strlen($attributes['value']) > 2) {
2315
			try {
2316
				$date = new DateTime($attributes['value']);
2317
				if ($format24Hours) {
2318
					$attributes['value'] = $date->format('H');
2319
				} else {
2320
					$attributes['value'] = $date->format('g');
2321
				}
2322
			} catch (Exception $e) {
2323
				$attributes['value'] = null;
2324
			}
2325
		} elseif ($attributes['value'] === false) {
2326
			$attributes['value'] = null;
2327
		}
2328
 
2329
		if ($attributes['value'] > 12 && !$format24Hours) {
2330
			$attributes['value'] -= 12;
2331
		}
2332
		if (($attributes['value'] === 0 || $attributes['value'] === '00') && !$format24Hours) {
2333
			$attributes['value'] = 12;
2334
		}
2335
 
2336
		return $this->select(
2337
			$fieldName . ".hour",
2338
			$this->_generateOptions($format24Hours ? 'hour24' : 'hour'),
2339
			$attributes
2340
		);
2341
	}
2342
 
2343
/**
2344
 * Returns a SELECT element for minutes.
2345
 *
2346
 * ### Attributes:
2347
 *
2348
 * - `empty` - If true, the empty select option is shown. If a string,
2349
 *   that string is displayed as the empty element.
2350
 * - `value` The selected value of the input.
2351
 *
2352
 * @param string $fieldName Prefix name for the SELECT element
2353
 * @param array $attributes Array of Attributes
2354
 * @return string Completed minute select input.
2355
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::minute
2356
 */
2357
	public function minute($fieldName, $attributes = array()) {
2358
		$attributes += array('empty' => true, 'value' => null);
2359
		$attributes = $this->_dateTimeSelected('min', $fieldName, $attributes);
2360
 
2361
		if (strlen($attributes['value']) > 2) {
2362
			$date = date_create($attributes['value']);
2363
			$attributes['value'] = null;
2364
			if ($date) {
2365
				$attributes['value'] = $date->format('i');
2366
			}
2367
		} elseif ($attributes['value'] === false) {
2368
			$attributes['value'] = null;
2369
		}
2370
		$minuteOptions = array();
2371
 
2372
		if (isset($attributes['interval'])) {
2373
			$minuteOptions['interval'] = $attributes['interval'];
2374
			unset($attributes['interval']);
2375
		}
2376
		return $this->select(
2377
			$fieldName . ".min", $this->_generateOptions('minute', $minuteOptions),
2378
			$attributes
2379
		);
2380
	}
2381
 
2382
/**
2383
 * Selects values for dateTime selects.
2384
 *
2385
 * @param string $select Name of element field. ex. 'day'
2386
 * @param string $fieldName Name of fieldName being generated ex. Model.created
2387
 * @param array $attributes Array of attributes, must contain 'empty' key.
2388
 * @return array Attributes array with currently selected value.
2389
 */
2390
	protected function _dateTimeSelected($select, $fieldName, $attributes) {
2391
		if ((empty($attributes['value']) || $attributes['value'] === true) && $value = $this->value($fieldName)) {
2392
			if (is_array($value)) {
2393
				$attributes['value'] = isset($value[$select]) ? $value[$select] : null;
2394
			} else {
2395
				if (empty($value)) {
2396
					if (!$attributes['empty']) {
2397
						$attributes['value'] = 'now';
2398
					}
2399
				} else {
2400
					$attributes['value'] = $value;
2401
				}
2402
			}
2403
		}
2404
		return $attributes;
2405
	}
2406
 
2407
/**
2408
 * Returns a SELECT element for AM or PM.
2409
 *
2410
 * ### Attributes:
2411
 *
2412
 * - `empty` - If true, the empty select option is shown. If a string,
2413
 *   that string is displayed as the empty element.
2414
 * - `value` The selected value of the input.
2415
 *
2416
 * @param string $fieldName Prefix name for the SELECT element
2417
 * @param array $attributes Array of Attributes
2418
 * @return string Completed meridian select input
2419
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::meridian
2420
 */
2421
	public function meridian($fieldName, $attributes = array()) {
2422
		$attributes += array('empty' => true, 'value' => null);
2423
		if ((empty($attributes['value']) || $attributes['value'] === true) && $value = $this->value($fieldName)) {
2424
			if (is_array($value)) {
2425
				$meridian = null;
2426
				extract($value);
2427
				$attributes['value'] = $meridian;
2428
			} else {
2429
				if (empty($value)) {
2430
					if (!$attributes['empty']) {
2431
						$attributes['value'] = date('a');
2432
					}
2433
				} else {
2434
					$date = date_create($attributes['value']);
2435
					$attributes['value'] = null;
2436
					if ($date) {
2437
						$attributes['value'] = $date->format('a');
2438
					}
2439
				}
2440
			}
2441
		}
2442
 
2443
		if ($attributes['value'] === false) {
2444
			$attributes['value'] = null;
2445
		}
2446
		return $this->select(
2447
			$fieldName . ".meridian", $this->_generateOptions('meridian'),
2448
			$attributes
2449
		);
2450
	}
2451
 
2452
/**
2453
 * Returns a set of SELECT elements for a full datetime setup: day, month and year, and then time.
2454
 *
2455
 * ### Attributes:
2456
 *
2457
 * - `monthNames` If false, 2 digit numbers will be used instead of text.
2458
 *   If a array, the given array will be used.
2459
 * - `minYear` The lowest year to use in the year select
2460
 * - `maxYear` The maximum year to use in the year select
2461
 * - `interval` The interval for the minutes select. Defaults to 1
2462
 * - `separator` The contents of the string between select elements. Defaults to '-'
2463
 * - `empty` - If true, the empty select option is shown. If a string,
2464
 *   that string is displayed as the empty element.
2465
 * - `round` - Set to `up` or `down` if you want to force rounding in either direction. Defaults to null.
2466
 * - `value` | `default` The default value to be used by the input. A value in `$this->data`
2467
 *   matching the field name will override this value. If no default is provided `time()` will be used.
2468
 *
2469
 * @param string $fieldName Prefix name for the SELECT element
2470
 * @param string $dateFormat DMY, MDY, YMD, or null to not generate date inputs.
2471
 * @param string $timeFormat 12, 24, or null to not generate time inputs.
2472
 * @param array $attributes Array of Attributes
2473
 * @return string Generated set of select boxes for the date and time formats chosen.
2474
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::dateTime
2475
 */
2476
	public function dateTime($fieldName, $dateFormat = 'DMY', $timeFormat = '12', $attributes = array()) {
2477
		$attributes += array('empty' => true, 'value' => null);
2478
		$year = $month = $day = $hour = $min = $meridian = null;
2479
 
2480
		if (empty($attributes['value'])) {
2481
			$attributes = $this->value($attributes, $fieldName);
2482
		}
2483
 
2484
		if ($attributes['value'] === null && $attributes['empty'] != true) {
2485
			$attributes['value'] = time();
2486
			if (!empty($attributes['maxYear']) && $attributes['maxYear'] < date('Y')) {
2487
				$attributes['value'] = strtotime(date($attributes['maxYear'] . '-m-d'));
2488
			}
2489
		}
2490
 
2491
		if (!empty($attributes['value'])) {
2492
			list($year, $month, $day, $hour, $min, $meridian) = $this->_getDateTimeValue(
2493
				$attributes['value'],
2494
				$timeFormat
2495
			);
2496
		}
2497
 
2498
		$defaults = array(
2499
			'minYear' => null, 'maxYear' => null, 'separator' => '-',
2500
			'interval' => 1, 'monthNames' => true, 'round' => null
2501
		);
2502
		$attributes = array_merge($defaults, (array)$attributes);
2503
		if (isset($attributes['minuteInterval'])) {
2504
			$attributes['interval'] = $attributes['minuteInterval'];
2505
			unset($attributes['minuteInterval']);
2506
		}
2507
		$minYear = $attributes['minYear'];
2508
		$maxYear = $attributes['maxYear'];
2509
		$separator = $attributes['separator'];
2510
		$interval = $attributes['interval'];
2511
		$monthNames = $attributes['monthNames'];
2512
		$round = $attributes['round'];
2513
		$attributes = array_diff_key($attributes, $defaults);
2514
 
2515
		if (!empty($interval) && $interval > 1 && !empty($min)) {
2516
			$current = new DateTime();
2517
			if ($year !== null) {
2518
				$current->setDate($year, $month, $day);
2519
			}
2520
			if ($hour !== null) {
2521
				$current->setTime($hour, $min);
2522
			}
2523
			$changeValue = $min * (1 / $interval);
2524
			switch ($round) {
2525
				case 'up':
2526
					$changeValue = ceil($changeValue);
2527
					break;
2528
				case 'down':
2529
					$changeValue = floor($changeValue);
2530
					break;
2531
				default:
2532
					$changeValue = round($changeValue);
2533
			}
2534
			$change = ($changeValue * $interval) - $min;
2535
			$current->modify($change > 0 ? "+$change minutes" : "$change minutes");
2536
			$format = ($timeFormat == 12) ? 'Y m d h i a' : 'Y m d H i a';
2537
			$newTime = explode(' ', $current->format($format));
2538
			list($year, $month, $day, $hour, $min, $meridian) = $newTime;
2539
		}
2540
 
2541
		$keys = array('Day', 'Month', 'Year', 'Hour', 'Minute', 'Meridian');
2542
		$attrs = array_fill_keys($keys, $attributes);
2543
 
2544
		$hasId = isset($attributes['id']);
2545
		if ($hasId && is_array($attributes['id'])) {
2546
			// check for missing ones and build selectAttr for each element
2547
			$attributes['id'] += array(
2548
				'month' => '',
2549
				'year' => '',
2550
				'day' => '',
2551
				'hour' => '',
2552
				'minute' => '',
2553
				'meridian' => ''
2554
			);
2555
			foreach ($keys as $key) {
2556
				$attrs[$key]['id'] = $attributes['id'][strtolower($key)];
2557
			}
2558
		}
2559
		if ($hasId && is_string($attributes['id'])) {
2560
			// build out an array version
2561
			foreach ($keys as $key) {
2562
				$attrs[$key]['id'] = $attributes['id'] . $key;
2563
			}
2564
		}
2565
 
2566
		if (is_array($attributes['empty'])) {
2567
			$attributes['empty'] += array(
2568
				'month' => true,
2569
				'year' => true,
2570
				'day' => true,
2571
				'hour' => true,
2572
				'minute' => true,
2573
				'meridian' => true
2574
			);
2575
			foreach ($keys as $key) {
2576
				$attrs[$key]['empty'] = $attributes['empty'][strtolower($key)];
2577
			}
2578
		}
2579
 
2580
		$selects = array();
2581
		foreach (preg_split('//', $dateFormat, -1, PREG_SPLIT_NO_EMPTY) as $char) {
2582
			switch ($char) {
2583
				case 'Y':
2584
					$attrs['Year']['value'] = $year;
2585
					$selects[] = $this->year(
2586
						$fieldName, $minYear, $maxYear, $attrs['Year']
2587
					);
2588
					break;
2589
				case 'M':
2590
					$attrs['Month']['value'] = $month;
2591
					$attrs['Month']['monthNames'] = $monthNames;
2592
					$selects[] = $this->month($fieldName, $attrs['Month']);
2593
					break;
2594
				case 'D':
2595
					$attrs['Day']['value'] = $day;
2596
					$selects[] = $this->day($fieldName, $attrs['Day']);
2597
					break;
2598
			}
2599
		}
2600
		$opt = implode($separator, $selects);
2601
 
2602
		$attrs['Minute']['interval'] = $interval;
2603
		switch ($timeFormat) {
2604
			case '24':
2605
				$attrs['Hour']['value'] = $hour;
2606
				$attrs['Minute']['value'] = $min;
2607
				$opt .= $this->hour($fieldName, true, $attrs['Hour']) . ':' .
2608
				$this->minute($fieldName, $attrs['Minute']);
2609
				break;
2610
			case '12':
2611
				$attrs['Hour']['value'] = $hour;
2612
				$attrs['Minute']['value'] = $min;
2613
				$attrs['Meridian']['value'] = $meridian;
2614
				$opt .= $this->hour($fieldName, false, $attrs['Hour']) . ':' .
2615
				$this->minute($fieldName, $attrs['Minute']) . ' ' .
2616
				$this->meridian($fieldName, $attrs['Meridian']);
2617
				break;
2618
		}
2619
		return $opt;
2620
	}
2621
 
2622
/**
2623
 * Parse the value for a datetime selected value
2624
 *
2625
 * @param string|array $value The selected value.
2626
 * @param int $timeFormat The time format
2627
 * @return array Array of selected value.
2628
 */
2629
	protected function _getDateTimeValue($value, $timeFormat) {
2630
		$year = $month = $day = $hour = $min = $meridian = null;
2631
		if (is_array($value)) {
2632
			extract($value);
2633
			if ($meridian === 'pm') {
2634
				$hour += 12;
2635
			}
2636
			return array($year, $month, $day, $hour, $min, $meridian);
2637
		}
2638
 
2639
		if (is_numeric($value)) {
2640
			$value = strftime('%Y-%m-%d %H:%M:%S', $value);
2641
		}
2642
		$meridian = 'am';
2643
		$pos = strpos($value, '-');
2644
		if ($pos !== false) {
2645
			$date = explode('-', $value);
2646
			$days = explode(' ', $date[2]);
2647
			$day = $days[0];
2648
			$month = $date[1];
2649
			$year = $date[0];
2650
		} else {
2651
			$days[1] = $value;
2652
		}
2653
 
2654
		if (!empty($timeFormat)) {
2655
			$time = explode(':', $days[1]);
2656
 
2657
			if ($time[0] >= 12) {
2658
				$meridian = 'pm';
2659
			}
2660
			$hour = $min = null;
2661
			if (isset($time[1])) {
2662
				$hour = $time[0];
2663
				$min = $time[1];
2664
			}
2665
		}
2666
		return array($year, $month, $day, $hour, $min, $meridian);
2667
	}
2668
 
2669
/**
2670
 * Gets the input field name for the current tag
2671
 *
2672
 * @param array $options Options list.
2673
 * @param string $field Field name.
2674
 * @param string $key Key name.
2675
 * @return array
2676
 */
2677
	protected function _name($options = array(), $field = null, $key = 'name') {
2678
		if ($this->requestType === 'get') {
2679
			if ($options === null) {
2680
				$options = array();
2681
			} elseif (is_string($options)) {
2682
				$field = $options;
2683
				$options = 0;
2684
			}
2685
 
2686
			if (!empty($field)) {
2687
				$this->setEntity($field);
2688
			}
2689
 
2690
			if (is_array($options) && isset($options[$key])) {
2691
				return $options;
2692
			}
2693
 
2694
			$entity = $this->entity();
2695
			$model = $this->model();
2696
			$name = $model === $entity[0] && isset($entity[1]) ? $entity[1] : $entity[0];
2697
			$last = $entity[count($entity) - 1];
2698
			if (in_array($last, $this->_fieldSuffixes)) {
2699
				$name .= '[' . $last . ']';
2700
			}
2701
 
2702
			if (is_array($options)) {
2703
				$options[$key] = $name;
2704
				return $options;
2705
			}
2706
			return $name;
2707
		}
2708
		return parent::_name($options, $field, $key);
2709
	}
2710
 
2711
/**
2712
 * Returns an array of formatted OPTION/OPTGROUP elements
2713
 *
2714
 * @param array $elements Elements to format.
2715
 * @param array $parents Parents for OPTGROUP.
2716
 * @param bool $showParents Whether to show parents.
2717
 * @param array $attributes HTML attributes.
2718
 * @return array
2719
 */
2720
	protected function _selectOptions($elements = array(), $parents = array(), $showParents = null, $attributes = array()) {
2721
		$select = array();
2722
		$attributes = array_merge(
2723
			array('escape' => true, 'style' => null, 'value' => null, 'class' => null),
2724
			$attributes
2725
		);
2726
		$selectedIsEmpty = ($attributes['value'] === '' || $attributes['value'] === null);
2727
		$selectedIsArray = is_array($attributes['value']);
2728
 
2729
		$this->_domIdSuffixes = array();
2730
		foreach ($elements as $name => $title) {
2731
			$htmlOptions = array();
2732
			if (is_array($title) && (!isset($title['name']) || !isset($title['value']))) {
2733
				if (!empty($name)) {
2734
					if ($attributes['style'] === 'checkbox') {
2735
						$select[] = $this->Html->useTag('fieldsetend');
2736
					} else {
2737
						$select[] = $this->Html->useTag('optiongroupend');
2738
					}
2739
					$parents[] = $name;
2740
				}
2741
				$select = array_merge($select, $this->_selectOptions(
2742
					$title, $parents, $showParents, $attributes
2743
				));
2744
 
2745
				if (!empty($name)) {
2746
					$name = $attributes['escape'] ? h($name) : $name;
2747
					if ($attributes['style'] === 'checkbox') {
2748
						$select[] = $this->Html->useTag('fieldsetstart', $name);
2749
					} else {
2750
						$select[] = $this->Html->useTag('optiongroup', $name, '');
2751
					}
2752
				}
2753
				$name = null;
2754
			} elseif (is_array($title)) {
2755
				$htmlOptions = $title;
2756
				$name = $title['value'];
2757
				$title = $title['name'];
2758
				unset($htmlOptions['name'], $htmlOptions['value']);
2759
			}
2760
 
2761
			if ($name !== null) {
2762
				$isNumeric = is_numeric($name);
2763
				if (
2764
					(!$selectedIsArray && !$selectedIsEmpty && (string)$attributes['value'] == (string)$name) ||
2765
					($selectedIsArray && in_array((string)$name, $attributes['value'], !$isNumeric))
2766
				) {
2767
					if ($attributes['style'] === 'checkbox') {
2768
						$htmlOptions['checked'] = true;
2769
					} else {
2770
						$htmlOptions['selected'] = 'selected';
2771
					}
2772
				}
2773
 
2774
				if ($showParents || (!in_array($title, $parents))) {
2775
					$title = ($attributes['escape']) ? h($title) : $title;
2776
 
2777
					$hasDisabled = !empty($attributes['disabled']);
2778
					if ($hasDisabled) {
2779
						$disabledIsArray = is_array($attributes['disabled']);
2780
						if ($disabledIsArray) {
2781
							$disabledIsNumeric = is_numeric($name);
2782
						}
2783
					}
2784
					if (
2785
						$hasDisabled &&
2786
						$disabledIsArray &&
2787
						in_array((string)$name, $attributes['disabled'], !$disabledIsNumeric)
2788
					) {
2789
						$htmlOptions['disabled'] = 'disabled';
2790
					}
2791
					if ($hasDisabled && !$disabledIsArray && $attributes['style'] === 'checkbox') {
2792
						$htmlOptions['disabled'] = $attributes['disabled'] === true ? 'disabled' : $attributes['disabled'];
2793
					}
2794
 
2795
					if ($attributes['style'] === 'checkbox') {
2796
						$htmlOptions['value'] = $name;
2797
 
2798
						$tagName = $attributes['id'] . $this->domIdSuffix($name);
2799
						$htmlOptions['id'] = $tagName;
2800
						$label = array('for' => $tagName);
2801
 
2802
						if (isset($htmlOptions['checked']) && $htmlOptions['checked'] === true) {
2803
							$label['class'] = 'selected';
2804
						}
2805
 
2806
						$name = $attributes['name'];
2807
 
2808
						if (empty($attributes['class'])) {
2809
							$attributes['class'] = 'checkbox';
2810
						} elseif ($attributes['class'] === 'form-error') {
2811
							$attributes['class'] = 'checkbox ' . $attributes['class'];
2812
						}
2813
						$label = $this->label(null, $title, $label);
2814
						$item = $this->Html->useTag('checkboxmultiple', $name, $htmlOptions);
2815
						$select[] = $this->Html->div($attributes['class'], $item . $label);
2816
					} else {
2817
						if ($attributes['escape']) {
2818
							$name = h($name);
2819
						}
2820
						$select[] = $this->Html->useTag('selectoption', $name, $htmlOptions, $title);
2821
					}
2822
				}
2823
			}
2824
		}
2825
 
2826
		return array_reverse($select, true);
2827
	}
2828
 
2829
/**
2830
 * Generates option lists for common <select /> menus
2831
 *
2832
 * @param string $name List type name.
2833
 * @param array $options Options list.
2834
 * @return array
2835
 */
2836
	protected function _generateOptions($name, $options = array()) {
2837
		if (!empty($this->options[$name])) {
2838
			return $this->options[$name];
2839
		}
2840
		$data = array();
2841
 
2842
		switch ($name) {
2843
			case 'minute':
2844
				if (isset($options['interval'])) {
2845
					$interval = $options['interval'];
2846
				} else {
2847
					$interval = 1;
2848
				}
2849
				$i = 0;
2850
				while ($i < 60) {
2851
					$data[sprintf('%02d', $i)] = sprintf('%02d', $i);
2852
					$i += $interval;
2853
				}
2854
				break;
2855
			case 'hour':
2856
				for ($i = 1; $i <= 12; $i++) {
2857
					$data[sprintf('%02d', $i)] = $i;
2858
				}
2859
				break;
2860
			case 'hour24':
2861
				for ($i = 0; $i <= 23; $i++) {
2862
					$data[sprintf('%02d', $i)] = $i;
2863
				}
2864
				break;
2865
			case 'meridian':
2866
				$data = array('am' => 'am', 'pm' => 'pm');
2867
				break;
2868
			case 'day':
2869
				for ($i = 1; $i <= 31; $i++) {
2870
					$data[sprintf('%02d', $i)] = $i;
2871
				}
2872
				break;
2873
			case 'month':
2874
				if ($options['monthNames'] === true) {
2875
					$data['01'] = __d('cake', 'January');
2876
					$data['02'] = __d('cake', 'February');
2877
					$data['03'] = __d('cake', 'March');
2878
					$data['04'] = __d('cake', 'April');
2879
					$data['05'] = __d('cake', 'May');
2880
					$data['06'] = __d('cake', 'June');
2881
					$data['07'] = __d('cake', 'July');
2882
					$data['08'] = __d('cake', 'August');
2883
					$data['09'] = __d('cake', 'September');
2884
					$data['10'] = __d('cake', 'October');
2885
					$data['11'] = __d('cake', 'November');
2886
					$data['12'] = __d('cake', 'December');
2887
				} elseif (is_array($options['monthNames'])) {
2888
					$data = $options['monthNames'];
2889
				} else {
2890
					for ($m = 1; $m <= 12; $m++) {
2891
						$data[sprintf("%02s", $m)] = strftime("%m", mktime(1, 1, 1, $m, 1, 1999));
2892
					}
2893
				}
2894
				break;
2895
			case 'year':
2896
				$current = intval(date('Y'));
2897
 
2898
				$min = !isset($options['min']) ? $current - 20 : (int)$options['min'];
2899
				$max = !isset($options['max']) ? $current + 20 : (int)$options['max'];
2900
 
2901
				if ($min > $max) {
2902
					list($min, $max) = array($max, $min);
2903
				}
2904
				if (
2905
					!empty($options['value']) &&
2906
					(int)$options['value'] < $min &&
2907
					(int)$options['value'] > 0
2908
				) {
2909
					$min = (int)$options['value'];
2910
				} elseif (!empty($options['value']) && (int)$options['value'] > $max) {
2911
					$max = (int)$options['value'];
2912
				}
2913
 
2914
				for ($i = $min; $i <= $max; $i++) {
2915
					$data[$i] = $i;
2916
				}
2917
				if ($options['order'] !== 'asc') {
2918
					$data = array_reverse($data, true);
2919
				}
2920
				break;
2921
		}
2922
		$this->_options[$name] = $data;
2923
		return $this->_options[$name];
2924
	}
2925
 
2926
/**
2927
 * Sets field defaults and adds field to form security input hash.
2928
 * Will also add a 'form-error' class if the field contains validation errors.
2929
 *
2930
 * ### Options
2931
 *
2932
 * - `secure` - boolean whether or not the field should be added to the security fields.
2933
 *   Disabling the field using the `disabled` option, will also omit the field from being
2934
 *   part of the hashed key.
2935
 *
2936
 * This method will convert a numerically indexed 'disabled' into a associative
2937
 * value. FormHelper's internals expect associative options.
2938
 *
2939
 * @param string $field Name of the field to initialize options for.
2940
 * @param array $options Array of options to append options into.
2941
 * @return array Array of options for the input.
2942
 */
2943
	protected function _initInputField($field, $options = array()) {
2944
		if (isset($options['secure'])) {
2945
			$secure = $options['secure'];
2946
			unset($options['secure']);
2947
		} else {
2948
			$secure = (isset($this->request['_Token']) && !empty($this->request['_Token']));
2949
		}
2950
 
2951
		$disabledIndex = array_search('disabled', $options, true);
2952
		if (is_int($disabledIndex)) {
2953
			unset($options[$disabledIndex]);
2954
			$options['disabled'] = true;
2955
		}
2956
 
2957
		$result = parent::_initInputField($field, $options);
2958
		if ($this->tagIsInvalid() !== false) {
2959
			$result = $this->addClass($result, 'form-error');
2960
		}
2961
 
2962
		if (!empty($result['disabled'])) {
2963
			return $result;
2964
		}
2965
 
2966
		if (!isset($result['required']) &&
2967
			$this->_introspectModel($this->model(), 'validates', $this->field())
2968
		) {
2969
			$result['required'] = true;
2970
		}
2971
 
2972
		if ($secure === self::SECURE_SKIP) {
2973
			return $result;
2974
		}
2975
 
2976
		$this->_secure($secure, $this->_secureFieldName($options));
2977
		return $result;
2978
	}
2979
 
2980
/**
2981
 * Get the field name for use with _secure().
2982
 *
2983
 * Parses the name attribute to create a dot separated name value for use
2984
 * in secured field hash.
2985
 *
2986
 * @param array $options An array of options possibly containing a name key.
2987
 * @return string|null
2988
 */
2989
	protected function _secureFieldName($options) {
2990
		if (isset($options['name'])) {
2991
			preg_match_all('/\[(.*?)\]/', $options['name'], $matches);
2992
			if (isset($matches[1])) {
2993
				return $matches[1];
2994
			}
2995
		}
2996
		return null;
2997
	}
2998
 
2999
/**
3000
 * Sets the last created form action.
3001
 *
3002
 * @param string|array $url URL.
3003
 * @return void
3004
 */
3005
	protected function _lastAction($url) {
3006
		$action = Router::url($url, true);
3007
		$query = parse_url($action, PHP_URL_QUERY);
3008
		$query = $query ? '?' . $query : '';
3009
		$this->_lastAction = parse_url($action, PHP_URL_PATH) . $query;
3010
	}
3011
 
3012
/**
3013
 * Set/Get inputDefaults for form elements
3014
 *
3015
 * @param array $defaults New default values
3016
 * @param bool $merge Merge with current defaults
3017
 * @return array inputDefaults
3018
 */
3019
	public function inputDefaults($defaults = null, $merge = false) {
3020
		if ($defaults !== null) {
3021
			if ($merge) {
3022
				$this->_inputDefaults = array_merge($this->_inputDefaults, (array)$defaults);
3023
			} else {
3024
				$this->_inputDefaults = (array)$defaults;
3025
			}
3026
		}
3027
		return $this->_inputDefaults;
3028
	}
3029
 
3030
}