統計
| ブランチ: | リビジョン:

pictcode / lib / Cake / View / Helper / FormHelper.php @ 635eef61

履歴 | 表示 | アノテート | ダウンロード (96.993 KB)

1
<?php
2
/**
3
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
4
 * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
5
 *
6
 * Licensed under The MIT License
7
 * For full copyright and license information, please see the LICENSE.txt
8
 * Redistributions of files must retain the above copyright notice.
9
 *
10
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
11
 * @link          http://cakephp.org CakePHP(tm) Project
12
 * @package       Cake.View.Helper
13
 * @since         CakePHP(tm) v 0.10.0.1076
14
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
15
 */
16

    
17
App::uses('ClassRegistry', 'Utility');
18
App::uses('AppHelper', 'View/Helper');
19
App::uses('Hash', 'Utility');
20
App::uses('Inflector', 'Utility');
21

    
22
/**
23
 * Form helper library.
24
 *
25
 * Automatic generation of HTML FORMs from given data.
26
 *
27
 * @package       Cake.View.Helper
28
 * @property      HtmlHelper $Html
29
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html
30
 */
31
class FormHelper extends AppHelper {
32

    
33
/**
34
 * Other helpers used by FormHelper
35
 *
36
 * @var array
37
 */
38
        public $helpers = array('Html');
39

    
40
/**
41
 * Options used by DateTime fields
42
 *
43
 * @var array
44
 */
45
        protected $_options = array(
46
                'day' => array(), 'minute' => array(), 'hour' => array(),
47
                'month' => array(), 'year' => array(), 'meridian' => array()
48
        );
49

    
50
/**
51
 * List of fields created, used with secure forms.
52
 *
53
 * @var array
54
 */
55
        public $fields = array();
56

    
57
/**
58
 * Constant used internally to skip the securing process,
59
 * and neither add the field to the hash or to the unlocked fields.
60
 *
61
 * @var string
62
 */
63
        const SECURE_SKIP = 'skip';
64

    
65
/**
66
 * Defines the type of form being created. Set by FormHelper::create().
67
 *
68
 * @var string
69
 */
70
        public $requestType = null;
71

    
72
/**
73
 * The default model being used for the current form.
74
 *
75
 * @var string
76
 */
77
        public $defaultModel = null;
78

    
79
/**
80
 * Persistent default options used by input(). Set by FormHelper::create().
81
 *
82
 * @var array
83
 */
84
        protected $_inputDefaults = array();
85

    
86
/**
87
 * An array of field names that have been excluded from
88
 * the Token hash used by SecurityComponent's validatePost method
89
 *
90
 * @see FormHelper::_secure()
91
 * @see SecurityComponent::validatePost()
92
 * @var array
93
 */
94
        protected $_unlockedFields = array();
95

    
96
/**
97
 * Holds the model references already loaded by this helper
98
 * product of trying to inspect them out of field names
99
 *
100
 * @var array
101
 */
102
        protected $_models = array();
103

    
104
/**
105
 * Holds all the validation errors for models loaded and inspected
106
 * it can also be set manually to be able to display custom error messages
107
 * in the any of the input fields generated by this helper
108
 *
109
 * @var array
110
 */
111
        public $validationErrors = array();
112

    
113
/**
114
 * Holds already used DOM ID suffixes to avoid collisions with multiple form field elements.
115
 *
116
 * @var array
117
 */
118
        protected $_domIdSuffixes = array();
119

    
120
/**
121
 * The action attribute value of the last created form.
122
 * Used to make form/request specific hashes for SecurityComponent.
123
 *
124
 * @var string
125
 */
126
        protected $_lastAction = '';
127

    
128
/**
129
 * Copies the validationErrors variable from the View object into this instance
130
 *
131
 * @param View $View The View this helper is being attached to.
132
 * @param array $settings Configuration settings for the helper.
133
 */
134
        public function __construct(View $View, $settings = array()) {
135
                parent::__construct($View, $settings);
136
                $this->validationErrors =& $View->validationErrors;
137
        }
138

    
139
/**
140
 * Guess the location for a model based on its name and tries to create a new instance
141
 * or get an already created instance of the model
142
 *
143
 * @param string $model Model name.
144
 * @return Model|null Model instance
145
 */
146
        protected function _getModel($model) {
147
                $object = null;
148
                if (!$model || $model === 'Model') {
149
                        return $object;
150
                }
151

    
152
                if (array_key_exists($model, $this->_models)) {
153
                        return $this->_models[$model];
154
                }
155

    
156
                if (ClassRegistry::isKeySet($model)) {
157
                        $object = ClassRegistry::getObject($model);
158
                } elseif (isset($this->request->params['models'][$model])) {
159
                        $plugin = $this->request->params['models'][$model]['plugin'];
160
                        $plugin .= ($plugin) ? '.' : null;
161
                        $object = ClassRegistry::init(array(
162
                                'class' => $plugin . $this->request->params['models'][$model]['className'],
163
                                'alias' => $model
164
                        ));
165
                } elseif (ClassRegistry::isKeySet($this->defaultModel)) {
166
                        $defaultObject = ClassRegistry::getObject($this->defaultModel);
167
                        if ($defaultObject && in_array($model, array_keys($defaultObject->getAssociated()), true) && isset($defaultObject->{$model})) {
168
                                $object = $defaultObject->{$model};
169
                        }
170
                } else {
171
                        $object = ClassRegistry::init($model, true);
172
                }
173

    
174
                $this->_models[$model] = $object;
175
                if (!$object) {
176
                        return null;
177
                }
178

    
179
                $this->fieldset[$model] = array('fields' => null, 'key' => $object->primaryKey, 'validates' => null);
180
                return $object;
181
        }
182

    
183
/**
184
 * Inspects the model properties to extract information from them.
185
 * Currently it can extract information from the the fields, the primary key and required fields
186
 *
187
 * The $key parameter accepts the following list of values:
188
 *
189
 * - key: Returns the name of the primary key for the model
190
 * - fields: Returns the model schema
191
 * - validates: returns the list of fields that are required
192
 * - errors: returns the list of validation errors
193
 *
194
 * If the $field parameter is passed if will return the information for that sole field.
195
 *
196
 * `$this->_introspectModel('Post', 'fields', 'title');` will return the schema information for title column
197
 *
198
 * @param string $model name of the model to extract information from
199
 * @param string $key name of the special information key to obtain (key, fields, validates, errors)
200
 * @param string $field name of the model field to get information from
201
 * @return mixed information extracted for the special key and field in a model
202
 */
203
        protected function _introspectModel($model, $key, $field = null) {
204
                $object = $this->_getModel($model);
205
                if (!$object) {
206
                        return null;
207
                }
208

    
209
                if ($key === 'key') {
210
                        return $this->fieldset[$model]['key'] = $object->primaryKey;
211
                }
212

    
213
                if ($key === 'fields') {
214
                        if (!isset($this->fieldset[$model]['fields'])) {
215
                                $this->fieldset[$model]['fields'] = $object->schema();
216
                                foreach ($object->hasAndBelongsToMany as $alias => $assocData) {
217
                                        $this->fieldset[$object->alias]['fields'][$alias] = array('type' => 'multiple');
218
                                }
219
                        }
220
                        if ($field === null || $field === false) {
221
                                return $this->fieldset[$model]['fields'];
222
                        } elseif (isset($this->fieldset[$model]['fields'][$field])) {
223
                                return $this->fieldset[$model]['fields'][$field];
224
                        }
225
                        return isset($object->hasAndBelongsToMany[$field]) ? array('type' => 'multiple') : null;
226
                }
227

    
228
                if ($key === 'errors' && !isset($this->validationErrors[$model])) {
229
                        $this->validationErrors[$model] =& $object->validationErrors;
230
                        return $this->validationErrors[$model];
231
                } elseif ($key === 'errors' && isset($this->validationErrors[$model])) {
232
                        return $this->validationErrors[$model];
233
                }
234

    
235
                if ($key === 'validates' && !isset($this->fieldset[$model]['validates'])) {
236
                        $validates = array();
237
                        foreach (iterator_to_array($object->validator(), true) as $validateField => $validateProperties) {
238
                                if ($this->_isRequiredField($validateProperties)) {
239
                                        $validates[$validateField] = true;
240
                                }
241
                        }
242
                        $this->fieldset[$model]['validates'] = $validates;
243
                }
244

    
245
                if ($key === 'validates') {
246
                        if (empty($field)) {
247
                                return $this->fieldset[$model]['validates'];
248
                        }
249
                        return isset($this->fieldset[$model]['validates'][$field]) ?
250
                                $this->fieldset[$model]['validates'] : null;
251
                }
252
        }
253

    
254
/**
255
 * Returns if a field is required to be filled based on validation properties from the validating object.
256
 *
257
 * @param CakeValidationSet $validationRules Validation rules set.
258
 * @return bool true if field is required to be filled, false otherwise
259
 */
260
        protected function _isRequiredField($validationRules) {
261
                if (empty($validationRules) || count($validationRules) === 0) {
262
                        return false;
263
                }
264

    
265
                $isUpdate = $this->requestType === 'put';
266
                foreach ($validationRules as $rule) {
267
                        $rule->isUpdate($isUpdate);
268
                        if ($rule->skip()) {
269
                                continue;
270
                        }
271

    
272
                        return !$rule->allowEmpty;
273
                }
274
                return false;
275
        }
276

    
277
/**
278
 * Returns false if given form field described by the current entity has no errors.
279
 * Otherwise it returns the validation message
280
 *
281
 * @return mixed Either false when there are no errors, or an array of error
282
 *    strings. An error string could be ''.
283
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::tagIsInvalid
284
 */
285
        public function tagIsInvalid() {
286
                $entity = $this->entity();
287
                $model = array_shift($entity);
288

    
289
                // 0.Model.field. Fudge entity path
290
                if (empty($model) || is_numeric($model)) {
291
                        array_splice($entity, 1, 0, $model);
292
                        $model = array_shift($entity);
293
                }
294

    
295
                $errors = array();
296
                if (!empty($entity) && isset($this->validationErrors[$model])) {
297
                        $errors = $this->validationErrors[$model];
298
                }
299
                if (!empty($entity) && empty($errors)) {
300
                        $errors = $this->_introspectModel($model, 'errors');
301
                }
302
                if (empty($errors)) {
303
                        return false;
304
                }
305
                $errors = Hash::get($errors, implode('.', $entity));
306
                return $errors === null ? false : $errors;
307
        }
308

    
309
/**
310
 * Returns an HTML FORM element.
311
 *
312
 * ### Options:
313
 *
314
 * - `type` Form method defaults to POST
315
 * - `action`  The controller action the form submits to, (optional).
316
 * - `url`  The URL the form submits to. Can be a string or a URL array. If you use 'url'
317
 *    you should leave 'action' undefined.
318
 * - `default`  Allows for the creation of Ajax forms. Set this to false to prevent the default event handler.
319
 *   Will create an onsubmit attribute if it doesn't not exist. If it does, default action suppression
320
 *   will be appended.
321
 * - `onsubmit` Used in conjunction with 'default' to create ajax forms.
322
 * - `inputDefaults` set the default $options for FormHelper::input(). Any options that would
323
 *   be set when using FormHelper::input() can be set here. Options set with `inputDefaults`
324
 *   can be overridden when calling input()
325
 * - `encoding` Set the accept-charset encoding for the form. Defaults to `Configure::read('App.encoding')`
326
 *
327
 * @param mixed $model The model name for which the form is being defined. Should
328
 *   include the plugin name for plugin models. e.g. `ContactManager.Contact`.
329
 *   If an array is passed and $options argument is empty, the array will be used as options.
330
 *   If `false` no model is used.
331
 * @param array $options An array of html attributes and options.
332
 * @return string A formatted opening FORM tag.
333
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#options-for-create
334
 */
335
        public function create($model = null, $options = array()) {
336
                $created = $id = false;
337
                $append = '';
338

    
339
                if (is_array($model) && empty($options)) {
340
                        $options = $model;
341
                        $model = null;
342
                }
343

    
344
                if (empty($model) && $model !== false && !empty($this->request->params['models'])) {
345
                        $model = key($this->request->params['models']);
346
                } elseif (empty($model) && empty($this->request->params['models'])) {
347
                        $model = false;
348
                }
349
                $this->defaultModel = $model;
350

    
351
                $key = null;
352
                if ($model !== false) {
353
                        list($plugin, $model) = pluginSplit($model, true);
354
                        $key = $this->_introspectModel($plugin . $model, 'key');
355
                        $this->setEntity($model, true);
356
                }
357

    
358
                if ($model !== false && $key) {
359
                        $recordExists = (
360
                                isset($this->request->data[$model]) &&
361
                                !empty($this->request->data[$model][$key]) &&
362
                                !is_array($this->request->data[$model][$key])
363
                        );
364

    
365
                        if ($recordExists) {
366
                                $created = true;
367
                                $id = $this->request->data[$model][$key];
368
                        }
369
                }
370

    
371
                $options += array(
372
                        'type' => ($created && empty($options['action'])) ? 'put' : 'post',
373
                        'action' => null,
374
                        'url' => null,
375
                        'default' => true,
376
                        'encoding' => strtolower(Configure::read('App.encoding')),
377
                        'inputDefaults' => array()
378
                );
379
                $this->inputDefaults($options['inputDefaults']);
380
                unset($options['inputDefaults']);
381

    
382
                if (!isset($options['id'])) {
383
                        $domId = isset($options['action']) ? $options['action'] : $this->request['action'];
384
                        $options['id'] = $this->domId($domId . 'Form');
385
                }
386

    
387
                if ($options['action'] === null && $options['url'] === null) {
388
                        $options['action'] = $this->request->here(false);
389
                } elseif (empty($options['url']) || is_array($options['url'])) {
390
                        if (empty($options['url']['controller'])) {
391
                                if (!empty($model)) {
392
                                        $options['url']['controller'] = Inflector::underscore(Inflector::pluralize($model));
393
                                } elseif (!empty($this->request->params['controller'])) {
394
                                        $options['url']['controller'] = Inflector::underscore($this->request->params['controller']);
395
                                }
396
                        }
397
                        if (empty($options['action'])) {
398
                                $options['action'] = $this->request->params['action'];
399
                        }
400

    
401
                        $plugin = null;
402
                        if ($this->plugin) {
403
                                $plugin = Inflector::underscore($this->plugin);
404
                        }
405
                        $actionDefaults = array(
406
                                'plugin' => $plugin,
407
                                'controller' => $this->_View->viewPath,
408
                                'action' => $options['action'],
409
                        );
410
                        $options['action'] = array_merge($actionDefaults, (array)$options['url']);
411
                        if (!isset($options['action'][0]) && !empty($id)) {
412
                                $options['action'][0] = $id;
413
                        }
414
                } elseif (is_string($options['url'])) {
415
                        $options['action'] = $options['url'];
416
                }
417
                unset($options['url']);
418

    
419
                switch (strtolower($options['type'])) {
420
                        case 'get':
421
                                $htmlAttributes['method'] = 'get';
422
                                break;
423
                        case 'file':
424
                                $htmlAttributes['enctype'] = 'multipart/form-data';
425
                                $options['type'] = ($created) ? 'put' : 'post';
426
                        case 'post':
427
                        case 'put':
428
                        case 'delete':
429
                                $append .= $this->hidden('_method', array(
430
                                        'name' => '_method', 'value' => strtoupper($options['type']), 'id' => null,
431
                                        'secure' => static::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' => static::SECURE_SKIP
492
                ));
493
        }
494

    
495
/**
496
 * Closes an HTML form, cleans up values set by FormHelper::create(), and writes hidden
497
 * input fields where appropriate.
498
 *
499
 * If $options is set a form submit button will be created. Options can be either a string or an array.
500
 *
501
 * ```
502
 * array usage:
503
 *
504
 * array('label' => 'save'); value="save"
505
 * array('label' => 'save', 'name' => 'Whatever'); value="save" name="Whatever"
506
 * array('name' => 'Whatever'); value="Submit" name="Whatever"
507
 * array('label' => 'save', 'name' => 'Whatever', 'div' => 'good') <div class="good"> value="save" name="Whatever"
508
 * array('label' => 'save', 'name' => 'Whatever', 'div' => array('class' => 'good')); <div class="good"> value="save" name="Whatever"
509
 * ```
510
 *
511
 * If $secureAttributes is set, these html attributes will be merged into the hidden input tags generated for the
512
 * Security Component. This is especially useful to set HTML5 attributes like 'form'
513
 *
514
 * @param string|array $options as a string will use $options as the value of button,
515
 * @param array $secureAttributes will be passed as html attributes into the hidden input elements generated for the
516
 *   Security Component.
517
 * @return string a closing FORM tag optional submit button.
518
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#closing-the-form
519
 */
520
        public function end($options = null, $secureAttributes = array()) {
521
                $out = null;
522
                $submit = null;
523

    
524
                if ($options !== null) {
525
                        $submitOptions = array();
526
                        if (is_string($options)) {
527
                                $submit = $options;
528
                        } else {
529
                                if (isset($options['label'])) {
530
                                        $submit = $options['label'];
531
                                        unset($options['label']);
532
                                }
533
                                $submitOptions = $options;
534
                        }
535
                        $out .= $this->submit($submit, $submitOptions);
536
                }
537
                if ($this->requestType !== 'get' &&
538
                        isset($this->request['_Token']) &&
539
                        !empty($this->request['_Token'])
540
                ) {
541
                        $out .= $this->secure($this->fields, $secureAttributes);
542
                        $this->fields = array();
543
                }
544
                $this->setEntity(null);
545
                $out .= $this->Html->useTag('formend');
546

    
547
                $this->_View->modelScope = false;
548
                $this->requestType = null;
549
                return $out;
550
        }
551

    
552
/**
553
 * Generates a hidden field with a security hash based on the fields used in
554
 * the form.
555
 *
556
 * If $secureAttributes is set, these html attributes will be merged into
557
 * the hidden input tags generated for the Security Component. This is
558
 * especially useful to set HTML5 attributes like 'form'.
559
 *
560
 * @param array|null $fields If set specifies the list of fields to use when
561
 *    generating the hash, else $this->fields is being used.
562
 * @param array $secureAttributes will be passed as html attributes into the hidden
563
 *    input elements generated for the Security Component.
564
 * @return string|null A hidden input field with a security hash, otherwise null.
565
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::secure
566
 */
567
        public function secure($fields = array(), $secureAttributes = array()) {
568
                if (!isset($this->request['_Token']) || empty($this->request['_Token'])) {
569
                        return null;
570
                }
571
                $locked = array();
572
                $unlockedFields = $this->_unlockedFields;
573

    
574
                foreach ($fields as $key => $value) {
575
                        if (!is_int($key)) {
576
                                $locked[$key] = $value;
577
                                unset($fields[$key]);
578
                        }
579
                }
580

    
581
                sort($unlockedFields, SORT_STRING);
582
                sort($fields, SORT_STRING);
583
                ksort($locked, SORT_STRING);
584
                $fields += $locked;
585

    
586
                $locked = implode(array_keys($locked), '|');
587
                $unlocked = implode($unlockedFields, '|');
588
                $hashParts = array(
589
                        $this->_lastAction,
590
                        serialize($fields),
591
                        $unlocked,
592
                        Configure::read('Security.salt')
593
                );
594
                $fields = Security::hash(implode('', $hashParts), 'sha1');
595

    
596
                $tokenFields = array_merge($secureAttributes, array(
597
                        'value' => urlencode($fields . ':' . $locked),
598
                        'id' => 'TokenFields' . mt_rand(),
599
                ));
600
                $out = $this->hidden('_Token.fields', $tokenFields);
601
                $tokenUnlocked = array_merge($secureAttributes, array(
602
                        'value' => urlencode($unlocked),
603
                        'id' => 'TokenUnlocked' . mt_rand(),
604
                ));
605
                $out .= $this->hidden('_Token.unlocked', $tokenUnlocked);
606
                return $this->Html->useTag('hiddenblock', $out);
607
        }
608

    
609
/**
610
 * Add to or get the list of fields that are currently unlocked.
611
 * Unlocked fields are not included in the field hash used by SecurityComponent
612
 * unlocking a field once its been added to the list of secured fields will remove
613
 * it from the list of fields.
614
 *
615
 * @param string $name The dot separated name for the field.
616
 * @return mixed Either null, or the list of fields.
617
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::unlockField
618
 */
619
        public function unlockField($name = null) {
620
                if ($name === null) {
621
                        return $this->_unlockedFields;
622
                }
623
                if (!in_array($name, $this->_unlockedFields)) {
624
                        $this->_unlockedFields[] = $name;
625
                }
626
                $index = array_search($name, $this->fields);
627
                if ($index !== false) {
628
                        unset($this->fields[$index]);
629
                }
630
                unset($this->fields[$name]);
631
        }
632

    
633
/**
634
 * Determine which fields of a form should be used for hash.
635
 * Populates $this->fields
636
 *
637
 * @param bool $lock Whether this field should be part of the validation
638
 *     or excluded as part of the unlockedFields.
639
 * @param string|array $field Reference to field to be secured. Should be dot separated to indicate nesting.
640
 * @param mixed $value Field value, if value should not be tampered with.
641
 * @return void
642
 */
643
        protected function _secure($lock, $field = null, $value = null) {
644
                if (!$field) {
645
                        $field = $this->entity();
646
                } elseif (is_string($field)) {
647
                        $field = Hash::filter(explode('.', $field));
648
                }
649

    
650
                foreach ($this->_unlockedFields as $unlockField) {
651
                        $unlockParts = explode('.', $unlockField);
652
                        if (array_values(array_intersect($field, $unlockParts)) === $unlockParts) {
653
                                return;
654
                        }
655
                }
656

    
657
                $field = implode('.', $field);
658
                $field = preg_replace('/(\.\d+)+$/', '', $field);
659

    
660
                if ($lock) {
661
                        if (!in_array($field, $this->fields)) {
662
                                if ($value !== null) {
663
                                        return $this->fields[$field] = $value;
664
                                } elseif (isset($this->fields[$field]) && $value === null) {
665
                                        unset($this->fields[$field]);
666
                                }
667
                                $this->fields[] = $field;
668
                        }
669
                } else {
670
                        $this->unlockField($field);
671
                }
672
        }
673

    
674
/**
675
 * Returns true if there is an error for the given field, otherwise false
676
 *
677
 * @param string $field This should be "Modelname.fieldname"
678
 * @return bool If there are errors this method returns true, else false.
679
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::isFieldError
680
 */
681
        public function isFieldError($field) {
682
                $this->setEntity($field);
683
                return (bool)$this->tagIsInvalid();
684
        }
685

    
686
/**
687
 * Returns a formatted error message for given FORM field, NULL if no errors.
688
 *
689
 * ### Options:
690
 *
691
 * - `escape` boolean - Whether or not to html escape the contents of the error.
692
 * - `wrap` mixed - Whether or not the error message should be wrapped in a div. If a
693
 *   string, will be used as the HTML tag to use.
694
 * - `class` string - The class name for the error message
695
 *
696
 * @param string $field A field name, like "Modelname.fieldname"
697
 * @param string|array $text Error message as string or array of messages.
698
 *   If array contains `attributes` key it will be used as options for error container
699
 * @param array $options Rendering options for <div /> wrapper tag
700
 * @return string|null If there are errors this method returns an error message, otherwise null.
701
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::error
702
 */
703
        public function error($field, $text = null, $options = array()) {
704
                $defaults = array('wrap' => true, 'class' => 'error-message', 'escape' => true);
705
                $options += $defaults;
706
                $this->setEntity($field);
707

    
708
                $error = $this->tagIsInvalid();
709
                if ($error === false) {
710
                        return null;
711
                }
712
                if (is_array($text)) {
713
                        if (isset($text['attributes']) && is_array($text['attributes'])) {
714
                                $options = array_merge($options, $text['attributes']);
715
                                unset($text['attributes']);
716
                        }
717
                        $tmp = array();
718
                        foreach ($error as &$e) {
719
                                if (isset($text[$e])) {
720
                                        $tmp[] = $text[$e];
721
                                } else {
722
                                        $tmp[] = $e;
723
                                }
724
                        }
725
                        $text = $tmp;
726
                }
727

    
728
                if ($text !== null) {
729
                        $error = $text;
730
                }
731
                if (is_array($error)) {
732
                        foreach ($error as &$e) {
733
                                if (is_numeric($e)) {
734
                                        $e = __d('cake', 'Error in field %s', Inflector::humanize($this->field()));
735
                                }
736
                        }
737
                }
738
                if ($options['escape']) {
739
                        $error = h($error);
740
                        unset($options['escape']);
741
                }
742
                if (is_array($error)) {
743
                        if (count($error) > 1) {
744
                                $listParams = array();
745
                                if (isset($options['listOptions'])) {
746
                                        if (is_string($options['listOptions'])) {
747
                                                $listParams[] = $options['listOptions'];
748
                                        } else {
749
                                                if (isset($options['listOptions']['itemOptions'])) {
750
                                                        $listParams[] = $options['listOptions']['itemOptions'];
751
                                                        unset($options['listOptions']['itemOptions']);
752
                                                } else {
753
                                                        $listParams[] = array();
754
                                                }
755
                                                if (isset($options['listOptions']['tag'])) {
756
                                                        $listParams[] = $options['listOptions']['tag'];
757
                                                        unset($options['listOptions']['tag']);
758
                                                }
759
                                                array_unshift($listParams, $options['listOptions']);
760
                                        }
761
                                        unset($options['listOptions']);
762
                                }
763
                                array_unshift($listParams, $error);
764
                                $error = call_user_func_array(array($this->Html, 'nestedList'), $listParams);
765
                        } else {
766
                                $error = array_pop($error);
767
                        }
768
                }
769
                if ($options['wrap']) {
770
                        $tag = is_string($options['wrap']) ? $options['wrap'] : 'div';
771
                        unset($options['wrap']);
772
                        return $this->Html->tag($tag, $error, $options);
773
                }
774
                return $error;
775
        }
776

    
777
/**
778
 * Returns a formatted LABEL element for HTML FORMs. Will automatically generate
779
 * a `for` attribute if one is not provided.
780
 *
781
 * ### Options
782
 *
783
 * - `for` - Set the for attribute, if its not defined the for attribute
784
 *   will be generated from the $fieldName parameter using
785
 *   FormHelper::domId().
786
 *
787
 * Examples:
788
 *
789
 * The text and for attribute are generated off of the fieldname
790
 *
791
 * ```
792
 * echo $this->Form->label('Post.published');
793
 * <label for="PostPublished">Published</label>
794
 * ```
795
 *
796
 * Custom text:
797
 *
798
 * ```
799
 * echo $this->Form->label('Post.published', 'Publish');
800
 * <label for="PostPublished">Publish</label>
801
 * ```
802
 *
803
 * Custom class name:
804
 *
805
 * ```
806
 * echo $this->Form->label('Post.published', 'Publish', 'required');
807
 * <label for="PostPublished" class="required">Publish</label>
808
 * ```
809
 *
810
 * Custom attributes:
811
 *
812
 * ```
813
 * echo $this->Form->label('Post.published', 'Publish', array(
814
 *                'for' => 'post-publish'
815
 * ));
816
 * <label for="post-publish">Publish</label>
817
 * ```
818
 *
819
 * *Warning* Unlike most FormHelper methods, this method does not automatically
820
 * escape the $text parameter. You must escape the $text parameter yourself if you
821
 * are using user supplied data.
822
 *
823
 * @param string $fieldName This should be "Modelname.fieldname"
824
 * @param string $text Text that will appear in the label field. If
825
 *   $text is left undefined the text will be inflected from the
826
 *   fieldName.
827
 * @param array|string $options An array of HTML attributes, or a string, to be used as a class name.
828
 * @return string The formatted LABEL element
829
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::label
830
 */
831
        public function label($fieldName = null, $text = null, $options = array()) {
832
                if ($fieldName === null) {
833
                        $fieldName = implode('.', $this->entity());
834
                }
835

    
836
                if ($text === null) {
837
                        if (strpos($fieldName, '.') !== false) {
838
                                $fieldElements = explode('.', $fieldName);
839
                                $text = array_pop($fieldElements);
840
                        } else {
841
                                $text = $fieldName;
842
                        }
843
                        if (substr($text, -3) === '_id') {
844
                                $text = substr($text, 0, -3);
845
                        }
846
                        $text = __(Inflector::humanize(Inflector::underscore($text)));
847
                }
848

    
849
                if (is_string($options)) {
850
                        $options = array('class' => $options);
851
                }
852

    
853
                if (isset($options['for'])) {
854
                        $labelFor = $options['for'];
855
                        unset($options['for']);
856
                } else {
857
                        $labelFor = $this->domId($fieldName);
858
                }
859

    
860
                return $this->Html->useTag('label', $labelFor, $options, $text);
861
        }
862

    
863
/**
864
 * Generate a set of inputs for `$fields`. If $fields is null the fields of current model
865
 * will be used.
866
 *
867
 * You can customize individual inputs through `$fields`.
868
 * ```
869
 *        $this->Form->inputs(array(
870
 *                'name' => array('label' => 'custom label')
871
 *        ));
872
 * ```
873
 *
874
 * In addition to controller fields output, `$fields` can be used to control legend
875
 * and fieldset rendering.
876
 * `$this->Form->inputs('My legend');` Would generate an input set with a custom legend.
877
 * Passing `fieldset` and `legend` key in `$fields` array has been deprecated since 2.3,
878
 * for more fine grained control use the `fieldset` and `legend` keys in `$options` param.
879
 *
880
 * @param array $fields An array of fields to generate inputs for, or null.
881
 * @param array $blacklist A simple array of fields to not create inputs for.
882
 * @param array $options Options array. Valid keys are:
883
 * - `fieldset` Set to false to disable the fieldset. If a string is supplied it will be used as
884
 *    the class name for the fieldset element.
885
 * - `legend` Set to false to disable the legend for the generated input set. Or supply a string
886
 *    to customize the legend text.
887
 * @return string Completed form inputs.
888
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::inputs
889
 */
890
        public function inputs($fields = null, $blacklist = null, $options = array()) {
891
                $fieldset = $legend = true;
892
                $modelFields = array();
893
                $model = $this->model();
894
                if ($model) {
895
                        $modelFields = array_keys((array)$this->_introspectModel($model, 'fields'));
896
                }
897
                if (is_array($fields)) {
898
                        if (array_key_exists('legend', $fields) && !in_array('legend', $modelFields)) {
899
                                $legend = $fields['legend'];
900
                                unset($fields['legend']);
901
                        }
902

    
903
                        if (isset($fields['fieldset']) && !in_array('fieldset', $modelFields)) {
904
                                $fieldset = $fields['fieldset'];
905
                                unset($fields['fieldset']);
906
                        }
907
                } elseif ($fields !== null) {
908
                        $fieldset = $legend = $fields;
909
                        if (!is_bool($fieldset)) {
910
                                $fieldset = true;
911
                        }
912
                        $fields = array();
913
                }
914

    
915
                if (isset($options['legend'])) {
916
                        $legend = $options['legend'];
917
                }
918
                if (isset($options['fieldset'])) {
919
                        $fieldset = $options['fieldset'];
920
                }
921

    
922
                if (empty($fields)) {
923
                        $fields = $modelFields;
924
                }
925

    
926
                if ($legend === true) {
927
                        $actionName = __d('cake', 'New %s');
928
                        $isEdit = (
929
                                strpos($this->request->params['action'], 'update') !== false ||
930
                                strpos($this->request->params['action'], 'edit') !== false
931
                        );
932
                        if ($isEdit) {
933
                                $actionName = __d('cake', 'Edit %s');
934
                        }
935
                        $modelName = Inflector::humanize(Inflector::underscore($model));
936
                        $legend = sprintf($actionName, __($modelName));
937
                }
938

    
939
                $out = null;
940
                foreach ($fields as $name => $options) {
941
                        if (is_numeric($name) && !is_array($options)) {
942
                                $name = $options;
943
                                $options = array();
944
                        }
945
                        $entity = explode('.', $name);
946
                        $blacklisted = (
947
                                is_array($blacklist) &&
948
                                (in_array($name, $blacklist) || in_array(end($entity), $blacklist))
949
                        );
950
                        if ($blacklisted) {
951
                                continue;
952
                        }
953
                        $out .= $this->input($name, $options);
954
                }
955

    
956
                if (is_string($fieldset)) {
957
                        $fieldsetClass = sprintf(' class="%s"', $fieldset);
958
                } else {
959
                        $fieldsetClass = '';
960
                }
961

    
962
                if ($fieldset) {
963
                        if ($legend) {
964
                                $out = $this->Html->useTag('legend', $legend) . $out;
965
                        }
966
                        $out = $this->Html->useTag('fieldset', $fieldsetClass, $out);
967
                }
968
                return $out;
969
        }
970

    
971
/**
972
 * Generates a form input element complete with label and wrapper div
973
 *
974
 * ### Options
975
 *
976
 * See each field type method for more information. Any options that are part of
977
 * $attributes or $options for the different **type** methods can be included in `$options` for input().i
978
 * Additionally, any unknown keys that are not in the list below, or part of the selected type's options
979
 * will be treated as a regular html attribute for the generated input.
980
 *
981
 * - `type` - Force the type of widget you want. e.g. `type => 'select'`
982
 * - `label` - Either a string label, or an array of options for the label. See FormHelper::label().
983
 * - `div` - Either `false` to disable the div, or an array of options for the div.
984
 *        See HtmlHelper::div() for more options.
985
 * - `options` - For widgets that take options e.g. radio, select.
986
 * - `error` - Control the error message that is produced. Set to `false` to disable any kind of error reporting (field
987
 *    error and error messages).
988
 * - `errorMessage` - Boolean to control rendering error messages (field error will still occur).
989
 * - `empty` - String or boolean to enable empty select box options.
990
 * - `before` - Content to place before the label + input.
991
 * - `after` - Content to place after the label + input.
992
 * - `between` - Content to place between the label + input.
993
 * - `format` - Format template for element order. Any element that is not in the array, will not be in the output.
994
 *        - Default input format order: array('before', 'label', 'between', 'input', 'after', 'error')
995
 *        - Default checkbox format order: array('before', 'input', 'between', 'label', 'after', 'error')
996
 *        - Hidden input will not be formatted
997
 *        - Radio buttons cannot have the order of input and label elements controlled with these settings.
998
 *
999
 * @param string $fieldName This should be "Modelname.fieldname"
1000
 * @param array $options Each type of input takes different options.
1001
 * @return string Completed form widget.
1002
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#creating-form-elements
1003
 */
1004
        public function input($fieldName, $options = array()) {
1005
                $this->setEntity($fieldName);
1006
                $options = $this->_parseOptions($options);
1007

    
1008
                $divOptions = $this->_divOptions($options);
1009
                unset($options['div']);
1010

    
1011
                if ($options['type'] === 'radio' && isset($options['options'])) {
1012
                        $radioOptions = (array)$options['options'];
1013
                        unset($options['options']);
1014
                }
1015

    
1016
                $label = $this->_getLabel($fieldName, $options);
1017
                if ($options['type'] !== 'radio') {
1018
                        unset($options['label']);
1019
                }
1020

    
1021
                $error = $this->_extractOption('error', $options, null);
1022
                unset($options['error']);
1023

    
1024
                $errorMessage = $this->_extractOption('errorMessage', $options, true);
1025
                unset($options['errorMessage']);
1026

    
1027
                $selected = $this->_extractOption('selected', $options, null);
1028
                unset($options['selected']);
1029

    
1030
                if ($options['type'] === 'datetime' || $options['type'] === 'date' || $options['type'] === 'time') {
1031
                        $dateFormat = $this->_extractOption('dateFormat', $options, 'MDY');
1032
                        $timeFormat = $this->_extractOption('timeFormat', $options, 12);
1033
                        unset($options['dateFormat'], $options['timeFormat']);
1034
                }
1035

    
1036
                $type = $options['type'];
1037
                $out = array('before' => $options['before'], 'label' => $label, 'between' => $options['between'], 'after' => $options['after']);
1038
                $format = $this->_getFormat($options);
1039

    
1040
                unset($options['type'], $options['before'], $options['between'], $options['after'], $options['format']);
1041

    
1042
                $out['error'] = null;
1043
                if ($type !== 'hidden' && $error !== false) {
1044
                        $errMsg = $this->error($fieldName, $error);
1045
                        if ($errMsg) {
1046
                                $divOptions = $this->addClass($divOptions, 'error');
1047
                                if ($errorMessage) {
1048
                                        $out['error'] = $errMsg;
1049
                                }
1050
                        }
1051
                }
1052

    
1053
                if ($type === 'radio' && isset($out['between'])) {
1054
                        $options['between'] = $out['between'];
1055
                        $out['between'] = null;
1056
                }
1057
                $out['input'] = $this->_getInput(compact('type', 'fieldName', 'options', 'radioOptions', 'selected', 'dateFormat', 'timeFormat'));
1058

    
1059
                $output = '';
1060
                foreach ($format as $element) {
1061
                        $output .= $out[$element];
1062
                }
1063

    
1064
                if (!empty($divOptions['tag'])) {
1065
                        $tag = $divOptions['tag'];
1066
                        unset($divOptions['tag']);
1067
                        $output = $this->Html->tag($tag, $output, $divOptions);
1068
                }
1069
                return $output;
1070
        }
1071

    
1072
/**
1073
 * Generates an input element
1074
 *
1075
 * @param array $args The options for the input element
1076
 * @return string The generated input element
1077
 */
1078
        protected function _getInput($args) {
1079
                extract($args);
1080
                switch ($type) {
1081
                        case 'hidden':
1082
                                return $this->hidden($fieldName, $options);
1083
                        case 'checkbox':
1084
                                return $this->checkbox($fieldName, $options);
1085
                        case 'radio':
1086
                                return $this->radio($fieldName, $radioOptions, $options);
1087
                        case 'file':
1088
                                return $this->file($fieldName, $options);
1089
                        case 'select':
1090
                                $options += array('options' => array(), 'value' => $selected);
1091
                                $list = $options['options'];
1092
                                unset($options['options']);
1093
                                return $this->select($fieldName, $list, $options);
1094
                        case 'time':
1095
                                $options += array('value' => $selected);
1096
                                return $this->dateTime($fieldName, null, $timeFormat, $options);
1097
                        case 'date':
1098
                                $options += array('value' => $selected);
1099
                                return $this->dateTime($fieldName, $dateFormat, null, $options);
1100
                        case 'datetime':
1101
                                $options += array('value' => $selected);
1102
                                return $this->dateTime($fieldName, $dateFormat, $timeFormat, $options);
1103
                        case 'textarea':
1104
                                return $this->textarea($fieldName, $options + array('cols' => '30', 'rows' => '6'));
1105
                        case 'url':
1106
                                return $this->text($fieldName, array('type' => 'url') + $options);
1107
                        default:
1108
                                return $this->{$type}($fieldName, $options);
1109
                }
1110
        }
1111

    
1112
/**
1113
 * Generates input options array
1114
 *
1115
 * @param array $options Options list.
1116
 * @return array Options
1117
 */
1118
        protected function _parseOptions($options) {
1119
                $options = array_merge(
1120
                        array('before' => null, 'between' => null, 'after' => null, 'format' => null),
1121
                        $this->_inputDefaults,
1122
                        $options
1123
                );
1124

    
1125
                if (!isset($options['type'])) {
1126
                        $options = $this->_magicOptions($options);
1127
                }
1128

    
1129
                if (in_array($options['type'], array('radio', 'select'))) {
1130
                        $options = $this->_optionsOptions($options);
1131
                }
1132

    
1133
                $options = $this->_maxLength($options);
1134

    
1135
                if (isset($options['rows']) || isset($options['cols'])) {
1136
                        $options['type'] = 'textarea';
1137
                }
1138

    
1139
                if ($options['type'] === 'datetime' || $options['type'] === 'date' || $options['type'] === 'time' || $options['type'] === 'select') {
1140
                        $options += array('empty' => false);
1141
                }
1142
                return $options;
1143
        }
1144

    
1145
/**
1146
 * Generates list of options for multiple select
1147
 *
1148
 * @param array $options Options list.
1149
 * @return array
1150
 */
1151
        protected function _optionsOptions($options) {
1152
                if (isset($options['options'])) {
1153
                        return $options;
1154
                }
1155
                $varName = Inflector::variable(
1156
                        Inflector::pluralize(preg_replace('/_id$/', '', $this->field()))
1157
                );
1158
                $varOptions = $this->_View->get($varName);
1159
                if (!is_array($varOptions)) {
1160
                        return $options;
1161
                }
1162
                if ($options['type'] !== 'radio') {
1163
                        $options['type'] = 'select';
1164
                }
1165
                $options['options'] = $varOptions;
1166
                return $options;
1167
        }
1168

    
1169
/**
1170
 * Magically set option type and corresponding options
1171
 *
1172
 * @param array $options Options list.
1173
 * @return array
1174
 */
1175
        protected function _magicOptions($options) {
1176
                $modelKey = $this->model();
1177
                $fieldKey = $this->field();
1178
                $options['type'] = 'text';
1179
                if (isset($options['options'])) {
1180
                        $options['type'] = 'select';
1181
                } elseif (in_array($fieldKey, array('psword', 'passwd', 'password'))) {
1182
                        $options['type'] = 'password';
1183
                } elseif (in_array($fieldKey, array('tel', 'telephone', 'phone'))) {
1184
                        $options['type'] = 'tel';
1185
                } elseif ($fieldKey === 'email') {
1186
                        $options['type'] = 'email';
1187
                } elseif (isset($options['checked'])) {
1188
                        $options['type'] = 'checkbox';
1189
                } elseif ($fieldDef = $this->_introspectModel($modelKey, 'fields', $fieldKey)) {
1190
                        $type = $fieldDef['type'];
1191
                        $primaryKey = $this->fieldset[$modelKey]['key'];
1192
                        $map = array(
1193
                                'string' => 'text', 'datetime' => 'datetime',
1194
                                'boolean' => 'checkbox', 'timestamp' => 'datetime',
1195
                                'text' => 'textarea', 'time' => 'time',
1196
                                'date' => 'date', 'float' => 'number',
1197
                                'integer' => 'number', 'decimal' => 'number',
1198
                                'binary' => 'file'
1199
                        );
1200

    
1201
                        if (isset($this->map[$type])) {
1202
                                $options['type'] = $this->map[$type];
1203
                        } elseif (isset($map[$type])) {
1204
                                $options['type'] = $map[$type];
1205
                        }
1206
                        if ($fieldKey === $primaryKey) {
1207
                                $options['type'] = 'hidden';
1208
                        }
1209
                        if ($options['type'] === 'number' &&
1210
                                !isset($options['step'])
1211
                        ) {
1212
                                if ($type === 'decimal' && isset($fieldDef['length'])) {
1213
                                        $decimalPlaces = substr($fieldDef['length'], strpos($fieldDef['length'], ',') + 1);
1214
                                        $options['step'] = sprintf('%.' . $decimalPlaces . 'F', pow(10, -1 * $decimalPlaces));
1215
                                } elseif ($type === 'float' || $type === 'decimal') {
1216
                                        $options['step'] = 'any';
1217
                                }
1218
                        }
1219
                }
1220

    
1221
                if (preg_match('/_id$/', $fieldKey) && $options['type'] !== 'hidden') {
1222
                        $options['type'] = 'select';
1223
                }
1224

    
1225
                if ($modelKey === $fieldKey) {
1226
                        $options['type'] = 'select';
1227
                        if (!isset($options['multiple'])) {
1228
                                $options['multiple'] = 'multiple';
1229
                        }
1230
                }
1231
                if (in_array($options['type'], array('text', 'number'))) {
1232
                        $options = $this->_optionsOptions($options);
1233
                }
1234
                if ($options['type'] === 'select' && array_key_exists('step', $options)) {
1235
                        unset($options['step']);
1236
                }
1237

    
1238
                return $options;
1239
        }
1240

    
1241
/**
1242
 * Generate format options
1243
 *
1244
 * @param array $options Options list.
1245
 * @return array
1246
 */
1247
        protected function _getFormat($options) {
1248
                if ($options['type'] === 'hidden') {
1249
                        return array('input');
1250
                }
1251
                if (is_array($options['format']) && in_array('input', $options['format'])) {
1252
                        return $options['format'];
1253
                }
1254
                if ($options['type'] === 'checkbox') {
1255
                        return array('before', 'input', 'between', 'label', 'after', 'error');
1256
                }
1257
                return array('before', 'label', 'between', 'input', 'after', 'error');
1258
        }
1259

    
1260
/**
1261
 * Generate label for input
1262
 *
1263
 * @param string $fieldName Field name.
1264
 * @param array $options Options list.
1265
 * @return bool|string false or Generated label element
1266
 */
1267
        protected function _getLabel($fieldName, $options) {
1268
                if ($options['type'] === 'radio') {
1269
                        return false;
1270
                }
1271

    
1272
                $label = null;
1273
                if (isset($options['label'])) {
1274
                        $label = $options['label'];
1275
                }
1276

    
1277
                if ($label === false) {
1278
                        return false;
1279
                }
1280
                return $this->_inputLabel($fieldName, $label, $options);
1281
        }
1282

    
1283
/**
1284
 * Calculates maxlength option
1285
 *
1286
 * @param array $options Options list.
1287
 * @return array
1288
 */
1289
        protected function _maxLength($options) {
1290
                $fieldDef = $this->_introspectModel($this->model(), 'fields', $this->field());
1291
                $autoLength = (
1292
                        !array_key_exists('maxlength', $options) &&
1293
                        isset($fieldDef['length']) &&
1294
                        is_scalar($fieldDef['length']) &&
1295
                        $fieldDef['length'] < 1000000 &&
1296
                        $fieldDef['type'] !== 'decimal' &&
1297
                        $options['type'] !== 'select'
1298
                );
1299
                if ($autoLength &&
1300
                        in_array($options['type'], array('text', 'textarea', 'email', 'tel', 'url', 'search'))
1301
                ) {
1302
                        $options['maxlength'] = (int)$fieldDef['length'];
1303
                }
1304
                return $options;
1305
        }
1306

    
1307
/**
1308
 * Generate div options for input
1309
 *
1310
 * @param array $options Options list.
1311
 * @return array
1312
 */
1313
        protected function _divOptions($options) {
1314
                if ($options['type'] === 'hidden') {
1315
                        return array();
1316
                }
1317
                $div = $this->_extractOption('div', $options, true);
1318
                if (!$div) {
1319
                        return array();
1320
                }
1321

    
1322
                $divOptions = array('class' => 'input');
1323
                $divOptions = $this->addClass($divOptions, $options['type']);
1324
                if (is_string($div)) {
1325
                        $divOptions['class'] = $div;
1326
                } elseif (is_array($div)) {
1327
                        $divOptions = array_merge($divOptions, $div);
1328
                }
1329
                if ($this->_extractOption('required', $options) !== false &&
1330
                        $this->_introspectModel($this->model(), 'validates', $this->field())
1331
                ) {
1332
                        $divOptions = $this->addClass($divOptions, 'required');
1333
                }
1334
                if (!isset($divOptions['tag'])) {
1335
                        $divOptions['tag'] = 'div';
1336
                }
1337
                return $divOptions;
1338
        }
1339

    
1340
/**
1341
 * Extracts a single option from an options array.
1342
 *
1343
 * @param string $name The name of the option to pull out.
1344
 * @param array $options The array of options you want to extract.
1345
 * @param mixed $default The default option value
1346
 * @return mixed the contents of the option or default
1347
 */
1348
        protected function _extractOption($name, $options, $default = null) {
1349
                if (array_key_exists($name, $options)) {
1350
                        return $options[$name];
1351
                }
1352
                return $default;
1353
        }
1354

    
1355
/**
1356
 * Generate a label for an input() call.
1357
 *
1358
 * $options can contain a hash of id overrides. These overrides will be
1359
 * used instead of the generated values if present.
1360
 *
1361
 * @param string $fieldName Field name.
1362
 * @param string|array $label Label text or array with text and options.
1363
 * @param array $options Options for the label element. 'NONE' option is
1364
 *   deprecated and will be removed in 3.0
1365
 * @return string Generated label element
1366
 */
1367
        protected function _inputLabel($fieldName, $label, $options) {
1368
                $labelAttributes = $this->domId(array(), 'for');
1369
                $idKey = null;
1370
                if ($options['type'] === 'date' || $options['type'] === 'datetime') {
1371
                        $firstInput = 'M';
1372
                        if (array_key_exists('dateFormat', $options) &&
1373
                                ($options['dateFormat'] === null || $options['dateFormat'] === 'NONE')
1374
                        ) {
1375
                                $firstInput = 'H';
1376
                        } elseif (!empty($options['dateFormat'])) {
1377
                                $firstInput = substr($options['dateFormat'], 0, 1);
1378
                        }
1379
                        switch ($firstInput) {
1380
                                case 'D':
1381
                                        $idKey = 'day';
1382
                                        $labelAttributes['for'] .= 'Day';
1383
                                        break;
1384
                                case 'Y':
1385
                                        $idKey = 'year';
1386
                                        $labelAttributes['for'] .= 'Year';
1387
                                        break;
1388
                                case 'M':
1389
                                        $idKey = 'month';
1390
                                        $labelAttributes['for'] .= 'Month';
1391
                                        break;
1392
                                case 'H':
1393
                                        $idKey = 'hour';
1394
                                        $labelAttributes['for'] .= 'Hour';
1395
                        }
1396
                }
1397
                if ($options['type'] === 'time') {
1398
                        $labelAttributes['for'] .= 'Hour';
1399
                        $idKey = 'hour';
1400
                }
1401
                if (isset($idKey) && isset($options['id']) && isset($options['id'][$idKey])) {
1402
                        $labelAttributes['for'] = $options['id'][$idKey];
1403
                }
1404

    
1405
                if (is_array($label)) {
1406
                        $labelText = null;
1407
                        if (isset($label['text'])) {
1408
                                $labelText = $label['text'];
1409
                                unset($label['text']);
1410
                        }
1411
                        $labelAttributes = array_merge($labelAttributes, $label);
1412
                } else {
1413
                        $labelText = $label;
1414
                }
1415

    
1416
                if (isset($options['id']) && is_string($options['id'])) {
1417
                        $labelAttributes = array_merge($labelAttributes, array('for' => $options['id']));
1418
                }
1419
                return $this->label($fieldName, $labelText, $labelAttributes);
1420
        }
1421

    
1422
/**
1423
 * Creates a checkbox input widget.
1424
 *
1425
 * ### Options:
1426
 *
1427
 * - `value` - the value of the checkbox
1428
 * - `checked` - boolean indicate that this checkbox is checked.
1429
 * - `hiddenField` - boolean to indicate if you want the results of checkbox() to include
1430
 *    a hidden input with a value of ''.
1431
 * - `disabled` - create a disabled input.
1432
 * - `default` - Set the default value for the checkbox. This allows you to start checkboxes
1433
 *    as checked, without having to check the POST data. A matching POST data value, will overwrite
1434
 *    the default value.
1435
 *
1436
 * @param string $fieldName Name of a field, like this "Modelname.fieldname"
1437
 * @param array $options Array of HTML attributes.
1438
 * @return string An HTML text input element.
1439
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#options-for-select-checkbox-and-radio-inputs
1440
 */
1441
        public function checkbox($fieldName, $options = array()) {
1442
                $valueOptions = array();
1443
                if (isset($options['default'])) {
1444
                        $valueOptions['default'] = $options['default'];
1445
                        unset($options['default']);
1446
                }
1447

    
1448
                $options += array('value' => 1, 'required' => false);
1449
                $options = $this->_initInputField($fieldName, $options) + array('hiddenField' => true);
1450
                $value = current($this->value($valueOptions));
1451
                $output = '';
1452

    
1453
                if ((!isset($options['checked']) && !empty($value) && $value == $options['value']) ||
1454
                        !empty($options['checked'])
1455
                ) {
1456
                        $options['checked'] = 'checked';
1457
                }
1458
                if ($options['hiddenField']) {
1459
                        $hiddenOptions = array(
1460
                                'id' => $options['id'] . '_',
1461
                                'name' => $options['name'],
1462
                                'value' => ($options['hiddenField'] !== true ? $options['hiddenField'] : '0'),
1463
                                'form' => isset($options['form']) ? $options['form'] : null,
1464
                                'secure' => false,
1465
                        );
1466
                        if (isset($options['disabled']) && $options['disabled']) {
1467
                                $hiddenOptions['disabled'] = 'disabled';
1468
                        }
1469
                        $output = $this->hidden($fieldName, $hiddenOptions);
1470
                }
1471
                unset($options['hiddenField']);
1472

    
1473
                return $output . $this->Html->useTag('checkbox', $options['name'], array_diff_key($options, array('name' => null)));
1474
        }
1475

    
1476
/**
1477
 * Creates a set of radio widgets. Will create a legend and fieldset
1478
 * by default. Use $options to control this
1479
 *
1480
 * You can also customize each radio input element using an array of arrays:
1481
 *
1482
 * ```
1483
 * $options = array(
1484
 *  array('name' => 'United states', 'value' => 'US', 'title' => 'My title'),
1485
 *  array('name' => 'Germany', 'value' => 'DE', 'class' => 'de-de', 'title' => 'Another title'),
1486
 * );
1487
 * ```
1488
 *
1489
 * ### Attributes:
1490
 *
1491
 * - `separator` - define the string in between the radio buttons
1492
 * - `between` - the string between legend and input set or array of strings to insert
1493
 *    strings between each input block
1494
 * - `legend` - control whether or not the widget set has a fieldset & legend
1495
 * - `value` - indicate a value that is should be checked
1496
 * - `label` - boolean to indicate whether or not labels for widgets show be displayed
1497
 * - `hiddenField` - boolean to indicate if you want the results of radio() to include
1498
 *    a hidden input with a value of ''. This is useful for creating radio sets that non-continuous
1499
 * - `disabled` - Set to `true` or `disabled` to disable all the radio buttons.
1500
 * - `empty` - Set to `true` to create an input with the value '' as the first option. When `true`
1501
 *   the radio label will be 'empty'. Set this option to a string to control the label value.
1502
 *
1503
 * @param string $fieldName Name of a field, like this "Modelname.fieldname"
1504
 * @param array $options Radio button options array.
1505
 * @param array $attributes Array of HTML attributes, and special attributes above.
1506
 * @return string Completed radio widget set.
1507
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#options-for-select-checkbox-and-radio-inputs
1508
 */
1509
        public function radio($fieldName, $options = array(), $attributes = array()) {
1510
                $attributes['options'] = $options;
1511
                $attributes = $this->_initInputField($fieldName, $attributes);
1512
                unset($attributes['options']);
1513

    
1514
                $showEmpty = $this->_extractOption('empty', $attributes);
1515
                if ($showEmpty) {
1516
                        $showEmpty = ($showEmpty === true) ? __d('cake', 'empty') : $showEmpty;
1517
                        $options = array('' => $showEmpty) + $options;
1518
                }
1519
                unset($attributes['empty']);
1520

    
1521
                $legend = false;
1522
                if (isset($attributes['legend'])) {
1523
                        $legend = $attributes['legend'];
1524
                        unset($attributes['legend']);
1525
                } elseif (count($options) > 1) {
1526
                        $legend = __(Inflector::humanize($this->field()));
1527
                }
1528

    
1529
                $label = true;
1530
                if (isset($attributes['label'])) {
1531
                        $label = $attributes['label'];
1532
                        unset($attributes['label']);
1533
                }
1534

    
1535
                $separator = null;
1536
                if (isset($attributes['separator'])) {
1537
                        $separator = $attributes['separator'];
1538
                        unset($attributes['separator']);
1539
                }
1540

    
1541
                $between = null;
1542
                if (isset($attributes['between'])) {
1543
                        $between = $attributes['between'];
1544
                        unset($attributes['between']);
1545
                }
1546

    
1547
                $value = null;
1548
                if (isset($attributes['value'])) {
1549
                        $value = $attributes['value'];
1550
                } else {
1551
                        $value = $this->value($fieldName);
1552
                }
1553

    
1554
                $disabled = array();
1555
                if (isset($attributes['disabled'])) {
1556
                        $disabled = $attributes['disabled'];
1557
                }
1558

    
1559
                $out = array();
1560

    
1561
                $hiddenField = isset($attributes['hiddenField']) ? $attributes['hiddenField'] : true;
1562
                unset($attributes['hiddenField']);
1563

    
1564
                if (isset($value) && is_bool($value)) {
1565
                        $value = $value ? 1 : 0;
1566
                }
1567

    
1568
                $this->_domIdSuffixes = array();
1569
                foreach ($options as $optValue => $optTitle) {
1570
                        $optionsHere = array('value' => $optValue, 'disabled' => false);
1571
                        if (is_array($optTitle)) {
1572
                                if (isset($optTitle['value'])) {
1573
                                        $optionsHere['value'] = $optTitle['value'];
1574
                                }
1575

    
1576
                                $optionsHere += $optTitle;
1577
                                $optTitle = $optionsHere['name'];
1578
                                unset($optionsHere['name']);
1579
                        }
1580

    
1581
                        if (isset($value) && strval($optValue) === strval($value)) {
1582
                                $optionsHere['checked'] = 'checked';
1583
                        }
1584
                        $isNumeric = is_numeric($optValue);
1585
                        if ($disabled && (!is_array($disabled) || in_array((string)$optValue, $disabled, !$isNumeric))) {
1586
                                $optionsHere['disabled'] = true;
1587
                        }
1588
                        $tagName = $attributes['id'] . $this->domIdSuffix($optValue);
1589

    
1590
                        if ($label) {
1591
                                $labelOpts = is_array($label) ? $label : array();
1592
                                $labelOpts += array('for' => $tagName);
1593
                                $optTitle = $this->label($tagName, $optTitle, $labelOpts);
1594
                        }
1595

    
1596
                        if (is_array($between)) {
1597
                                $optTitle .= array_shift($between);
1598
                        }
1599
                        $allOptions = $optionsHere + $attributes;
1600
                        $out[] = $this->Html->useTag('radio', $attributes['name'], $tagName,
1601
                                array_diff_key($allOptions, array('name' => null, 'type' => null, 'id' => null)),
1602
                                $optTitle
1603
                        );
1604
                }
1605
                $hidden = null;
1606

    
1607
                if ($hiddenField) {
1608
                        if (!isset($value) || $value === '') {
1609
                                $hidden = $this->hidden($fieldName, array(
1610
                                        'form' => isset($attributes['form']) ? $attributes['form'] : null,
1611
                                        'id' => $attributes['id'] . '_',
1612
                                        'value' => '',
1613
                                        'name' => $attributes['name']
1614
                                ));
1615
                        }
1616
                }
1617
                $out = $hidden . implode($separator, $out);
1618

    
1619
                if (is_array($between)) {
1620
                        $between = '';
1621
                }
1622
                if ($legend) {
1623
                        $out = $this->Html->useTag('fieldset', '', $this->Html->useTag('legend', $legend) . $between . $out);
1624
                }
1625
                return $out;
1626
        }
1627

    
1628
/**
1629
 * Missing method handler - implements various simple input types. Is used to create inputs
1630
 * of various types. e.g. `$this->Form->text();` will create `<input type="text" />` while
1631
 * `$this->Form->range();` will create `<input type="range" />`
1632
 *
1633
 * ### Usage
1634
 *
1635
 * `$this->Form->search('User.query', array('value' => 'test'));`
1636
 *
1637
 * Will make an input like:
1638
 *
1639
 * `<input type="search" id="UserQuery" name="data[User][query]" value="test" />`
1640
 *
1641
 * The first argument to an input type should always be the fieldname, in `Model.field` format.
1642
 * The second argument should always be an array of attributes for the input.
1643
 *
1644
 * @param string $method Method name / input type to make.
1645
 * @param array $params Parameters for the method call
1646
 * @return string Formatted input method.
1647
 * @throws CakeException When there are no params for the method call.
1648
 */
1649
        public function __call($method, $params) {
1650
                $options = array();
1651
                if (empty($params)) {
1652
                        throw new CakeException(__d('cake_dev', 'Missing field name for FormHelper::%s', $method));
1653
                }
1654
                if (isset($params[1])) {
1655
                        $options = $params[1];
1656
                }
1657
                if (!isset($options['type'])) {
1658
                        $options['type'] = $method;
1659
                }
1660
                $options = $this->_initInputField($params[0], $options);
1661
                return $this->Html->useTag('input', $options['name'], array_diff_key($options, array('name' => null)));
1662
        }
1663

    
1664
/**
1665
 * Creates a textarea widget.
1666
 *
1667
 * ### Options:
1668
 *
1669
 * - `escape` - Whether or not the contents of the textarea should be escaped. Defaults to true.
1670
 *
1671
 * @param string $fieldName Name of a field, in the form "Modelname.fieldname"
1672
 * @param array $options Array of HTML attributes, and special options above.
1673
 * @return string A generated HTML text input element
1674
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::textarea
1675
 */
1676
        public function textarea($fieldName, $options = array()) {
1677
                $options = $this->_initInputField($fieldName, $options);
1678
                $value = null;
1679

    
1680
                if (array_key_exists('value', $options)) {
1681
                        $value = $options['value'];
1682
                        if (!array_key_exists('escape', $options) || $options['escape'] !== false) {
1683
                                $value = h($value);
1684
                        }
1685
                        unset($options['value']);
1686
                }
1687
                return $this->Html->useTag('textarea', $options['name'], array_diff_key($options, array('type' => null, 'name' => null)), $value);
1688
        }
1689

    
1690
/**
1691
 * Creates a hidden input field.
1692
 *
1693
 * @param string $fieldName Name of a field, in the form of "Modelname.fieldname"
1694
 * @param array $options Array of HTML attributes.
1695
 * @return string A generated hidden input
1696
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::hidden
1697
 */
1698
        public function hidden($fieldName, $options = array()) {
1699
                $options += array('required' => false, 'secure' => true);
1700

    
1701
                $secure = $options['secure'];
1702
                unset($options['secure']);
1703

    
1704
                $options = $this->_initInputField($fieldName, array_merge(
1705
                        $options, array('secure' => static::SECURE_SKIP)
1706
                ));
1707

    
1708
                if ($secure === true) {
1709
                        $this->_secure(true, null, '' . $options['value']);
1710
                }
1711

    
1712
                return $this->Html->useTag('hidden', $options['name'], array_diff_key($options, array('name' => null)));
1713
        }
1714

    
1715
/**
1716
 * Creates file input widget.
1717
 *
1718
 * @param string $fieldName Name of a field, in the form "Modelname.fieldname"
1719
 * @param array $options Array of HTML attributes.
1720
 * @return string A generated file input.
1721
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::file
1722
 */
1723
        public function file($fieldName, $options = array()) {
1724
                $options += array('secure' => true);
1725
                $secure = $options['secure'];
1726
                $options['secure'] = static::SECURE_SKIP;
1727

    
1728
                $options = $this->_initInputField($fieldName, $options);
1729
                $field = $this->entity();
1730

    
1731
                foreach (array('name', 'type', 'tmp_name', 'error', 'size') as $suffix) {
1732
                        $this->_secure($secure, array_merge($field, array($suffix)));
1733
                }
1734

    
1735
                $exclude = array('name' => null, 'value' => null);
1736
                return $this->Html->useTag('file', $options['name'], array_diff_key($options, $exclude));
1737
        }
1738

    
1739
/**
1740
 * Creates a `<button>` tag. The type attribute defaults to `type="submit"`
1741
 * You can change it to a different value by using `$options['type']`.
1742
 *
1743
 * ### Options:
1744
 *
1745
 * - `escape` - HTML entity encode the $title of the button. Defaults to false.
1746
 *
1747
 * @param string $title The button's caption. Not automatically HTML encoded
1748
 * @param array $options Array of options and HTML attributes.
1749
 * @return string A HTML button tag.
1750
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::button
1751
 */
1752
        public function button($title, $options = array()) {
1753
                $options += array('type' => 'submit', 'escape' => false, 'secure' => false);
1754
                if ($options['escape']) {
1755
                        $title = h($title);
1756
                }
1757
                if (isset($options['name'])) {
1758
                        $name = str_replace(array('[', ']'), array('.', ''), $options['name']);
1759
                        $this->_secure($options['secure'], $name);
1760
                }
1761
                return $this->Html->useTag('button', $options, $title);
1762
        }
1763

    
1764
/**
1765
 * Create a `<button>` tag with a surrounding `<form>` that submits via POST.
1766
 *
1767
 * This method creates a `<form>` element. So do not use this method in an already opened form.
1768
 * Instead use FormHelper::submit() or FormHelper::button() to create buttons inside opened forms.
1769
 *
1770
 * ### Options:
1771
 *
1772
 * - `data` - Array with key/value to pass in input hidden
1773
 * - Other options is the same of button method.
1774
 *
1775
 * @param string $title The button's caption. Not automatically HTML encoded
1776
 * @param string|array $url URL as string or array
1777
 * @param array $options Array of options and HTML attributes.
1778
 * @return string A HTML button tag.
1779
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::postButton
1780
 */
1781
        public function postButton($title, $url, $options = array()) {
1782
                $out = $this->create(false, array('id' => false, 'url' => $url));
1783
                if (isset($options['data']) && is_array($options['data'])) {
1784
                        foreach (Hash::flatten($options['data']) as $key => $value) {
1785
                                $out .= $this->hidden($key, array('value' => $value, 'id' => false));
1786
                        }
1787
                        unset($options['data']);
1788
                }
1789
                $out .= $this->button($title, $options);
1790
                $out .= $this->end();
1791
                return $out;
1792
        }
1793

    
1794
/**
1795
 * Creates an HTML link, but access the URL using the method you specify (defaults to POST).
1796
 * Requires javascript to be enabled in browser.
1797
 *
1798
 * This method creates a `<form>` element. So do not use this method inside an existing form.
1799
 * Instead you should add a submit button using FormHelper::submit()
1800
 *
1801
 * ### Options:
1802
 *
1803
 * - `data` - Array with key/value to pass in input hidden
1804
 * - `method` - Request method to use. Set to 'delete' to simulate HTTP/1.1 DELETE request. Defaults to 'post'.
1805
 * - `confirm` - Can be used instead of $confirmMessage.
1806
 * - `inline` - Whether or not the associated form tag should be output inline.
1807
 *   Set to false to have the form tag appended to the 'postLink' view block.
1808
 *   Defaults to true.
1809
 * - `block` - Choose a custom block to append the form tag to. Using this option
1810
 *   will override the inline option.
1811
 * - Other options are the same of HtmlHelper::link() method.
1812
 * - The option `onclick` will be replaced.
1813
 *
1814
 * @param string $title The content to be wrapped by <a> tags.
1815
 * @param string|array $url Cake-relative URL or array of URL parameters, or external URL (starts with http://)
1816
 * @param array $options Array of HTML attributes.
1817
 * @param bool|string $confirmMessage JavaScript confirmation message. This
1818
 *   argument is deprecated as of 2.6. Use `confirm` key in $options instead.
1819
 * @return string An `<a />` element.
1820
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::postLink
1821
 */
1822
        public function postLink($title, $url = null, $options = array(), $confirmMessage = false) {
1823
                $options = (array)$options + array('inline' => true, 'block' => null);
1824
                if (!$options['inline'] && empty($options['block'])) {
1825
                        $options['block'] = __FUNCTION__;
1826
                }
1827
                unset($options['inline']);
1828

    
1829
                $requestMethod = 'POST';
1830
                if (!empty($options['method'])) {
1831
                        $requestMethod = strtoupper($options['method']);
1832
                        unset($options['method']);
1833
                }
1834
                if (!empty($options['confirm'])) {
1835
                        $confirmMessage = $options['confirm'];
1836
                        unset($options['confirm']);
1837
                }
1838

    
1839
                $formName = str_replace('.', '', uniqid('post_', true));
1840
                $formUrl = $this->url($url);
1841
                $formOptions = array(
1842
                        'name' => $formName,
1843
                        'id' => $formName,
1844
                        'style' => 'display:none;',
1845
                        'method' => 'post',
1846
                );
1847
                if (isset($options['target'])) {
1848
                        $formOptions['target'] = $options['target'];
1849
                        unset($options['target']);
1850
                }
1851

    
1852
                $this->_lastAction($url);
1853

    
1854
                $out = $this->Html->useTag('form', $formUrl, $formOptions);
1855
                $out .= $this->Html->useTag('hidden', '_method', array(
1856
                        'value' => $requestMethod
1857
                ));
1858
                $out .= $this->_csrfField();
1859

    
1860
                $fields = array();
1861
                if (isset($options['data']) && is_array($options['data'])) {
1862
                        foreach (Hash::flatten($options['data']) as $key => $value) {
1863
                                $fields[$key] = $value;
1864
                                $out .= $this->hidden($key, array('value' => $value, 'id' => false));
1865
                        }
1866
                        unset($options['data']);
1867
                }
1868
                $out .= $this->secure($fields);
1869
                $out .= $this->Html->useTag('formend');
1870

    
1871
                if ($options['block']) {
1872
                        $this->_View->append($options['block'], $out);
1873
                        $out = '';
1874
                }
1875
                unset($options['block']);
1876

    
1877
                $url = '#';
1878
                $onClick = 'document.' . $formName . '.submit();';
1879
                if ($confirmMessage) {
1880
                        $options['onclick'] = $this->_confirm($confirmMessage, $onClick, '', $options);
1881
                } else {
1882
                        $options['onclick'] = $onClick . ' ';
1883
                }
1884
                $options['onclick'] .= 'event.returnValue = false; return false;';
1885

    
1886
                $out .= $this->Html->link($title, $url, $options);
1887
                return $out;
1888
        }
1889

    
1890
/**
1891
 * Creates a submit button element. This method will generate `<input />` elements that
1892
 * can be used to submit, and reset forms by using $options. image submits can be created by supplying an
1893
 * image path for $caption.
1894
 *
1895
 * ### Options
1896
 *
1897
 * - `div` - Include a wrapping div?  Defaults to true. Accepts sub options similar to
1898
 *   FormHelper::input().
1899
 * - `before` - Content to include before the input.
1900
 * - `after` - Content to include after the input.
1901
 * - `type` - Set to 'reset' for reset inputs. Defaults to 'submit'
1902
 * - Other attributes will be assigned to the input element.
1903
 *
1904
 * ### Options
1905
 *
1906
 * - `div` - Include a wrapping div?  Defaults to true. Accepts sub options similar to
1907
 *   FormHelper::input().
1908
 * - Other attributes will be assigned to the input element.
1909
 *
1910
 * @param string $caption The label appearing on the button OR if string contains :// or the
1911
 *  extension .jpg, .jpe, .jpeg, .gif, .png use an image if the extension
1912
 *  exists, AND the first character is /, image is relative to webroot,
1913
 *  OR if the first character is not /, image is relative to webroot/img.
1914
 * @param array $options Array of options. See above.
1915
 * @return string A HTML submit button
1916
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::submit
1917
 */
1918
        public function submit($caption = null, $options = array()) {
1919
                if (!is_string($caption) && empty($caption)) {
1920
                        $caption = __d('cake', 'Submit');
1921
                }
1922
                $out = null;
1923
                $div = true;
1924

    
1925
                if (isset($options['div'])) {
1926
                        $div = $options['div'];
1927
                        unset($options['div']);
1928
                }
1929
                $options += array('type' => 'submit', 'before' => null, 'after' => null, 'secure' => false);
1930
                $divOptions = array('tag' => 'div');
1931

    
1932
                if ($div === true) {
1933
                        $divOptions['class'] = 'submit';
1934
                } elseif ($div === false) {
1935
                        unset($divOptions);
1936
                } elseif (is_string($div)) {
1937
                        $divOptions['class'] = $div;
1938
                } elseif (is_array($div)) {
1939
                        $divOptions = array_merge(array('class' => 'submit', 'tag' => 'div'), $div);
1940
                }
1941

    
1942
                if (isset($options['name'])) {
1943
                        $name = str_replace(array('[', ']'), array('.', ''), $options['name']);
1944
                        $this->_secure($options['secure'], $name);
1945
                }
1946
                unset($options['secure']);
1947

    
1948
                $before = $options['before'];
1949
                $after = $options['after'];
1950
                unset($options['before'], $options['after']);
1951

    
1952
                $isUrl = strpos($caption, '://') !== false;
1953
                $isImage = preg_match('/\.(jpg|jpe|jpeg|gif|png|ico)$/', $caption);
1954

    
1955
                if ($isUrl || $isImage) {
1956
                        $unlockFields = array('x', 'y');
1957
                        if (isset($options['name'])) {
1958
                                $unlockFields = array(
1959
                                        $options['name'] . '_x', $options['name'] . '_y'
1960
                                );
1961
                        }
1962
                        foreach ($unlockFields as $ignore) {
1963
                                $this->unlockField($ignore);
1964
                        }
1965
                }
1966

    
1967
                if ($isUrl) {
1968
                        unset($options['type']);
1969
                        $tag = $this->Html->useTag('submitimage', $caption, $options);
1970
                } elseif ($isImage) {
1971
                        unset($options['type']);
1972
                        if ($caption{0} !== '/') {
1973
                                $url = $this->webroot(Configure::read('App.imageBaseUrl') . $caption);
1974
                        } else {
1975
                                $url = $this->webroot(trim($caption, '/'));
1976
                        }
1977
                        $url = $this->assetTimestamp($url);
1978
                        $tag = $this->Html->useTag('submitimage', $url, $options);
1979
                } else {
1980
                        $options['value'] = $caption;
1981
                        $tag = $this->Html->useTag('submit', $options);
1982
                }
1983
                $out = $before . $tag . $after;
1984

    
1985
                if (isset($divOptions)) {
1986
                        $tag = $divOptions['tag'];
1987
                        unset($divOptions['tag']);
1988
                        $out = $this->Html->tag($tag, $out, $divOptions);
1989
                }
1990
                return $out;
1991
        }
1992

    
1993
/**
1994
 * Returns a formatted SELECT element.
1995
 *
1996
 * ### Attributes:
1997
 *
1998
 * - `showParents` - If included in the array and set to true, an additional option element
1999
 *   will be added for the parent of each option group. You can set an option with the same name
2000
 *   and it's key will be used for the value of the option.
2001
 * - `multiple` - show a multiple select box. If set to 'checkbox' multiple checkboxes will be
2002
 *   created instead.
2003
 * - `empty` - If true, the empty select option is shown. If a string,
2004
 *   that string is displayed as the empty element.
2005
 * - `escape` - If true contents of options will be HTML entity encoded. Defaults to true.
2006
 * - `value` The selected value of the input.
2007
 * - `class` - When using multiple = checkbox the class name to apply to the divs. Defaults to 'checkbox'.
2008
 * - `disabled` - Control the disabled attribute. When creating a select box, set to true to disable the
2009
 *   select box. When creating checkboxes, `true` will disable all checkboxes. You can also set disabled
2010
 *   to a list of values you want to disable when creating checkboxes.
2011
 *
2012
 * ### Using options
2013
 *
2014
 * A simple array will create normal options:
2015
 *
2016
 * ```
2017
 * $options = array(1 => 'one', 2 => 'two);
2018
 * $this->Form->select('Model.field', $options));
2019
 * ```
2020
 *
2021
 * While a nested options array will create optgroups with options inside them.
2022
 * ```
2023
 * $options = array(
2024
 *  1 => 'bill',
2025
 *  'fred' => array(
2026
 *     2 => 'fred',
2027
 *     3 => 'fred jr.'
2028
 *  )
2029
 * );
2030
 * $this->Form->select('Model.field', $options);
2031
 * ```
2032
 *
2033
 * In the above `2 => 'fred'` will not generate an option element. You should enable the `showParents`
2034
 * attribute to show the fred option.
2035
 *
2036
 * If you have multiple options that need to have the same value attribute, you can
2037
 * use an array of arrays to express this:
2038
 *
2039
 * ```
2040
 * $options = array(
2041
 *  array('name' => 'United states', 'value' => 'USA'),
2042
 *  array('name' => 'USA', 'value' => 'USA'),
2043
 * );
2044
 * ```
2045
 *
2046
 * @param string $fieldName Name attribute of the SELECT
2047
 * @param array $options Array of the OPTION elements (as 'value'=>'Text' pairs) to be used in the
2048
 *        SELECT element
2049
 * @param array $attributes The HTML attributes of the select element.
2050
 * @return string Formatted SELECT element
2051
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#options-for-select-checkbox-and-radio-inputs
2052
 */
2053
        public function select($fieldName, $options = array(), $attributes = array()) {
2054
                $select = array();
2055
                $style = null;
2056
                $tag = null;
2057
                $attributes += array(
2058
                        'class' => null,
2059
                        'escape' => true,
2060
                        'secure' => true,
2061
                        'empty' => '',
2062
                        'showParents' => false,
2063
                        'hiddenField' => true,
2064
                        'disabled' => false
2065
                );
2066

    
2067
                $escapeOptions = $this->_extractOption('escape', $attributes);
2068
                $secure = $this->_extractOption('secure', $attributes);
2069
                $showEmpty = $this->_extractOption('empty', $attributes);
2070
                $showParents = $this->_extractOption('showParents', $attributes);
2071
                $hiddenField = $this->_extractOption('hiddenField', $attributes);
2072
                unset($attributes['escape'], $attributes['secure'], $attributes['empty'], $attributes['showParents'], $attributes['hiddenField']);
2073
                $id = $this->_extractOption('id', $attributes);
2074

    
2075
                $attributes = $this->_initInputField($fieldName, array_merge(
2076
                        (array)$attributes, array('secure' => static::SECURE_SKIP)
2077
                ));
2078

    
2079
                if (is_string($options) && isset($this->_options[$options])) {
2080
                        $options = $this->_generateOptions($options);
2081
                } elseif (!is_array($options)) {
2082
                        $options = array();
2083
                }
2084
                if (isset($attributes['type'])) {
2085
                        unset($attributes['type']);
2086
                }
2087

    
2088
                if (!empty($attributes['multiple'])) {
2089
                        $style = ($attributes['multiple'] === 'checkbox') ? 'checkbox' : null;
2090
                        $template = ($style) ? 'checkboxmultiplestart' : 'selectmultiplestart';
2091
                        $tag = $template;
2092
                        if ($hiddenField) {
2093
                                $hiddenAttributes = array(
2094
                                        'value' => '',
2095
                                        'id' => $attributes['id'] . ($style ? '' : '_'),
2096
                                        'secure' => false,
2097
                                        'form' => isset($attributes['form']) ? $attributes['form'] : null,
2098
                                        'name' => $attributes['name'],
2099
                                        'disabled' => $attributes['disabled'] === true || $attributes['disabled'] === 'disabled'
2100
                                );
2101
                                $select[] = $this->hidden(null, $hiddenAttributes);
2102
                        }
2103
                } else {
2104
                        $tag = 'selectstart';
2105
                }
2106

    
2107
                if ($tag === 'checkboxmultiplestart') {
2108
                        unset($attributes['required']);
2109
                }
2110

    
2111
                if (!empty($tag) || isset($template)) {
2112
                        $hasOptions = (count($options) > 0 || $showEmpty);
2113
                        // Secure the field if there are options, or its a multi select.
2114
                        // Single selects with no options don't submit, but multiselects do.
2115
                        if ((!isset($secure) || $secure) &&
2116
                                empty($attributes['disabled']) &&
2117
                                (!empty($attributes['multiple']) || $hasOptions)
2118
                        ) {
2119
                                $this->_secure(true, $this->_secureFieldName($attributes));
2120
                        }
2121
                        $filter = array('name' => null, 'value' => null);
2122
                        if (is_array($attributes['disabled'])) {
2123
                                $filter['disabled'] = null;
2124
                        }
2125
                        $select[] = $this->Html->useTag($tag, $attributes['name'], array_diff_key($attributes, $filter));
2126
                }
2127
                $emptyMulti = (
2128
                        $showEmpty !== null && $showEmpty !== false && !(
2129
                                empty($showEmpty) && (isset($attributes) &&
2130
                                array_key_exists('multiple', $attributes))
2131
                        )
2132
                );
2133

    
2134
                if ($emptyMulti) {
2135
                        $showEmpty = ($showEmpty === true) ? '' : $showEmpty;
2136
                        $options = array('' => $showEmpty) + $options;
2137
                }
2138

    
2139
                if (!$id) {
2140
                        $attributes['id'] = Inflector::camelize($attributes['id']);
2141
                }
2142

    
2143
                $select = array_merge($select, $this->_selectOptions(
2144
                        array_reverse($options, true),
2145
                        array(),
2146
                        $showParents,
2147
                        array(
2148
                                'escape' => $escapeOptions,
2149
                                'style' => $style,
2150
                                'name' => $attributes['name'],
2151
                                'value' => $attributes['value'],
2152
                                'class' => $attributes['class'],
2153
                                'id' => $attributes['id'],
2154
                                'disabled' => $attributes['disabled'],
2155
                        )
2156
                ));
2157

    
2158
                $template = ($style === 'checkbox') ? 'checkboxmultipleend' : 'selectend';
2159
                $select[] = $this->Html->useTag($template);
2160
                return implode("\n", $select);
2161
        }
2162

    
2163
/**
2164
 * Generates a valid DOM ID suffix from a string.
2165
 * Also avoids collisions when multiple values are coverted to the same suffix by
2166
 * appending a numeric value.
2167
 *
2168
 * For pre-HTML5 IDs only characters like a-z 0-9 - _ are valid. HTML5 doesn't have that
2169
 * limitation, but to avoid layout issues it still filters out some sensitive chars.
2170
 *
2171
 * @param string $value The value that should be transferred into a DOM ID suffix.
2172
 * @param string $type Doctype to use. Defaults to html4.
2173
 * @return string DOM ID
2174
 */
2175
        public function domIdSuffix($value, $type = 'html4') {
2176
                if ($type === 'html5') {
2177
                        $value = str_replace(array('@', '<', '>', ' ', '"', '\''), '_', $value);
2178
                } else {
2179
                        $value = Inflector::camelize(Inflector::slug($value));
2180
                }
2181
                $value = Inflector::camelize($value);
2182
                $count = 1;
2183
                $suffix = $value;
2184
                while (in_array($suffix, $this->_domIdSuffixes)) {
2185
                        $suffix = $value . $count++;
2186
                }
2187
                $this->_domIdSuffixes[] = $suffix;
2188
                return $suffix;
2189
        }
2190

    
2191
/**
2192
 * Returns a SELECT element for days.
2193
 *
2194
 * ### Attributes:
2195
 *
2196
 * - `empty` - If true, the empty select option is shown. If a string,
2197
 *   that string is displayed as the empty element.
2198
 * - `value` The selected value of the input.
2199
 *
2200
 * @param string $fieldName Prefix name for the SELECT element
2201
 * @param array $attributes HTML attributes for the select element
2202
 * @return string A generated day select box.
2203
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::day
2204
 */
2205
        public function day($fieldName = null, $attributes = array()) {
2206
                $attributes += array('empty' => true, 'value' => null);
2207
                $attributes = $this->_dateTimeSelected('day', $fieldName, $attributes);
2208

    
2209
                if (strlen($attributes['value']) > 2) {
2210
                        $date = date_create($attributes['value']);
2211
                        $attributes['value'] = null;
2212
                        if ($date) {
2213
                                $attributes['value'] = $date->format('d');
2214
                        }
2215
                } elseif ($attributes['value'] === false) {
2216
                        $attributes['value'] = null;
2217
                }
2218
                return $this->select($fieldName . ".day", $this->_generateOptions('day'), $attributes);
2219
        }
2220

    
2221
/**
2222
 * Returns a SELECT element for years
2223
 *
2224
 * ### Attributes:
2225
 *
2226
 * - `empty` - If true, the empty select option is shown. If a string,
2227
 *   that string is displayed as the empty element.
2228
 * - `orderYear` - Ordering of year values in select options.
2229
 *   Possible values 'asc', 'desc'. Default 'desc'
2230
 * - `value` The selected value of the input.
2231
 *
2232
 * @param string $fieldName Prefix name for the SELECT element
2233
 * @param int $minYear First year in sequence
2234
 * @param int $maxYear Last year in sequence
2235
 * @param array $attributes Attribute array for the select elements.
2236
 * @return string Completed year select input
2237
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::year
2238
 */
2239
        public function year($fieldName, $minYear = null, $maxYear = null, $attributes = array()) {
2240
                if (is_array($minYear)) {
2241
                        $attributes = $minYear;
2242
                        $minYear = null;
2243
                }
2244

    
2245
                $attributes += array('empty' => true, 'value' => null);
2246
                if ((empty($attributes['value']) || $attributes['value'] === true) && $value = $this->value($fieldName)) {
2247
                        if (is_array($value)) {
2248
                                $year = null;
2249
                                extract($value);
2250
                                $attributes['value'] = $year;
2251
                        } else {
2252
                                if (empty($value)) {
2253
                                        if (!$attributes['empty'] && !$maxYear) {
2254
                                                $attributes['value'] = 'now';
2255

    
2256
                                        } elseif (!$attributes['empty'] && $maxYear && !$attributes['value']) {
2257
                                                $attributes['value'] = $maxYear;
2258
                                        }
2259
                                } else {
2260
                                        $attributes['value'] = $value;
2261
                                }
2262
                        }
2263
                }
2264

    
2265
                if (strlen($attributes['value']) > 4 || $attributes['value'] === 'now') {
2266
                        $date = date_create($attributes['value']);
2267
                        $attributes['value'] = null;
2268
                        if ($date) {
2269
                                $attributes['value'] = $date->format('Y');
2270
                        }
2271
                } elseif ($attributes['value'] === false) {
2272
                        $attributes['value'] = null;
2273
                }
2274
                $yearOptions = array('value' => $attributes['value'], 'min' => $minYear, 'max' => $maxYear, 'order' => 'desc');
2275
                if (isset($attributes['orderYear'])) {
2276
                        $yearOptions['order'] = $attributes['orderYear'];
2277
                        unset($attributes['orderYear']);
2278
                }
2279
                return $this->select(
2280
                        $fieldName . '.year', $this->_generateOptions('year', $yearOptions),
2281
                        $attributes
2282
                );
2283
        }
2284

    
2285
/**
2286
 * Returns a SELECT element for months.
2287
 *
2288
 * ### Attributes:
2289
 *
2290
 * - `monthNames` - If false, 2 digit numbers will be used instead of text.
2291
 *   If an array, the given array will be used.
2292
 * - `empty` - If true, the empty select option is shown. If a string,
2293
 *   that string is displayed as the empty element.
2294
 * - `value` The selected value of the input.
2295
 *
2296
 * @param string $fieldName Prefix name for the SELECT element
2297
 * @param array $attributes Attributes for the select element
2298
 * @return string A generated month select dropdown.
2299
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::month
2300
 */
2301
        public function month($fieldName, $attributes = array()) {
2302
                $attributes += array('empty' => true, 'value' => null);
2303
                $attributes = $this->_dateTimeSelected('month', $fieldName, $attributes);
2304

    
2305
                if (strlen($attributes['value']) > 2) {
2306
                        $date = date_create($attributes['value']);
2307
                        $attributes['value'] = null;
2308
                        if ($date) {
2309
                                $attributes['value'] = $date->format('m');
2310
                        }
2311
                } elseif ($attributes['value'] === false) {
2312
                        $attributes['value'] = null;
2313
                }
2314
                $defaults = array('monthNames' => true);
2315
                $attributes = array_merge($defaults, (array)$attributes);
2316
                $monthNames = $attributes['monthNames'];
2317
                unset($attributes['monthNames']);
2318

    
2319
                return $this->select(
2320
                        $fieldName . ".month",
2321
                        $this->_generateOptions('month', array('monthNames' => $monthNames)),
2322
                        $attributes
2323
                );
2324
        }
2325

    
2326
/**
2327
 * Returns a SELECT element for hours.
2328
 *
2329
 * ### Attributes:
2330
 *
2331
 * - `empty` - If true, the empty select option is shown. If a string,
2332
 *   that string is displayed as the empty element.
2333
 * - `value` The selected value of the input.
2334
 *
2335
 * @param string $fieldName Prefix name for the SELECT element
2336
 * @param bool $format24Hours True for 24 hours format
2337
 * @param array $attributes List of HTML attributes
2338
 * @return string Completed hour select input
2339
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::hour
2340
 */
2341
        public function hour($fieldName, $format24Hours = false, $attributes = array()) {
2342
                if (is_array($format24Hours)) {
2343
                        $attributes = $format24Hours;
2344
                        $format24Hours = false;
2345
                }
2346

    
2347
                $attributes += array('empty' => true, 'value' => null);
2348
                $attributes = $this->_dateTimeSelected('hour', $fieldName, $attributes);
2349

    
2350
                if (strlen($attributes['value']) > 2) {
2351
                        try {
2352
                                $date = new DateTime($attributes['value']);
2353
                                if ($format24Hours) {
2354
                                        $attributes['value'] = $date->format('H');
2355
                                } else {
2356
                                        $attributes['value'] = $date->format('g');
2357
                                }
2358
                        } catch (Exception $e) {
2359
                                $attributes['value'] = null;
2360
                        }
2361
                } elseif ($attributes['value'] === false) {
2362
                        $attributes['value'] = null;
2363
                }
2364

    
2365
                if ($attributes['value'] > 12 && !$format24Hours) {
2366
                        $attributes['value'] -= 12;
2367
                }
2368
                if (($attributes['value'] === 0 || $attributes['value'] === '00') && !$format24Hours) {
2369
                        $attributes['value'] = 12;
2370
                }
2371

    
2372
                return $this->select(
2373
                        $fieldName . ".hour",
2374
                        $this->_generateOptions($format24Hours ? 'hour24' : 'hour'),
2375
                        $attributes
2376
                );
2377
        }
2378

    
2379
/**
2380
 * Returns a SELECT element for minutes.
2381
 *
2382
 * ### Attributes:
2383
 *
2384
 * - `empty` - If true, the empty select option is shown. If a string,
2385
 *   that string is displayed as the empty element.
2386
 * - `value` The selected value of the input.
2387
 *
2388
 * @param string $fieldName Prefix name for the SELECT element
2389
 * @param array $attributes Array of Attributes
2390
 * @return string Completed minute select input.
2391
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::minute
2392
 */
2393
        public function minute($fieldName, $attributes = array()) {
2394
                $attributes += array('empty' => true, 'value' => null);
2395
                $attributes = $this->_dateTimeSelected('min', $fieldName, $attributes);
2396

    
2397
                if (strlen($attributes['value']) > 2) {
2398
                        $date = date_create($attributes['value']);
2399
                        $attributes['value'] = null;
2400
                        if ($date) {
2401
                                $attributes['value'] = $date->format('i');
2402
                        }
2403
                } elseif ($attributes['value'] === false) {
2404
                        $attributes['value'] = null;
2405
                }
2406
                $minuteOptions = array();
2407

    
2408
                if (isset($attributes['interval'])) {
2409
                        $minuteOptions['interval'] = $attributes['interval'];
2410
                        unset($attributes['interval']);
2411
                }
2412
                return $this->select(
2413
                        $fieldName . ".min", $this->_generateOptions('minute', $minuteOptions),
2414
                        $attributes
2415
                );
2416
        }
2417

    
2418
/**
2419
 * Selects values for dateTime selects.
2420
 *
2421
 * @param string $select Name of element field. ex. 'day'
2422
 * @param string $fieldName Name of fieldName being generated ex. Model.created
2423
 * @param array $attributes Array of attributes, must contain 'empty' key.
2424
 * @return array Attributes array with currently selected value.
2425
 */
2426
        protected function _dateTimeSelected($select, $fieldName, $attributes) {
2427
                if ((empty($attributes['value']) || $attributes['value'] === true) && $value = $this->value($fieldName)) {
2428
                        if (is_array($value)) {
2429
                                $attributes['value'] = isset($value[$select]) ? $value[$select] : null;
2430
                        } else {
2431
                                if (empty($value)) {
2432
                                        if (!$attributes['empty']) {
2433
                                                $attributes['value'] = 'now';
2434
                                        }
2435
                                } else {
2436
                                        $attributes['value'] = $value;
2437
                                }
2438
                        }
2439
                }
2440
                return $attributes;
2441
        }
2442

    
2443
/**
2444
 * Returns a SELECT element for AM or PM.
2445
 *
2446
 * ### Attributes:
2447
 *
2448
 * - `empty` - If true, the empty select option is shown. If a string,
2449
 *   that string is displayed as the empty element.
2450
 * - `value` The selected value of the input.
2451
 *
2452
 * @param string $fieldName Prefix name for the SELECT element
2453
 * @param array $attributes Array of Attributes
2454
 * @return string Completed meridian select input
2455
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::meridian
2456
 */
2457
        public function meridian($fieldName, $attributes = array()) {
2458
                $attributes += array('empty' => true, 'value' => null);
2459
                if ((empty($attributes['value']) || $attributes['value'] === true) && $value = $this->value($fieldName)) {
2460
                        if (is_array($value)) {
2461
                                $meridian = null;
2462
                                extract($value);
2463
                                $attributes['value'] = $meridian;
2464
                        } else {
2465
                                if (empty($value)) {
2466
                                        if (!$attributes['empty']) {
2467
                                                $attributes['value'] = date('a');
2468
                                        }
2469
                                } else {
2470
                                        $date = date_create($attributes['value']);
2471
                                        $attributes['value'] = null;
2472
                                        if ($date) {
2473
                                                $attributes['value'] = $date->format('a');
2474
                                        }
2475
                                }
2476
                        }
2477
                }
2478

    
2479
                if ($attributes['value'] === false) {
2480
                        $attributes['value'] = null;
2481
                }
2482
                return $this->select(
2483
                        $fieldName . ".meridian", $this->_generateOptions('meridian'),
2484
                        $attributes
2485
                );
2486
        }
2487

    
2488
/**
2489
 * Returns a set of SELECT elements for a full datetime setup: day, month and year, and then time.
2490
 *
2491
 * ### Attributes:
2492
 *
2493
 * - `monthNames` If false, 2 digit numbers will be used instead of text.
2494
 *   If an array, the given array will be used.
2495
 * - `minYear` The lowest year to use in the year select
2496
 * - `maxYear` The maximum year to use in the year select
2497
 * - `interval` The interval for the minutes select. Defaults to 1
2498
 * - `separator` The contents of the string between select elements. Defaults to '-'
2499
 * - `empty` - If true, the empty select option is shown. If a string,
2500
 *   that string is displayed as the empty element.
2501
 * - `round` - Set to `up` or `down` if you want to force rounding in either direction. Defaults to null.
2502
 * - `value` | `default` The default value to be used by the input. A value in `$this->data`
2503
 *   matching the field name will override this value. If no default is provided `time()` will be used.
2504
 *
2505
 * @param string $fieldName Prefix name for the SELECT element
2506
 * @param string $dateFormat DMY, MDY, YMD, or null to not generate date inputs.
2507
 * @param string $timeFormat 12, 24, or null to not generate time inputs.
2508
 * @param array $attributes Array of Attributes
2509
 * @return string Generated set of select boxes for the date and time formats chosen.
2510
 * @link http://book.cakephp.org/2.0/en/core-libraries/helpers/form.html#FormHelper::dateTime
2511
 */
2512
        public function dateTime($fieldName, $dateFormat = 'DMY', $timeFormat = '12', $attributes = array()) {
2513
                $attributes += array('empty' => true, 'value' => null);
2514
                $year = $month = $day = $hour = $min = $meridian = null;
2515

    
2516
                if (empty($attributes['value'])) {
2517
                        $attributes = $this->value($attributes, $fieldName);
2518
                }
2519

    
2520
                if ($attributes['value'] === null && $attributes['empty'] != true) {
2521
                        $attributes['value'] = time();
2522
                        if (!empty($attributes['maxYear']) && $attributes['maxYear'] < date('Y')) {
2523
                                $attributes['value'] = strtotime(date($attributes['maxYear'] . '-m-d'));
2524
                        }
2525
                }
2526

    
2527
                if (!empty($attributes['value'])) {
2528
                        list($year, $month, $day, $hour, $min, $meridian) = $this->_getDateTimeValue(
2529
                                $attributes['value'],
2530
                                $timeFormat
2531
                        );
2532
                }
2533

    
2534
                $defaults = array(
2535
                        'minYear' => null, 'maxYear' => null, 'separator' => '-',
2536
                        'interval' => 1, 'monthNames' => true, 'round' => null
2537
                );
2538
                $attributes = array_merge($defaults, (array)$attributes);
2539
                if (isset($attributes['minuteInterval'])) {
2540
                        $attributes['interval'] = $attributes['minuteInterval'];
2541
                        unset($attributes['minuteInterval']);
2542
                }
2543
                $minYear = $attributes['minYear'];
2544
                $maxYear = $attributes['maxYear'];
2545
                $separator = $attributes['separator'];
2546
                $interval = $attributes['interval'];
2547
                $monthNames = $attributes['monthNames'];
2548
                $round = $attributes['round'];
2549
                $attributes = array_diff_key($attributes, $defaults);
2550

    
2551
                if (!empty($interval) && $interval > 1 && !empty($min)) {
2552
                        $current = new DateTime();
2553
                        if ($year !== null) {
2554
                                $current->setDate($year, $month, $day);
2555
                        }
2556
                        if ($hour !== null) {
2557
                                $current->setTime($hour, $min);
2558
                        }
2559
                        $changeValue = $min * (1 / $interval);
2560
                        switch ($round) {
2561
                                case 'up':
2562
                                        $changeValue = ceil($changeValue);
2563
                                        break;
2564
                                case 'down':
2565
                                        $changeValue = floor($changeValue);
2566
                                        break;
2567
                                default:
2568
                                        $changeValue = round($changeValue);
2569
                        }
2570
                        $change = ($changeValue * $interval) - $min;
2571
                        $current->modify($change > 0 ? "+$change minutes" : "$change minutes");
2572
                        $format = ($timeFormat == 12) ? 'Y m d h i a' : 'Y m d H i a';
2573
                        $newTime = explode(' ', $current->format($format));
2574
                        list($year, $month, $day, $hour, $min, $meridian) = $newTime;
2575
                }
2576

    
2577
                $keys = array('Day', 'Month', 'Year', 'Hour', 'Minute', 'Meridian');
2578
                $attrs = array_fill_keys($keys, $attributes);
2579

    
2580
                $hasId = isset($attributes['id']);
2581
                if ($hasId && is_array($attributes['id'])) {
2582
                        // check for missing ones and build selectAttr for each element
2583
                        $attributes['id'] += array(
2584
                                'month' => '',
2585
                                'year' => '',
2586
                                'day' => '',
2587
                                'hour' => '',
2588
                                'minute' => '',
2589
                                'meridian' => ''
2590
                        );
2591
                        foreach ($keys as $key) {
2592
                                $attrs[$key]['id'] = $attributes['id'][strtolower($key)];
2593
                        }
2594
                }
2595
                if ($hasId && is_string($attributes['id'])) {
2596
                        // build out an array version
2597
                        foreach ($keys as $key) {
2598
                                $attrs[$key]['id'] = $attributes['id'] . $key;
2599
                        }
2600
                }
2601

    
2602
                if (is_array($attributes['empty'])) {
2603
                        $attributes['empty'] += array(
2604
                                'month' => true,
2605
                                'year' => true,
2606
                                'day' => true,
2607
                                'hour' => true,
2608
                                'minute' => true,
2609
                                'meridian' => true
2610
                        );
2611
                        foreach ($keys as $key) {
2612
                                $attrs[$key]['empty'] = $attributes['empty'][strtolower($key)];
2613
                        }
2614
                }
2615

    
2616
                $selects = array();
2617
                foreach (preg_split('//', $dateFormat, -1, PREG_SPLIT_NO_EMPTY) as $char) {
2618
                        switch ($char) {
2619
                                case 'Y':
2620
                                        $attrs['Year']['value'] = $year;
2621
                                        $selects[] = $this->year(
2622
                                                $fieldName, $minYear, $maxYear, $attrs['Year']
2623
                                        );
2624
                                        break;
2625
                                case 'M':
2626
                                        $attrs['Month']['value'] = $month;
2627
                                        $attrs['Month']['monthNames'] = $monthNames;
2628
                                        $selects[] = $this->month($fieldName, $attrs['Month']);
2629
                                        break;
2630
                                case 'D':
2631
                                        $attrs['Day']['value'] = $day;
2632
                                        $selects[] = $this->day($fieldName, $attrs['Day']);
2633
                                        break;
2634
                        }
2635
                }
2636
                $opt = implode($separator, $selects);
2637

    
2638
                $attrs['Minute']['interval'] = $interval;
2639
                switch ($timeFormat) {
2640
                        case '24':
2641
                                $attrs['Hour']['value'] = $hour;
2642
                                $attrs['Minute']['value'] = $min;
2643
                                $opt .= $this->hour($fieldName, true, $attrs['Hour']) . ':' .
2644
                                $this->minute($fieldName, $attrs['Minute']);
2645
                                break;
2646
                        case '12':
2647
                                $attrs['Hour']['value'] = $hour;
2648
                                $attrs['Minute']['value'] = $min;
2649
                                $attrs['Meridian']['value'] = $meridian;
2650
                                $opt .= $this->hour($fieldName, false, $attrs['Hour']) . ':' .
2651
                                $this->minute($fieldName, $attrs['Minute']) . ' ' .
2652
                                $this->meridian($fieldName, $attrs['Meridian']);
2653
                                break;
2654
                }
2655
                return $opt;
2656
        }
2657

    
2658
/**
2659
 * Parse the value for a datetime selected value
2660
 *
2661
 * @param string|array $value The selected value.
2662
 * @param int $timeFormat The time format
2663
 * @return array Array of selected value.
2664
 */
2665
        protected function _getDateTimeValue($value, $timeFormat) {
2666
                $year = $month = $day = $hour = $min = $meridian = null;
2667
                if (is_array($value)) {
2668
                        extract($value);
2669
                        if ($meridian === 'pm') {
2670
                                $hour += 12;
2671
                        }
2672
                        return array($year, $month, $day, $hour, $min, $meridian);
2673
                }
2674

    
2675
                if (is_numeric($value)) {
2676
                        $value = strftime('%Y-%m-%d %H:%M:%S', $value);
2677
                }
2678
                $meridian = 'am';
2679
                $pos = strpos($value, '-');
2680
                if ($pos !== false) {
2681
                        $date = explode('-', $value);
2682
                        $days = explode(' ', $date[2]);
2683
                        $day = $days[0];
2684
                        $month = $date[1];
2685
                        $year = $date[0];
2686
                } else {
2687
                        $days[1] = $value;
2688
                }
2689

    
2690
                if (!empty($timeFormat)) {
2691
                        $time = explode(':', $days[1]);
2692

    
2693
                        if ($time[0] >= 12) {
2694
                                $meridian = 'pm';
2695
                        }
2696
                        $hour = $min = null;
2697
                        if (isset($time[1])) {
2698
                                $hour = $time[0];
2699
                                $min = $time[1];
2700
                        }
2701
                }
2702
                return array($year, $month, $day, $hour, $min, $meridian);
2703
        }
2704

    
2705
/**
2706
 * Gets the input field name for the current tag
2707
 *
2708
 * @param array $options Options list.
2709
 * @param string $field Field name.
2710
 * @param string $key Key name.
2711
 * @return array
2712
 */
2713
        protected function _name($options = array(), $field = null, $key = 'name') {
2714
                if ($this->requestType === 'get') {
2715
                        if ($options === null) {
2716
                                $options = array();
2717
                        } elseif (is_string($options)) {
2718
                                $field = $options;
2719
                                $options = 0;
2720
                        }
2721

    
2722
                        if (!empty($field)) {
2723
                                $this->setEntity($field);
2724
                        }
2725

    
2726
                        if (is_array($options) && isset($options[$key])) {
2727
                                return $options;
2728
                        }
2729

    
2730
                        $entity = $this->entity();
2731
                        $model = $this->model();
2732
                        $name = $model === $entity[0] && isset($entity[1]) ? $entity[1] : $entity[0];
2733
                        $last = $entity[count($entity) - 1];
2734
                        if (in_array($last, $this->_fieldSuffixes)) {
2735
                                $name .= '[' . $last . ']';
2736
                        }
2737

    
2738
                        if (is_array($options)) {
2739
                                $options[$key] = $name;
2740
                                return $options;
2741
                        }
2742
                        return $name;
2743
                }
2744
                return parent::_name($options, $field, $key);
2745
        }
2746

    
2747
/**
2748
 * Returns an array of formatted OPTION/OPTGROUP elements
2749
 *
2750
 * @param array $elements Elements to format.
2751
 * @param array $parents Parents for OPTGROUP.
2752
 * @param bool $showParents Whether to show parents.
2753
 * @param array $attributes HTML attributes.
2754
 * @return array
2755
 */
2756
        protected function _selectOptions($elements = array(), $parents = array(), $showParents = null, $attributes = array()) {
2757
                $select = array();
2758
                $attributes = array_merge(
2759
                        array('escape' => true, 'style' => null, 'value' => null, 'class' => null),
2760
                        $attributes
2761
                );
2762
                $selectedIsEmpty = ($attributes['value'] === '' || $attributes['value'] === null);
2763
                $selectedIsArray = is_array($attributes['value']);
2764

    
2765
                $this->_domIdSuffixes = array();
2766
                foreach ($elements as $name => $title) {
2767
                        $htmlOptions = array();
2768
                        if (is_array($title) && (!isset($title['name']) || !isset($title['value']))) {
2769
                                if (!empty($name)) {
2770
                                        if ($attributes['style'] === 'checkbox') {
2771
                                                $select[] = $this->Html->useTag('fieldsetend');
2772
                                        } else {
2773
                                                $select[] = $this->Html->useTag('optiongroupend');
2774
                                        }
2775
                                        $parents[] = $name;
2776
                                }
2777
                                $select = array_merge($select, $this->_selectOptions(
2778
                                        $title, $parents, $showParents, $attributes
2779
                                ));
2780

    
2781
                                if (!empty($name)) {
2782
                                        $name = $attributes['escape'] ? h($name) : $name;
2783
                                        if ($attributes['style'] === 'checkbox') {
2784
                                                $select[] = $this->Html->useTag('fieldsetstart', $name);
2785
                                        } else {
2786
                                                $select[] = $this->Html->useTag('optiongroup', $name, '');
2787
                                        }
2788
                                }
2789
                                $name = null;
2790
                        } elseif (is_array($title)) {
2791
                                $htmlOptions = $title;
2792
                                $name = $title['value'];
2793
                                $title = $title['name'];
2794
                                unset($htmlOptions['name'], $htmlOptions['value']);
2795
                        }
2796

    
2797
                        if ($name !== null) {
2798
                                $isNumeric = is_numeric($name);
2799
                                if ((!$selectedIsArray && !$selectedIsEmpty && (string)$attributes['value'] == (string)$name) ||
2800
                                        ($selectedIsArray && in_array((string)$name, $attributes['value'], !$isNumeric))
2801
                                ) {
2802
                                        if ($attributes['style'] === 'checkbox') {
2803
                                                $htmlOptions['checked'] = true;
2804
                                        } else {
2805
                                                $htmlOptions['selected'] = 'selected';
2806
                                        }
2807
                                }
2808

    
2809
                                if ($showParents || (!in_array($title, $parents))) {
2810
                                        $title = ($attributes['escape']) ? h($title) : $title;
2811

    
2812
                                        $hasDisabled = !empty($attributes['disabled']);
2813
                                        if ($hasDisabled) {
2814
                                                $disabledIsArray = is_array($attributes['disabled']);
2815
                                                if ($disabledIsArray) {
2816
                                                        $disabledIsNumeric = is_numeric($name);
2817
                                                }
2818
                                        }
2819
                                        if ($hasDisabled &&
2820
                                                $disabledIsArray &&
2821
                                                in_array((string)$name, $attributes['disabled'], !$disabledIsNumeric)
2822
                                        ) {
2823
                                                $htmlOptions['disabled'] = 'disabled';
2824
                                        }
2825
                                        if ($hasDisabled && !$disabledIsArray && $attributes['style'] === 'checkbox') {
2826
                                                $htmlOptions['disabled'] = $attributes['disabled'] === true ? 'disabled' : $attributes['disabled'];
2827
                                        }
2828

    
2829
                                        if ($attributes['style'] === 'checkbox') {
2830
                                                $htmlOptions['value'] = $name;
2831

    
2832
                                                $tagName = $attributes['id'] . $this->domIdSuffix($name);
2833
                                                $htmlOptions['id'] = $tagName;
2834
                                                $label = array('for' => $tagName);
2835

    
2836
                                                if (isset($htmlOptions['checked']) && $htmlOptions['checked'] === true) {
2837
                                                        $label['class'] = 'selected';
2838
                                                }
2839

    
2840
                                                $name = $attributes['name'];
2841

    
2842
                                                if (empty($attributes['class'])) {
2843
                                                        $attributes['class'] = 'checkbox';
2844
                                                } elseif ($attributes['class'] === 'form-error') {
2845
                                                        $attributes['class'] = 'checkbox ' . $attributes['class'];
2846
                                                }
2847
                                                $label = $this->label(null, $title, $label);
2848
                                                $item = $this->Html->useTag('checkboxmultiple', $name, $htmlOptions);
2849
                                                $select[] = $this->Html->div($attributes['class'], $item . $label);
2850
                                        } else {
2851
                                                if ($attributes['escape']) {
2852
                                                        $name = h($name);
2853
                                                }
2854
                                                $select[] = $this->Html->useTag('selectoption', $name, $htmlOptions, $title);
2855
                                        }
2856
                                }
2857
                        }
2858
                }
2859

    
2860
                return array_reverse($select, true);
2861
        }
2862

    
2863
/**
2864
 * Generates option lists for common <select /> menus
2865
 *
2866
 * @param string $name List type name.
2867
 * @param array $options Options list.
2868
 * @return array
2869
 */
2870
        protected function _generateOptions($name, $options = array()) {
2871
                if (!empty($this->options[$name])) {
2872
                        return $this->options[$name];
2873
                }
2874
                $data = array();
2875

    
2876
                switch ($name) {
2877
                        case 'minute':
2878
                                if (isset($options['interval'])) {
2879
                                        $interval = $options['interval'];
2880
                                } else {
2881
                                        $interval = 1;
2882
                                }
2883
                                $i = 0;
2884
                                while ($i < 60) {
2885
                                        $data[sprintf('%02d', $i)] = sprintf('%02d', $i);
2886
                                        $i += $interval;
2887
                                }
2888
                                break;
2889
                        case 'hour':
2890
                                for ($i = 1; $i <= 12; $i++) {
2891
                                        $data[sprintf('%02d', $i)] = $i;
2892
                                }
2893
                                break;
2894
                        case 'hour24':
2895
                                for ($i = 0; $i <= 23; $i++) {
2896
                                        $data[sprintf('%02d', $i)] = $i;
2897
                                }
2898
                                break;
2899
                        case 'meridian':
2900
                                $data = array('am' => 'am', 'pm' => 'pm');
2901
                                break;
2902
                        case 'day':
2903
                                for ($i = 1; $i <= 31; $i++) {
2904
                                        $data[sprintf('%02d', $i)] = $i;
2905
                                }
2906
                                break;
2907
                        case 'month':
2908
                                if ($options['monthNames'] === true) {
2909
                                        $data['01'] = __d('cake', 'January');
2910
                                        $data['02'] = __d('cake', 'February');
2911
                                        $data['03'] = __d('cake', 'March');
2912
                                        $data['04'] = __d('cake', 'April');
2913
                                        $data['05'] = __d('cake', 'May');
2914
                                        $data['06'] = __d('cake', 'June');
2915
                                        $data['07'] = __d('cake', 'July');
2916
                                        $data['08'] = __d('cake', 'August');
2917
                                        $data['09'] = __d('cake', 'September');
2918
                                        $data['10'] = __d('cake', 'October');
2919
                                        $data['11'] = __d('cake', 'November');
2920
                                        $data['12'] = __d('cake', 'December');
2921
                                } elseif (is_array($options['monthNames'])) {
2922
                                        $data = $options['monthNames'];
2923
                                } else {
2924
                                        for ($m = 1; $m <= 12; $m++) {
2925
                                                $data[sprintf("%02s", $m)] = strftime("%m", mktime(1, 1, 1, $m, 1, 1999));
2926
                                        }
2927
                                }
2928
                                break;
2929
                        case 'year':
2930
                                $current = (int)date('Y');
2931

    
2932
                                $min = !isset($options['min']) ? $current - 20 : (int)$options['min'];
2933
                                $max = !isset($options['max']) ? $current + 20 : (int)$options['max'];
2934

    
2935
                                if ($min > $max) {
2936
                                        list($min, $max) = array($max, $min);
2937
                                }
2938
                                if (!empty($options['value']) &&
2939
                                        (int)$options['value'] < $min &&
2940
                                        (int)$options['value'] > 0
2941
                                ) {
2942
                                        $min = (int)$options['value'];
2943
                                } elseif (!empty($options['value']) && (int)$options['value'] > $max) {
2944
                                        $max = (int)$options['value'];
2945
                                }
2946

    
2947
                                for ($i = $min; $i <= $max; $i++) {
2948
                                        $data[$i] = $i;
2949
                                }
2950
                                if ($options['order'] !== 'asc') {
2951
                                        $data = array_reverse($data, true);
2952
                                }
2953
                                break;
2954
                }
2955
                $this->_options[$name] = $data;
2956
                return $this->_options[$name];
2957
        }
2958

    
2959
/**
2960
 * Sets field defaults and adds field to form security input hash.
2961
 * Will also add a 'form-error' class if the field contains validation errors.
2962
 *
2963
 * ### Options
2964
 *
2965
 * - `secure` - boolean whether or not the field should be added to the security fields.
2966
 *   Disabling the field using the `disabled` option, will also omit the field from being
2967
 *   part of the hashed key.
2968
 *
2969
 * This method will convert a numerically indexed 'disabled' into an associative
2970
 * value. FormHelper's internals expect associative options.
2971
 *
2972
 * @param string $field Name of the field to initialize options for.
2973
 * @param array $options Array of options to append options into.
2974
 * @return array Array of options for the input.
2975
 */
2976
        protected function _initInputField($field, $options = array()) {
2977
                if (isset($options['secure'])) {
2978
                        $secure = $options['secure'];
2979
                        unset($options['secure']);
2980
                } else {
2981
                        $secure = (isset($this->request['_Token']) && !empty($this->request['_Token']));
2982
                }
2983

    
2984
                $disabledIndex = array_search('disabled', $options, true);
2985
                if (is_int($disabledIndex)) {
2986
                        unset($options[$disabledIndex]);
2987
                        $options['disabled'] = true;
2988
                }
2989

    
2990
                $result = parent::_initInputField($field, $options);
2991
                if ($this->tagIsInvalid() !== false) {
2992
                        $result = $this->addClass($result, 'form-error');
2993
                }
2994

    
2995
                $isDisabled = false;
2996
                if (isset($result['disabled'])) {
2997
                        $isDisabled = (
2998
                                $result['disabled'] === true ||
2999
                                $result['disabled'] === 'disabled' ||
3000
                                (is_array($result['disabled']) &&
3001
                                        !empty($result['options']) &&
3002
                                        array_diff($result['options'], $result['disabled']) === array()
3003
                                )
3004
                        );
3005
                }
3006
                if ($isDisabled) {
3007
                        return $result;
3008
                }
3009

    
3010
                if (!isset($result['required']) &&
3011
                        $this->_introspectModel($this->model(), 'validates', $this->field())
3012
                ) {
3013
                        $result['required'] = true;
3014
                }
3015

    
3016
                if ($secure === static::SECURE_SKIP) {
3017
                        return $result;
3018
                }
3019

    
3020
                $this->_secure($secure, $this->_secureFieldName($options));
3021
                return $result;
3022
        }
3023

    
3024
/**
3025
 * Get the field name for use with _secure().
3026
 *
3027
 * Parses the name attribute to create a dot separated name value for use
3028
 * in secured field hash.
3029
 *
3030
 * @param array $options An array of options possibly containing a name key.
3031
 * @return string|null
3032
 */
3033
        protected function _secureFieldName($options) {
3034
                if (isset($options['name'])) {
3035
                        preg_match_all('/\[(.*?)\]/', $options['name'], $matches);
3036
                        if (isset($matches[1])) {
3037
                                return $matches[1];
3038
                        }
3039
                }
3040
                return null;
3041
        }
3042

    
3043
/**
3044
 * Sets the last created form action.
3045
 *
3046
 * @param string|array $url URL.
3047
 * @return void
3048
 */
3049
        protected function _lastAction($url) {
3050
                $action = Router::url($url, true);
3051
                $query = parse_url($action, PHP_URL_QUERY);
3052
                $query = $query ? '?' . $query : '';
3053
                $this->_lastAction = parse_url($action, PHP_URL_PATH) . $query;
3054
        }
3055

    
3056
/**
3057
 * Set/Get inputDefaults for form elements
3058
 *
3059
 * @param array $defaults New default values
3060
 * @param bool $merge Merge with current defaults
3061
 * @return array inputDefaults
3062
 */
3063
        public function inputDefaults($defaults = null, $merge = false) {
3064
                if ($defaults !== null) {
3065
                        if ($merge) {
3066
                                $this->_inputDefaults = array_merge($this->_inputDefaults, (array)$defaults);
3067
                        } else {
3068
                                $this->_inputDefaults = (array)$defaults;
3069
                        }
3070
                }
3071
                return $this->_inputDefaults;
3072
        }
3073

    
3074
}