Subversion Repositories SmartDukaan

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
16591 anikendra 1
<?php
2
/**
3
 * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
4
 * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
5
 *
6
 * Licensed under The MIT License
7
 * For full copyright and license information, please see the LICENSE.txt
8
 * Redistributions of files must retain the above copyright notice.
9
 *
10
 * @copyright     Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
11
 * @link          http://cakephp.org CakePHP(tm) Project
12
 * @since         CakePHP(tm) v 1.2.0.3830
13
 * @license       http://www.opensource.org/licenses/mit-license.php MIT License
14
 */
15
 
16
App::uses('Multibyte', 'I18n');
17
App::uses('File', 'Utility');
18
App::uses('CakeNumber', 'Utility');
19
 
20
// Load multibyte if the extension is missing.
21
if (!function_exists('mb_strlen')) {
22
	class_exists('Multibyte');
23
}
24
 
25
/**
26
 * Validation Class. Used for validation of model data
27
 *
28
 * Offers different validation methods.
29
 *
30
 * @package       Cake.Utility
31
 */
32
class Validation {
33
 
34
/**
35
 * Some complex patterns needed in multiple places
36
 *
37
 * @var array
38
 */
39
	protected static $_pattern = array(
40
		'hostname' => '(?:[_\p{L}0-9][-_\p{L}0-9]*\.)*(?:[\p{L}0-9][-\p{L}0-9]{0,62})\.(?:(?:[a-z]{2}\.)?[a-z]{2,})'
41
	);
42
 
43
/**
44
 * Holds an array of errors messages set in this class.
45
 * These are used for debugging purposes
46
 *
47
 * @var array
48
 */
49
	public static $errors = array();
50
 
51
/**
52
 * Backwards compatibility wrapper for Validation::notBlank().
53
 *
54
 * @param string|array $check Value to check.
55
 * @return bool Success.
56
 * @deprecated 2.7.0 Use Validation::notBlank() instead.
57
 * @see Validation::notBlank()
58
 */
59
	public static function notEmpty($check) {
60
		trigger_error('Validation::notEmpty() is deprecated. Use Validation::notBlank() instead.', E_USER_DEPRECATED);
61
		return static::notBlank($check);
62
	}
63
 
64
/**
65
 * Checks that a string contains something other than whitespace
66
 *
67
 * Returns true if string contains something other than whitespace
68
 *
69
 * $check can be passed as an array:
70
 * array('check' => 'valueToCheck');
71
 *
72
 * @param string|array $check Value to check
73
 * @return bool Success
74
 */
75
	public static function notBlank($check) {
76
		if (is_array($check)) {
77
			extract(static::_defaults($check));
78
		}
79
 
80
		if (empty($check) && (string)$check !== '0') {
81
			return false;
82
		}
83
		return static::_check($check, '/[^\s]+/m');
84
	}
85
 
86
/**
87
 * Checks that a string contains only integer or letters
88
 *
89
 * Returns true if string contains only integer or letters
90
 *
91
 * $check can be passed as an array:
92
 * array('check' => 'valueToCheck');
93
 *
94
 * @param string|array $check Value to check
95
 * @return bool Success
96
 */
97
	public static function alphaNumeric($check) {
98
		if (is_array($check)) {
99
			extract(static::_defaults($check));
100
		}
101
 
102
		if (empty($check) && $check != '0') {
103
			return false;
104
		}
105
		return static::_check($check, '/^[\p{Ll}\p{Lm}\p{Lo}\p{Lt}\p{Lu}\p{Nd}]+$/Du');
106
	}
107
 
108
/**
109
 * Checks that a string length is within s specified range.
110
 * Spaces are included in the character count.
111
 * Returns true is string matches value min, max, or between min and max,
112
 *
113
 * @param string $check Value to check for length
114
 * @param int $min Minimum value in range (inclusive)
115
 * @param int $max Maximum value in range (inclusive)
116
 * @return bool Success
117
 */
118
	public static function lengthBetween($check, $min, $max) {
119
		$length = mb_strlen($check);
120
		return ($length >= $min && $length <= $max);
121
	}
122
 
123
/**
124
 * Alias of Validator::lengthBetween() for backwards compatibility.
125
 *
126
 * @param string $check Value to check for length
127
 * @param int $min Minimum value in range (inclusive)
128
 * @param int $max Maximum value in range (inclusive)
129
 * @return bool Success
130
 * @see Validator::lengthBetween()
131
 * @deprecated Deprecated 2.6. Use Validator::lengthBetween() instead.
132
 */
133
	public static function between($check, $min, $max) {
134
		return static::lengthBetween($check, $min, $max);
135
	}
136
 
137
/**
138
 * Returns true if field is left blank -OR- only whitespace characters are present in its value
139
 * Whitespace characters include Space, Tab, Carriage Return, Newline
140
 *
141
 * $check can be passed as an array:
142
 * array('check' => 'valueToCheck');
143
 *
144
 * @param string|array $check Value to check
145
 * @return bool Success
146
 */
147
	public static function blank($check) {
148
		if (is_array($check)) {
149
			extract(static::_defaults($check));
150
		}
151
		return !static::_check($check, '/[^\\s]/');
152
	}
153
 
154
/**
155
 * Validation of credit card numbers.
156
 * Returns true if $check is in the proper credit card format.
157
 *
158
 * @param string|array $check credit card number to validate
159
 * @param string|array $type 'all' may be passed as a sting, defaults to fast which checks format of most major credit
160
 * cards
161
 *    if an array is used only the values of the array are checked.
162
 *    Example: array('amex', 'bankcard', 'maestro')
163
 * @param bool $deep set to true this will check the Luhn algorithm of the credit card.
164
 * @param string $regex A custom regex can also be passed, this will be used instead of the defined regex values
165
 * @return bool Success
166
 * @see Validation::luhn()
167
 */
168
	public static function cc($check, $type = 'fast', $deep = false, $regex = null) {
169
		if (is_array($check)) {
170
			extract(static::_defaults($check));
171
		}
172
 
173
		$check = str_replace(array('-', ' '), '', $check);
174
		if (mb_strlen($check) < 13) {
175
			return false;
176
		}
177
 
178
		if ($regex !== null) {
179
			if (static::_check($check, $regex)) {
180
				return static::luhn($check, $deep);
181
			}
182
		}
183
		$cards = array(
184
			'all' => array(
185
				'amex'		=> '/^3[4|7]\\d{13}$/',
186
				'bankcard'	=> '/^56(10\\d\\d|022[1-5])\\d{10}$/',
187
				'diners'	=> '/^(?:3(0[0-5]|[68]\\d)\\d{11})|(?:5[1-5]\\d{14})$/',
188
				'disc'		=> '/^(?:6011|650\\d)\\d{12}$/',
189
				'electron'	=> '/^(?:417500|4917\\d{2}|4913\\d{2})\\d{10}$/',
190
				'enroute'	=> '/^2(?:014|149)\\d{11}$/',
191
				'jcb'		=> '/^(3\\d{4}|2100|1800)\\d{11}$/',
192
				'maestro'	=> '/^(?:5020|6\\d{3})\\d{12}$/',
193
				'mc'		=> '/^5[1-5]\\d{14}$/',
194
				'solo'		=> '/^(6334[5-9][0-9]|6767[0-9]{2})\\d{10}(\\d{2,3})?$/',
195
				'switch'	=>
196
				'/^(?:49(03(0[2-9]|3[5-9])|11(0[1-2]|7[4-9]|8[1-2])|36[0-9]{2})\\d{10}(\\d{2,3})?)|(?:564182\\d{10}(\\d{2,3})?)|(6(3(33[0-4][0-9])|759[0-9]{2})\\d{10}(\\d{2,3})?)$/',
197
				'visa'		=> '/^4\\d{12}(\\d{3})?$/',
198
				'voyager'	=> '/^8699[0-9]{11}$/'
199
			),
200
			'fast' =>
201
			'/^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6011[0-9]{12}|3(?:0[0-5]|[68][0-9])[0-9]{11}|3[47][0-9]{13})$/'
202
		);
203
 
204
		if (is_array($type)) {
205
			foreach ($type as $value) {
206
				$regex = $cards['all'][strtolower($value)];
207
 
208
				if (static::_check($check, $regex)) {
209
					return static::luhn($check, $deep);
210
				}
211
			}
212
		} elseif ($type === 'all') {
213
			foreach ($cards['all'] as $value) {
214
				$regex = $value;
215
 
216
				if (static::_check($check, $regex)) {
217
					return static::luhn($check, $deep);
218
				}
219
			}
220
		} else {
221
			$regex = $cards['fast'];
222
 
223
			if (static::_check($check, $regex)) {
224
				return static::luhn($check, $deep);
225
			}
226
		}
227
		return false;
228
	}
229
 
230
/**
231
 * Used to compare 2 numeric values.
232
 *
233
 * @param string|array $check1 if string is passed for a string must also be passed for $check2
234
 *    used as an array it must be passed as array('check1' => value, 'operator' => 'value', 'check2' -> value)
235
 * @param string $operator Can be either a word or operand
236
 *    is greater >, is less <, greater or equal >=
237
 *    less or equal <=, is less <, equal to ==, not equal !=
238
 * @param int $check2 only needed if $check1 is a string
239
 * @return bool Success
240
 */
241
	public static function comparison($check1, $operator = null, $check2 = null) {
242
		if (is_array($check1)) {
243
			extract($check1, EXTR_OVERWRITE);
244
		}
245
 
246
		if ((float)$check1 != $check1) {
247
			return false;
248
		}
249
		$operator = str_replace(array(' ', "\t", "\n", "\r", "\0", "\x0B"), '', strtolower($operator));
250
 
251
		switch ($operator) {
252
			case 'isgreater':
253
			case '>':
254
				if ($check1 > $check2) {
255
					return true;
256
				}
257
				break;
258
			case 'isless':
259
			case '<':
260
				if ($check1 < $check2) {
261
					return true;
262
				}
263
				break;
264
			case 'greaterorequal':
265
			case '>=':
266
				if ($check1 >= $check2) {
267
					return true;
268
				}
269
				break;
270
			case 'lessorequal':
271
			case '<=':
272
				if ($check1 <= $check2) {
273
					return true;
274
				}
275
				break;
276
			case 'equalto':
277
			case '==':
278
				if ($check1 == $check2) {
279
					return true;
280
				}
281
				break;
282
			case 'notequal':
283
			case '!=':
284
				if ($check1 != $check2) {
285
					return true;
286
				}
287
				break;
288
			default:
289
				static::$errors[] = __d('cake_dev', 'You must define the $operator parameter for %s', 'Validation::comparison()');
290
		}
291
		return false;
292
	}
293
 
294
/**
295
 * Used when a custom regular expression is needed.
296
 *
297
 * @param string|array $check When used as a string, $regex must also be a valid regular expression.
298
 *    As and array: array('check' => value, 'regex' => 'valid regular expression')
299
 * @param string $regex If $check is passed as a string, $regex must also be set to valid regular expression
300
 * @return bool Success
301
 */
302
	public static function custom($check, $regex = null) {
303
		if (is_array($check)) {
304
			extract(static::_defaults($check));
305
		}
306
		if ($regex === null) {
307
			static::$errors[] = __d('cake_dev', 'You must define a regular expression for %s', 'Validation::custom()');
308
			return false;
309
		}
310
		return static::_check($check, $regex);
311
	}
312
 
313
/**
314
 * Date validation, determines if the string passed is a valid date.
315
 * keys that expect full month, day and year will validate leap years.
316
 *
317
 * Years are valid from 1800 to 2999.
318
 *
319
 * ### Formats:
320
 *
321
 * - `dmy` 27-12-2006 or 27-12-06 separators can be a space, period, dash, forward slash
322
 * - `mdy` 12-27-2006 or 12-27-06 separators can be a space, period, dash, forward slash
323
 * - `ymd` 2006-12-27 or 06-12-27 separators can be a space, period, dash, forward slash
324
 * - `dMy` 27 December 2006 or 27 Dec 2006
325
 * - `Mdy` December 27, 2006 or Dec 27, 2006 comma is optional
326
 * - `My` December 2006 or Dec 2006
327
 * - `my` 12/2006 or 12/06 separators can be a space, period, dash, forward slash
328
 * - `ym` 2006/12 or 06/12 separators can be a space, period, dash, forward slash
329
 * - `y` 2006 just the year without any separators
330
 *
331
 * @param string $check a valid date string
332
 * @param string|array $format Use a string or an array of the keys above.
333
 *    Arrays should be passed as array('dmy', 'mdy', etc)
334
 * @param string $regex If a custom regular expression is used this is the only validation that will occur.
335
 * @return bool Success
336
 */
337
	public static function date($check, $format = 'ymd', $regex = null) {
338
		if ($regex !== null) {
339
			return static::_check($check, $regex);
340
		}
341
		$month = '(0[123456789]|10|11|12)';
342
		$separator = '([- /.])';
343
		$fourDigitYear = '(([1][8-9][0-9][0-9])|([2][0-9][0-9][0-9]))';
344
		$twoDigitYear = '([0-9]{2})';
345
		$year = '(?:' . $fourDigitYear . '|' . $twoDigitYear . ')';
346
 
347
		$regex['dmy'] = '%^(?:(?:31(\\/|-|\\.|\\x20)(?:0?[13578]|1[02]))\\1|(?:(?:29|30)' .
348
			$separator . '(?:0?[1,3-9]|1[0-2])\\2))(?:(?:1[6-9]|[2-9]\\d)?\\d{2})$|^(?:29' .
349
			$separator . '0?2\\3(?:(?:(?:1[6-9]|[2-9]\\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\\d|2[0-8])' .
350
			$separator . '(?:(?:0?[1-9])|(?:1[0-2]))\\4(?:(?:1[6-9]|[2-9]\\d)?\\d{2})$%';
351
 
352
		$regex['mdy'] = '%^(?:(?:(?:0?[13578]|1[02])(\\/|-|\\.|\\x20)31)\\1|(?:(?:0?[13-9]|1[0-2])' .
353
			$separator . '(?:29|30)\\2))(?:(?:1[6-9]|[2-9]\\d)?\\d{2})$|^(?:0?2' . $separator . '29\\3(?:(?:(?:1[6-9]|[2-9]\\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:(?:0?[1-9])|(?:1[0-2]))' .
354
			$separator . '(?:0?[1-9]|1\\d|2[0-8])\\4(?:(?:1[6-9]|[2-9]\\d)?\\d{2})$%';
355
 
356
		$regex['ymd'] = '%^(?:(?:(?:(?:(?:1[6-9]|[2-9]\\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00)))' .
357
			$separator . '(?:0?2\\1(?:29)))|(?:(?:(?:1[6-9]|[2-9]\\d)?\\d{2})' .
358
			$separator . '(?:(?:(?:0?[13578]|1[02])\\2(?:31))|(?:(?:0?[1,3-9]|1[0-2])\\2(29|30))|(?:(?:0?[1-9])|(?:1[0-2]))\\2(?:0?[1-9]|1\\d|2[0-8]))))$%';
359
 
360
		$regex['dMy'] = '/^((31(?!\\ (Feb(ruary)?|Apr(il)?|June?|(Sep(?=\\b|t)t?|Nov)(ember)?)))|((30|29)(?!\\ Feb(ruary)?))|(29(?=\\ Feb(ruary)?\\ (((1[6-9]|[2-9]\\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)))))|(0?[1-9])|1\\d|2[0-8])\\ (Jan(uary)?|Feb(ruary)?|Ma(r(ch)?|y)|Apr(il)?|Ju((ly?)|(ne?))|Aug(ust)?|Oct(ober)?|(Sep(?=\\b|t)t?|Nov|Dec)(ember)?)\\ ((1[6-9]|[2-9]\\d)\\d{2})$/';
361
 
362
		$regex['Mdy'] = '/^(?:(((Jan(uary)?|Ma(r(ch)?|y)|Jul(y)?|Aug(ust)?|Oct(ober)?|Dec(ember)?)\\ 31)|((Jan(uary)?|Ma(r(ch)?|y)|Apr(il)?|Ju((ly?)|(ne?))|Aug(ust)?|Oct(ober)?|(Sep)(tember)?|(Nov|Dec)(ember)?)\\ (0?[1-9]|([12]\\d)|30))|(Feb(ruary)?\\ (0?[1-9]|1\\d|2[0-8]|(29(?=,?\\ ((1[6-9]|[2-9]\\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00)))))))\\,?\\ ((1[6-9]|[2-9]\\d)\\d{2}))$/';
363
 
364
		$regex['My'] = '%^(Jan(uary)?|Feb(ruary)?|Ma(r(ch)?|y)|Apr(il)?|Ju((ly?)|(ne?))|Aug(ust)?|Oct(ober)?|(Sep(?=\\b|t)t?|Nov|Dec)(ember)?)' .
365
			$separator . '((1[6-9]|[2-9]\\d)\\d{2})$%';
366
 
367
		$regex['my'] = '%^(' . $month . $separator . $year . ')$%';
368
		$regex['ym'] = '%^(' . $year . $separator . $month . ')$%';
369
		$regex['y'] = '%^(' . $fourDigitYear . ')$%';
370
 
371
		$format = (is_array($format)) ? array_values($format) : array($format);
372
		foreach ($format as $key) {
373
			if (static::_check($check, $regex[$key]) === true) {
374
				return true;
375
			}
376
		}
377
		return false;
378
	}
379
 
380
/**
381
 * Validates a datetime value
382
 *
383
 * All values matching the "date" core validation rule, and the "time" one will be valid
384
 *
385
 * @param string $check Value to check
386
 * @param string|array $dateFormat Format of the date part. See Validation::date for more information.
387
 * @param string $regex Regex for the date part. If a custom regular expression is used this is the only validation that will occur.
388
 * @return bool True if the value is valid, false otherwise
389
 * @see Validation::date
390
 * @see Validation::time
391
 */
392
	public static function datetime($check, $dateFormat = 'ymd', $regex = null) {
393
		$valid = false;
394
		$parts = explode(' ', $check);
395
		if (!empty($parts) && count($parts) > 1) {
396
			$time = array_pop($parts);
397
			$date = implode(' ', $parts);
398
			$valid = static::date($date, $dateFormat, $regex) && static::time($time);
399
		}
400
		return $valid;
401
	}
402
 
403
/**
404
 * Time validation, determines if the string passed is a valid time.
405
 * Validates time as 24hr (HH:MM) or am/pm ([H]H:MM[a|p]m)
406
 * Does not allow/validate seconds.
407
 *
408
 * @param string $check a valid time string
409
 * @return bool Success
410
 */
411
	public static function time($check) {
412
		return static::_check($check, '%^((0?[1-9]|1[012])(:[0-5]\d){0,2} ?([AP]M|[ap]m))$|^([01]\d|2[0-3])(:[0-5]\d){0,2}$%');
413
	}
414
 
415
/**
416
 * Boolean validation, determines if value passed is a boolean integer or true/false.
417
 *
418
 * @param string $check a valid boolean
419
 * @return bool Success
420
 */
421
	public static function boolean($check) {
422
		$booleanList = array(0, 1, '0', '1', true, false);
423
		return in_array($check, $booleanList, true);
424
	}
425
 
426
/**
427
 * Checks that a value is a valid decimal. Both the sign and exponent are optional.
428
 *
429
 * Valid Places:
430
 *
431
 * - null => Any number of decimal places, including none. The '.' is not required.
432
 * - true => Any number of decimal places greater than 0, or a float|double. The '.' is required.
433
 * - 1..N => Exactly that many number of decimal places. The '.' is required.
434
 *
435
 * @param float $check The value the test for decimal.
436
 * @param int $places Decimal places.
437
 * @param string $regex If a custom regular expression is used, this is the only validation that will occur.
438
 * @return bool Success
439
 */
440
	public static function decimal($check, $places = null, $regex = null) {
441
		if ($regex === null) {
442
			$lnum = '[0-9]+';
443
			$dnum = "[0-9]*[\.]{$lnum}";
444
			$sign = '[+-]?';
445
			$exp = "(?:[eE]{$sign}{$lnum})?";
446
 
447
			if ($places === null) {
448
				$regex = "/^{$sign}(?:{$lnum}|{$dnum}){$exp}$/";
449
 
450
			} elseif ($places === true) {
451
				if (is_float($check) && floor($check) === $check) {
452
					$check = sprintf("%.1f", $check);
453
				}
454
				$regex = "/^{$sign}{$dnum}{$exp}$/";
455
 
456
			} elseif (is_numeric($places)) {
457
				$places = '[0-9]{' . $places . '}';
458
				$dnum = "(?:[0-9]*[\.]{$places}|{$lnum}[\.]{$places})";
459
				$regex = "/^{$sign}{$dnum}{$exp}$/";
460
			}
461
		}
462
 
463
		// account for localized floats.
464
		$data = localeconv();
465
		$check = str_replace($data['thousands_sep'], '', $check);
466
		$check = str_replace($data['decimal_point'], '.', $check);
467
 
468
		return static::_check($check, $regex);
469
	}
470
 
471
/**
472
 * Validates for an email address.
473
 *
474
 * Only uses getmxrr() checking for deep validation if PHP 5.3.0+ is used, or
475
 * any PHP version on a non-Windows distribution
476
 *
477
 * @param string $check Value to check
478
 * @param bool $deep Perform a deeper validation (if true), by also checking availability of host
479
 * @param string $regex Regex to use (if none it will use built in regex)
480
 * @return bool Success
481
 */
482
	public static function email($check, $deep = false, $regex = null) {
483
		if (is_array($check)) {
484
			extract(static::_defaults($check));
485
		}
486
 
487
		if ($regex === null) {
488
			$regex = '/^[\p{L}0-9!#$%&\'*+\/=?^_`{|}~-]+(?:\.[\p{L}0-9!#$%&\'*+\/=?^_`{|}~-]+)*@' . static::$_pattern['hostname'] . '$/ui';
489
		}
490
		$return = static::_check($check, $regex);
491
		if ($deep === false || $deep === null) {
492
			return $return;
493
		}
494
 
495
		if ($return === true && preg_match('/@(' . static::$_pattern['hostname'] . ')$/i', $check, $regs)) {
496
			if (function_exists('getmxrr') && getmxrr($regs[1], $mxhosts)) {
497
				return true;
498
			}
499
			if (function_exists('checkdnsrr') && checkdnsrr($regs[1], 'MX')) {
500
				return true;
501
			}
502
			return is_array(gethostbynamel($regs[1]));
503
		}
504
		return false;
505
	}
506
 
507
/**
508
 * Check that value is exactly $comparedTo.
509
 *
510
 * @param mixed $check Value to check
511
 * @param mixed $comparedTo Value to compare
512
 * @return bool Success
513
 */
514
	public static function equalTo($check, $comparedTo) {
515
		return ($check === $comparedTo);
516
	}
517
 
518
/**
519
 * Check that value has a valid file extension.
520
 *
521
 * @param string|array $check Value to check
522
 * @param array $extensions file extensions to allow. By default extensions are 'gif', 'jpeg', 'png', 'jpg'
523
 * @return bool Success
524
 */
525
	public static function extension($check, $extensions = array('gif', 'jpeg', 'png', 'jpg')) {
526
		if (is_array($check)) {
527
			return static::extension(array_shift($check), $extensions);
528
		}
529
		$extension = strtolower(pathinfo($check, PATHINFO_EXTENSION));
530
		foreach ($extensions as $value) {
531
			if ($extension === strtolower($value)) {
532
				return true;
533
			}
534
		}
535
		return false;
536
	}
537
 
538
/**
539
 * Validation of an IP address.
540
 *
541
 * @param string $check The string to test.
542
 * @param string $type The IP Protocol version to validate against
543
 * @return bool Success
544
 */
545
	public static function ip($check, $type = 'both') {
546
		$type = strtolower($type);
547
		$flags = 0;
548
		if ($type === 'ipv4') {
549
			$flags = FILTER_FLAG_IPV4;
550
		}
551
		if ($type === 'ipv6') {
552
			$flags = FILTER_FLAG_IPV6;
553
		}
554
		return (bool)filter_var($check, FILTER_VALIDATE_IP, array('flags' => $flags));
555
	}
556
 
557
/**
558
 * Checks whether the length of a string is greater or equal to a minimal length.
559
 *
560
 * @param string $check The string to test
561
 * @param int $min The minimal string length
562
 * @return bool Success
563
 */
564
	public static function minLength($check, $min) {
565
		return mb_strlen($check) >= $min;
566
	}
567
 
568
/**
569
 * Checks whether the length of a string is smaller or equal to a maximal length..
570
 *
571
 * @param string $check The string to test
572
 * @param int $max The maximal string length
573
 * @return bool Success
574
 */
575
	public static function maxLength($check, $max) {
576
		return mb_strlen($check) <= $max;
577
	}
578
 
579
/**
580
 * Checks that a value is a monetary amount.
581
 *
582
 * @param string $check Value to check
583
 * @param string $symbolPosition Where symbol is located (left/right)
584
 * @return bool Success
585
 */
586
	public static function money($check, $symbolPosition = 'left') {
587
		$money = '(?!0,?\d)(?:\d{1,3}(?:([, .])\d{3})?(?:\1\d{3})*|(?:\d+))((?!\1)[,.]\d{1,2})?';
588
		if ($symbolPosition === 'right') {
589
			$regex = '/^' . $money . '(?<!\x{00a2})\p{Sc}?$/u';
590
		} else {
591
			$regex = '/^(?!\x{00a2})\p{Sc}?' . $money . '$/u';
592
		}
593
		return static::_check($check, $regex);
594
	}
595
 
596
/**
597
 * Validate a multiple select. Comparison is case sensitive by default.
598
 *
599
 * Valid Options
600
 *
601
 * - in => provide a list of choices that selections must be made from
602
 * - max => maximum number of non-zero choices that can be made
603
 * - min => minimum number of non-zero choices that can be made
604
 *
605
 * @param array $check Value to check
606
 * @param array $options Options for the check.
607
 * @param bool $caseInsensitive Set to true for case insensitive comparison.
608
 * @return bool Success
609
 */
610
	public static function multiple($check, $options = array(), $caseInsensitive = false) {
611
		$defaults = array('in' => null, 'max' => null, 'min' => null);
612
		$options += $defaults;
613
 
614
		$check = array_filter((array)$check, 'strlen');
615
		if (empty($check)) {
616
			return false;
617
		}
618
		if ($options['max'] && count($check) > $options['max']) {
619
			return false;
620
		}
621
		if ($options['min'] && count($check) < $options['min']) {
622
			return false;
623
		}
624
		if ($options['in'] && is_array($options['in'])) {
625
			if ($caseInsensitive) {
626
				$options['in'] = array_map('mb_strtolower', $options['in']);
627
			}
628
			foreach ($check as $val) {
629
				$strict = !is_numeric($val);
630
				if ($caseInsensitive) {
631
					$val = mb_strtolower($val);
632
				}
633
				if (!in_array((string)$val, $options['in'], $strict)) {
634
					return false;
635
				}
636
			}
637
		}
638
		return true;
639
	}
640
 
641
/**
642
 * Checks if a value is numeric.
643
 *
644
 * @param string $check Value to check
645
 * @return bool Success
646
 */
647
	public static function numeric($check) {
648
		return is_numeric($check);
649
	}
650
 
651
/**
652
 * Checks if a value is a natural number.
653
 *
654
 * @param string $check Value to check
655
 * @param bool $allowZero Set true to allow zero, defaults to false
656
 * @return bool Success
657
 * @see http://en.wikipedia.org/wiki/Natural_number
658
 */
659
	public static function naturalNumber($check, $allowZero = false) {
660
		$regex = $allowZero ? '/^(?:0|[1-9][0-9]*)$/' : '/^[1-9][0-9]*$/';
661
		return static::_check($check, $regex);
662
	}
663
 
664
/**
665
 * Check that a value is a valid phone number.
666
 *
667
 * @param string|array $check Value to check (string or array)
668
 * @param string $regex Regular expression to use
669
 * @param string $country Country code (defaults to 'all')
670
 * @return bool Success
671
 */
672
	public static function phone($check, $regex = null, $country = 'all') {
673
		if (is_array($check)) {
674
			extract(static::_defaults($check));
675
		}
676
 
677
		if ($regex === null) {
678
			switch ($country) {
679
				case 'us':
680
				case 'ca':
681
				case 'can': // deprecated three-letter-code
682
				case 'all':
683
					// includes all NANPA members.
684
					// see http://en.wikipedia.org/wiki/North_American_Numbering_Plan#List_of_NANPA_countries_and_territories
685
					$regex = '/^(?:(?:\+?1\s*(?:[.-]\s*)?)?';
686
 
687
					// Area code 555, X11 is not allowed.
688
					$areaCode = '(?![2-9]11)(?!555)([2-9][0-8][0-9])';
689
					$regex .= '(?:\(\s*' . $areaCode . '\s*\)|' . $areaCode . ')';
690
					$regex .= '\s*(?:[.-]\s*)?)';
691
 
692
					// Exchange and 555-XXXX numbers
693
					$regex .= '(?!(555(?:\s*(?:[.\-\s]\s*))(01([0-9][0-9])|1212)))';
694
					$regex .= '(?!(555(01([0-9][0-9])|1212)))';
695
					$regex .= '([2-9]1[02-9]|[2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)';
696
 
697
					// Local number and extension
698
					$regex .= '?([0-9]{4})';
699
					$regex .= '(?:\s*(?:#|x\.?|ext\.?|extension)\s*(\d+))?$/';
700
				break;
701
			}
702
		}
703
		if (empty($regex)) {
704
			return static::_pass('phone', $check, $country);
705
		}
706
		return static::_check($check, $regex);
707
	}
708
 
709
/**
710
 * Checks that a given value is a valid postal code.
711
 *
712
 * @param string|array $check Value to check
713
 * @param string $regex Regular expression to use
714
 * @param string $country Country to use for formatting
715
 * @return bool Success
716
 */
717
	public static function postal($check, $regex = null, $country = 'us') {
718
		if (is_array($check)) {
719
			extract(static::_defaults($check));
720
		}
721
 
722
		if ($regex === null) {
723
			switch ($country) {
724
				case 'uk':
725
					$regex = '/\\A\\b[A-Z]{1,2}[0-9][A-Z0-9]? [0-9][ABD-HJLNP-UW-Z]{2}\\b\\z/i';
726
					break;
727
				case 'ca':
728
					$district = '[ABCEGHJKLMNPRSTVYX]';
729
					$letters = '[ABCEGHJKLMNPRSTVWXYZ]';
730
					$regex = "/\\A\\b{$district}[0-9]{$letters} [0-9]{$letters}[0-9]\\b\\z/i";
731
					break;
732
				case 'it':
733
				case 'de':
734
					$regex = '/^[0-9]{5}$/i';
735
					break;
736
				case 'be':
737
					$regex = '/^[1-9]{1}[0-9]{3}$/i';
738
					break;
739
				case 'us':
740
					$regex = '/\\A\\b[0-9]{5}(?:-[0-9]{4})?\\b\\z/i';
741
					break;
742
			}
743
		}
744
		if (empty($regex)) {
745
			return static::_pass('postal', $check, $country);
746
		}
747
		return static::_check($check, $regex);
748
	}
749
 
750
/**
751
 * Validate that a number is in specified range.
752
 * if $lower and $upper are not set, will return true if
753
 * $check is a legal finite on this platform
754
 *
755
 * @param string $check Value to check
756
 * @param int|float $lower Lower limit
757
 * @param int|float $upper Upper limit
758
 * @return bool Success
759
 */
760
	public static function range($check, $lower = null, $upper = null) {
761
		if (!is_numeric($check)) {
762
			return false;
763
		}
764
		if ((float)$check != $check) {
765
			return false;
766
		}
767
		if (isset($lower) && isset($upper)) {
768
			return ($check > $lower && $check < $upper);
769
		}
770
		return is_finite($check);
771
	}
772
 
773
/**
774
 * Checks that a value is a valid Social Security Number.
775
 *
776
 * @param string|array $check Value to check
777
 * @param string $regex Regular expression to use
778
 * @param string $country Country
779
 * @return bool Success
780
 * @deprecated Deprecated 2.6. Will be removed in 3.0.
781
 */
782
	public static function ssn($check, $regex = null, $country = null) {
783
		if (is_array($check)) {
784
			extract(static::_defaults($check));
785
		}
786
 
787
		if ($regex === null) {
788
			switch ($country) {
789
				case 'dk':
790
					$regex = '/\\A\\b[0-9]{6}-[0-9]{4}\\b\\z/i';
791
					break;
792
				case 'nl':
793
					$regex = '/\\A\\b[0-9]{9}\\b\\z/i';
794
					break;
795
				case 'us':
796
					$regex = '/\\A\\b[0-9]{3}-[0-9]{2}-[0-9]{4}\\b\\z/i';
797
					break;
798
			}
799
		}
800
		if (empty($regex)) {
801
			return static::_pass('ssn', $check, $country);
802
		}
803
		return static::_check($check, $regex);
804
	}
805
 
806
/**
807
 * Checks that a value is a valid URL according to http://www.w3.org/Addressing/URL/url-spec.txt
808
 *
809
 * The regex checks for the following component parts:
810
 *
811
 * - a valid, optional, scheme
812
 * - a valid ip address OR
813
 *   a valid domain name as defined by section 2.3.1 of http://www.ietf.org/rfc/rfc1035.txt
814
 *   with an optional port number
815
 * - an optional valid path
816
 * - an optional query string (get parameters)
817
 * - an optional fragment (anchor tag)
818
 *
819
 * @param string $check Value to check
820
 * @param bool $strict Require URL to be prefixed by a valid scheme (one of http(s)/ftp(s)/file/news/gopher)
821
 * @return bool Success
822
 */
823
	public static function url($check, $strict = false) {
824
		static::_populateIp();
825
		$validChars = '([' . preg_quote('!"$&\'()*+,-.@_:;=~[]') . '\/0-9\p{L}\p{N}]|(%[0-9a-f]{2}))';
826
		$regex = '/^(?:(?:https?|ftps?|sftp|file|news|gopher):\/\/)' . (!empty($strict) ? '' : '?') .
827
			'(?:' . static::$_pattern['IPv4'] . '|\[' . static::$_pattern['IPv6'] . '\]|' . static::$_pattern['hostname'] . ')(?::[1-9][0-9]{0,4})?' .
828
			'(?:\/?|\/' . $validChars . '*)?' .
829
			'(?:\?' . $validChars . '*)?' .
830
			'(?:#' . $validChars . '*)?$/iu';
831
		return static::_check($check, $regex);
832
	}
833
 
834
/**
835
 * Checks if a value is in a given list. Comparison is case sensitive by default.
836
 *
837
 * @param string $check Value to check.
838
 * @param array $list List to check against.
839
 * @param bool $caseInsensitive Set to true for case insensitive comparison.
840
 * @return bool Success.
841
 */
842
	public static function inList($check, $list, $caseInsensitive = false) {
843
		if ($caseInsensitive) {
844
			$list = array_map('mb_strtolower', $list);
845
			$check = mb_strtolower($check);
846
		} else {
847
			$list = array_map('strval', $list);
848
		}
849
		return in_array((string)$check, $list, true);
850
	}
851
 
852
/**
853
 * Runs an user-defined validation.
854
 *
855
 * @param string|array $check value that will be validated in user-defined methods.
856
 * @param object $object class that holds validation method
857
 * @param string $method class method name for validation to run
858
 * @param array $args arguments to send to method
859
 * @return mixed user-defined class class method returns
860
 */
861
	public static function userDefined($check, $object, $method, $args = null) {
862
		return call_user_func_array(array($object, $method), array($check, $args));
863
	}
864
 
865
/**
866
 * Checks that a value is a valid UUID - http://tools.ietf.org/html/rfc4122
867
 *
868
 * @param string $check Value to check
869
 * @return bool Success
870
 */
871
	public static function uuid($check) {
872
		$regex = '/^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[0-5][a-fA-F0-9]{3}-[089aAbB][a-fA-F0-9]{3}-[a-fA-F0-9]{12}$/';
873
		return static::_check($check, $regex);
874
	}
875
 
876
/**
877
 * Attempts to pass unhandled Validation locales to a class starting with $classPrefix
878
 * and ending with Validation. For example $classPrefix = 'nl', the class would be
879
 * `NlValidation`.
880
 *
881
 * @param string $method The method to call on the other class.
882
 * @param mixed $check The value to check or an array of parameters for the method to be called.
883
 * @param string $classPrefix The prefix for the class to do the validation.
884
 * @return mixed Return of Passed method, false on failure
885
 */
886
	protected static function _pass($method, $check, $classPrefix) {
887
		$className = ucwords($classPrefix) . 'Validation';
888
		if (!class_exists($className)) {
889
			trigger_error(__d('cake_dev', 'Could not find %s class, unable to complete validation.', $className), E_USER_WARNING);
890
			return false;
891
		}
892
		if (!method_exists($className, $method)) {
893
			trigger_error(__d('cake_dev', 'Method %s does not exist on %s unable to complete validation.', $method, $className), E_USER_WARNING);
894
			return false;
895
		}
896
		$check = (array)$check;
897
		return call_user_func_array(array($className, $method), $check);
898
	}
899
 
900
/**
901
 * Runs a regular expression match.
902
 *
903
 * @param string $check Value to check against the $regex expression
904
 * @param string $regex Regular expression
905
 * @return bool Success of match
906
 */
907
	protected static function _check($check, $regex) {
908
		if (is_string($regex) && preg_match($regex, $check)) {
909
			return true;
910
		}
911
		return false;
912
	}
913
 
914
/**
915
 * Get the values to use when value sent to validation method is
916
 * an array.
917
 *
918
 * @param array $params Parameters sent to validation method
919
 * @return void
920
 */
921
	protected static function _defaults($params) {
922
		static::_reset();
923
		$defaults = array(
924
			'check' => null,
925
			'regex' => null,
926
			'country' => null,
927
			'deep' => false,
928
			'type' => null
929
		);
930
		$params += $defaults;
931
		if ($params['country'] !== null) {
932
			$params['country'] = mb_strtolower($params['country']);
933
		}
934
		return $params;
935
	}
936
 
937
/**
938
 * Luhn algorithm
939
 *
940
 * @param string|array $check Value to check.
941
 * @param bool $deep If true performs deep check.
942
 * @return bool Success
943
 * @see http://en.wikipedia.org/wiki/Luhn_algorithm
944
 */
945
	public static function luhn($check, $deep = false) {
946
		if (is_array($check)) {
947
			extract(static::_defaults($check));
948
		}
949
		if ($deep !== true) {
950
			return true;
951
		}
952
		if ((int)$check === 0) {
953
			return false;
954
		}
955
		$sum = 0;
956
		$length = strlen($check);
957
 
958
		for ($position = 1 - ($length % 2); $position < $length; $position += 2) {
959
			$sum += $check[$position];
960
		}
961
 
962
		for ($position = ($length % 2); $position < $length; $position += 2) {
963
			$number = $check[$position] * 2;
964
			$sum += ($number < 10) ? $number : $number - 9;
965
		}
966
 
967
		return ($sum % 10 === 0);
968
	}
969
 
970
/**
971
 * Checks the mime type of a file.
972
 *
973
 * @param string|array $check Value to check.
974
 * @param array|string $mimeTypes Array of mime types or regex pattern to check.
975
 * @return bool Success
976
 * @throws CakeException when mime type can not be determined.
977
 */
978
	public static function mimeType($check, $mimeTypes = array()) {
979
		if (is_array($check) && isset($check['tmp_name'])) {
980
			$check = $check['tmp_name'];
981
		}
982
 
983
		$File = new File($check);
984
		$mime = $File->mime();
985
 
986
		if ($mime === false) {
987
			throw new CakeException(__d('cake_dev', 'Can not determine the mimetype.'));
988
		}
989
 
990
		if (is_string($mimeTypes)) {
991
			return static::_check($mime, $mimeTypes);
992
		}
993
 
994
		foreach ($mimeTypes as $key => $val) {
995
			$mimeTypes[$key] = strtolower($val);
996
		}
997
		return in_array($mime, $mimeTypes);
998
	}
999
 
1000
/**
1001
 * Checks the filesize
1002
 *
1003
 * @param string|array $check Value to check.
1004
 * @param string $operator See `Validation::comparison()`.
1005
 * @param int|string $size Size in bytes or human readable string like '5MB'.
1006
 * @return bool Success
1007
 */
1008
	public static function fileSize($check, $operator = null, $size = null) {
1009
		if (is_array($check) && isset($check['tmp_name'])) {
1010
			$check = $check['tmp_name'];
1011
		}
1012
 
1013
		if (is_string($size)) {
1014
			$size = CakeNumber::fromReadableSize($size);
1015
		}
1016
		$filesize = filesize($check);
1017
 
1018
		return static::comparison($filesize, $operator, $size);
1019
	}
1020
 
1021
/**
1022
 * Checking for upload errors
1023
 *
1024
 * @param string|array $check Value to check.
1025
 * @return bool
1026
 * @see http://www.php.net/manual/en/features.file-upload.errors.php
1027
 */
1028
	public static function uploadError($check) {
1029
		if (is_array($check) && isset($check['error'])) {
1030
			$check = $check['error'];
1031
		}
1032
 
1033
		return (int)$check === UPLOAD_ERR_OK;
1034
	}
1035
 
1036
/**
1037
 * Lazily populate the IP address patterns used for validations
1038
 *
1039
 * @return void
1040
 */
1041
	protected static function _populateIp() {
1042
		if (!isset(static::$_pattern['IPv6'])) {
1043
			$pattern = '((([0-9A-Fa-f]{1,4}:){7}(([0-9A-Fa-f]{1,4})|:))|(([0-9A-Fa-f]{1,4}:){6}';
1044
			$pattern .= '(:|((25[0-5]|2[0-4]\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})';
1045
			$pattern .= '|(:[0-9A-Fa-f]{1,4})))|(([0-9A-Fa-f]{1,4}:){5}((:((25[0-5]|2[0-4]\d|[01]?\d{1,2})';
1046
			$pattern .= '(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|((:[0-9A-Fa-f]{1,4}){1,2})))|(([0-9A-Fa-f]{1,4}:)';
1047
			$pattern .= '{4}(:[0-9A-Fa-f]{1,4}){0,1}((:((25[0-5]|2[0-4]\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2}))';
1048
			$pattern .= '{3})?)|((:[0-9A-Fa-f]{1,4}){1,2})))|(([0-9A-Fa-f]{1,4}:){3}(:[0-9A-Fa-f]{1,4}){0,2}';
1049
			$pattern .= '((:((25[0-5]|2[0-4]\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|';
1050
			$pattern .= '((:[0-9A-Fa-f]{1,4}){1,2})))|(([0-9A-Fa-f]{1,4}:){2}(:[0-9A-Fa-f]{1,4}){0,3}';
1051
			$pattern .= '((:((25[0-5]|2[0-4]\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2}))';
1052
			$pattern .= '{3})?)|((:[0-9A-Fa-f]{1,4}){1,2})))|(([0-9A-Fa-f]{1,4}:)(:[0-9A-Fa-f]{1,4})';
1053
			$pattern .= '{0,4}((:((25[0-5]|2[0-4]\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)';
1054
			$pattern .= '|((:[0-9A-Fa-f]{1,4}){1,2})))|(:(:[0-9A-Fa-f]{1,4}){0,5}((:((25[0-5]|2[0-4]';
1055
			$pattern .= '\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})?)|((:[0-9A-Fa-f]{1,4})';
1056
			$pattern .= '{1,2})))|(((25[0-5]|2[0-4]\d|[01]?\d{1,2})(\.(25[0-5]|2[0-4]\d|[01]?\d{1,2})){3})))(%.+)?';
1057
 
1058
			static::$_pattern['IPv6'] = $pattern;
1059
		}
1060
		if (!isset(static::$_pattern['IPv4'])) {
1061
			$pattern = '(?:(?:25[0-5]|2[0-4][0-9]|(?:(?:1[0-9])?|[1-9]?)[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|(?:(?:1[0-9])?|[1-9]?)[0-9])';
1062
			static::$_pattern['IPv4'] = $pattern;
1063
		}
1064
	}
1065
 
1066
/**
1067
 * Reset internal variables for another validation run.
1068
 *
1069
 * @return void
1070
 */
1071
	protected static function _reset() {
1072
		static::$errors = array();
1073
	}
1074
 
1075
}