PageRenderTime 40ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 0ms

/library/core/functions.validation.php

https://github.com/Emaratilicious/Garden
PHP | 350 lines | 256 code | 44 blank | 50 comment | 80 complexity | e8fbadbf04e9c4e4272de3988550a671 MD5 | raw file
  1. <?php if (!defined('APPLICATION')) exit();
  2. /*
  3. Copyright 2008, 2009 Vanilla Forums Inc.
  4. This file is part of Garden.
  5. Garden is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
  6. Garden is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  7. You should have received a copy of the GNU General Public License along with Garden. If not, see <http://www.gnu.org/licenses/>.
  8. Contact Vanilla Forums Inc. at support [at] vanillaforums [dot] com
  9. */
  10. /**
  11. * All of these functions are used by ./class.validation.php to validate form
  12. * input strings. With the exception of ValidateRegex, each function receives
  13. * two parameters (the field value and the related database field properties)
  14. * and is expected to return a boolean TRUE or FALSE indicating if the
  15. * validation was successful.
  16. *
  17. * Note: $Field will be an object of field properties as defined in
  18. * @@MySQLDriver->_FetchTableSchema (at the bottom of the file). Properties
  19. * are: (string) Name, (bool) PrimaryKey, (string) Type, (bool) AllowNull,
  20. * (string) Default, (int) Length, (array) Enum.
  21. *
  22. * @package Garden
  23. */
  24. if (!function_exists('ValidateCaptcha')) {
  25. function ValidateCaptcha($Value) {
  26. $CaptchaPrivateKey = Gdn::Config('Garden.Registration.CaptchaPrivateKey', '');
  27. $Response = recaptcha_check_answer($CaptchaPrivateKey, ArrayValue('REMOTE_ADDR', $_SERVER, ''), ArrayValue('recaptcha_challenge_field', $_POST, ''), ArrayValue('recaptcha_response_field', $_POST, ''));
  28. return $Response->is_valid ? TRUE : 'The reCAPTCHA value was not entered correctly. Please try again.';
  29. }
  30. }
  31. if (!function_exists('ValidateRegex')) {
  32. function ValidateRegex($Value, $Regex) {
  33. preg_match($Regex, $Value, $Matches);
  34. return is_array($Matches) && count($Matches) > 0 ? TRUE : FALSE;
  35. }
  36. }
  37. if (!function_exists('ValidateRequired')) {
  38. function ValidateRequired($Value, $Field = '') {
  39. if (is_array($Value) === TRUE)
  40. return count($Value) > 0 ? TRUE : FALSE;
  41. if (is_string($Value))
  42. return trim($Value) == '' ? FALSE : TRUE;
  43. if (is_numeric($Value))
  44. return TRUE;
  45. return FALSE;
  46. }
  47. }
  48. if (!function_exists('ValidateRequiredArray')) {
  49. /**
  50. * Checkbox lists and DropDown lists that have no values selected return a
  51. * value of FALSE. Since this could be a valid entry in any other kind of
  52. * input, these "array" form-data types need their own "required" validation
  53. * method.
  54. */
  55. function ValidateRequiredArray($Value, $Field) {
  56. if (is_array($Value) === TRUE)
  57. return count($Value) > 0 ? TRUE : FALSE;
  58. return FALSE;
  59. }
  60. }
  61. if (!function_exists('ValidateConnection')) {
  62. function ValidateConnection($Value, $Field, $FormPostedValues) {
  63. $DatabaseHost = ArrayValue('Database.Host', $FormPostedValues, '~~Invalid~~');
  64. $DatabaseName = ArrayValue('Database.Name', $FormPostedValues, '~~Invalid~~');
  65. $DatabaseUser = ArrayValue('Database.User', $FormPostedValues, '~~Invalid~~');
  66. $DatabasePassword = ArrayValue('Database.Password', $FormPostedValues, '~~Invalid~~');
  67. $ConnectionString = GetConnectionString($DatabaseName, $DatabaseHost);
  68. try {
  69. $Connection = new PDO(
  70. $ConnectionString,
  71. $DatabaseUser,
  72. $DatabasePassword
  73. );
  74. } catch (PDOException $Exception) {
  75. return sprintf(T('ValidateConnection'), strip_tags($Exception->getMessage()));
  76. }
  77. return TRUE;
  78. }
  79. }
  80. if (!function_exists('ValidateOldPassword')) {
  81. function ValidateOldPassword($Value, $Field, $FormPostedValues) {
  82. $OldPassword = ArrayValue('OldPassword', $FormPostedValues, '');
  83. $Session = Gdn::Session();
  84. $UserModel = new UserModel();
  85. $UserID = $Session->UserID;
  86. return (bool) $UserModel->ValidateCredentials(
  87. '', $UserID, $OldPassword);
  88. }
  89. }
  90. if (!function_exists('ValidateEmail')) {
  91. function ValidateEmail($Value, $Field = '') {
  92. $Result = PHPMailer::ValidateAddress($Value);
  93. $Result = (bool)$Result;
  94. return $Result;
  95. }
  96. }
  97. if (!function_exists('ValidateWebAddress')) {
  98. function ValidateWebAddress($Value, $Field = '') {
  99. if ($Value == '')
  100. return TRUE; // Required picks up this error
  101. return filter_var($Value, FILTER_VALIDATE_URL, FILTER_FLAG_SCHEME_REQUIRED) !== FALSE;
  102. }
  103. }
  104. if (!function_exists('ValidateUsernameRegex')) {
  105. function ValidateUsernameRegex() {
  106. static $ValidateUsernameRegex;
  107. if (is_null($ValidateUsernameRegex)) {
  108. $ValidateUsernameRegex = sprintf("[%s]%s",
  109. C("Garden.User.ValidationRegex","\d\w_"),
  110. C("Garden.User.ValidationLength","{3,20}"));
  111. }
  112. return $ValidateUsernameRegex;
  113. }
  114. }
  115. if (!function_exists('ValidateUsername')) {
  116. function ValidateUsername($Value, $Field = '') {
  117. $ValidateUsernameRegex = ValidateUsernameRegex();
  118. return ValidateRegex(
  119. $Value,
  120. "/^({$ValidateUsernameRegex})?$/siu"
  121. );
  122. }
  123. }
  124. if (!function_exists('ValidateUrlString')) {
  125. function ValidateUrlString($Value, $Field = '') {
  126. return ValidateRegex(
  127. $Value,
  128. '/^([\d\w_\-]+)?$/si'
  129. );
  130. }
  131. }
  132. if (!function_exists('ValidateUrlStringRelaxed')) {
  133. function ValidateUrlStringRelaxed($Value, $Field = '') {
  134. if (preg_match('`[/\\\<>\'"]`', $Value))
  135. return FALSE;
  136. return TRUE;
  137. }
  138. }
  139. if (!function_exists('ValidateDate')) {
  140. function ValidateDate($Value) {
  141. // Dates should be in YYYY-MM-DD or YYYY-MM-DD HH:MM:SS format
  142. if (empty($Value)) {
  143. return TRUE; // blank dates validated through required.
  144. } else {
  145. $Matches = array();
  146. if(preg_match('/^(\d{4})-(\d{2})-(\d{2})(?:\s{1}(\d{2}):(\d{2})(?::(\d{2}))?)?$/', $Value, $Matches)) {
  147. $Year = $Matches[1];
  148. $Month = $Matches[2];
  149. $Day = $Matches[3];
  150. $Hour = ArrayValue(4, $Matches, 0);
  151. $Minutes = ArrayValue(5, $Matches, 0);
  152. $Seconds = ArrayValue(6, $Matches, 0);
  153. return checkdate($Month, $Day, $Year) && $Hour < 24 && $Minutes < 61 && $Seconds < 61;
  154. }
  155. }
  156. return FALSE;
  157. }
  158. }
  159. if (!function_exists('ValidateMinimumAge')) {
  160. function ValidateMinimumAge($Value, $Field, $FormPostedValues) {
  161. $MinimumAge = C('Garden.Validate.MinimumAge', 13);
  162. // Dates should be in YYYY-MM-DD format
  163. if (preg_match("/^[\d]{4}-{1}[\d]{2}-{1}[\d]{2}$/", $Value) == 1) {
  164. $Year = intval(substr($Value, 0, 4));
  165. $Month = intval(substr($Value, 5, 2));
  166. $Day = intval(substr($Value, 8));
  167. $CurrentDay = date('j');
  168. $CurrentMonth = date('n');
  169. $CurrentYear = date('Y');
  170. // The minimum age for joining is 13 years before now.
  171. if ($Year + $MinimumAge < $CurrentYear
  172. || ($Year + $MinimumAge == $CurrentYear && $Month < $CurrentMonth)
  173. || ($Year + $MinimumAge == $CurrentYear && $Month == $CurrentMonth && $Day <= $CurrentDay))
  174. return TRUE;
  175. }
  176. return T('ValidateMinimumAge', 'You must be at least ' . $MinimumAge . ' years old to proceed.');
  177. }
  178. }
  179. if (!function_exists('ValidateInteger')) {
  180. function ValidateInteger($Value, $Field = NULL) {
  181. if (!$Value || (is_string($Value) && !trim($Value)))
  182. return TRUE;
  183. $Integer = intval($Value);
  184. $String = strval($Integer);
  185. return $String == $Value ? TRUE : FALSE;
  186. }
  187. }
  188. if (!function_exists('ValidateBoolean')) {
  189. function ValidateBoolean($Value, $Field) {
  190. $String = strval($Value);
  191. return in_array($String, array('1', '0', 'TRUE', 'FALSE', '')) ? TRUE : FALSE;
  192. }
  193. }
  194. if (!function_exists('ValidateDecimal')) {
  195. function ValidateDecimal($Value, $Field) {
  196. if (is_object($Field) && $Field->AllowNull && $Value === NULL) return TRUE;
  197. return is_numeric($Value);
  198. }
  199. }
  200. if (!function_exists('ValidateTime')) {
  201. function ValidateTime($Value, $Field) {
  202. // TODO: VALIDATE AS HH:MM:SS OR HH:MM
  203. return FALSE;
  204. }
  205. }
  206. if (!function_exists('ValidateTimestamp')) {
  207. function ValidateTimestamp($Value, $Field) {
  208. // TODO: VALIDATE A TIMESTAMP
  209. return FALSE;
  210. }
  211. }
  212. if (!function_exists('ValidateLength')) {
  213. function ValidateLength($Value, $Field) {
  214. if (function_exists('mb_strlen'))
  215. $Diff = mb_strlen($Value, 'UTF-8') - $Field->Length;
  216. else
  217. $Diff = strlen($Value) - $Field->Length;
  218. if ($Diff <= 0) {
  219. return TRUE;
  220. } else {
  221. return sprintf(T('ValidateLength'), T($Field->Name), $Diff);
  222. }
  223. }
  224. }
  225. if (!function_exists('ValidateEnum')) {
  226. function ValidateEnum($Value, $Field) {
  227. return in_array($Value, $Field->Enum);
  228. }
  229. }
  230. if (!function_exists('ValidateOneOrMoreArrayItemRequired')) {
  231. function ValidateOneOrMoreArrayItemRequired($Value, $Field) {
  232. return is_array($Value) === TRUE && count($Value) > 0 ? TRUE : FALSE;
  233. }
  234. }
  235. if (!function_exists('ValidatePermissionFormat')) {
  236. function ValidatePermissionFormat($Permission) {
  237. // Make sure there are at least three "parts" to each permission.
  238. if (is_array($Permission) === FALSE)
  239. $Permission = explode(',', $Permission);
  240. $PermissionCount = count($Permission);
  241. for ($i = 0; $i < $PermissionCount; ++$i) {
  242. if (count(explode('.', $Permission[$i])) < 3)
  243. return sprintf(T('The following permission did not meet the permission naming requirements and could not be added: %s'), $Permission[$i]);
  244. }
  245. return TRUE;
  246. }
  247. }
  248. if (!function_exists('ValidateMatch')) {
  249. /**
  250. * Takes the FieldName being validated, appends "Match" to it, and searches
  251. * $PostedFields for the Match fieldname, compares their values, and returns
  252. * true if they match.
  253. */
  254. function ValidateMatch($Value, $Field, $PostedFields) {
  255. $MatchValue = ArrayValue($Field->Name.'Match', $PostedFields);
  256. return $Value == $MatchValue ? TRUE : FALSE;
  257. }
  258. }
  259. if (!function_exists('ValidateVersion')) {
  260. function ValidateVersion($Value) {
  261. if (empty($Value))
  262. return TRUE;
  263. if (preg_match('`(?:\d+\.)*\d+\s*([a-z]*)\d*`i', $Value, $Matches)) {
  264. // Get the version word out of the matches and validate it.
  265. $Word = $Matches[1];
  266. if (!in_array(trim($Word), array('', 'dev', 'alpha', 'a', 'beta', 'b', 'RC', 'rc', '#', 'pl', 'p')))
  267. return FALSE;
  268. return TRUE;
  269. }
  270. return FALSE;
  271. }
  272. }
  273. /**
  274. * Validate phone number against North American Numbering Plan.
  275. * @link http://blog.stevenlevithan.com/archives/validate-phone-number
  276. */
  277. if (!function_exists('ValidatePhoneNA')) {
  278. function ValidatePhoneNA($Value, $Field = '') {
  279. if ($Value == '')
  280. return true; // Do not require by default.
  281. $Valid = ValidateRegex($Value, '/^(?:\+?1[-. ]?)?\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/');
  282. return ($Valid) ? $Valid : T('ValidatePhone', 'Phone number is invalid.');
  283. }
  284. }
  285. /**
  286. * Loose validation for international phone number (but must start with a plus sign).
  287. */
  288. if (!function_exists('ValidatePhoneInt')) {
  289. function ValidatePhoneInt($Value, $Field = '') {
  290. if ($Value == '')
  291. return true; // Do not require by default.
  292. $Valid = ValidateRegex($Value, '/^\+(?:[0-9] ?){6,14}[0-9]$/');
  293. return ($Valid) ? $Valid : T('ValidatePhone', 'Phone number is invalid.');
  294. }
  295. }
  296. /**
  297. * Validate US zip code (5-digit or 9-digit with hyphen).
  298. */
  299. if (!function_exists('ValidateZipCode')) {
  300. function ValidateZipCode($Value, $Field = '') {
  301. if ($Value == '')
  302. return true; // Do not require by default.
  303. $Valid = ValidateRegex($Value, '/^([0-9]{5})(-[0-9]{4})?$/');
  304. return ($Valid) ? $Valid : T('ValidateZipCode', 'Zip code is invalid.');
  305. }
  306. }