Subversion Repositories SmartDukaan

Rev

Details | Last modification | View Log | RSS feed

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