Merge branch 'MDL-78173' of https://github.com/paulholden/moodle
[moodle.git] / lib / classes / param.php
blob359ffc37b293673d90e32ff8ca3706d3f5e1125f
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 namespace core;
19 use coding_exception;
20 use core_text;
21 use core\ip_utils;
22 use invalid_parameter_exception;
23 use moodle_exception;
25 // phpcs:disable Generic.CodeAnalysis.EmptyStatement.DetectedIf
27 /**
28 * Parameter validation helpers for Moodle.
30 * @package core
31 * @copyright 2023 Andrew Lyons <andrew@nicols.co.uk>
32 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
34 enum param: string {
35 /**
36 * PARAM_ALPHA - contains only English ascii letters [a-zA-Z].
38 case ALPHA = 'alpha';
40 /**
41 * PARAM_ALPHAEXT the same contents as PARAM_ALPHA (English ascii letters [a-zA-Z]) plus the chars in quotes: "_-" allowed
42 * NOTE: originally this allowed "/" too, please use PARAM_SAFEPATH if "/" needed
44 case ALPHAEXT = 'alphaext';
46 /**
47 * PARAM_ALPHANUM - expected numbers 0-9 and English ascii letters [a-zA-Z] only.
49 case ALPHANUM = 'alphanum';
51 /**
52 * PARAM_ALPHANUMEXT - expected numbers 0-9, letters (English ascii letters [a-zA-Z]) and _- only.
54 case ALPHANUMEXT = 'alphanumext';
56 /**
57 * PARAM_AUTH - actually checks to make sure the string is a valid auth plugin
59 case AUTH = 'auth';
61 /**
62 * PARAM_BASE64 - Base 64 encoded format
64 case BASE64 = 'base64';
66 /**
67 * PARAM_BOOL - converts input into 0 or 1, use for switches in forms and urls.
69 case BOOL = 'bool';
71 /**
72 * PARAM_CAPABILITY - A capability name, like 'moodle/role:manage'. Actually
73 * checked against the list of capabilities in the database.
75 case CAPABILITY = 'capability';
77 /**
78 * PARAM_CLEANHTML - cleans submitted HTML code. Note that you almost never want
79 * to use this. The normal mode of operation is to use PARAM_RAW when receiving
80 * the input (required/optional_param or formslib) and then sanitise the HTML
81 * using format_text on output. This is for the rare cases when you want to
82 * sanitise the HTML on input. This cleaning may also fix xhtml strictness.
84 case CLEANHTML = 'cleanhtml';
86 /**
87 * PARAM_EMAIL - an email address following the RFC
89 case EMAIL = 'email';
91 /**
92 * PARAM_FILE - safe file name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
94 case FILE = 'file';
96 /**
97 * PARAM_FLOAT - a real/floating point number.
99 * Note that you should not use PARAM_FLOAT for numbers typed in by the user.
100 * It does not work for languages that use , as a decimal separator.
101 * Use PARAM_LOCALISEDFLOAT instead.
103 case FLOAT = 'float';
106 * PARAM_LOCALISEDFLOAT - a localised real/floating point number.
107 * This is preferred over PARAM_FLOAT for numbers typed in by the user.
108 * Cleans localised numbers to computer readable numbers; false for invalid numbers.
110 case LOCALISEDFLOAT = 'localisedfloat';
113 * PARAM_HOST - expected fully qualified domain name (FQDN) or an IPv4 dotted quad (IP address)
115 case HOST = 'host';
118 * PARAM_INT - integers only, use when expecting only numbers.
120 case INT = 'int';
123 * PARAM_LANG - checks to see if the string is a valid installed language in the current site.
125 case LANG = 'lang';
128 * PARAM_LOCALURL - expected properly formatted URL as well as one that refers to the local server itself. (NOT orthogonal to the
129 * others! Implies PARAM_URL!)
131 case LOCALURL = 'localurl';
134 * PARAM_NOTAGS - all html tags are stripped from the text. Do not abuse this type.
136 case NOTAGS = 'notags';
139 * PARAM_PATH - safe relative path name, all dangerous chars are stripped, protects against XSS, SQL injections and directory
140 * traversals note: the leading slash is not removed, window drive letter is not allowed
142 case PATH = 'path';
145 * PARAM_PEM - Privacy Enhanced Mail format
147 case PEM = 'pem';
150 * PARAM_PERMISSION - A permission, one of CAP_INHERIT, CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT.
152 case PERMISSION = 'permission';
155 * PARAM_RAW specifies a parameter that is not cleaned/processed in any way except the discarding of the invalid utf-8 characters
157 case RAW = 'raw';
160 * PARAM_RAW_TRIMMED like PARAM_RAW but leading and trailing whitespace is stripped.
162 case RAW_TRIMMED = 'raw_trimmed';
165 * PARAM_SAFEDIR - safe directory name, suitable for include() and require()
167 case SAFEDIR = 'safedir';
170 * PARAM_SAFEPATH - several PARAM_SAFEDIR joined by "/", suitable for include() and require(), plugin paths
171 * and other references to Moodle code files.
173 * This is NOT intended to be used for absolute paths or any user uploaded files.
175 case SAFEPATH = 'safepath';
178 * PARAM_SEQUENCE - expects a sequence of numbers like 8 to 1,5,6,4,6,8,9. Numbers and comma only.
180 case SEQUENCE = 'sequence';
183 * PARAM_TAG - one tag (interests, blogs, etc.) - mostly international characters and space, <> not supported
185 case TAG = 'tag';
188 * PARAM_TAGLIST - list of tags separated by commas (interests, blogs, etc.)
190 case TAGLIST = 'taglist';
193 * PARAM_TEXT - general plain text compatible with multilang filter, no other html tags. Please note '<', or '>' are allowed here.
195 case TEXT = 'text';
198 * PARAM_THEME - Checks to see if the string is a valid theme name in the current site
200 case THEME = 'theme';
203 * PARAM_URL - expected properly formatted URL. Please note that domain part is required, http://localhost/ is not accepted but
204 * http://localhost.localdomain/ is ok.
206 case URL = 'url';
209 * PARAM_USERNAME - Clean username to only contains allowed characters. This is to be used ONLY when manually creating user
210 * accounts, do NOT use when syncing with external systems!!
212 case USERNAME = 'username';
215 * PARAM_STRINGID - used to check if the given string is valid string identifier for get_string()
217 case STRINGID = 'stringid';
220 * PARAM_CLEAN - obsoleted, please use a more specific type of parameter.
221 * It was one of the first types, that is why it is abused so much ;-)
222 * @deprecated since 2.0
224 #[deprecated(
225 'param::CLEAN',
226 since: '2.0',
227 reason: 'Please use a more specific type of parameter',
228 emit: false,
230 case CLEAN = 'clean';
233 * PARAM_INTEGER - deprecated alias for PARAM_INT
234 * @deprecated since 2.0
236 #[deprecated(
237 'param::INTEGER',
238 since: '2.0',
239 reason: 'Alias for INT',
240 final: true,
242 case INTEGER = 'integer';
245 * PARAM_NUMBER - deprecated alias of PARAM_FLOAT
246 * @deprecated since 2.0
248 #[deprecated(
249 'param::NUMBER',
250 since: '2.0',
251 reason: 'Alias for FLOAT',
252 final: true,
254 case NUMBER = 'number';
257 * PARAM_ACTION - deprecated alias for PARAM_ALPHANUMEXT, use for various actions in forms and urls
258 * NOTE: originally alias for PARAM_ALPHANUMEXT
259 * @deprecated since 2.0
261 #[deprecated(
262 'param::ACTION',
263 since: '2.0',
264 reason: 'Alias for PARAM_ALPHANUMEXT',
265 final: true,
267 case ACTION = 'action';
270 * PARAM_FORMAT - deprecated alias for PARAM_ALPHANUMEXT, use for names of plugins, formats, etc.
271 * NOTE: originally alias for PARAM_APLHA
272 * @deprecated since 2.0
274 #[deprecated(
275 'param::FORMAT',
276 since: '2.0',
277 reason: 'Alias for PARAM_ALPHANUMEXT',
278 final: true,
280 case FORMAT = 'format';
283 * PARAM_MULTILANG - deprecated alias of PARAM_TEXT.
284 * @deprecated since 2.0
286 #[deprecated(
287 'param::MULTILANG',
288 since: '2.0',
289 reason: 'Alias for PARAM_TEXT',
290 final: true,
292 case MULTILANG = 'multilang';
295 * PARAM_TIMEZONE - expected timezone. Timezone can be int +-(0-13) or float +-(0.5-12.5) or
296 * string separated by '/' and can have '-' &/ '_' (eg. America/North_Dakota/New_Salem
297 * America/Port-au-Prince)
299 case TIMEZONE = 'timezone';
302 * PARAM_CLEANFILE - deprecated alias of PARAM_FILE; originally was removing regional chars too
303 * @deprecated since 2.0
305 #[deprecated(
306 'param::CLEANFILE',
307 since: '2.0',
308 reason: 'Alias for PARAM_FILE',
310 case CLEANFILE = 'cleanfile';
313 * PARAM_COMPONENT is used for full component names (aka frankenstyle) such as 'mod_forum = 'core_rating', 'auth_ldap'.
314 * Short legacy subsystem names and module names are accepted too ex: 'forum = 'rating', 'user'.
315 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
316 * NOTE: numbers and underscores are strongly discouraged in plugin names!
318 case COMPONENT = 'component';
321 * PARAM_AREA is a name of area used when addressing files, comments, ratings, etc.
322 * It is usually used together with context id and component.
323 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
325 case AREA = 'area';
328 * PARAM_PLUGIN is used for plugin names such as 'forum = 'glossary', 'ldap', 'paypal', 'completionstatus'.
329 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
330 * NOTE: numbers and underscores are strongly discouraged in plugin names! Underscores are forbidden in module names.
332 case PLUGIN = 'plugin';
335 * Get the canonical enumerated parameter from the parameter type name.
337 * @param string $paramname
338 * @return param
339 * @throws coding_exception If the parameter is unknown.
341 public static function from_type(string $paramname): self {
342 $from = self::tryFrom($paramname)?->canonical();
343 if ($from) {
344 return $from;
347 throw new \coding_exception("Unknown parameter type '{$paramname}'");
351 * Canonicalise the parameter.
353 * This method is used to support aliasing of deprecated parameters.
355 * @return param
357 private function canonical(): self {
358 return match ($this) {
359 self::ACTION => self::ALPHANUMEXT,
360 self::CLEANFILE => self::FILE,
361 self::FORMAT => self::ALPHANUMEXT,
362 self::INTEGER => self::INT,
363 self::MULTILANG => self::TEXT,
364 self::NUMBER => self::FLOAT,
366 default => $this,
371 * Used by {@link optional_param()} and {@link required_param()} to
372 * clean the variables and/or cast to specific types, based on
373 * an options field.
375 * <code>
376 * $course->format = param::ALPHA->clean($course->format);
377 * $selectedgradeitem = param::INT->clean($selectedgradeitem);
378 * </code>
380 * @param mixed $value the value to clean
381 * @return mixed
382 * @throws coding_exception
384 public function clean(mixed $value): mixed {
385 // Check and emit a deprecation notice if required.
386 deprecation::emit_deprecation_if_present($this);
388 if (is_array($value)) {
389 throw new coding_exception('clean() can not process arrays, please use clean_array() instead.');
390 } else if (is_object($value)) {
391 if (method_exists($value, '__toString')) {
392 $value = $value->__toString();
393 } else {
394 throw new coding_exception('clean() can not process objects, please use clean_array() instead.');
398 $canonical = $this->canonical();
399 if ($this !== $canonical) {
400 return $canonical->clean($value);
403 $methodname = "clean_param_value_{$this->value}";
404 if (!method_exists(self::class, $methodname)) {
405 throw new coding_exception("Method not found for cleaning {$this->value}");
408 return $this->{$methodname}($value);
412 * Returns a value for the named variable, taken from request arguments.
414 * This function should be used to initialise all required values
415 * in a script that are based on parameters. Usually it will be
416 * used like this:
417 * $id = param::INT->required_param('id');
420 * @param string $paramname the name of the page parameter we want
421 * @return mixed
422 * @throws moodle_exception
424 public function required_param(string $paramname): mixed {
425 return $this->clean($this->get_request_parameter($paramname, true));
429 * Returns a particular array value for the named variable, taken from request arguments.
430 * If the parameter doesn't exist then an error is thrown because we require this variable.
432 * This function should be used to initialise all required values
433 * in a script that are based on parameters. Usually it will be
434 * used like this:
435 * $ids = required_param_array('ids', PARAM_INT);
437 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
439 * @param string $paramname the name of the page parameter we want
440 * @return array
441 * @throws moodle_exception
443 public function required_param_array(string $paramname): array {
444 $param = $this->get_request_parameter($paramname, true);
446 if (!is_array($param)) {
447 throw new \moodle_exception('missingparam', '', '', $paramname);
450 $result = [];
451 foreach ($param as $key => $value) {
452 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
453 debugging(
454 "Invalid key name in required_param_array() detected: {$key}, parameter: {$paramname}",
456 continue;
458 $result[$key] = $this->clean($value);
461 return $result;
465 * Returns a particular value for the named variable from the request arguments,
466 * otherwise returning a given default.
468 * This function should be used to initialise all optional values
469 * in a script that are based on parameters. Usually it will be
470 * used like this:
471 * $name = param::TEXT->optional_param('name', 'Fred');
473 * @param string $paramname the name of the page parameter we want
474 * @param mixed $default the default value to return if nothing is found
475 * @return mixed
477 public function optional_param(string $paramname, mixed $default): mixed {
478 $param = $this->get_request_parameter($paramname, false);
479 if ($param === null) {
480 return $default;
483 return $this->clean($param);
487 * Returns a particular array value for the named variable from the request arguments,
488 * otherwise returning a given default.
490 * This function should be used to initialise all optional values
491 * in a script that are based on parameters. Usually it will be
492 * used like this:
493 * $ids = param::INT->optional_param_arrayt('id', array());
495 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported.
497 * @param string $paramname the name of the page parameter we want
498 * @param mixed $default the default value to return if nothing is found
499 * @return array
501 public function optional_param_array(string $paramname, mixed $default): mixed {
502 $param = $this->get_request_parameter($paramname, false);
503 if ($param === null) {
504 return $default;
507 if (!is_array($param)) {
508 debugging(
509 "optional_param_array() only expects array parameters: {$paramname}",
511 return $default;
514 $result = [];
515 foreach ($param as $key => $value) {
516 if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
517 debugging(
518 "Invalid key name in optional_param_array() detected: {$key}, parameter: {$paramname}",
520 continue;
522 $result[$key] = $this->clean($value);
525 return $result;
529 * Returns a particular value for the named variable, taken from the POST, or GET params.
531 * Parameters are fetched from POST first, then GET.
533 * @param string $paramname
534 * @param bool $require
535 * @return mixed
536 * @throws moodle_exception If the parameter was not found and the value is required
538 private function get_request_parameter(
539 string $paramname,
540 bool $require,
541 ): mixed {
542 if (isset($_POST[$paramname])) {
543 return $_POST[$paramname];
544 } else if (isset($_GET[$paramname])) {
545 return $_GET[$paramname];
546 } else if ($require) {
547 throw new \moodle_exception('missingparam', '', '', $paramname);
550 return null;
554 * Strict validation of parameter values, the values are only converted
555 * to requested PHP type. Internally it is using clean_param, the values
556 * before and after cleaning must be equal - otherwise
557 * an invalid_parameter_exception is thrown.
558 * Objects and classes are not accepted.
560 * @param mixed $param
561 * @param bool $allownull are nulls valid value?
562 * @param string $debuginfo optional debug information
563 * @return mixed the $param value converted to PHP type
564 * @throws invalid_parameter_exception if $param is not of given type
566 public function validate_param(
567 mixed $param,
568 bool $allownull = NULL_NOT_ALLOWED,
569 string $debuginfo = '',
570 ): mixed {
571 if (is_null($param)) {
572 if ($allownull == NULL_ALLOWED) {
573 return null;
574 } else {
575 throw new invalid_parameter_exception($debuginfo);
578 if (is_array($param) || is_object($param)) {
579 throw new invalid_parameter_exception($debuginfo);
582 $cleaned = $this->clean($param);
584 if ($this->canonical() === self::FLOAT) {
585 // Do not detect precision loss here.
586 if (is_float($param) || is_int($param)) {
587 // These always fit.
588 } else if (!is_numeric($param) || !preg_match('/^[\+-]?[0-9]*\.?[0-9]*(e[-+]?[0-9]+)?$/i', (string)$param)) {
589 throw new invalid_parameter_exception($debuginfo);
591 } else if ((string) $param !== (string) $cleaned) {
592 // Conversion to string is usually lossless.
593 throw new invalid_parameter_exception($debuginfo);
596 return $cleaned;
600 * Makes sure array contains only the allowed types, this function does not validate array key names!
602 * <code>
603 * $options = param::INT->clean_param_array($options);
604 * </code>
606 * @param array|null $param the variable array we are cleaning
607 * @param bool $recursive clean recursive arrays
608 * @return array
609 * @throws coding_exception
611 public function clean_param_array(
612 ?array $param,
613 bool $recursive = false,
615 // Convert null to empty array.
616 $param = (array) $param;
617 foreach ($param as $key => $value) {
618 if (is_array($value)) {
619 if ($recursive) {
620 $param[$key] = $this->clean_param_array($value, true);
621 } else {
622 throw new coding_exception('clean_param_array can not process multidimensional arrays when $recursive is false.');
624 } else {
625 $param[$key] = $this->clean($value);
628 return $param;
632 * Validation for PARAM_RAW.
634 * @param mixed $param
635 * @return mixed
637 protected function clean_param_value_raw(mixed $param): mixed {
638 // No cleaning at all.
639 return fix_utf8($param);
643 * Validation for PARAM_RAW_TRIMMED.
645 * @param mixed $param
646 * @return string
648 protected function clean_param_value_raw_trimmed(mixed $param): string {
649 // No cleaning, but strip leading and trailing whitespace.
650 return trim((string) $this->clean_param_value_raw($param));
654 * Validation for PARAM_CLEAN.
656 * @param mixed $param
657 * @return string
659 protected function clean_param_value_clean(mixed $param): string {
660 // General HTML cleaning, try to use more specific type if possible this is deprecated!
661 // Please use more specific type instead.
662 if (is_numeric($param)) {
663 return $param;
665 $param = fix_utf8($param);
666 // Sweep for scripts, etc.
667 return clean_text($param);
671 * Validation for PARAM_CLEANHTML.
673 protected function clean_param_value_cleanhtml(mixed $param): mixed {
674 // Clean html fragment.
675 $param = (string)fix_utf8($param);
676 // Sweep for scripts, etc.
677 $param = clean_text($param, FORMAT_HTML);
679 return trim($param);
683 * Validation for PARAM_INT.
685 * @param mixed $param
686 * @return int
688 protected function clean_param_value_int(mixed $param): int {
689 // Convert to integer.
690 return (int)$param;
694 * Validation for PARAM_FLOAT.
696 * @param mixed $param
697 * @return float
699 protected function clean_param_value_float(mixed $param): float {
700 // Convert to float.
701 return (float)$param;
705 * Validation for PARAM_LOCALISEDFLOAT.
707 * @param mixed $param
708 * @return mixed
710 protected function clean_param_value_localisedfloat(mixed $param): mixed {
711 // Convert to float.
712 return unformat_float($param, true);
716 * Validation for PARAM_ALPHA.
718 * @param mixed $param
719 * @return mixed
721 protected function clean_param_value_alpha(mixed $param): mixed {
722 // Remove everything not `a-z`.
723 return preg_replace('/[^a-zA-Z]/i', '', (string)$param);
727 * Validation for PARAM_ALPHAEXT.
729 * @param mixed $param
730 * @return mixed
732 protected function clean_param_value_alphaext(mixed $param): mixed {
733 // Remove everything not `a-zA-Z_-` (originally allowed "/" too).
734 return preg_replace('/[^a-zA-Z_-]/i', '', (string)$param);
738 * Validation for PARAM_ALPHANUM.
740 * @param mixed $param
741 * @return mixed
743 protected function clean_param_value_alphanum(mixed $param): mixed {
744 // Remove everything not `a-zA-Z0-9`.
745 return preg_replace('/[^A-Za-z0-9]/i', '', (string)$param);
749 * Validation for PARAM_ALPHANUMEXT.
751 * @param mixed $param
752 * @return mixed
754 protected function clean_param_value_alphanumext(mixed $param): mixed {
755 // Remove everything not `a-zA-Z0-9_-`.
756 return preg_replace('/[^A-Za-z0-9_-]/i', '', (string)$param);
760 * Validation for PARAM_SEQUENCE.
762 * @param mixed $param
763 * @return mixed
765 protected function clean_param_value_sequence(mixed $param): mixed {
766 // Remove everything not `0-9,`.
767 return preg_replace('/[^0-9,]/i', '', (string)$param);
771 * Validation for PARAM_BOOL.
773 * @param mixed $param
774 * @return mixed
776 protected function clean_param_value_bool(mixed $param): mixed {
777 // Convert to 1 or 0.
778 $tempstr = strtolower((string)$param);
779 if ($tempstr === 'on' || $tempstr === 'yes' || $tempstr === 'true') {
780 $param = 1;
781 } else if ($tempstr === 'off' || $tempstr === 'no' || $tempstr === 'false') {
782 $param = 0;
783 } else {
784 $param = empty($param) ? 0 : 1;
786 return $param;
790 * Validation for PARAM_NOTAGS.
792 * @param mixed $param
793 * @return mixed
795 protected function clean_param_value_notags(mixed $param): mixed {
796 // Strip all tags.
797 $param = fix_utf8($param);
798 return strip_tags((string)$param);
802 * Validation for PARAM_TEXT.
804 * @param mixed $param
805 * @return mixed
807 protected function clean_param_value_text(mixed $param): mixed {
808 // Leave only tags needed for multilang.
809 $param = fix_utf8($param);
810 // If the multilang syntax is not correct we strip all tags because it would break xhtml strict which is required
811 // for accessibility standards please note this cleaning does not strip unbalanced '>' for BC compatibility reasons.
812 do {
813 if (strpos((string)$param, '</lang>') !== false) {
814 // Old and future mutilang syntax.
815 $param = strip_tags($param, '<lang>');
816 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
817 break;
819 $open = false;
820 foreach ($matches[0] as $match) {
821 if ($match === '</lang>') {
822 if ($open) {
823 $open = false;
824 continue;
825 } else {
826 break 2;
829 if (!preg_match('/^<lang lang="[a-zA-Z0-9_-]+"\s*>$/u', $match)) {
830 break 2;
831 } else {
832 $open = true;
835 if ($open) {
836 break;
838 return $param;
839 } else if (strpos((string)$param, '</span>') !== false) {
840 // Current problematic multilang syntax.
841 $param = strip_tags($param, '<span>');
842 if (!preg_match_all('/<.*>/suU', $param, $matches)) {
843 break;
845 $open = false;
846 foreach ($matches[0] as $match) {
847 if ($match === '</span>') {
848 if ($open) {
849 $open = false;
850 continue;
851 } else {
852 break 2;
855 if (!preg_match('/^<span(\s+lang="[a-zA-Z0-9_-]+"|\s+class="multilang"){2}\s*>$/u', $match)) {
856 break 2;
857 } else {
858 $open = true;
861 if ($open) {
862 break;
864 return $param;
866 } while (false);
867 // Easy, just strip all tags, if we ever want to fix orphaned '&' we have to do that in format_string().
868 return strip_tags((string)$param);
872 * Validation for PARAM_COMPONENT.
874 * @param mixed $param
875 * @return string
877 protected function clean_param_value_component(mixed $param): string {
878 // We do not want any guessing here, either the name is correct or not
879 // please note only normalised component names are accepted.
880 $param = (string)$param;
881 if (!preg_match('/^[a-z][a-z0-9]*(_[a-z][a-z0-9_]*)?[a-z0-9]+$/', $param)) {
882 return '';
884 if (strpos($param, '__') !== false) {
885 return '';
887 if (strpos($param, 'mod_') === 0) {
888 // Module names must not contain underscores because we need to differentiate them from invalid plugin types.
889 if (substr_count($param, '_') != 1) {
890 return '';
893 return $param;
897 * Validation for PARAM_PLUGIN.
899 * @param mixed $param
900 * @return string
902 protected function clean_param_value_plugin(mixed $param): string {
903 return $this->clean_param_value_area($param);
907 * Validation for PARAM_AREA.
909 * @param mixed $param
910 * @return string
912 protected function clean_param_value_area(mixed $param): string {
913 // We do not want any guessing here, either the name is correct or not.
914 if (!is_valid_plugin_name($param)) {
915 return '';
917 return $param;
921 * Validation for PARAM_SAFEDIR
923 * @param mixed $param
924 * @return string
926 protected function clean_param_value_safedir(mixed $param): string {
927 // Remove everything not a-zA-Z0-9_- .
928 return preg_replace('/[^a-zA-Z0-9_-]/i', '', (string)$param);
932 * Validation for PARAM_SAFEPATH.
934 * @param mixed $param
935 * @return string
937 protected function clean_param_value_safepath(mixed $param): string {
938 // Remove everything not a-zA-Z0-9/_- .
939 return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', (string)$param);
943 * Validation for PARAM_FILE.
945 * @param mixed $param
946 * @return string
948 protected function clean_param_value_file(mixed $param): string {
949 // Strip all suspicious characters from filename.
950 $param = (string)fix_utf8($param);
951 // phpcs:ignore moodle.Strings.ForbiddenStrings.Found
952 $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
953 if ($param === '.' || $param === '..') {
954 $param = '';
956 return $param;
960 * Validation for PARAM_PATH.
962 * @param mixed $param
963 * @return string
965 protected function clean_param_value_path(mixed $param): string {
966 // Strip all suspicious characters from file path.
967 $param = (string)fix_utf8($param);
968 $param = str_replace('\\', '/', $param);
970 // Explode the path and clean each element using the PARAM_FILE rules.
971 $breadcrumb = explode('/', $param);
972 foreach ($breadcrumb as $key => $crumb) {
973 if ($crumb === '.' && $key === 0) {
974 // Special condition to allow for relative current path such as ./currentdirfile.txt.
975 } else {
976 $crumb = clean_param($crumb, PARAM_FILE);
978 $breadcrumb[$key] = $crumb;
980 $param = implode('/', $breadcrumb);
982 // Remove multiple current path (./././) and multiple slashes (///).
983 $param = preg_replace('~//+~', '/', $param);
984 $param = preg_replace('~/(\./)+~', '/', $param);
985 return $param;
989 * Validation for PARAM_HOST.
991 * @param mixed $param
992 * @return string
994 protected function clean_param_value_host(mixed $param): string {
995 // Allow FQDN or IPv4 dotted quad.
996 if (!ip_utils::is_domain_name($param) && !ip_utils::is_ipv4_address($param)) {
997 $param = '';
999 return $param;
1003 * Validation for PARAM_URL.
1005 * @param mixed $param
1006 * @return string
1008 protected function clean_param_value_url(mixed $param): string {
1009 global $CFG;
1011 // Allow safe urls.
1012 $param = (string)fix_utf8($param);
1013 include_once($CFG->dirroot . '/lib/validateurlsyntax.php');
1014 if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E-u-P-a?I?p?f?q?r?')) {
1015 // All is ok, param is respected.
1016 } else {
1017 // Not really ok.
1018 $param = '';
1020 return $param;
1024 * Validation for PARAM_LOCALURL.
1026 * @param mixed $param
1027 * @return string
1029 protected function clean_param_value_localurl(mixed $param): string {
1030 global $CFG;
1032 // Allow http absolute, root relative and relative URLs within wwwroot.
1033 $param = clean_param($param, PARAM_URL);
1034 if (!empty($param)) {
1035 if ($param === $CFG->wwwroot) {
1036 // Exact match.
1037 } else if (preg_match(':^/:', $param)) {
1038 // Root-relative, ok!
1039 } else if (preg_match('/^' . preg_quote($CFG->wwwroot . '/', '/') . '/i', $param)) {
1040 // Absolute, and matches our wwwroot.
1041 } else {
1042 // Relative - let's make sure there are no tricks.
1043 if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?') && !preg_match('/javascript:/i', $param)) {
1044 // Looks ok.
1045 } else {
1046 $param = '';
1050 return $param;
1054 * Validation for PARAM_PEM.
1056 * @param mixed $param
1057 * @return string
1059 protected function clean_param_value_pem(mixed $param): string {
1060 $param = trim((string)$param);
1061 // PEM formatted strings may contain letters/numbers and the symbols:
1062 // - forward slash: /
1063 // - plus sign: +
1064 // - equal sign: =
1065 // - , surrounded by BEGIN and END CERTIFICATE prefix and suffixes.
1066 if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
1067 [$wholething, $body] = $matches;
1068 unset($wholething, $matches);
1069 $b64 = clean_param($body, PARAM_BASE64);
1070 if (!empty($b64)) {
1071 return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
1072 } else {
1073 return '';
1076 return '';
1080 * Validation for PARAM_BASE64.
1082 * @param mixed $param
1083 * @return string
1085 protected function clean_param_value_base64(mixed $param): string {
1086 if (!empty($param)) {
1087 // PEM formatted strings may contain letters/numbers and the symbols
1088 // - forward slash: /
1089 // - plus sign: +
1090 // - equal sign: =.
1091 if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
1092 return '';
1094 $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
1095 // Each line of base64 encoded data must be 64 characters in length, except for the last line which may be less
1096 // than (or equal to) 64 characters long.
1097 for ($i = 0, $j = count($lines); $i < $j; $i++) {
1098 if ($i + 1 == $j) {
1099 if (64 < strlen($lines[$i])) {
1100 return '';
1102 continue;
1105 if (64 != strlen($lines[$i])) {
1106 return '';
1109 return implode("\n", $lines);
1110 } else {
1111 return '';
1116 * Validation for PARAM_TAG.
1118 * @param mixed $param
1119 * @return string
1121 protected function clean_param_value_tag(mixed $param): string {
1122 $param = (string)fix_utf8($param);
1123 // Please note it is not safe to use the tag name directly anywhere,
1124 // it must be processed with s(), urlencode() before embedding anywhere.
1125 // Remove some nasties.
1126 // phpcs:ignore moodle.Strings.ForbiddenStrings.Found
1127 $param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param);
1128 // Convert many whitespace chars into one.
1129 $param = preg_replace('/\s+/u', ' ', $param);
1130 $param = core_text::substr(trim($param), 0, TAG_MAX_LENGTH);
1131 return $param;
1135 * Validation for PARAM_TAGLIST.
1137 * @param mixed $param
1138 * @return string
1140 protected function clean_param_value_taglist(mixed $param): string {
1141 $param = (string)fix_utf8($param);
1142 $tags = explode(',', $param);
1143 $result = [];
1144 foreach ($tags as $tag) {
1145 $res = clean_param($tag, PARAM_TAG);
1146 if ($res !== '') {
1147 $result[] = $res;
1150 if ($result) {
1151 return implode(',', $result);
1152 } else {
1153 return '';
1158 * Validation for PARAM_CAPABILITY.
1160 * @param mixed $param
1161 * @return string
1163 protected function clean_param_value_capability(mixed $param): string {
1164 if (get_capability_info($param)) {
1165 return $param;
1166 } else {
1167 return '';
1172 * Validation for PARAM_PERMISSION.
1174 * @param mixed $param
1175 * @return int
1177 protected function clean_param_value_permission(mixed $param): int {
1178 $param = (int)$param;
1179 if (in_array($param, [CAP_INHERIT, CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT])) {
1180 return $param;
1181 } else {
1182 return CAP_INHERIT;
1187 * Validation for PARAM_AUTH.
1189 * @param mixed $param
1190 * @return string
1192 protected function clean_param_value_auth(mixed $param): string {
1193 $param = clean_param($param, PARAM_PLUGIN);
1194 if (empty($param)) {
1195 return '';
1196 } else if (exists_auth_plugin($param)) {
1197 return $param;
1198 } else {
1199 return '';
1204 * Validation for PARAM_LANG.
1206 * @param mixed $param
1207 * @return string
1209 protected function clean_param_value_lang(mixed $param): string {
1210 $param = clean_param($param, PARAM_SAFEDIR);
1211 if (get_string_manager()->translation_exists($param)) {
1212 return $param;
1213 } else {
1214 // Specified language is not installed or param malformed.
1215 return '';
1220 * Validation for PARAM_THEME.
1222 * @param mixed $param
1223 * @return string
1225 protected function clean_param_value_theme(mixed $param): string {
1226 global $CFG;
1228 $param = clean_param($param, PARAM_PLUGIN);
1229 if (empty($param)) {
1230 return '';
1231 } else if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
1232 return $param;
1233 } else if (!empty($CFG->themedir) && file_exists("$CFG->themedir/$param/config.php")) {
1234 return $param;
1235 } else {
1236 // Specified theme is not installed.
1237 return '';
1242 * Validation for PARAM_USERNAME.
1244 * @param mixed $param
1245 * @return string
1247 protected function clean_param_value_username(mixed $param): string {
1248 global $CFG;
1250 $param = (string)fix_utf8($param);
1251 $param = trim($param);
1252 // Convert uppercase to lowercase MDL-16919.
1253 $param = core_text::strtolower($param);
1254 if (empty($CFG->extendedusernamechars)) {
1255 $param = str_replace(" ", "", $param);
1256 // Regular expression, eliminate all chars EXCEPT:
1257 // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
1258 $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
1260 return $param;
1264 * Validation for PARAM_EMAIL.
1266 * @param mixed $param
1267 * @return string
1269 protected function clean_param_value_email(mixed $param): string {
1270 $param = fix_utf8($param);
1271 if (validate_email($param ?? '')) {
1272 return $param;
1273 } else {
1274 return '';
1279 * Validation for PARAM_STRINGID.
1281 * @param mixed $param
1282 * @return string
1284 protected function clean_param_value_stringid(mixed $param): string {
1285 if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', (string)$param)) {
1286 return $param;
1287 } else {
1288 return '';
1293 * Validation for PARAM_TIMEZONE.
1295 * @param mixed $param
1296 * @return string
1298 protected function clean_param_value_timezone(mixed $param): string {
1299 // Can be int, float(with .5 or .0) or string seperated by '/' and can have '-_'.
1300 $param = (string)fix_utf8($param);
1301 $timezonepattern = '/^(([+-]?(0?[0-9](\.[5|0])?|1[0-3](\.0)?|1[0-2]\.5))|(99)|[[:alnum:]]+(\/?[[:alpha:]_-])+)$/';
1302 if (preg_match($timezonepattern, $param)) {
1303 return $param;
1304 } else {
1305 return '';
1310 * Whether the parameter is deprecated.
1312 * @return bool
1314 public function is_deprecated(): bool {
1315 return deprecation::is_deprecated($this);