forked from moodle/moodle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
moodlelib.php
9770 lines (8545 loc) · 337 KB
/
moodlelib.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* moodlelib.php - Moodle main library
*
* Main library file of miscellaneous general-purpose Moodle functions.
* Other main libraries:
* - weblib.php - functions that produce web output
* - datalib.php - functions that access the database
*
* @package core
* @subpackage lib
* @copyright 1999 onwards Martin Dougiamas http://dougiamas.com
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
// CONSTANTS (Encased in phpdoc proper comments).
// Date and time constants.
/**
* Time constant - the number of seconds in a year
*/
define('YEARSECS', 31536000);
/**
* Time constant - the number of seconds in a week
*/
define('WEEKSECS', 604800);
/**
* Time constant - the number of seconds in a day
*/
define('DAYSECS', 86400);
/**
* Time constant - the number of seconds in an hour
*/
define('HOURSECS', 3600);
/**
* Time constant - the number of seconds in a minute
*/
define('MINSECS', 60);
/**
* Time constant - the number of minutes in a day
*/
define('DAYMINS', 1440);
/**
* Time constant - the number of minutes in an hour
*/
define('HOURMINS', 60);
// Parameter constants - every call to optional_param(), required_param()
// or clean_param() should have a specified type of parameter.
/**
* PARAM_ALPHA - contains only english ascii letters a-zA-Z.
*/
define('PARAM_ALPHA', 'alpha');
/**
* PARAM_ALPHAEXT the same contents as PARAM_ALPHA plus the chars in quotes: "_-" allowed
* NOTE: originally this allowed "/" too, please use PARAM_SAFEPATH if "/" needed
*/
define('PARAM_ALPHAEXT', 'alphaext');
/**
* PARAM_ALPHANUM - expected numbers and letters only.
*/
define('PARAM_ALPHANUM', 'alphanum');
/**
* PARAM_ALPHANUMEXT - expected numbers, letters only and _-.
*/
define('PARAM_ALPHANUMEXT', 'alphanumext');
/**
* PARAM_AUTH - actually checks to make sure the string is a valid auth plugin
*/
define('PARAM_AUTH', 'auth');
/**
* PARAM_BASE64 - Base 64 encoded format
*/
define('PARAM_BASE64', 'base64');
/**
* PARAM_BOOL - converts input into 0 or 1, use for switches in forms and urls.
*/
define('PARAM_BOOL', 'bool');
/**
* PARAM_CAPABILITY - A capability name, like 'moodle/role:manage'. Actually
* checked against the list of capabilities in the database.
*/
define('PARAM_CAPABILITY', 'capability');
/**
* PARAM_CLEANHTML - cleans submitted HTML code. Note that you almost never want
* to use this. The normal mode of operation is to use PARAM_RAW when recieving
* the input (required/optional_param or formslib) and then sanitse the HTML
* using format_text on output. This is for the rare cases when you want to
* sanitise the HTML on input. This cleaning may also fix xhtml strictness.
*/
define('PARAM_CLEANHTML', 'cleanhtml');
/**
* PARAM_EMAIL - an email address following the RFC
*/
define('PARAM_EMAIL', 'email');
/**
* PARAM_FILE - safe file name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
*/
define('PARAM_FILE', 'file');
/**
* PARAM_FLOAT - a real/floating point number.
*
* Note that you should not use PARAM_FLOAT for numbers typed in by the user.
* It does not work for languages that use , as a decimal separator.
* Instead, do something like
* $rawvalue = required_param('name', PARAM_RAW);
* // ... other code including require_login, which sets current lang ...
* $realvalue = unformat_float($rawvalue);
* // ... then use $realvalue
*/
define('PARAM_FLOAT', 'float');
/**
* PARAM_HOST - expected fully qualified domain name (FQDN) or an IPv4 dotted quad (IP address)
*/
define('PARAM_HOST', 'host');
/**
* PARAM_INT - integers only, use when expecting only numbers.
*/
define('PARAM_INT', 'int');
/**
* PARAM_LANG - checks to see if the string is a valid installed language in the current site.
*/
define('PARAM_LANG', 'lang');
/**
* PARAM_LOCALURL - expected properly formatted URL as well as one that refers to the local server itself. (NOT orthogonal to the
* others! Implies PARAM_URL!)
*/
define('PARAM_LOCALURL', 'localurl');
/**
* PARAM_NOTAGS - all html tags are stripped from the text. Do not abuse this type.
*/
define('PARAM_NOTAGS', 'notags');
/**
* PARAM_PATH - safe relative path name, all dangerous chars are stripped, protects against XSS, SQL injections and directory
* traversals note: the leading slash is not removed, window drive letter is not allowed
*/
define('PARAM_PATH', 'path');
/**
* PARAM_PEM - Privacy Enhanced Mail format
*/
define('PARAM_PEM', 'pem');
/**
* PARAM_PERMISSION - A permission, one of CAP_INHERIT, CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT.
*/
define('PARAM_PERMISSION', 'permission');
/**
* PARAM_RAW specifies a parameter that is not cleaned/processed in any way except the discarding of the invalid utf-8 characters
*/
define('PARAM_RAW', 'raw');
/**
* PARAM_RAW_TRIMMED like PARAM_RAW but leading and trailing whitespace is stripped.
*/
define('PARAM_RAW_TRIMMED', 'raw_trimmed');
/**
* PARAM_SAFEDIR - safe directory name, suitable for include() and require()
*/
define('PARAM_SAFEDIR', 'safedir');
/**
* PARAM_SAFEPATH - several PARAM_SAFEDIR joined by "/", suitable for include() and require(), plugin paths, etc.
*/
define('PARAM_SAFEPATH', 'safepath');
/**
* PARAM_SEQUENCE - expects a sequence of numbers like 8 to 1,5,6,4,6,8,9. Numbers and comma only.
*/
define('PARAM_SEQUENCE', 'sequence');
/**
* PARAM_TAG - one tag (interests, blogs, etc.) - mostly international characters and space, <> not supported
*/
define('PARAM_TAG', 'tag');
/**
* PARAM_TAGLIST - list of tags separated by commas (interests, blogs, etc.)
*/
define('PARAM_TAGLIST', 'taglist');
/**
* PARAM_TEXT - general plain text compatible with multilang filter, no other html tags. Please note '<', or '>' are allowed here.
*/
define('PARAM_TEXT', 'text');
/**
* PARAM_THEME - Checks to see if the string is a valid theme name in the current site
*/
define('PARAM_THEME', 'theme');
/**
* PARAM_URL - expected properly formatted URL. Please note that domain part is required, http://localhost/ is not accepted but
* http://localhost.localdomain/ is ok.
*/
define('PARAM_URL', 'url');
/**
* PARAM_USERNAME - Clean username to only contains allowed characters. This is to be used ONLY when manually creating user
* accounts, do NOT use when syncing with external systems!!
*/
define('PARAM_USERNAME', 'username');
/**
* PARAM_STRINGID - used to check if the given string is valid string identifier for get_string()
*/
define('PARAM_STRINGID', 'stringid');
// DEPRECATED PARAM TYPES OR ALIASES - DO NOT USE FOR NEW CODE.
/**
* PARAM_CLEAN - obsoleted, please use a more specific type of parameter.
* It was one of the first types, that is why it is abused so much ;-)
* @deprecated since 2.0
*/
define('PARAM_CLEAN', 'clean');
/**
* PARAM_INTEGER - deprecated alias for PARAM_INT
* @deprecated since 2.0
*/
define('PARAM_INTEGER', 'int');
/**
* PARAM_NUMBER - deprecated alias of PARAM_FLOAT
* @deprecated since 2.0
*/
define('PARAM_NUMBER', 'float');
/**
* PARAM_ACTION - deprecated alias for PARAM_ALPHANUMEXT, use for various actions in forms and urls
* NOTE: originally alias for PARAM_APLHA
* @deprecated since 2.0
*/
define('PARAM_ACTION', 'alphanumext');
/**
* PARAM_FORMAT - deprecated alias for PARAM_ALPHANUMEXT, use for names of plugins, formats, etc.
* NOTE: originally alias for PARAM_APLHA
* @deprecated since 2.0
*/
define('PARAM_FORMAT', 'alphanumext');
/**
* PARAM_MULTILANG - deprecated alias of PARAM_TEXT.
* @deprecated since 2.0
*/
define('PARAM_MULTILANG', 'text');
/**
* PARAM_TIMEZONE - expected timezone. Timezone can be int +-(0-13) or float +-(0.5-12.5) or
* string separated by '/' and can have '-' &/ '_' (eg. America/North_Dakota/New_Salem
* America/Port-au-Prince)
*/
define('PARAM_TIMEZONE', 'timezone');
/**
* PARAM_CLEANFILE - deprecated alias of PARAM_FILE; originally was removing regional chars too
*/
define('PARAM_CLEANFILE', 'file');
/**
* PARAM_COMPONENT is used for full component names (aka frankenstyle) such as 'mod_forum', 'core_rating', 'auth_ldap'.
* Short legacy subsystem names and module names are accepted too ex: 'forum', 'rating', 'user'.
* Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
* NOTE: numbers and underscores are strongly discouraged in plugin names!
*/
define('PARAM_COMPONENT', 'component');
/**
* PARAM_AREA is a name of area used when addressing files, comments, ratings, etc.
* It is usually used together with context id and component.
* Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
*/
define('PARAM_AREA', 'area');
/**
* PARAM_PLUGIN is used for plugin names such as 'forum', 'glossary', 'ldap', 'radius', 'paypal', 'completionstatus'.
* Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
* NOTE: numbers and underscores are strongly discouraged in plugin names! Underscores are forbidden in module names.
*/
define('PARAM_PLUGIN', 'plugin');
// Web Services.
/**
* VALUE_REQUIRED - if the parameter is not supplied, there is an error
*/
define('VALUE_REQUIRED', 1);
/**
* VALUE_OPTIONAL - if the parameter is not supplied, then the param has no value
*/
define('VALUE_OPTIONAL', 2);
/**
* VALUE_DEFAULT - if the parameter is not supplied, then the default value is used
*/
define('VALUE_DEFAULT', 0);
/**
* NULL_NOT_ALLOWED - the parameter can not be set to null in the database
*/
define('NULL_NOT_ALLOWED', false);
/**
* NULL_ALLOWED - the parameter can be set to null in the database
*/
define('NULL_ALLOWED', true);
// Page types.
/**
* PAGE_COURSE_VIEW is a definition of a page type. For more information on the page class see moodle/lib/pagelib.php.
*/
define('PAGE_COURSE_VIEW', 'course-view');
/** Get remote addr constant */
define('GETREMOTEADDR_SKIP_HTTP_CLIENT_IP', '1');
/** Get remote addr constant */
define('GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR', '2');
// Blog access level constant declaration.
define ('BLOG_USER_LEVEL', 1);
define ('BLOG_GROUP_LEVEL', 2);
define ('BLOG_COURSE_LEVEL', 3);
define ('BLOG_SITE_LEVEL', 4);
define ('BLOG_GLOBAL_LEVEL', 5);
// Tag constants.
/**
* To prevent problems with multibytes strings,Flag updating in nav not working on the review page. this should not exceed the
* length of "varchar(255) / 3 (bytes / utf-8 character) = 85".
* TODO: this is not correct, varchar(255) are 255 unicode chars ;-)
*
* @todo define(TAG_MAX_LENGTH) this is not correct, varchar(255) are 255 unicode chars ;-)
*/
define('TAG_MAX_LENGTH', 50);
// Password policy constants.
define ('PASSWORD_LOWER', 'abcdefghijklmnopqrstuvwxyz');
define ('PASSWORD_UPPER', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
define ('PASSWORD_DIGITS', '0123456789');
define ('PASSWORD_NONALPHANUM', '.,;:!?_-+/*@#&$');
// Feature constants.
// Used for plugin_supports() to report features that are, or are not, supported by a module.
/** True if module can provide a grade */
define('FEATURE_GRADE_HAS_GRADE', 'grade_has_grade');
/** True if module supports outcomes */
define('FEATURE_GRADE_OUTCOMES', 'outcomes');
/** True if module supports advanced grading methods */
define('FEATURE_ADVANCED_GRADING', 'grade_advanced_grading');
/** True if module controls the grade visibility over the gradebook */
define('FEATURE_CONTROLS_GRADE_VISIBILITY', 'controlsgradevisbility');
/** True if module supports plagiarism plugins */
define('FEATURE_PLAGIARISM', 'plagiarism');
/** True if module has code to track whether somebody viewed it */
define('FEATURE_COMPLETION_TRACKS_VIEWS', 'completion_tracks_views');
/** True if module has custom completion rules */
define('FEATURE_COMPLETION_HAS_RULES', 'completion_has_rules');
/** True if module has no 'view' page (like label) */
define('FEATURE_NO_VIEW_LINK', 'viewlink');
/** True if module supports outcomes */
define('FEATURE_IDNUMBER', 'idnumber');
/** True if module supports groups */
define('FEATURE_GROUPS', 'groups');
/** True if module supports groupings */
define('FEATURE_GROUPINGS', 'groupings');
/** True if module supports groupmembersonly */
define('FEATURE_GROUPMEMBERSONLY', 'groupmembersonly');
/** Type of module */
define('FEATURE_MOD_ARCHETYPE', 'mod_archetype');
/** True if module supports intro editor */
define('FEATURE_MOD_INTRO', 'mod_intro');
/** True if module has default completion */
define('FEATURE_MODEDIT_DEFAULT_COMPLETION', 'modedit_default_completion');
define('FEATURE_COMMENT', 'comment');
define('FEATURE_RATE', 'rate');
/** True if module supports backup/restore of moodle2 format */
define('FEATURE_BACKUP_MOODLE2', 'backup_moodle2');
/** True if module can show description on course main page */
define('FEATURE_SHOW_DESCRIPTION', 'showdescription');
/** True if module uses the question bank */
define('FEATURE_USES_QUESTIONS', 'usesquestions');
/** Unspecified module archetype */
define('MOD_ARCHETYPE_OTHER', 0);
/** Resource-like type module */
define('MOD_ARCHETYPE_RESOURCE', 1);
/** Assignment module archetype */
define('MOD_ARCHETYPE_ASSIGNMENT', 2);
/** System (not user-addable) module archetype */
define('MOD_ARCHETYPE_SYSTEM', 3);
/** Return this from modname_get_types callback to use default display in activity chooser */
define('MOD_SUBTYPE_NO_CHILDREN', 'modsubtypenochildren');
/**
* Security token used for allowing access
* from external application such as web services.
* Scripts do not use any session, performance is relatively
* low because we need to load access info in each request.
* Scripts are executed in parallel.
*/
define('EXTERNAL_TOKEN_PERMANENT', 0);
/**
* Security token used for allowing access
* of embedded applications, the code is executed in the
* active user session. Token is invalidated after user logs out.
* Scripts are executed serially - normal session locking is used.
*/
define('EXTERNAL_TOKEN_EMBEDDED', 1);
/**
* The home page should be the site home
*/
define('HOMEPAGE_SITE', 0);
/**
* The home page should be the users my page
*/
define('HOMEPAGE_MY', 1);
/**
* The home page can be chosen by the user
*/
define('HOMEPAGE_USER', 2);
/**
* Hub directory url (should be moodle.org)
*/
define('HUB_HUBDIRECTORYURL', "http://hubdirectory.moodle.org");
/**
* Moodle.org url (should be moodle.org)
*/
define('HUB_MOODLEORGHUBURL', "http://hub.moodle.org");
/**
* Moodle mobile app service name
*/
define('MOODLE_OFFICIAL_MOBILE_SERVICE', 'moodle_mobile_app');
/**
* Indicates the user has the capabilities required to ignore activity and course file size restrictions
*/
define('USER_CAN_IGNORE_FILE_SIZE_LIMITS', -1);
/**
* Course display settings: display all sections on one page.
*/
define('COURSE_DISPLAY_SINGLEPAGE', 0);
/**
* Course display settings: split pages into a page per section.
*/
define('COURSE_DISPLAY_MULTIPAGE', 1);
/**
* Authentication constant: String used in password field when password is not stored.
*/
define('AUTH_PASSWORD_NOT_CACHED', 'not cached');
// PARAMETER HANDLING.
/**
* Returns a particular value for the named variable, taken from
* POST or GET. If the parameter doesn't exist then an error is
* thrown because we require this variable.
*
* This function should be used to initialise all required values
* in a script that are based on parameters. Usually it will be
* used like this:
* $id = required_param('id', PARAM_INT);
*
* Please note the $type parameter is now required and the value can not be array.
*
* @param string $parname the name of the page parameter we want
* @param string $type expected type of parameter
* @return mixed
* @throws coding_exception
*/
function required_param($parname, $type) {
if (func_num_args() != 2 or empty($parname) or empty($type)) {
throw new coding_exception('required_param() requires $parname and $type to be specified (parameter: '.$parname.')');
}
// POST has precedence.
if (isset($_POST[$parname])) {
$param = $_POST[$parname];
} else if (isset($_GET[$parname])) {
$param = $_GET[$parname];
} else {
print_error('missingparam', '', '', $parname);
}
if (is_array($param)) {
debugging('Invalid array parameter detected in required_param(): '.$parname);
// TODO: switch to fatal error in Moodle 2.3.
return required_param_array($parname, $type);
}
return clean_param($param, $type);
}
/**
* Returns a particular array value for the named variable, taken from
* POST or GET. If the parameter doesn't exist then an error is
* thrown because we require this variable.
*
* This function should be used to initialise all required values
* in a script that are based on parameters. Usually it will be
* used like this:
* $ids = required_param_array('ids', PARAM_INT);
*
* Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
*
* @param string $parname the name of the page parameter we want
* @param string $type expected type of parameter
* @return array
* @throws coding_exception
*/
function required_param_array($parname, $type) {
if (func_num_args() != 2 or empty($parname) or empty($type)) {
throw new coding_exception('required_param_array() requires $parname and $type to be specified (parameter: '.$parname.')');
}
// POST has precedence.
if (isset($_POST[$parname])) {
$param = $_POST[$parname];
} else if (isset($_GET[$parname])) {
$param = $_GET[$parname];
} else {
print_error('missingparam', '', '', $parname);
}
if (!is_array($param)) {
print_error('missingparam', '', '', $parname);
}
$result = array();
foreach ($param as $key => $value) {
if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
debugging('Invalid key name in required_param_array() detected: '.$key.', parameter: '.$parname);
continue;
}
$result[$key] = clean_param($value, $type);
}
return $result;
}
/**
* Returns a particular value for the named variable, taken from
* POST or GET, otherwise returning a given default.
*
* This function should be used to initialise all optional values
* in a script that are based on parameters. Usually it will be
* used like this:
* $name = optional_param('name', 'Fred', PARAM_TEXT);
*
* Please note the $type parameter is now required and the value can not be array.
*
* @param string $parname the name of the page parameter we want
* @param mixed $default the default value to return if nothing is found
* @param string $type expected type of parameter
* @return mixed
* @throws coding_exception
*/
function optional_param($parname, $default, $type) {
if (func_num_args() != 3 or empty($parname) or empty($type)) {
throw new coding_exception('optional_param requires $parname, $default + $type to be specified (parameter: '.$parname.')');
}
if (!isset($default)) {
$default = null;
}
// POST has precedence.
if (isset($_POST[$parname])) {
$param = $_POST[$parname];
} else if (isset($_GET[$parname])) {
$param = $_GET[$parname];
} else {
return $default;
}
if (is_array($param)) {
debugging('Invalid array parameter detected in required_param(): '.$parname);
// TODO: switch to $default in Moodle 2.3.
return optional_param_array($parname, $default, $type);
}
return clean_param($param, $type);
}
/**
* Returns a particular array value for the named variable, taken from
* POST or GET, otherwise returning a given default.
*
* This function should be used to initialise all optional values
* in a script that are based on parameters. Usually it will be
* used like this:
* $ids = optional_param('id', array(), PARAM_INT);
*
* Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
*
* @param string $parname the name of the page parameter we want
* @param mixed $default the default value to return if nothing is found
* @param string $type expected type of parameter
* @return array
* @throws coding_exception
*/
function optional_param_array($parname, $default, $type) {
if (func_num_args() != 3 or empty($parname) or empty($type)) {
throw new coding_exception('optional_param_array requires $parname, $default + $type to be specified (parameter: '.$parname.')');
}
// POST has precedence.
if (isset($_POST[$parname])) {
$param = $_POST[$parname];
} else if (isset($_GET[$parname])) {
$param = $_GET[$parname];
} else {
return $default;
}
if (!is_array($param)) {
debugging('optional_param_array() expects array parameters only: '.$parname);
return $default;
}
$result = array();
foreach ($param as $key => $value) {
if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
debugging('Invalid key name in optional_param_array() detected: '.$key.', parameter: '.$parname);
continue;
}
$result[$key] = clean_param($value, $type);
}
return $result;
}
/**
* Strict validation of parameter values, the values are only converted
* to requested PHP type. Internally it is using clean_param, the values
* before and after cleaning must be equal - otherwise
* an invalid_parameter_exception is thrown.
* Objects and classes are not accepted.
*
* @param mixed $param
* @param string $type PARAM_ constant
* @param bool $allownull are nulls valid value?
* @param string $debuginfo optional debug information
* @return mixed the $param value converted to PHP type
* @throws invalid_parameter_exception if $param is not of given type
*/
function validate_param($param, $type, $allownull=NULL_NOT_ALLOWED, $debuginfo='') {
if (is_null($param)) {
if ($allownull == NULL_ALLOWED) {
return null;
} else {
throw new invalid_parameter_exception($debuginfo);
}
}
if (is_array($param) or is_object($param)) {
throw new invalid_parameter_exception($debuginfo);
}
$cleaned = clean_param($param, $type);
if ($type == PARAM_FLOAT) {
// Do not detect precision loss here.
if (is_float($param) or is_int($param)) {
// These always fit.
} else if (!is_numeric($param) or !preg_match('/^[\+-]?[0-9]*\.?[0-9]*(e[-+]?[0-9]+)?$/i', (string)$param)) {
throw new invalid_parameter_exception($debuginfo);
}
} else if ((string)$param !== (string)$cleaned) {
// Conversion to string is usually lossless.
throw new invalid_parameter_exception($debuginfo);
}
return $cleaned;
}
/**
* Makes sure array contains only the allowed types, this function does not validate array key names!
*
* <code>
* $options = clean_param($options, PARAM_INT);
* </code>
*
* @param array $param the variable array we are cleaning
* @param string $type expected format of param after cleaning.
* @param bool $recursive clean recursive arrays
* @return array
* @throws coding_exception
*/
function clean_param_array(array $param = null, $type, $recursive = false) {
// Convert null to empty array.
$param = (array)$param;
foreach ($param as $key => $value) {
if (is_array($value)) {
if ($recursive) {
$param[$key] = clean_param_array($value, $type, true);
} else {
throw new coding_exception('clean_param_array can not process multidimensional arrays when $recursive is false.');
}
} else {
$param[$key] = clean_param($value, $type);
}
}
return $param;
}
/**
* Used by {@link optional_param()} and {@link required_param()} to
* clean the variables and/or cast to specific types, based on
* an options field.
* <code>
* $course->format = clean_param($course->format, PARAM_ALPHA);
* $selectedgradeitem = clean_param($selectedgradeitem, PARAM_INT);
* </code>
*
* @param mixed $param the variable we are cleaning
* @param string $type expected format of param after cleaning.
* @return mixed
* @throws coding_exception
*/
function clean_param($param, $type) {
global $CFG;
if (is_array($param)) {
throw new coding_exception('clean_param() can not process arrays, please use clean_param_array() instead.');
} else if (is_object($param)) {
if (method_exists($param, '__toString')) {
$param = $param->__toString();
} else {
throw new coding_exception('clean_param() can not process objects, please use clean_param_array() instead.');
}
}
switch ($type) {
case PARAM_RAW:
// No cleaning at all.
$param = fix_utf8($param);
return $param;
case PARAM_RAW_TRIMMED:
// No cleaning, but strip leading and trailing whitespace.
$param = fix_utf8($param);
return trim($param);
case PARAM_CLEAN:
// General HTML cleaning, try to use more specific type if possible this is deprecated!
// Please use more specific type instead.
if (is_numeric($param)) {
return $param;
}
$param = fix_utf8($param);
// Sweep for scripts, etc.
return clean_text($param);
case PARAM_CLEANHTML:
// Clean html fragment.
$param = fix_utf8($param);
// Sweep for scripts, etc.
$param = clean_text($param, FORMAT_HTML);
return trim($param);
case PARAM_INT:
// Convert to integer.
return (int)$param;
case PARAM_FLOAT:
// Convert to float.
return (float)$param;
case PARAM_ALPHA:
// Remove everything not `a-z`.
return preg_replace('/[^a-zA-Z]/i', '', $param);
case PARAM_ALPHAEXT:
// Remove everything not `a-zA-Z_-` (originally allowed "/" too).
return preg_replace('/[^a-zA-Z_-]/i', '', $param);
case PARAM_ALPHANUM:
// Remove everything not `a-zA-Z0-9`.
return preg_replace('/[^A-Za-z0-9]/i', '', $param);
case PARAM_ALPHANUMEXT:
// Remove everything not `a-zA-Z0-9_-`.
return preg_replace('/[^A-Za-z0-9_-]/i', '', $param);
case PARAM_SEQUENCE:
// Remove everything not `0-9,`.
return preg_replace('/[^0-9,]/i', '', $param);
case PARAM_BOOL:
// Convert to 1 or 0.
$tempstr = strtolower($param);
if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
$param = 1;
} else if ($tempstr === 'off' or $tempstr === 'no' or $tempstr === 'false') {
$param = 0;
} else {
$param = empty($param) ? 0 : 1;
}
return $param;
case PARAM_NOTAGS:
// Strip all tags.
$param = fix_utf8($param);
return strip_tags($param);
case PARAM_TEXT:
// Leave only tags needed for multilang.
$param = fix_utf8($param);
// If the multilang syntax is not correct we strip all tags because it would break xhtml strict which is required
// for accessibility standards please note this cleaning does not strip unbalanced '>' for BC compatibility reasons.
do {
if (strpos($param, '</lang>') !== false) {
// Old and future mutilang syntax.
$param = strip_tags($param, '<lang>');
if (!preg_match_all('/<.*>/suU', $param, $matches)) {
break;
}
$open = false;
foreach ($matches[0] as $match) {
if ($match === '</lang>') {
if ($open) {
$open = false;
continue;
} else {
break 2;
}
}
if (!preg_match('/^<lang lang="[a-zA-Z0-9_-]+"\s*>$/u', $match)) {
break 2;
} else {
$open = true;
}
}
if ($open) {
break;
}
return $param;
} else if (strpos($param, '</span>') !== false) {
// Current problematic multilang syntax.
$param = strip_tags($param, '<span>');
if (!preg_match_all('/<.*>/suU', $param, $matches)) {
break;
}
$open = false;
foreach ($matches[0] as $match) {
if ($match === '</span>') {
if ($open) {
$open = false;
continue;
} else {
break 2;
}
}
if (!preg_match('/^<span(\s+lang="[a-zA-Z0-9_-]+"|\s+class="multilang"){2}\s*>$/u', $match)) {
break 2;
} else {
$open = true;
}
}
if ($open) {
break;
}
return $param;
}
} while (false);
// Easy, just strip all tags, if we ever want to fix orphaned '&' we have to do that in format_string().
return strip_tags($param);
case PARAM_COMPONENT:
// We do not want any guessing here, either the name is correct or not
// please note only normalised component names are accepted.
if (!preg_match('/^[a-z]+(_[a-z][a-z0-9_]*)?[a-z0-9]+$/', $param)) {
return '';
}
if (strpos($param, '__') !== false) {
return '';
}
if (strpos($param, 'mod_') === 0) {
// Module names must not contain underscores because we need to differentiate them from invalid plugin types.
if (substr_count($param, '_') != 1) {
return '';
}
}
return $param;
case PARAM_PLUGIN:
case PARAM_AREA:
// We do not want any guessing here, either the name is correct or not.
if (!is_valid_plugin_name($param)) {
return '';
}
return $param;
case PARAM_SAFEDIR:
// Remove everything not a-zA-Z0-9_- .
return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
case PARAM_SAFEPATH:
// Remove everything not a-zA-Z0-9/_- .
return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);
case PARAM_FILE:
// Strip all suspicious characters from filename.
$param = fix_utf8($param);
$param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
if ($param === '.' || $param === '..') {
$param = '';
}
return $param;
case PARAM_PATH:
// Strip all suspicious characters from file path.
$param = fix_utf8($param);
$param = str_replace('\\', '/', $param);
// Explode the path and clean each element using the PARAM_FILE rules.
$breadcrumb = explode('/', $param);
foreach ($breadcrumb as $key => $crumb) {
if ($crumb === '.' && $key === 0) {
// Special condition to allow for relative current path such as ./currentdirfile.txt.
} else {
$crumb = clean_param($crumb, PARAM_FILE);
}
$breadcrumb[$key] = $crumb;
}
$param = implode('/', $breadcrumb);
// Remove multiple current path (./././) and multiple slashes (///).
$param = preg_replace('~//+~', '/', $param);
$param = preg_replace('~/(\./)+~', '/', $param);
return $param;
case PARAM_HOST:
// Allow FQDN or IPv4 dotted quad.
$param = preg_replace('/[^\.\d\w-]/', '', $param );
// Match ipv4 dotted quad.
if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/', $param, $match)) {
// Confirm values are ok.
if ( $match[0] > 255
|| $match[1] > 255