Proyectos de Subversion Moodle

Rev

Rev 1 | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 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.
13
//
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/>.
16
 
17
namespace core;
18
 
19
use coding_exception;
20
use core_text;
21
use core\attribute\deprecated;
22
use core\ip_utils;
23
use invalid_parameter_exception;
24
use moodle_exception;
25
 
26
// phpcs:disable Generic.CodeAnalysis.EmptyStatement.DetectedIf
27
 
28
/**
29
 * Parameter validation helpers for Moodle.
30
 *
31
 * @package    core
32
 * @copyright  2023 Andrew Lyons <andrew@nicols.co.uk>
33
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
34
 */
35
enum param: string {
36
    /**
37
     * PARAM_ALPHA - contains only English ascii letters [a-zA-Z].
38
     */
1441 ariadna 39
    #[param_clientside_regex('^[a-zA-Z]+$')]
1 efrain 40
    case ALPHA = 'alpha';
41
 
42
    /**
43
     * PARAM_ALPHAEXT the same contents as PARAM_ALPHA (English ascii letters [a-zA-Z]) plus the chars in quotes: "_-" allowed
44
     * NOTE: originally this allowed "/" too, please use PARAM_SAFEPATH if "/" needed
45
     */
1441 ariadna 46
    #[param_clientside_regex('^[a-zA-Z_\-]*$')]
1 efrain 47
    case ALPHAEXT = 'alphaext';
48
 
49
    /**
50
     * PARAM_ALPHANUM - expected numbers 0-9 and English ascii letters [a-zA-Z] only.
51
     */
1441 ariadna 52
    #[param_clientside_regex('^[a-zA-Z0-9]*$')]
1 efrain 53
    case ALPHANUM = 'alphanum';
54
 
55
    /**
56
     * PARAM_ALPHANUMEXT - expected numbers 0-9, letters (English ascii letters [a-zA-Z]) and _- only.
57
     */
1441 ariadna 58
    #[param_clientside_regex('^[a-zA-Z0-9_\-]*$')]
1 efrain 59
    case ALPHANUMEXT = 'alphanumext';
60
 
61
    /**
62
     * PARAM_AUTH - actually checks to make sure the string is a valid auth plugin
63
     */
64
    case AUTH = 'auth';
65
 
66
    /**
67
     * PARAM_BASE64 - Base 64 encoded format
68
     */
69
    case BASE64 = 'base64';
70
 
71
    /**
72
     * PARAM_BOOL - converts input into 0 or 1, use for switches in forms and urls.
73
     */
74
    case BOOL = 'bool';
75
 
76
    /**
77
     * PARAM_CAPABILITY - A capability name, like 'moodle/role:manage'. Actually
78
     * checked against the list of capabilities in the database.
79
     */
80
    case CAPABILITY = 'capability';
81
 
82
    /**
83
     * PARAM_CLEANHTML - cleans submitted HTML code. Note that you almost never want
84
     * to use this. The normal mode of operation is to use PARAM_RAW when receiving
85
     * the input (required/optional_param or formslib) and then sanitise the HTML
86
     * using format_text on output. This is for the rare cases when you want to
87
     * sanitise the HTML on input. This cleaning may also fix xhtml strictness.
88
     */
89
    case CLEANHTML = 'cleanhtml';
90
 
91
    /**
92
     * PARAM_EMAIL - an email address following the RFC
93
     */
94
    case EMAIL = 'email';
95
 
96
    /**
97
     * PARAM_FILE - safe file name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
98
     */
99
    case FILE = 'file';
100
 
101
    /**
102
     * PARAM_FLOAT - a real/floating point number.
103
     *
104
     * Note that you should not use PARAM_FLOAT for numbers typed in by the user.
105
     * It does not work for languages that use , as a decimal separator.
106
     * Use PARAM_LOCALISEDFLOAT instead.
107
     */
108
    case FLOAT = 'float';
109
 
110
    /**
111
     * PARAM_LOCALISEDFLOAT - a localised real/floating point number.
112
     * This is preferred over PARAM_FLOAT for numbers typed in by the user.
113
     * Cleans localised numbers to computer readable numbers; false for invalid numbers.
114
     */
1441 ariadna 115
    #[param_clientside_regex('^\d*([\.,])\d+$')]
1 efrain 116
    case LOCALISEDFLOAT = 'localisedfloat';
117
 
118
    /**
119
     * PARAM_HOST - expected fully qualified domain name (FQDN) or an IPv4 dotted quad (IP address)
120
     */
121
    case HOST = 'host';
122
 
123
    /**
124
     * PARAM_INT - integers only, use when expecting only numbers.
125
     */
126
    case INT = 'int';
127
 
128
    /**
129
     * PARAM_LANG - checks to see if the string is a valid installed language in the current site.
130
     */
131
    case LANG = 'lang';
132
 
133
    /**
134
     * PARAM_LOCALURL - expected properly formatted URL as well as one that refers to the local server itself. (NOT orthogonal to the
135
     * others! Implies PARAM_URL!)
136
     */
137
    case LOCALURL = 'localurl';
138
 
139
    /**
140
     * PARAM_NOTAGS - all html tags are stripped from the text. Do not abuse this type.
141
     */
142
    case NOTAGS = 'notags';
143
 
144
    /**
145
     * PARAM_PATH - safe relative path name, all dangerous chars are stripped, protects against XSS, SQL injections and directory
146
     * traversals note: the leading slash is not removed, window drive letter is not allowed
147
     */
148
    case PATH = 'path';
149
 
150
    /**
151
     * PARAM_PEM - Privacy Enhanced Mail format
152
     */
153
    case PEM = 'pem';
154
 
155
    /**
156
     * PARAM_PERMISSION - A permission, one of CAP_INHERIT, CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT.
157
     */
158
    case PERMISSION = 'permission';
159
 
160
    /**
161
     * PARAM_RAW specifies a parameter that is not cleaned/processed in any way except the discarding of the invalid utf-8 characters
162
     */
163
    case RAW = 'raw';
164
 
165
    /**
166
     * PARAM_RAW_TRIMMED like PARAM_RAW but leading and trailing whitespace is stripped.
167
     */
168
    case RAW_TRIMMED = 'raw_trimmed';
169
 
170
    /**
171
     * PARAM_SAFEDIR - safe directory name, suitable for include() and require()
172
     */
1441 ariadna 173
    #[param_clientside_regex('^[a-zA-Z0-9_\-]*$')]
1 efrain 174
    case SAFEDIR = 'safedir';
175
 
176
    /**
177
     * PARAM_SAFEPATH - several PARAM_SAFEDIR joined by "/", suitable for include() and require(), plugin paths
178
     * and other references to Moodle code files.
179
     *
180
     * This is NOT intended to be used for absolute paths or any user uploaded files.
181
     */
1441 ariadna 182
    #[param_clientside_regex('^[a-zA-Z0-9\/_\-]*$')]
1 efrain 183
    case SAFEPATH = 'safepath';
184
 
185
    /**
186
     * PARAM_SEQUENCE - expects a sequence of numbers like 8 to 1,5,6,4,6,8,9.  Numbers and comma only.
187
     */
1441 ariadna 188
    #[param_clientside_regex('^[0-9,]*$')]
1 efrain 189
    case SEQUENCE = 'sequence';
190
 
191
    /**
192
     * PARAM_TAG - one tag (interests, blogs, etc.) - mostly international characters and space, <> not supported
193
     */
194
    case TAG = 'tag';
195
 
196
    /**
197
     * PARAM_TAGLIST - list of tags separated by commas (interests, blogs, etc.)
198
     */
199
    case TAGLIST = 'taglist';
200
 
201
    /**
202
     * PARAM_TEXT - general plain text compatible with multilang filter, no other html tags. Please note '<', or '>' are allowed here.
203
     */
204
    case TEXT = 'text';
205
 
206
    /**
207
     * PARAM_THEME - Checks to see if the string is a valid theme name in the current site
208
     */
209
    case THEME = 'theme';
210
 
211
    /**
212
     * PARAM_URL - expected properly formatted URL. Please note that domain part is required, http://localhost/ is not accepted but
213
     * http://localhost.localdomain/ is ok.
214
     */
215
    case URL = 'url';
216
 
217
    /**
218
     * PARAM_USERNAME - Clean username to only contains allowed characters. This is to be used ONLY when manually creating user
219
     * accounts, do NOT use when syncing with external systems!!
220
     */
221
    case USERNAME = 'username';
222
 
223
    /**
224
     * PARAM_STRINGID - used to check if the given string is valid string identifier for get_string()
225
     */
226
    case STRINGID = 'stringid';
227
 
228
    /**
229
     * PARAM_CLEAN - obsoleted, please use a more specific type of parameter.
230
     * It was one of the first types, that is why it is abused so much ;-)
231
     * @deprecated since 2.0
232
     */
233
    #[deprecated(
234
        replacement: 'a more specific type of parameter',
235
        since: '2.0',
236
        reason: 'The CLEAN param type is too generic to perform satisfactory validation',
237
        emit: false,
238
    )]
239
    case CLEAN = 'clean';
240
 
241
    /**
242
     * PARAM_INTEGER - deprecated alias for PARAM_INT
243
     * @deprecated since 2.0
244
     */
245
    #[deprecated(
246
        replacement: 'param::INT',
247
        since: '2.0',
248
        reason: 'Alias for INT',
249
        final: true,
250
    )]
251
    case INTEGER = 'integer';
252
 
253
    /**
254
     * PARAM_NUMBER - deprecated alias of PARAM_FLOAT
255
     * @deprecated since 2.0
256
     */
257
    #[deprecated(
258
        replacement: 'param::FLOAT',
259
        since: '2.0',
260
        reason: 'Alias for FLOAT',
261
        final: true,
262
    )]
263
    case NUMBER = 'number';
264
 
265
    /**
266
     * PARAM_ACTION - deprecated alias for PARAM_ALPHANUMEXT, use for various actions in forms and urls
267
     * NOTE: originally alias for PARAM_ALPHANUMEXT
268
     * @deprecated since 2.0
269
     */
270
    #[deprecated(
271
        replacement: 'param::ALPHANUMEXT',
272
        since: '2.0',
273
        reason: 'Alias for PARAM_ALPHANUMEXT',
274
        final: true,
275
    )]
276
    case ACTION = 'action';
277
 
278
    /**
279
     * PARAM_FORMAT - deprecated alias for PARAM_ALPHANUMEXT, use for names of plugins, formats, etc.
280
     * NOTE: originally alias for PARAM_APLHA
281
     * @deprecated since 2.0
282
     */
283
    #[deprecated(
284
        replacement: 'param::ALPHANUMEXT',
285
        since: '2.0',
286
        reason: 'Alias for PARAM_ALPHANUMEXT',
287
        final: true,
288
    )]
289
    case FORMAT = 'format';
290
 
291
    /**
292
     * PARAM_MULTILANG - deprecated alias of PARAM_TEXT.
293
     * @deprecated since 2.0
294
     */
295
    #[deprecated(
296
        replacement: 'param::TEXT',
297
        since: '2.0',
298
        reason: 'Alias for PARAM_TEXT',
299
        final: true,
300
    )]
301
    case MULTILANG = 'multilang';
302
 
303
    /**
304
     * PARAM_TIMEZONE - expected timezone. Timezone can be int +-(0-13) or float +-(0.5-12.5) or
305
     * string separated by '/' and can have '-' &/ '_' (eg. America/North_Dakota/New_Salem
306
     * America/Port-au-Prince)
307
     */
308
    case TIMEZONE = 'timezone';
309
 
310
    /**
311
     * PARAM_CLEANFILE - deprecated alias of PARAM_FILE; originally was removing regional chars too
312
     * @deprecated since 2.0
313
     */
314
    #[deprecated(
315
        replacement: 'param::FILE',
316
        since: '2.0',
317
        reason: 'Alias for PARAM_FILE',
318
    )]
319
    case CLEANFILE = 'cleanfile';
320
 
321
    /**
322
     * PARAM_COMPONENT is used for full component names (aka frankenstyle) such as 'mod_forum = 'core_rating', 'auth_ldap'.
323
     * Short legacy subsystem names and module names are accepted too ex: 'forum = 'rating', 'user'.
324
     * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
325
     * NOTE: numbers and underscores are strongly discouraged in plugin names!
326
     */
1441 ariadna 327
    #[param_clientside_regex('^[a-z][a-z0-9]*(_(?:[a-z][a-z0-9_](?!__))*)?[a-z0-9]+$')]
1 efrain 328
    case COMPONENT = 'component';
329
 
330
    /**
331
     * PARAM_AREA is a name of area used when addressing files, comments, ratings, etc.
332
     * It is usually used together with context id and component.
333
     * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
334
     */
1441 ariadna 335
    #[param_clientside_regex('^[a-z](?:[a-z0-9_](?!__))*[a-z0-9]+$')]
1 efrain 336
    case AREA = 'area';
337
 
338
    /**
339
     * PARAM_PLUGIN is used for plugin names such as 'forum = 'glossary', 'ldap', 'paypal', 'completionstatus'.
340
     * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
341
     * NOTE: numbers and underscores are strongly discouraged in plugin names! Underscores are forbidden in module names.
342
     */
1441 ariadna 343
    #[param_clientside_regex('^[a-z](?:[a-z0-9_](?!__))*[a-z0-9]+$')]
1 efrain 344
    case PLUGIN = 'plugin';
345
 
346
    /**
347
     * Get the canonical enumerated parameter from the parameter type name.
348
     *
349
     * @param string $paramname
350
     * @return param
351
     * @throws coding_exception If the parameter is unknown.
352
     */
353
    public static function from_type(string $paramname): self {
354
        $from = self::tryFrom($paramname)?->canonical();
355
        if ($from) {
356
            return $from;
357
        }
358
 
359
        throw new \coding_exception("Unknown parameter type '{$paramname}'");
360
    }
361
 
362
    /**
363
     * Canonicalise the parameter.
364
     *
365
     * This method is used to support aliasing of deprecated parameters.
366
     *
367
     * @return param
368
     */
369
    private function canonical(): self {
370
        return match ($this) {
371
            self::ACTION => self::ALPHANUMEXT,
372
            self::CLEANFILE => self::FILE,
373
            self::FORMAT => self::ALPHANUMEXT,
374
            self::INTEGER => self::INT,
375
            self::MULTILANG => self::TEXT,
376
            self::NUMBER => self::FLOAT,
377
 
378
            default => $this,
379
        };
380
    }
381
 
382
    /**
383
     * Used by {@link optional_param()} and {@link required_param()} to
384
     * clean the variables and/or cast to specific types, based on
385
     * an options field.
386
     *
387
     * <code>
388
     * $course->format = param::ALPHA->clean($course->format);
389
     * $selectedgradeitem = param::INT->clean($selectedgradeitem);
390
     * </code>
391
     *
392
     * @param mixed $value the value to clean
393
     * @return mixed
394
     * @throws coding_exception
395
     */
396
    public function clean(mixed $value): mixed {
397
        // Check and emit a deprecation notice if required.
398
        deprecation::emit_deprecation_if_present($this);
399
 
400
        if (is_array($value)) {
401
            throw new coding_exception('clean() can not process arrays, please use clean_array() instead.');
402
        } else if (is_object($value)) {
403
            if (method_exists($value, '__toString')) {
404
                $value = $value->__toString();
405
            } else {
406
                throw new coding_exception('clean() can not process objects, please use clean_array() instead.');
407
            }
408
        }
409
 
410
        $canonical = $this->canonical();
411
        if ($this !== $canonical) {
412
            return $canonical->clean($value);
413
        }
414
 
415
        $methodname = "clean_param_value_{$this->value}";
416
        if (!method_exists(self::class, $methodname)) {
417
            throw new coding_exception("Method not found for cleaning {$this->value}");
418
        }
419
 
420
        return $this->{$methodname}($value);
421
    }
422
 
423
    /**
1441 ariadna 424
     * Get the clientside regular expression for this parameter.
425
     *
426
     * @return null|string
427
     */
428
    public function get_clientside_expression(): ?string {
429
        $ref = new \ReflectionClassConstant(self::class, $this->name);
430
        $attributes = $ref->getAttributes(param_clientside_regex::class);
431
        if (count($attributes) === 0) {
432
            return null;
433
        }
434
 
435
        return $attributes[0]->newInstance()->regex;
436
    }
437
 
438
    /**
1 efrain 439
     * Returns a value for the named variable, taken from request arguments.
440
     *
441
     * This function should be used to initialise all required values
442
     * in a script that are based on parameters.  Usually it will be
443
     * used like this:
444
     *    $id = param::INT->required_param('id');
445
     *
446
     *
447
     * @param string $paramname the name of the page parameter we want
448
     * @return mixed
449
     * @throws moodle_exception
450
     */
451
    public function required_param(string $paramname): mixed {
452
        return $this->clean($this->get_request_parameter($paramname, true));
453
    }
454
 
455
    /**
456
     * Returns a particular array value for the named variable, taken from request arguments.
457
     * If the parameter doesn't exist then an error is thrown because we require this variable.
458
     *
459
     * This function should be used to initialise all required values
460
     * in a script that are based on parameters.  Usually it will be
461
     * used like this:
462
     *    $ids = required_param_array('ids', PARAM_INT);
463
     *
464
     * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
465
     *
466
     * @param string $paramname the name of the page parameter we want
467
     * @return array
468
     * @throws moodle_exception
469
     */
470
    public function required_param_array(string $paramname): array {
471
        $param = $this->get_request_parameter($paramname, true);
472
 
473
        if (!is_array($param)) {
474
            throw new \moodle_exception('missingparam', '', '', $paramname);
475
        }
476
 
477
        $result = [];
478
        foreach ($param as $key => $value) {
479
            if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
480
                debugging(
481
                    "Invalid key name in required_param_array() detected: {$key}, parameter: {$paramname}",
482
                );
483
                continue;
484
            }
485
            $result[$key] = $this->clean($value);
486
        }
487
 
488
        return $result;
489
    }
490
 
491
    /**
492
     * Returns a particular value for the named variable from the request arguments,
493
     * otherwise returning a given default.
494
     *
495
     * This function should be used to initialise all optional values
496
     * in a script that are based on parameters.  Usually it will be
497
     * used like this:
498
     *    $name = param::TEXT->optional_param('name', 'Fred');
499
     *
500
     * @param string $paramname the name of the page parameter we want
501
     * @param mixed  $default the default value to return if nothing is found
502
     * @return mixed
503
     */
504
    public function optional_param(string $paramname, mixed $default): mixed {
505
        $param = $this->get_request_parameter($paramname, false);
506
        if ($param === null) {
507
            return $default;
508
        }
509
 
510
        return $this->clean($param);
511
    }
512
 
513
    /**
514
     * Returns a particular array value for the named variable from the request arguments,
515
     * otherwise returning a given default.
516
     *
517
     * This function should be used to initialise all optional values
518
     * in a script that are based on parameters.  Usually it will be
519
     * used like this:
520
     *    $ids = param::INT->optional_param_arrayt('id', array());
521
     *
522
     * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported.
523
     *
524
     * @param string $paramname the name of the page parameter we want
525
     * @param mixed $default the default value to return if nothing is found
526
     * @return array
527
     */
528
    public function optional_param_array(string $paramname, mixed $default): mixed {
529
        $param = $this->get_request_parameter($paramname, false);
530
        if ($param === null) {
531
            return $default;
532
        }
533
 
534
        if (!is_array($param)) {
535
            debugging(
536
                "optional_param_array() only expects array parameters: {$paramname}",
537
            );
538
            return $default;
539
        }
540
 
541
        $result = [];
542
        foreach ($param as $key => $value) {
543
            if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
544
                debugging(
545
                    "Invalid key name in optional_param_array() detected: {$key}, parameter: {$paramname}",
546
                );
547
                continue;
548
            }
549
            $result[$key] = $this->clean($value);
550
        }
551
 
552
        return $result;
553
    }
554
 
555
    /**
556
     * Returns a particular value for the named variable, taken from the POST, or GET params.
557
     *
558
     * Parameters are fetched from POST first, then GET.
559
     *
560
     * @param string $paramname
561
     * @param bool $require
562
     * @return mixed
563
     * @throws moodle_exception If the parameter was not found and the value is required
564
     */
565
    private function get_request_parameter(
566
        string $paramname,
567
        bool $require,
568
    ): mixed {
569
        if (isset($_POST[$paramname])) {
570
            return $_POST[$paramname];
571
        } else if (isset($_GET[$paramname])) {
572
            return $_GET[$paramname];
573
        } else if ($require) {
574
            throw new \moodle_exception('missingparam', '', '', $paramname);
575
        }
576
 
577
        return null;
578
    }
579
 
580
    /**
581
     * Strict validation of parameter values, the values are only converted
582
     * to requested PHP type. Internally it is using clean_param, the values
583
     * before and after cleaning must be equal - otherwise
584
     * an invalid_parameter_exception is thrown.
585
     * Objects and classes are not accepted.
586
     *
587
     * @param mixed $param
588
     * @param bool $allownull are nulls valid value?
589
     * @param string $debuginfo optional debug information
590
     * @return mixed the $param value converted to PHP type
591
     * @throws invalid_parameter_exception if $param is not of given type
592
     */
593
    public function validate_param(
594
        mixed $param,
595
        bool $allownull = NULL_NOT_ALLOWED,
596
        string $debuginfo = '',
597
    ): mixed {
598
        if (is_null($param)) {
599
            if ($allownull == NULL_ALLOWED) {
600
                return null;
601
            } else {
602
                throw new invalid_parameter_exception($debuginfo);
603
            }
604
        }
605
        if (is_array($param) || is_object($param)) {
606
            throw new invalid_parameter_exception($debuginfo);
607
        }
608
 
609
        $cleaned = $this->clean($param);
610
 
611
        if ($this->canonical() === self::FLOAT) {
612
            // Do not detect precision loss here.
613
            if (is_float($param) || is_int($param)) {
614
                // These always fit.
615
            } else if (!is_numeric($param) || !preg_match('/^[\+-]?[0-9]*\.?[0-9]*(e[-+]?[0-9]+)?$/i', (string)$param)) {
616
                throw new invalid_parameter_exception($debuginfo);
617
            }
618
        } else if ((string) $param !== (string) $cleaned) {
619
            // Conversion to string is usually lossless.
620
            throw new invalid_parameter_exception($debuginfo);
621
        }
622
 
623
        return $cleaned;
624
    }
625
 
626
    /**
627
     * Makes sure array contains only the allowed types, this function does not validate array key names!
628
     *
629
     * <code>
630
     * $options = param::INT->clean_param_array($options);
631
     * </code>
632
     *
633
     * @param array|null $param the variable array we are cleaning
634
     * @param bool $recursive clean recursive arrays
635
     * @return array
636
     * @throws coding_exception
637
     */
638
    public function clean_param_array(
639
        ?array $param,
640
        bool $recursive = false,
641
    ) {
642
        // Convert null to empty array.
643
        $param = (array) $param;
644
        foreach ($param as $key => $value) {
645
            if (is_array($value)) {
646
                if ($recursive) {
647
                    $param[$key] = $this->clean_param_array($value, true);
648
                } else {
649
                    throw new coding_exception('clean_param_array can not process multidimensional arrays when $recursive is false.');
650
                }
651
            } else {
652
                $param[$key] = $this->clean($value);
653
            }
654
        }
655
        return $param;
656
    }
657
 
658
    /**
659
     * Validation for PARAM_RAW.
660
     *
661
     * @param mixed $param
662
     * @return mixed
663
     */
664
    protected function clean_param_value_raw(mixed $param): mixed {
665
        // No cleaning at all.
666
        return fix_utf8($param);
667
    }
668
 
669
    /**
670
     * Validation for PARAM_RAW_TRIMMED.
671
     *
672
     * @param mixed $param
673
     * @return string
674
     */
675
    protected function clean_param_value_raw_trimmed(mixed $param): string {
676
        // No cleaning, but strip leading and trailing whitespace.
677
        return trim((string) $this->clean_param_value_raw($param));
678
    }
679
 
680
    /**
681
     * Validation for PARAM_CLEAN.
682
     *
683
     * @param mixed $param
684
     * @return string
685
     */
686
    protected function clean_param_value_clean(mixed $param): string {
687
        // General HTML cleaning, try to use more specific type if possible this is deprecated!
688
        // Please use more specific type instead.
689
        if (is_numeric($param)) {
690
            return $param;
691
        }
692
        $param = fix_utf8($param);
693
        // Sweep for scripts, etc.
694
        return clean_text($param);
695
    }
696
 
697
    /**
698
     * Validation for PARAM_CLEANHTML.
699
     */
700
    protected function clean_param_value_cleanhtml(mixed $param): mixed {
701
        // Clean html fragment.
702
        $param = (string)fix_utf8($param);
703
        // Sweep for scripts, etc.
704
        $param = clean_text($param, FORMAT_HTML);
705
 
706
        return trim($param);
707
    }
708
 
709
    /**
710
     * Validation for PARAM_INT.
711
     *
712
     * @param mixed $param
713
     * @return int
714
     */
715
    protected function clean_param_value_int(mixed $param): int {
716
        // Convert to integer.
717
        return (int)$param;
718
    }
719
 
720
    /**
721
     * Validation for PARAM_FLOAT.
722
     *
723
     * @param mixed $param
724
     * @return float
725
     */
726
    protected function clean_param_value_float(mixed $param): float {
727
        // Convert to float.
728
        return (float)$param;
729
    }
730
 
731
    /**
732
     * Validation for PARAM_LOCALISEDFLOAT.
733
     *
734
     * @param mixed $param
735
     * @return mixed
736
     */
737
    protected function clean_param_value_localisedfloat(mixed $param): mixed {
738
        // Convert to float.
739
        return unformat_float($param, true);
740
    }
741
 
742
    /**
743
     * Validation for PARAM_ALPHA.
744
     *
745
     * @param mixed $param
746
     * @return mixed
747
     */
748
    protected function clean_param_value_alpha(mixed $param): mixed {
749
        // Remove everything not `a-z`.
750
        return preg_replace('/[^a-zA-Z]/i', '', (string)$param);
751
    }
752
 
753
    /**
754
     * Validation for PARAM_ALPHAEXT.
755
     *
756
     * @param mixed $param
757
     * @return mixed
758
     */
759
    protected function clean_param_value_alphaext(mixed $param): mixed {
760
        // Remove everything not `a-zA-Z_-` (originally allowed "/" too).
761
        return preg_replace('/[^a-zA-Z_-]/i', '', (string)$param);
762
    }
763
 
764
    /**
765
     * Validation for PARAM_ALPHANUM.
766
     *
767
     * @param mixed $param
768
     * @return mixed
769
     */
770
    protected function clean_param_value_alphanum(mixed $param): mixed {
771
        // Remove everything not `a-zA-Z0-9`.
772
        return preg_replace('/[^A-Za-z0-9]/i', '', (string)$param);
773
    }
774
 
775
    /**
776
     * Validation for PARAM_ALPHANUMEXT.
777
     *
778
     * @param mixed $param
779
     * @return mixed
780
     */
781
    protected function clean_param_value_alphanumext(mixed $param): mixed {
782
        // Remove everything not `a-zA-Z0-9_-`.
783
        return preg_replace('/[^A-Za-z0-9_-]/i', '', (string)$param);
784
    }
785
 
786
    /**
787
     * Validation for PARAM_SEQUENCE.
788
     *
789
     * @param mixed $param
790
     * @return mixed
791
     */
792
    protected function clean_param_value_sequence(mixed $param): mixed {
793
        // Remove everything not `0-9,`.
794
        return preg_replace('/[^0-9,]/i', '', (string)$param);
795
    }
796
 
797
    /**
798
     * Validation for PARAM_BOOL.
799
     *
800
     * @param mixed $param
801
     * @return mixed
802
     */
803
    protected function clean_param_value_bool(mixed $param): mixed {
804
        // Convert to 1 or 0.
805
        $tempstr = strtolower((string)$param);
806
        if ($tempstr === 'on' || $tempstr === 'yes' || $tempstr === 'true') {
807
            $param = 1;
808
        } else if ($tempstr === 'off' || $tempstr === 'no' || $tempstr === 'false') {
809
            $param = 0;
810
        } else {
811
            $param = empty($param) ? 0 : 1;
812
        }
813
        return $param;
814
    }
815
 
816
    /**
817
     * Validation for PARAM_NOTAGS.
818
     *
819
     * @param mixed $param
820
     * @return mixed
821
     */
822
    protected function clean_param_value_notags(mixed $param): mixed {
823
        // Strip all tags.
824
        $param = fix_utf8($param);
825
        return strip_tags((string)$param);
826
    }
827
 
828
    /**
829
     * Validation for PARAM_TEXT.
830
     *
831
     * @param mixed $param
832
     * @return mixed
833
     */
834
    protected function clean_param_value_text(mixed $param): mixed {
835
        // Leave only tags needed for multilang.
836
        $param = fix_utf8($param);
837
        // If the multilang syntax is not correct we strip all tags because it would break xhtml strict which is required
838
        // for accessibility standards please note this cleaning does not strip unbalanced '>' for BC compatibility reasons.
839
        do {
840
            if (strpos((string)$param, '</lang>') !== false) {
841
                // Old and future mutilang syntax.
842
                $param = strip_tags($param, '<lang>');
843
                if (!preg_match_all('/<.*>/suU', $param, $matches)) {
844
                    break;
845
                }
846
                $open = false;
847
                foreach ($matches[0] as $match) {
848
                    if ($match === '</lang>') {
849
                        if ($open) {
850
                            $open = false;
851
                            continue;
852
                        } else {
853
                            break 2;
854
                        }
855
                    }
856
                    if (!preg_match('/^<lang lang="[a-zA-Z0-9_-]+"\s*>$/u', $match)) {
857
                        break 2;
858
                    } else {
859
                        $open = true;
860
                    }
861
                }
862
                if ($open) {
863
                    break;
864
                }
865
                return $param;
866
            } else if (strpos((string)$param, '</span>') !== false) {
867
                // Current problematic multilang syntax.
868
                $param = strip_tags($param, '<span>');
869
                if (!preg_match_all('/<.*>/suU', $param, $matches)) {
870
                    break;
871
                }
872
                $open = false;
873
                foreach ($matches[0] as $match) {
874
                    if ($match === '</span>') {
875
                        if ($open) {
876
                            $open = false;
877
                            continue;
878
                        } else {
879
                            break 2;
880
                        }
881
                    }
882
                    if (!preg_match('/^<span(\s+lang="[a-zA-Z0-9_-]+"|\s+class="multilang"){2}\s*>$/u', $match)) {
883
                        break 2;
884
                    } else {
885
                        $open = true;
886
                    }
887
                }
888
                if ($open) {
889
                    break;
890
                }
891
                return $param;
892
            }
893
        } while (false);
894
        // Easy, just strip all tags, if we ever want to fix orphaned '&' we have to do that in format_string().
895
        return strip_tags((string)$param);
896
    }
897
 
898
    /**
899
     * Validation for PARAM_COMPONENT.
900
     *
901
     * @param mixed $param
902
     * @return string
903
     */
904
    protected function clean_param_value_component(mixed $param): string {
905
        // We do not want any guessing here, either the name is correct or not
906
        // please note only normalised component names are accepted.
907
        $param = (string)$param;
908
        if (!preg_match('/^[a-z][a-z0-9]*(_[a-z][a-z0-9_]*)?[a-z0-9]+$/', $param)) {
909
            return '';
910
        }
911
        if (strpos($param, '__') !== false) {
912
            return '';
913
        }
914
        if (strpos($param, 'mod_') === 0) {
915
            // Module names must not contain underscores because we need to differentiate them from invalid plugin types.
916
            if (substr_count($param, '_') != 1) {
917
                return '';
918
            }
919
        }
920
        return $param;
921
    }
922
 
923
    /**
924
     * Validation for PARAM_PLUGIN.
925
     *
926
     * @param mixed $param
927
     * @return string
928
     */
929
    protected function clean_param_value_plugin(mixed $param): string {
930
        return $this->clean_param_value_area($param);
931
    }
932
 
933
    /**
934
     * Validation for PARAM_AREA.
935
     *
936
     * @param mixed $param
937
     * @return string
938
     */
939
    protected function clean_param_value_area(mixed $param): string {
940
        // We do not want any guessing here, either the name is correct or not.
941
        if (!is_valid_plugin_name($param)) {
942
            return '';
943
        }
944
        return $param;
945
    }
946
 
947
    /**
948
     * Validation for PARAM_SAFEDIR
949
     *
950
     * @param mixed $param
951
     * @return string
952
     */
953
    protected function clean_param_value_safedir(mixed $param): string {
954
        // Remove everything not a-zA-Z0-9_- .
955
        return preg_replace('/[^a-zA-Z0-9_-]/i', '', (string)$param);
956
    }
957
 
958
    /**
959
     * Validation for PARAM_SAFEPATH.
960
     *
961
     * @param mixed $param
962
     * @return string
963
     */
964
    protected function clean_param_value_safepath(mixed $param): string {
965
        // Remove everything not a-zA-Z0-9/_- .
966
        return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', (string)$param);
967
    }
968
 
969
    /**
970
     * Validation for PARAM_FILE.
971
     *
972
     * @param mixed $param
973
     * @return string
974
     */
975
    protected function clean_param_value_file(mixed $param): string {
976
        // Strip all suspicious characters from filename.
977
        $param = (string)fix_utf8($param);
978
        // phpcs:ignore moodle.Strings.ForbiddenStrings.Found
979
        $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
980
        if ($param === '.' || $param === '..') {
981
            $param = '';
982
        }
983
        return $param;
984
    }
985
 
986
    /**
987
     * Validation for PARAM_PATH.
988
     *
989
     * @param mixed $param
990
     * @return string
991
     */
992
    protected function clean_param_value_path(mixed $param): string {
993
        // Strip all suspicious characters from file path.
994
        $param = (string)fix_utf8($param);
995
        $param = str_replace('\\', '/', $param);
996
 
997
        // Explode the path and clean each element using the PARAM_FILE rules.
998
        $breadcrumb = explode('/', $param);
999
        foreach ($breadcrumb as $key => $crumb) {
1000
            if ($crumb === '.' && $key === 0) {
1001
                // Special condition to allow for relative current path such as ./currentdirfile.txt.
1002
            } else {
1003
                $crumb = clean_param($crumb, PARAM_FILE);
1004
            }
1005
            $breadcrumb[$key] = $crumb;
1006
        }
1007
        $param = implode('/', $breadcrumb);
1008
 
1009
        // Remove multiple current path (./././) and multiple slashes (///).
1010
        $param = preg_replace('~//+~', '/', $param);
1011
        $param = preg_replace('~/(\./)+~', '/', $param);
1012
        return $param;
1013
    }
1014
 
1015
    /**
1016
     * Validation for PARAM_HOST.
1017
     *
1018
     * @param mixed $param
1019
     * @return string
1020
     */
1021
    protected function clean_param_value_host(mixed $param): string {
1022
        // Allow FQDN or IPv4 dotted quad.
1023
        if (!ip_utils::is_domain_name($param) && !ip_utils::is_ipv4_address($param)) {
1024
            $param = '';
1025
        }
1026
        return $param;
1027
    }
1028
 
1029
    /**
1030
     * Validation for PARAM_URL.
1031
     *
1032
     * @param mixed $param
1033
     * @return string
1034
     */
1035
    protected function clean_param_value_url(mixed $param): string {
1036
        global $CFG;
1037
 
1038
        // Allow safe urls.
1039
        $param = (string)fix_utf8($param);
1040
        include_once($CFG->dirroot . '/lib/validateurlsyntax.php');
1041
        if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E-u-P-a?I?p?f?q?r?')) {
1042
            // All is ok, param is respected.
1043
        } else {
1044
            // Not really ok.
1045
            $param = '';
1046
        }
1047
        return $param;
1048
    }
1049
 
1050
    /**
1051
     * Validation for PARAM_LOCALURL.
1052
     *
1053
     * @param mixed $param
1054
     * @return string
1055
     */
1056
    protected function clean_param_value_localurl(mixed $param): string {
1057
        global $CFG;
1058
 
1059
        // Allow http absolute, root relative and relative URLs within wwwroot.
1060
        $param = clean_param($param, PARAM_URL);
1061
        if (!empty($param)) {
1062
            if ($param === $CFG->wwwroot) {
1063
                // Exact match.
1064
            } else if (preg_match(':^/:', $param)) {
1065
                // Root-relative, ok!
1066
            } else if (preg_match('/^' . preg_quote($CFG->wwwroot . '/', '/') . '/i', $param)) {
1067
                // Absolute, and matches our wwwroot.
1068
            } else {
1069
                // Relative - let's make sure there are no tricks.
1441 ariadna 1070
                if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?') &&
1071
                        !preg_match('/javascript(?:.*\/{2,})?:/i', rawurldecode($param))) {
1072
                    // Valid relative local URL.
1 efrain 1073
                } else {
1074
                    $param = '';
1075
                }
1076
            }
1077
        }
1078
        return $param;
1079
    }
1080
 
1081
    /**
1082
     * Validation for PARAM_PEM.
1083
     *
1084
     * @param mixed $param
1085
     * @return string
1086
     */
1087
    protected function clean_param_value_pem(mixed $param): string {
1088
        $param = trim((string)$param);
1089
        // PEM formatted strings may contain letters/numbers and the symbols:
1090
        // - forward slash: /
1091
        // - plus sign:     +
1092
        // - equal sign:    =
1093
        // - , surrounded by BEGIN and END CERTIFICATE prefix and suffixes.
1094
        if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
1095
            [$wholething, $body] = $matches;
1096
            unset($wholething, $matches);
1097
            $b64 = clean_param($body, PARAM_BASE64);
1098
            if (!empty($b64)) {
1099
                return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
1100
            } else {
1101
                return '';
1102
            }
1103
        }
1104
        return '';
1105
    }
1106
 
1107
    /**
1108
     * Validation for PARAM_BASE64.
1109
     *
1110
     * @param mixed $param
1111
     * @return string
1112
     */
1113
    protected function clean_param_value_base64(mixed $param): string {
1114
        if (!empty($param)) {
1115
            // PEM formatted strings may contain letters/numbers and the symbols
1116
            // - forward slash: /
1117
            // - plus sign:     +
1118
            // - equal sign:    =.
1119
            if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
1120
                return '';
1121
            }
1122
            $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
1123
            // Each line of base64 encoded data must be 64 characters in length, except for the last line which may be less
1124
            // than (or equal to) 64 characters long.
1125
            for ($i = 0, $j = count($lines); $i < $j; $i++) {
1126
                if ($i + 1 == $j) {
1127
                    if (64 < strlen($lines[$i])) {
1128
                        return '';
1129
                    }
1130
                    continue;
1131
                }
1132
 
1133
                if (64 != strlen($lines[$i])) {
1134
                    return '';
1135
                }
1136
            }
1137
            return implode("\n", $lines);
1138
        } else {
1139
            return '';
1140
        }
1141
    }
1142
 
1143
    /**
1144
     * Validation for PARAM_TAG.
1145
     *
1146
     * @param mixed $param
1147
     * @return string
1148
     */
1149
    protected function clean_param_value_tag(mixed $param): string {
1150
        $param = (string)fix_utf8($param);
1151
        // Please note it is not safe to use the tag name directly anywhere,
1152
        // it must be processed with s(), urlencode() before embedding anywhere.
1153
        // Remove some nasties.
1154
        // phpcs:ignore moodle.Strings.ForbiddenStrings.Found
1155
        $param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param);
1156
        // Convert many whitespace chars into one.
1157
        $param = preg_replace('/\s+/u', ' ', $param);
1158
        $param = core_text::substr(trim($param), 0, TAG_MAX_LENGTH);
1159
        return $param;
1160
    }
1161
 
1162
    /**
1163
     * Validation for PARAM_TAGLIST.
1164
     *
1165
     * @param mixed $param
1166
     * @return string
1167
     */
1168
    protected function clean_param_value_taglist(mixed $param): string {
1169
        $param = (string)fix_utf8($param);
1170
        $tags = explode(',', $param);
1171
        $result = [];
1172
        foreach ($tags as $tag) {
1173
            $res = clean_param($tag, PARAM_TAG);
1174
            if ($res !== '') {
1175
                $result[] = $res;
1176
            }
1177
        }
1178
        if ($result) {
1179
            return implode(',', $result);
1180
        } else {
1181
            return '';
1182
        }
1183
    }
1184
 
1185
    /**
1186
     * Validation for PARAM_CAPABILITY.
1187
     *
1188
     * @param mixed $param
1189
     * @return string
1190
     */
1191
    protected function clean_param_value_capability(mixed $param): string {
1441 ariadna 1192
        if (!empty($param) && get_capability_info($param)) {
1 efrain 1193
            return $param;
1194
        } else {
1195
            return '';
1196
        }
1197
    }
1198
 
1199
    /**
1200
     * Validation for PARAM_PERMISSION.
1201
     *
1202
     * @param mixed $param
1203
     * @return int
1204
     */
1205
    protected function clean_param_value_permission(mixed $param): int {
1206
        $param = (int)$param;
1207
        if (in_array($param, [CAP_INHERIT, CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT])) {
1208
            return $param;
1209
        } else {
1210
            return CAP_INHERIT;
1211
        }
1212
    }
1213
 
1214
    /**
1215
     * Validation for PARAM_AUTH.
1216
     *
1217
     * @param mixed $param
1218
     * @return string
1219
     */
1220
    protected function clean_param_value_auth(mixed $param): string {
1221
        $param = clean_param($param, PARAM_PLUGIN);
1222
        if (empty($param)) {
1223
            return '';
1224
        } else if (exists_auth_plugin($param)) {
1225
            return $param;
1226
        } else {
1227
            return '';
1228
        }
1229
    }
1230
 
1231
    /**
1232
     * Validation for PARAM_LANG.
1233
     *
1234
     * @param mixed $param
1235
     * @return string
1236
     */
1237
    protected function clean_param_value_lang(mixed $param): string {
1238
        $param = clean_param($param, PARAM_SAFEDIR);
1239
        if (get_string_manager()->translation_exists($param)) {
1240
            return $param;
1241
        } else {
1242
            // Specified language is not installed or param malformed.
1243
            return '';
1244
        }
1245
    }
1246
 
1247
    /**
1248
     * Validation for PARAM_THEME.
1249
     *
1250
     * @param mixed $param
1251
     * @return string
1252
     */
1253
    protected function clean_param_value_theme(mixed $param): string {
1254
        global $CFG;
1255
 
1256
        $param = clean_param($param, PARAM_PLUGIN);
1257
        if (empty($param)) {
1258
            return '';
1259
        } else if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
1260
            return $param;
1261
        } else if (!empty($CFG->themedir) && file_exists("$CFG->themedir/$param/config.php")) {
1262
            return $param;
1263
        } else {
1264
            // Specified theme is not installed.
1265
            return '';
1266
        }
1267
    }
1268
 
1269
    /**
1270
     * Validation for PARAM_USERNAME.
1271
     *
1272
     * @param mixed $param
1273
     * @return string
1274
     */
1275
    protected function clean_param_value_username(mixed $param): string {
1276
        global $CFG;
1277
 
1278
        $param = (string)fix_utf8($param);
1279
        $param = trim($param);
1280
        // Convert uppercase to lowercase MDL-16919.
1281
        $param = core_text::strtolower($param);
1282
        if (empty($CFG->extendedusernamechars)) {
1283
            $param = str_replace(" ", "", $param);
1284
            // Regular expression, eliminate all chars EXCEPT:
1285
            // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
1286
            $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
1287
        }
1288
        return $param;
1289
    }
1290
 
1291
    /**
1292
     * Validation for PARAM_EMAIL.
1293
     *
1294
     * @param mixed $param
1295
     * @return string
1296
     */
1297
    protected function clean_param_value_email(mixed $param): string {
1298
        $param = fix_utf8($param);
1299
        if (validate_email($param ?? '')) {
1300
            return $param;
1301
        } else {
1302
            return '';
1303
        }
1304
    }
1305
 
1306
    /**
1307
     * Validation for PARAM_STRINGID.
1308
     *
1309
     * @param mixed $param
1310
     * @return string
1311
     */
1312
    protected function clean_param_value_stringid(mixed $param): string {
1313
        if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', (string)$param)) {
1314
            return $param;
1315
        } else {
1316
            return '';
1317
        }
1318
    }
1319
 
1320
    /**
1321
     * Validation for PARAM_TIMEZONE.
1322
     *
1323
     * @param mixed $param
1324
     * @return string
1325
     */
1326
    protected function clean_param_value_timezone(mixed $param): string {
1327
        // Can be int, float(with .5 or .0) or string seperated by '/' and can have '-_'.
1328
        $param = (string)fix_utf8($param);
1329
        $timezonepattern = '/^(([+-]?(0?[0-9](\.[5|0])?|1[0-3](\.0)?|1[0-2]\.5))|(99)|[[:alnum:]]+(\/?[[:alpha:]_-])+)$/';
1330
        if (preg_match($timezonepattern, $param)) {
1331
            return $param;
1332
        } else {
1333
            return '';
1334
        }
1335
    }
1336
 
1337
    /**
1338
     * Whether the parameter is deprecated.
1339
     *
1340
     * @return bool
1341
     */
1342
    public function is_deprecated(): bool {
1343
        return deprecation::is_deprecated($this);
1344
    }
1345
}