Subversion Repositories SmartDukaan

Rev

Details | Last modification | View Log | RSS feed

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