Subversion Repositories SmartDukaan

Rev

Details | Last modification | View Log | RSS feed

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