summaryrefslogtreecommitdiff
path: root/modules/forge/libraries/Form_Input.php
blob: 3031194136bf8f1dc8988ea528a1364c95d91b8e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
<?php defined("SYSPATH") or die("No direct script access.");
/**
 * FORGE base input library.
 *
 * $Id: Form_Input.php 3326 2008-08-09 21:24:30Z Shadowhand $
 *
 * @package    Forge
 * @author     Kohana Team
 * @copyright  (c) 2007-2008 Kohana Team
 * @license    http://kohanaphp.com/license.html
 */
class Form_Input_Core {

	// Input method
	public $method;

	// Element data
	protected $data = array
	(
		'type'    => 'text',
		'class'   => 'textbox',
		'value'   => ''
	);

	// Protected data keys
	protected $protect = array();

	// Validation rules, matches, and callbacks
	protected $rules = array();
	protected $matches = array();
	protected $callbacks = array();

	// Validation check
	protected $is_valid;

	// Errors
	protected $errors = array();
	protected $error_messages = array();

	/**
	 * Sets the input element name.
	 */
	public function __construct($name)
	{
		$this->data['name'] = $name;
	}

	/**
	 * Sets form attributes, or return rules.
	 */
	public function __call($method, $args)
	{
		if ($method == 'rules')
		{
			if (empty($args))
				return $this->rules;

			// Set rules and action
			$rules  = $args[0];
			$action = substr($rules, 0, 1);

			if (in_array($action, array('-', '+', '=')))
			{
				// Remove the action from the rules
				$rules = substr($rules, 1);
			}
			else
			{
				// Default action is append
				$action = '';
			}

			$this->add_rules(explode('|', $rules), $action);
		}
		elseif ($method == 'name')
		{
			// Do nothing. The name should stay static once it is set.
		}
		else
		{
			$this->data[$method] = $args[0];
		}

		return $this;
	}

	/**
	 * Returns form attributes.
	 *
	 * @param   string  attribute name
	 * @return  string
	 */
	public function __get($key)
	{
		if (isset($this->data[$key]))
		{
			return $this->data[$key];
		}
	}

	/**
	 * Sets a form element that this element must match the value of.
	 *
	 * @chainable
	 * @param   object  another Forge input
	 * @return  object
	 */
	public function matches($input)
	{
		if ( ! in_array($input, $this->matches, TRUE))
		{
			$this->matches[] = $input;
		}

		return $this;
	}

	/**
	 * Sets a callback method as a rule for this input.
	 *
	 * @chainable
	 * @param   callback
	 * @return  object
	 */
	public function callback($callback)
	{
		if ( ! in_array($callback, $this->callbacks, TRUE))
		{
			$this->callbacks[] = $callback;
		}

		return $this;
	}

	/**
	 * Sets or returns the input label.
	 *
	 * @chainable
	 * @param   string   label to set
	 * @return  string|object
	 */
	public function label($val = NULL)
	{
		if ($val === NULL)
		{
			if (isset($this->data['name']) AND isset($this->data['label']))
			{
				return form::label($this->data['name'], $this->data['label']);
			}
			return FALSE;
		}
		else
		{
			$this->data['label'] = ($val === TRUE) ? utf8::ucwords(inflector::humanize($this->name)) : $val;
			return $this;
		}
	}

	/**
	 * Set or return the error message.
	 *
	 * @chainable
	 * @param   string  error message
	 * @return  strong|object
	 */
	public function message($val = NULL)
	{
		if ($val === NULL)
		{
			if (isset($this->data['message']))
				return $this->data['message'];
		}
		else
		{
			$this->data['message'] = $val;
			return $this;
		}
	}

	/**
	 * Runs validation and returns the element HTML.
	 *
	 * @return  string
	 */
	public function render()
	{
		// Make sure validation runs
		$this->validate();

		return $this->html_element();
	}

	/**
	 * Returns the form input HTML.
	 *
	 * @return  string
	 */
	protected function html_element()
	{
		$data = $this->data;

		unset($data['label']);
		unset($data['message']);

		return form::input($data);
	}

	/**
	 * Replace, remove, or append rules.
	 *
	 * @param   array   rules to change
	 * @param   string  action to use: replace, remove, append
	 */
	protected function add_rules( array $rules, $action)
	{
		if ($action === '=')
		{
			// Just replace the rules
			$this->rules = $rules;
			return;
		}

		foreach ($rules as $rule)
		{
			if ($action === '-')
			{
				if (($key = array_search($rule, $this->rules)) !== FALSE)
				{
					// Remove the rule
					unset($this->rules[$key]);
				}
			}
			else
			{
				if ( ! in_array($rule, $this->rules))
				{
					if ($action == '+')
					{
						array_unshift($this->rules, $rule);
					}
					else
					{
						$this->rules[] = $rule;
					}
				}
			}
		}
	}

	/**
	 * Add an error to the input.
	 *
	 * @chainable
	 * @return object
	 */
	public function add_error($key, $val)
	{
		if ( ! isset($this->errors[$key]))
		{
			$this->errors[$key] = $val;
		}

		return $this;
	}

	/**
	 * Set or return the error messages.
	 *
	 * @chainable
	 * @param   string|array  failed validation function, or an array of messages
	 * @param   string        error message
	 * @return  object|array
	 */
	public function error_messages($func = NULL, $message = NULL)
	{
		// Set custom error messages
		if ( ! empty($func))
		{
			if (is_array($func))
			{
				// Replace all
				$this->error_messages = $func;
			}
			else
			{
				if (empty($message))
				{
					// Single error, replaces all others
					$this->error_messages = $func;
				}
				else
				{
					// Add custom error
					$this->error_messages[$func] = $message;
				}
			}
			return $this;
		}

		// Make sure validation runs
		is_null($this->is_valid) and $this->validate();

		// Return single error
		if ( ! is_array($this->error_messages) AND ! empty($this->errors))
			return array($this->error_messages);

		$messages = array();
		foreach ($this->errors as $func => $args)
		{
			if (is_string($args))
			{
				$error = $args;
			}
			else
			{
				// Force args to be an array
				$args = is_array($args) ? $args : array();

				// Add the label or name to the beginning of the args
				array_unshift($args, $this->label ? utf8::strtolower($this->label) : $this->name);

				if (isset($this->error_messages[$func]))
				{
					// Use custom error message
					$error = vsprintf($this->error_messages[$func], $args);
				}
				else
				{
					// Get the proper i18n entry, very hacky but it works
					switch ($func)
					{
						case 'valid_url':
						case 'valid_email':
						case 'valid_ip':
							// Fetch an i18n error message
							$error = Kohana::lang('validation.'.$func, $args);
							break;
						case substr($func, 0, 6) === 'valid_':
							// Strip 'valid_' from func name
							$func = (substr($func, 0, 6) === 'valid_') ? substr($func, 6) : $func;
						case 'alpha':
						case 'alpha_dash':
						case 'digit':
						case 'numeric':
							// i18n strings have to be inserted into valid_type
							$args[] = Kohana::lang('validation.'.$func);
							$error = Kohana::lang('validation.valid_type', $args);
							break;
						default:
							$error = Kohana::lang('validation.'.$func, $args);
					}
				}
			}

			// Add error to list
			$messages[] = $error;
		}

		return $messages;
	}

	/**
	 * Get the global input value.
	 *
	 * @return  string|bool
	 */
	protected function input_value($name = array())
	{
		// Get the Input instance
		$input = Input::instance();

		// Fetch the method for this object
		$method = $this->method;

		return $input->$method($name, NULL);
	}

	/**
	 * Load the value of the input, if form data is present.
	 *
	 * @return  void
	 */
	protected function load_value()
	{
		if (is_bool($this->is_valid))
			return;

		if ($name = $this->name)
		{
			// Load POSTed value, but only for named inputs
			$this->data['value'] = $this->input_value($name);
		}

		if (is_string($this->data['value']))
		{
			// Trim string values
			$this->data['value'] = trim($this->data['value']);
		}
	}

	/**
	 * Validate this input based on the set rules.
	 *
	 * @return  bool
	 */
	public function validate()
	{
		// Validation has already run
		if (is_bool($this->is_valid))
			return $this->is_valid;

		// No data to validate
		if ($this->input_value() == FALSE)
			return $this->is_valid = FALSE;

		// Load the submitted value
		$this->load_value();

		// No rules to validate
		if (count($this->rules) == 0 AND count($this->matches) == 0 AND count($this->callbacks) == 0)
			return $this->is_valid = TRUE;

		if ( ! empty($this->rules))
		{
			foreach ($this->rules as $rule)
			{
				if (($offset = strpos($rule, '[')) !== FALSE)
				{
					// Get the args
					$args = preg_split('/, ?/', trim(substr($rule, $offset), '[]'));

					// Remove the args from the rule
					$rule = substr($rule, 0, $offset);
				}

				if (substr($rule, 0, 6) === 'valid_' AND method_exists('valid', substr($rule, 6)))
				{
					$func = substr($rule, 6);

					if ($this->value AND ! valid::$func($this->value))
					{
						$this->errors[$rule] = TRUE;
					}
				}
				elseif (method_exists($this, 'rule_'.$rule))
				{
					// The rule function is always prefixed with rule_
					$rule = 'rule_'.$rule;

					if (isset($args))
					{
						// Manually call up to 2 args for speed
						switch (count($args))
						{
							case 1:
								$this->$rule($args[0]);
							break;
							case 2:
								$this->$rule($args[0], $args[1]);
							break;
							default:
								call_user_func_array(array($this, $rule), $args);
							break;
						}
					}
					else
					{
						// Just call the rule
						$this->$rule();
					}

					// Prevent args from being re-used
					unset($args);
				}
				else
				{
					throw new Kohana_Exception('validation.invalid_rule', $rule);
				}

				// Stop when an error occurs
				if ( ! empty($this->errors))
					break;
			}
		}

		if ( ! empty($this->matches))
		{
			foreach ($this->matches as $input)
			{
				if ($this->value != $input->value)
				{
					// Field does not match
					$this->errors['matches'] = array($input->label ? utf8::strtolower($input->label) : $input->name);
					break;
				}
			}
		}

		if ( ! empty($this->callbacks))
		{
			foreach ($this->callbacks as $callback)
			{
				call_user_func($callback, $this);

				// Stop when an error occurs
				if ( ! empty($this->errors))
					break;
			}
		}

		// If there are errors, validation failed
		return $this->is_valid = empty($this->errors);
	}

	/**
	 * Validate required.
	 */
	protected function rule_required()
	{
		if ($this->value === '' OR $this->value === NULL)
		{
			$this->errors['required'] = TRUE;
		}
	}

	/**
	 * Validate length.
	 */
	protected function rule_length($min, $max = NULL)
	{
		// Get the length, return if zero
		if (($length = utf8::strlen($this->value)) === 0)
			return;

		if ($max == NULL)
		{
			if ($length != $min)
			{
				$this->errors['exact_length'] = array($min);
			}
		}
		else
		{
			if ($length < $min)
			{
				$this->errors['min_length'] = array($min);
			}
			elseif ($length > $max)
			{
				$this->errors['max_length'] = array($max);
			}
		}
	}

} // End Form Input