Request.php 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808
  1. <?php
  2. namespace RequestResponse;
  3. use RequestResponse\Response as Response;
  4. class Request{
  5. function required_param($parname, $type) {
  6. if (func_num_args() != 2 or empty($parname) or empty($type)) {
  7. throw new \Exception('required_param() requires $parname and $type to be specified (parameter: '.$parname.')');
  8. }
  9. // POST has precedence.
  10. if (isset($_POST[$parname])) {
  11. $param = $_POST[$parname];
  12. } else if (isset($_GET[$parname])) {
  13. $param = $_GET[$parname];
  14. } else {
  15. throw new \Exception('');
  16. }
  17. if (is_array($param)) {
  18. return required_param_array($parname, $type);
  19. }
  20. return self::clean_param($param, $type);
  21. }
  22. function required_param_array($parname, $type) {
  23. if (func_num_args() != 2 or empty($parname) or empty($type)) {
  24. throw new \Exception('required_param_array() requires $parname and $type to be specified (parameter: '.$parname.')');
  25. }
  26. // POST has precedence.
  27. if (isset($_POST[$parname])) {
  28. $param = $_POST[$parname];
  29. } else if (isset($_GET[$parname])) {
  30. $param = $_GET[$parname];
  31. } else {
  32. throw new \Exception('');
  33. }
  34. if (!is_array($param)) {
  35. throw new \Exception('');
  36. }
  37. $result = array();
  38. foreach ($param as $key => $value) {
  39. if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
  40. continue;
  41. }
  42. $result[$key] = clean_param($value, $type);
  43. }
  44. return $result;
  45. }
  46. public static function optional_param($parname, $default = '', $type){
  47. if (func_num_args() != 3 or empty($parname) or empty($type)) {
  48. throw new \Exception('optional_param requires $parname, $default + $type to be specified (parameter: '.$parname.')');
  49. }
  50. if (isset($_POST[$parname])) {
  51. $param = $_POST[$parname];
  52. } else if (isset($_GET[$parname])) {
  53. $param = $_GET[$parname];
  54. } else {
  55. return $default;
  56. }
  57. if (is_array($param)) {
  58. return optional_param_array($parname, $default, $type);
  59. }
  60. return self::clean_param($param, $type);
  61. }
  62. public static function optional_param_array($parname, $default = Array(), $type) {
  63. if (func_num_args() != 3 or empty($parname) or empty($type)) {
  64. throw new \Exception('optional_param_array requires $parname, $default + $type to be specified (parameter: '.$parname.')');
  65. }
  66. // POST has precedence.
  67. if (isset($_POST[$parname])) {
  68. $param = $_POST[$parname];
  69. } else if (isset($_GET[$parname])) {
  70. $param = $_GET[$parname];
  71. } else {
  72. return $default;
  73. }
  74. if (!is_array($param)) {
  75. return $default;
  76. }
  77. $result = array();
  78. foreach ($param as $key => $value) {
  79. if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
  80. continue;
  81. }
  82. }
  83. return $result;
  84. }
  85. /**
  86. * Used by {@link optional_param()} and {@link required_param()} to
  87. * clean the variables and/or cast to specific types, based on
  88. * an options field.
  89. * <code>
  90. * $course->format = clean_param($course->format, PARAM_ALPHA);
  91. * $selectedgradeitem = clean_param($selectedgradeitem, PARAM_INT);
  92. * </code>
  93. *
  94. * @param mixed $param the variable we are cleaning
  95. * @param string $type expected format of param after cleaning.
  96. * @return mixed
  97. * @throws coding_exception
  98. */
  99. public static function clean_param($param, $type) {
  100. global $CFG;
  101. if (is_array($param)) {
  102. throw new coding_exception('clean_param() can not process arrays, please use clean_param_array() instead.');
  103. } else if (is_object($param)) {
  104. if (method_exists($param, '__toString')) {
  105. $param = $param->__toString();
  106. } else {
  107. throw new coding_exception('clean_param() can not process objects, please use clean_param_array() instead.');
  108. }
  109. }
  110. switch ($type) {
  111. case PARAM_RAW:
  112. // No cleaning at all.
  113. $param = fix_utf8($param);
  114. return $param;
  115. case PARAM_RAW_TRIMMED:
  116. // No cleaning, but strip leading and trailing whitespace.
  117. $param = fix_utf8($param);
  118. return trim($param);
  119. case PARAM_INT:
  120. // Convert to integer.
  121. return (int)$param;
  122. case PARAM_FLOAT:
  123. // Convert to float.
  124. return (float)$param;
  125. case PARAM_ALPHA:
  126. // Remove everything not `a-z`.
  127. return preg_replace('/[^a-zA-Z]/i', '', $param);
  128. case PARAM_ALPHAEXT:
  129. // Remove everything not `a-zA-Z_-` (originally allowed "/" too).
  130. return preg_replace('/[^a-zA-Z_-]/i', '', $param);
  131. case PARAM_ALPHANUM:
  132. // Remove everything not `a-zA-Z0-9`.
  133. return preg_replace('/[^A-Za-z0-9]/i', '', $param);
  134. case PARAM_ALPHANUMEXT:
  135. // Remove everything not `a-zA-Z0-9_-`.
  136. return preg_replace('/[^A-Za-z0-9_-]/i', '', $param);
  137. case PARAM_SEQUENCE:
  138. // Remove everything not `0-9,`.
  139. return preg_replace('/[^0-9,]/i', '', $param);
  140. case PARAM_BOOL:
  141. // Convert to 1 or 0.
  142. $tempstr = strtolower($param);
  143. if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
  144. $param = 1;
  145. } else if ($tempstr === 'off' or $tempstr === 'no' or $tempstr === 'false') {
  146. $param = 0;
  147. } else {
  148. $param = empty($param) ? 0 : 1;
  149. }
  150. return $param;
  151. case PARAM_NOTAGS:
  152. // Strip all tags.
  153. $param = fix_utf8($param);
  154. return strip_tags($param);
  155. case PARAM_TEXT:
  156. // Leave only tags needed for multilang.
  157. $param = fix_utf8($param);
  158. // If the multilang syntax is not correct we strip all tags because it would break xhtml strict which is required
  159. // for accessibility standards please note this cleaning does not strip unbalanced '>' for BC compatibility reasons.
  160. do {
  161. if (strpos($param, '</lang>') !== false) {
  162. // Old and future mutilang syntax.
  163. $param = strip_tags($param, '<lang>');
  164. if (!preg_match_all('/<.*>/suU', $param, $matches)) {
  165. break;
  166. }
  167. $open = false;
  168. foreach ($matches[0] as $match) {
  169. if ($match === '</lang>') {
  170. if ($open) {
  171. $open = false;
  172. continue;
  173. } else {
  174. break 2;
  175. }
  176. }
  177. if (!preg_match('/^<lang lang="[a-zA-Z0-9_-]+"\s*>$/u', $match)) {
  178. break 2;
  179. } else {
  180. $open = true;
  181. }
  182. }
  183. if ($open) {
  184. break;
  185. }
  186. return $param;
  187. } else if (strpos($param, '</span>') !== false) {
  188. // Current problematic multilang syntax.
  189. $param = strip_tags($param, '<span>');
  190. if (!preg_match_all('/<.*>/suU', $param, $matches)) {
  191. break;
  192. }
  193. $open = false;
  194. foreach ($matches[0] as $match) {
  195. if ($match === '</span>') {
  196. if ($open) {
  197. $open = false;
  198. continue;
  199. } else {
  200. break 2;
  201. }
  202. }
  203. if (!preg_match('/^<span(\s+lang="[a-zA-Z0-9_-]+"|\s+class="multilang"){2}\s*>$/u', $match)) {
  204. break 2;
  205. } else {
  206. $open = true;
  207. }
  208. }
  209. if ($open) {
  210. break;
  211. }
  212. return $param;
  213. }
  214. } while (false);
  215. // Easy, just strip all tags, if we ever want to fix orphaned '&' we have to do that in format_string().
  216. return strip_tags($param);
  217. case PARAM_COMPONENT:
  218. // We do not want any guessing here, either the name is correct or not
  219. // please note only normalised component names are accepted.
  220. if (!preg_match('/^[a-z]+(_[a-z][a-z0-9_]*)?[a-z0-9]+$/', $param)) {
  221. return '';
  222. }
  223. if (strpos($param, '__') !== false) {
  224. return '';
  225. }
  226. if (strpos($param, 'mod_') === 0) {
  227. // Module names must not contain underscores because we need to differentiate them from invalid plugin types.
  228. if (substr_count($param, '_') != 1) {
  229. return '';
  230. }
  231. }
  232. return $param;
  233. case PARAM_SAFEDIR:
  234. // Remove everything not a-zA-Z0-9_- .
  235. return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
  236. case PARAM_SAFEPATH:
  237. // Remove everything not a-zA-Z0-9/_- .
  238. return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);
  239. case PARAM_FILE:
  240. // Strip all suspicious characters from filename.
  241. $param = fix_utf8($param);
  242. $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
  243. if ($param === '.' || $param === '..') {
  244. $param = '';
  245. }
  246. return $param;
  247. case PARAM_PATH:
  248. // Strip all suspicious characters from file path.
  249. $param = fix_utf8($param);
  250. $param = str_replace('\\', '/', $param);
  251. // Explode the path and clean each element using the PARAM_FILE rules.
  252. $breadcrumb = explode('/', $param);
  253. foreach ($breadcrumb as $key => $crumb) {
  254. if ($crumb === '.' && $key === 0) {
  255. // Special condition to allow for relative current path such as ./currentdirfile.txt.
  256. } else {
  257. $crumb = clean_param($crumb, PARAM_FILE);
  258. }
  259. $breadcrumb[$key] = $crumb;
  260. }
  261. $param = implode('/', $breadcrumb);
  262. // Remove multiple current path (./././) and multiple slashes (///).
  263. $param = preg_replace('~//+~', '/', $param);
  264. $param = preg_replace('~/(\./)+~', '/', $param);
  265. return $param;
  266. case PARAM_HOST:
  267. // Allow FQDN or IPv4 dotted quad.
  268. $param = preg_replace('/[^\.\d\w-]/', '', $param );
  269. // Match ipv4 dotted quad.
  270. if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/', $param, $match)) {
  271. // Confirm values are ok.
  272. if ( $match[0] > 255
  273. || $match[1] > 255
  274. || $match[3] > 255
  275. || $match[4] > 255 ) {
  276. // Hmmm, what kind of dotted quad is this?
  277. $param = '';
  278. }
  279. } else if ( preg_match('/^[\w\d\.-]+$/', $param) // Dots, hyphens, numbers.
  280. && !preg_match('/^[\.-]/', $param) // No leading dots/hyphens.
  281. && !preg_match('/[\.-]$/', $param) // No trailing dots/hyphens.
  282. ) {
  283. // All is ok - $param is respected.
  284. } else {
  285. // All is not ok...
  286. $param='';
  287. }
  288. return $param;
  289. case PARAM_URL: // Allow safe ftp, http, mailto urls.
  290. $param = fix_utf8($param);
  291. if (!empty($param) && self::validateUrlSyntax($param, 's?H?S?F?E?u-P-a?I?p?f?q?r?')) {
  292. // All is ok, param is respected.
  293. } else {
  294. // Not really ok.
  295. $param ='';
  296. }
  297. return $param;
  298. case PARAM_PEM:
  299. $param = trim($param);
  300. // PEM formatted strings may contain letters/numbers and the symbols:
  301. // forward slash: /
  302. // plus sign: +
  303. // equal sign: =
  304. // , surrounded by BEGIN and END CERTIFICATE prefix and suffixes.
  305. if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
  306. list($wholething, $body) = $matches;
  307. unset($wholething, $matches);
  308. $b64 = clean_param($body, PARAM_BASE64);
  309. if (!empty($b64)) {
  310. return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
  311. } else {
  312. return '';
  313. }
  314. }
  315. return '';
  316. case PARAM_BASE64:
  317. if (!empty($param)) {
  318. // PEM formatted strings may contain letters/numbers and the symbols
  319. // forward slash: /
  320. // plus sign: +
  321. // equal sign: =.
  322. if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
  323. return '';
  324. }
  325. $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
  326. // Each line of base64 encoded data must be 64 characters in length, except for the last line which may be less
  327. // than (or equal to) 64 characters long.
  328. for ($i=0, $j=count($lines); $i < $j; $i++) {
  329. if ($i + 1 == $j) {
  330. if (64 < strlen($lines[$i])) {
  331. return '';
  332. }
  333. continue;
  334. }
  335. if (64 != strlen($lines[$i])) {
  336. return '';
  337. }
  338. }
  339. return implode("\n", $lines);
  340. } else {
  341. return '';
  342. }
  343. case PARAM_TAGLIST:
  344. $param = fix_utf8($param);
  345. $tags = explode(',', $param);
  346. $result = array();
  347. foreach ($tags as $tag) {
  348. $res = clean_param($tag, PARAM_TAG);
  349. if ($res !== '') {
  350. $result[] = $res;
  351. }
  352. }
  353. if ($result) {
  354. return implode(',', $result);
  355. } else {
  356. return '';
  357. }
  358. case PARAM_USERNAME:
  359. $param = fix_utf8($param);
  360. $param = trim($param);
  361. // Convert uppercase to lowercase MDL-16919.
  362. $param = core_text::strtolower($param);
  363. if (empty($CFG->extendedusernamechars)) {
  364. $param = str_replace(" " , "", $param);
  365. // Regular expression, eliminate all chars EXCEPT:
  366. // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
  367. $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
  368. }
  369. return $param;
  370. case PARAM_EMAIL:
  371. $param = fix_utf8($param);
  372. if (validate_email($param)) {
  373. return $param;
  374. } else {
  375. return '';
  376. }
  377. case PARAM_STRINGID:
  378. if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
  379. return $param;
  380. } else {
  381. return '';
  382. }
  383. case PARAM_TIMEZONE:
  384. // Can be int, float(with .5 or .0) or string seperated by '/' and can have '-_'.
  385. $param = fix_utf8($param);
  386. $timezonepattern = '/^(([+-]?(0?[0-9](\.[5|0])?|1[0-3](\.0)?|1[0-2]\.5))|(99)|[[:alnum:]]+(\/?[[:alpha:]_-])+)$/';
  387. if (preg_match($timezonepattern, $param)) {
  388. return $param;
  389. } else {
  390. return '';
  391. }
  392. default:
  393. // Doh! throw error, switched parameters in optional_param or another serious problem.
  394. print_error("unknownparamtype", '', '', $type);
  395. }
  396. }
  397. function fix_utf8($value) {
  398. if (is_null($value) or $value === '') {
  399. return $value;
  400. } else if (is_string($value)) {
  401. if ((string)(int)$value === $value) {
  402. // Shortcut.
  403. return $value;
  404. }
  405. // No null bytes expected in our data, so let's remove it.
  406. $value = str_replace("\0", '', $value);
  407. // Note: this duplicates min_fix_utf8() intentionally.
  408. static $buggyiconv = null;
  409. if ($buggyiconv === null) {
  410. $buggyiconv = (!function_exists('iconv') or @iconv('UTF-8', 'UTF-8//IGNORE', '100'.chr(130).'€') !== '100€');
  411. }
  412. if ($buggyiconv) {
  413. if (function_exists('mb_convert_encoding')) {
  414. $subst = mb_substitute_character();
  415. mb_substitute_character('');
  416. $result = mb_convert_encoding($value, 'utf-8', 'utf-8');
  417. mb_substitute_character($subst);
  418. } else {
  419. // Warn admins on admin/index.php page.
  420. $result = $value;
  421. }
  422. } else {
  423. $result = @iconv('UTF-8', 'UTF-8//IGNORE', $value);
  424. }
  425. return $result;
  426. } else if (is_array($value)) {
  427. foreach ($value as $k => $v) {
  428. $value[$k] = fix_utf8($v);
  429. }
  430. return $value;
  431. } else if (is_object($value)) {
  432. // Do not modify original.
  433. $value = clone($value);
  434. foreach ($value as $k => $v) {
  435. $value->$k = fix_utf8($v);
  436. }
  437. return $value;
  438. } else {
  439. // This is some other type, no utf-8 here.
  440. return $value;
  441. }
  442. }
  443. /**
  444. * Validations
  445. * @param $urladdr
  446. * @param string $options
  447. * @return bool
  448. */
  449. function validateUrlSyntax( $urladdr, $options="" ){
  450. // Force Options parameter to be lower case
  451. // DISABLED PERMAMENTLY - OK to remove from code
  452. // $options = strtolower($options);
  453. // Check Options Parameter
  454. if (!preg_match( '/^([sHSEFuPaIpfqr][+?-])*$/', $options ))
  455. {
  456. trigger_error("Options attribute malformed", E_USER_ERROR);
  457. }
  458. // Set Options Array, set defaults if options are not specified
  459. // Scheme
  460. if (strpos( $options, 's') === false) $aOptions['s'] = '?';
  461. else $aOptions['s'] = substr( $options, strpos( $options, 's') + 1, 1);
  462. // http://
  463. if (strpos( $options, 'H') === false) $aOptions['H'] = '?';
  464. else $aOptions['H'] = substr( $options, strpos( $options, 'H') + 1, 1);
  465. // https:// (SSL)
  466. if (strpos( $options, 'S') === false) $aOptions['S'] = '?';
  467. else $aOptions['S'] = substr( $options, strpos( $options, 'S') + 1, 1);
  468. // mailto: (email)
  469. if (strpos( $options, 'E') === false) $aOptions['E'] = '-';
  470. else $aOptions['E'] = substr( $options, strpos( $options, 'E') + 1, 1);
  471. // ftp://
  472. if (strpos( $options, 'F') === false) $aOptions['F'] = '-';
  473. else $aOptions['F'] = substr( $options, strpos( $options, 'F') + 1, 1);
  474. // User section
  475. if (strpos( $options, 'u') === false) $aOptions['u'] = '?';
  476. else $aOptions['u'] = substr( $options, strpos( $options, 'u') + 1, 1);
  477. // Password in user section
  478. if (strpos( $options, 'P') === false) $aOptions['P'] = '?';
  479. else $aOptions['P'] = substr( $options, strpos( $options, 'P') + 1, 1);
  480. // Address Section
  481. if (strpos( $options, 'a') === false) $aOptions['a'] = '+';
  482. else $aOptions['a'] = substr( $options, strpos( $options, 'a') + 1, 1);
  483. // IP Address in address section
  484. if (strpos( $options, 'I') === false) $aOptions['I'] = '?';
  485. else $aOptions['I'] = substr( $options, strpos( $options, 'I') + 1, 1);
  486. // Port number
  487. if (strpos( $options, 'p') === false) $aOptions['p'] = '?';
  488. else $aOptions['p'] = substr( $options, strpos( $options, 'p') + 1, 1);
  489. // File Path
  490. if (strpos( $options, 'f') === false) $aOptions['f'] = '?';
  491. else $aOptions['f'] = substr( $options, strpos( $options, 'f') + 1, 1);
  492. // Query Section
  493. if (strpos( $options, 'q') === false) $aOptions['q'] = '?';
  494. else $aOptions['q'] = substr( $options, strpos( $options, 'q') + 1, 1);
  495. // Fragment (Anchor)
  496. if (strpos( $options, 'r') === false) $aOptions['r'] = '?';
  497. else $aOptions['r'] = substr( $options, strpos( $options, 'r') + 1, 1);
  498. // Loop through options array, to search for and replace "-" to "{0}" and "+" to ""
  499. foreach($aOptions as $key => $value)
  500. {
  501. if ($value == '-')
  502. {
  503. $aOptions[$key] = '{0}';
  504. }
  505. if ($value == '+')
  506. {
  507. $aOptions[$key] = '';
  508. }
  509. }
  510. // DEBUGGING - Unescape following line to display to screen current option values
  511. // echo '<pre>'; print_r($aOptions); echo '</pre>';
  512. // Preset Allowed Characters
  513. $alphanum = '[a-zA-Z0-9]'; // Alpha Numeric
  514. $unreserved = '[a-zA-Z0-9_.!~*' . '\'' . '()-]';
  515. $escaped = '(%[0-9a-fA-F]{2})'; // Escape sequence - In Hex - %6d would be a 'm'
  516. $reserved = '[;/?:@&=+$,]'; // Special characters in the URI
  517. // Beginning Regular Expression
  518. // Scheme - Allows for 'http://', 'https://', 'mailto:', or 'ftp://'
  519. $scheme = '(';
  520. if ($aOptions['H'] === '') { $scheme .= 'http://'; }
  521. elseif ($aOptions['S'] === '') { $scheme .= 'https://'; }
  522. elseif ($aOptions['E'] === '') { $scheme .= 'mailto:'; }
  523. elseif ($aOptions['F'] === '') { $scheme .= 'ftp://'; }
  524. else
  525. {
  526. if ($aOptions['H'] === '?') { $scheme .= '|(http://)'; }
  527. if ($aOptions['S'] === '?') { $scheme .= '|(https://)'; }
  528. if ($aOptions['E'] === '?') { $scheme .= '|(mailto:)'; }
  529. if ($aOptions['F'] === '?') { $scheme .= '|(ftp://)'; }
  530. $scheme = str_replace('(|', '(', $scheme); // fix first pipe
  531. }
  532. $scheme .= ')' . $aOptions['s'];
  533. // End setting scheme
  534. // User Info - Allows for 'username@' or 'username:password@'. Note: contrary to rfc, I removed ':' from username section, allowing it only in password.
  535. // /---------------- Username -----------------------\ /-------------------------------- Password ------------------------------\
  536. $userinfo = '((' . $unreserved . '|' . $escaped . '|[;&=+$,]' . ')+(:(' . $unreserved . '|' . $escaped . '|[;:&=+$,]' . ')+)' . $aOptions['P'] . '@)' . $aOptions['u'];
  537. // IP ADDRESS - Allows 0.0.0.0 to 255.255.255.255
  538. $ipaddress = '((((2(([0-4][0-9])|(5[0-5])))|([01]?[0-9]?[0-9]))\.){3}((2(([0-4][0-9])|(5[0-5])))|([01]?[0-9]?[0-9])))';
  539. // Tertiary Domain(s) - Optional - Multi - Although some sites may use other characters, the RFC says tertiary domains have the same naming restrictions as second level domains
  540. $domain_tertiary = '(' . $alphanum . '(([a-zA-Z0-9-]{0,62})' . $alphanum . ')?\.)*';
  541. /* MDL-9295 - take out domain_secondary here and below, so that URLs like http://localhost/ and lan addresses like http://host/ are accepted.
  542. // Second Level Domain - Required - First and last characters must be Alpha-numeric. Hyphens are allowed inside.
  543. $domain_secondary = '(' . $alphanum . '(([a-zA-Z0-9-]{0,62})' . $alphanum . ')?\.)';
  544. */
  545. // we want more relaxed URLs in Moodle: MDL-11462
  546. // Top Level Domain - First character must be Alpha. Last character must be AlphaNumeric. Hyphens are allowed inside.
  547. $domain_toplevel = '([a-zA-Z](([a-zA-Z0-9-]*)[a-zA-Z0-9])?)';
  548. /* // Top Level Domain - Required - Domain List Current As Of December 2004. Use above escaped line to be forgiving of possible future TLD's
  549. $domain_toplevel = '(aero|biz|com|coop|edu|gov|info|int|jobs|mil|mobi|museum|name|net|org|post|pro|travel|ac|ad|ae|af|ag|ai|al|am|an|ao|aq|ar|as|at|au|aw|az|ax|ba|bb|bd|be|bf|bg|bh|bi|bj|bm|bn|bo|br|bs|bt|bv|bw|by|bz|ca|cc|cd|cf|cg|ch|ci|ck|cl|cm|cn|co|cr|cs|cu|cv|cx|cy|cz|de|dj|dk|dm|do|dz|ec|ee|eg|eh|er|es|et|eu|fi|fj|fk|fm|fo|fr|ga|gb|gd|ge|gf|gg|gh|gi|gl|gm|gn|gp|gq|gr|gs|gt|gu|gw|gy|hk|hm|hn|hr|ht|hu|id|ie|il|im|in|io|iq|ir|is|it|je|jm|jo|jp|ke|kg|kh|ki|km|kn|kp|kr|kw|ky|kz|la|lb|lc|li|lk|lr|ls|lt|lu|lv|ly|ma|mc|md|mg|mh|mk|ml|mm|mn|mo|mp|mq|mr|ms|mt|mu|mv|mw|mx|my|mz|na|nc|ne|nf|ng|ni|nl|no|np|nr|nu|nz|om|pa|pe|pf|pg|ph|pk|pl|pm|pn|pr|ps|pt|pw|py|qa|re|ro|ru|rw|sa|sb|sc|sd|se|sg|sh|si|sj|sk|sl|sm|sn|so|sr|st|sv|sy|sz|tc|td|tf|tg|th|tj|tk|tl|tm|tn|to|tp|tr|tt|tv|tw|tz|ua|ug|uk|um|us|uy|uz|va|vc|ve|vg|vi|vn|vu|wf|ws|ye|yt|yu|za|zm|zw)';
  550. */
  551. // Address can be IP address or Domain
  552. if ($aOptions['I'] === '{0}') { // IP Address Not Allowed
  553. $address = '(' . $domain_tertiary . /* MDL-9295 $domain_secondary . */ $domain_toplevel . ')';
  554. } elseif ($aOptions['I'] === '') { // IP Address Required
  555. $address = '(' . $ipaddress . ')';
  556. } else { // IP Address Optional
  557. $address = '((' . $ipaddress . ')|(' . $domain_tertiary . /* MDL-9295 $domain_secondary . */ $domain_toplevel . '))';
  558. }
  559. $address = $address . $aOptions['a'];
  560. // Port Number - :80 or :8080 or :65534 Allows range of :0 to :65535
  561. // (0-59999) |(60000-64999) |(65000-65499) |(65500-65529) |(65530-65535)
  562. $port_number = '(:(([0-5]?[0-9]{1,4})|(6[0-4][0-9]{3})|(65[0-4][0-9]{2})|(655[0-2][0-9])|(6553[0-5])))' . $aOptions['p'];
  563. // Path - Can be as simple as '/' or have multiple folders and filenames
  564. $path = '(/((;)?(' . $unreserved . '|' . $escaped . '|' . '[:@&=+$,]' . ')+(/)?)*)' . $aOptions['f'];
  565. // Query Section - Accepts ?var1=value1&var2=value2 or ?2393,1221 and much more
  566. $querystring = '(\?(' . $reserved . '|' . $unreserved . '|' . $escaped . ')*)' . $aOptions['q'];
  567. // Fragment Section - Accepts anchors such as #top
  568. $fragment = '(\#(' . $reserved . '|' . $unreserved . '|' . $escaped . ')*)' . $aOptions['r'];
  569. // Building Regular Expression
  570. $regexp = '#^' . $scheme . $userinfo . $address . $port_number . $path . $querystring . $fragment . '$#i';
  571. // DEBUGGING - Uncomment Line Below To Display The Regular Expression Built
  572. // echo '<pre>' . htmlentities(wordwrap($regexp,70,"\n",1)) . '</pre>';
  573. // Running the regular expression
  574. if (preg_match( $regexp, $urladdr ))
  575. {
  576. return true; // The domain passed
  577. }
  578. else
  579. {
  580. return false; // The domain didn't pass the expression
  581. }
  582. }
  583. function validateEmailSyntax( $emailaddr, $options="" ){
  584. // Check Options Parameter
  585. if (!preg_match( '/^([sHSEFuPaIpfqr][+?-])*$/', $options ))
  586. {
  587. trigger_error("Options attribute malformed", E_USER_ERROR);
  588. }
  589. // Set Options Array, set defaults if options are not specified
  590. // Scheme
  591. if (strpos( $options, 's') === false) $aOptions['s'] = '-';
  592. else $aOptions['s'] = substr( $options, strpos( $options, 's') + 1, 1);
  593. // http://
  594. if (strpos( $options, 'H') === false) $aOptions['H'] = '-';
  595. else $aOptions['H'] = substr( $options, strpos( $options, 'H') + 1, 1);
  596. // https:// (SSL)
  597. if (strpos( $options, 'S') === false) $aOptions['S'] = '-';
  598. else $aOptions['S'] = substr( $options, strpos( $options, 'S') + 1, 1);
  599. // mailto: (email)
  600. if (strpos( $options, 'E') === false) $aOptions['E'] = '?';
  601. else $aOptions['E'] = substr( $options, strpos( $options, 'E') + 1, 1);
  602. // ftp://
  603. if (strpos( $options, 'F') === false) $aOptions['F'] = '-';
  604. else $aOptions['F'] = substr( $options, strpos( $options, 'F') + 1, 1);
  605. // User section
  606. if (strpos( $options, 'u') === false) $aOptions['u'] = '+';
  607. else $aOptions['u'] = substr( $options, strpos( $options, 'u') + 1, 1);
  608. // Password in user section
  609. if (strpos( $options, 'P') === false) $aOptions['P'] = '-';
  610. else $aOptions['P'] = substr( $options, strpos( $options, 'P') + 1, 1);
  611. // Address Section
  612. if (strpos( $options, 'a') === false) $aOptions['a'] = '+';
  613. else $aOptions['a'] = substr( $options, strpos( $options, 'a') + 1, 1);
  614. // IP Address in address section
  615. if (strpos( $options, 'I') === false) $aOptions['I'] = '-';
  616. else $aOptions['I'] = substr( $options, strpos( $options, 'I') + 1, 1);
  617. // Port number
  618. if (strpos( $options, 'p') === false) $aOptions['p'] = '-';
  619. else $aOptions['p'] = substr( $options, strpos( $options, 'p') + 1, 1);
  620. // File Path
  621. if (strpos( $options, 'f') === false) $aOptions['f'] = '-';
  622. else $aOptions['f'] = substr( $options, strpos( $options, 'f') + 1, 1);
  623. // Query Section
  624. if (strpos( $options, 'q') === false) $aOptions['q'] = '-';
  625. else $aOptions['q'] = substr( $options, strpos( $options, 'q') + 1, 1);
  626. // Fragment (Anchor)
  627. if (strpos( $options, 'r') === false) $aOptions['r'] = '-';
  628. else $aOptions['r'] = substr( $options, strpos( $options, 'r') + 1, 1);
  629. // Generate options
  630. $newoptions = '';
  631. foreach($aOptions as $key => $value)
  632. {
  633. $newoptions .= $key . $value;
  634. }
  635. // DEBUGGING - Uncomment line below to display generated options
  636. // echo '<pre>' . $newoptions . '</pre>';
  637. // Send to validateUrlSyntax() and return result
  638. return validateUrlSyntax( $emailaddr, $newoptions);
  639. }
  640. function validateFtpSyntax( $ftpaddr, $options="" ){
  641. // Check Options Parameter
  642. if (!preg_match( '/^([sHSEFuPaIpfqr][+?-])*$/', $options ))
  643. {
  644. trigger_error("Options attribute malformed", E_USER_ERROR);
  645. }
  646. // Set Options Array, set defaults if options are not specified
  647. // Scheme
  648. if (strpos( $options, 's') === false) $aOptions['s'] = '?';
  649. else $aOptions['s'] = substr( $options, strpos( $options, 's') + 1, 1);
  650. // http://
  651. if (strpos( $options, 'H') === false) $aOptions['H'] = '-';
  652. else $aOptions['H'] = substr( $options, strpos( $options, 'H') + 1, 1);
  653. // https:// (SSL)
  654. if (strpos( $options, 'S') === false) $aOptions['S'] = '-';
  655. else $aOptions['S'] = substr( $options, strpos( $options, 'S') + 1, 1);
  656. // mailto: (email)
  657. if (strpos( $options, 'E') === false) $aOptions['E'] = '-';
  658. else $aOptions['E'] = substr( $options, strpos( $options, 'E') + 1, 1);
  659. // ftp://
  660. if (strpos( $options, 'F') === false) $aOptions['F'] = '+';
  661. else $aOptions['F'] = substr( $options, strpos( $options, 'F') + 1, 1);
  662. // User section
  663. if (strpos( $options, 'u') === false) $aOptions['u'] = '?';
  664. else $aOptions['u'] = substr( $options, strpos( $options, 'u') + 1, 1);
  665. // Password in user section
  666. if (strpos( $options, 'P') === false) $aOptions['P'] = '?';
  667. else $aOptions['P'] = substr( $options, strpos( $options, 'P') + 1, 1);
  668. // Address Section
  669. if (strpos( $options, 'a') === false) $aOptions['a'] = '+';
  670. else $aOptions['a'] = substr( $options, strpos( $options, 'a') + 1, 1);
  671. // IP Address in address section
  672. if (strpos( $options, 'I') === false) $aOptions['I'] = '?';
  673. else $aOptions['I'] = substr( $options, strpos( $options, 'I') + 1, 1);
  674. // Port number
  675. if (strpos( $options, 'p') === false) $aOptions['p'] = '?';
  676. else $aOptions['p'] = substr( $options, strpos( $options, 'p') + 1, 1);
  677. // File Path
  678. if (strpos( $options, 'f') === false) $aOptions['f'] = '?';
  679. else $aOptions['f'] = substr( $options, strpos( $options, 'f') + 1, 1);
  680. // Query Section
  681. if (strpos( $options, 'q') === false) $aOptions['q'] = '-';
  682. else $aOptions['q'] = substr( $options, strpos( $options, 'q') + 1, 1);
  683. // Fragment (Anchor)
  684. if (strpos( $options, 'r') === false) $aOptions['r'] = '-';
  685. else $aOptions['r'] = substr( $options, strpos( $options, 'r') + 1, 1);
  686. // Generate options
  687. $newoptions = '';
  688. foreach($aOptions as $key => $value)
  689. {
  690. $newoptions .= $key . $value;
  691. }
  692. // DEBUGGING - Uncomment line below to display generated options
  693. // echo '<pre>' . $newoptions . '</pre>';
  694. // Send to validateUrlSyntax() and return result
  695. return validateUrlSyntax( $ftpaddr, $newoptions);
  696. }
  697. }