Proyectos de Subversion Moodle

Rev

Rev 11 | Ir a la última revisión | | 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
/**
18
 * moodlelib.php - Moodle main library
19
 *
20
 * Main library file of miscellaneous general-purpose Moodle functions.
21
 * Other main libraries:
22
 *  - weblib.php      - functions that produce web output
23
 *  - datalib.php     - functions that access the database
24
 *
25
 * @package    core
26
 * @subpackage lib
27
 * @copyright  1999 onwards Martin Dougiamas  http://dougiamas.com
28
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
29
 */
30
 
31
use core\di;
32
use core\hook;
33
 
34
defined('MOODLE_INTERNAL') || die();
35
 
36
// CONSTANTS (Encased in phpdoc proper comments).
37
 
38
// Date and time constants.
39
/**
40
 * Time constant - the number of seconds in a year
41
 */
42
define('YEARSECS', 31536000);
43
 
44
/**
45
 * Time constant - the number of seconds in a week
46
 */
47
define('WEEKSECS', 604800);
48
 
49
/**
50
 * Time constant - the number of seconds in a day
51
 */
52
define('DAYSECS', 86400);
53
 
54
/**
55
 * Time constant - the number of seconds in an hour
56
 */
57
define('HOURSECS', 3600);
58
 
59
/**
60
 * Time constant - the number of seconds in a minute
61
 */
62
define('MINSECS', 60);
63
 
64
/**
65
 * Time constant - the number of minutes in a day
66
 */
67
define('DAYMINS', 1440);
68
 
69
/**
70
 * Time constant - the number of minutes in an hour
71
 */
72
define('HOURMINS', 60);
73
 
74
// Parameter constants - every call to optional_param(), required_param()
75
// or clean_param() should have a specified type of parameter.
76
 
77
// We currently include \core\param manually here to avoid broken upgrades.
78
// This may change after the next LTS release as LTS releases require the previous LTS release.
79
require_once(__DIR__ . '/classes/deprecation.php');
80
require_once(__DIR__ . '/classes/param.php');
81
 
82
/**
83
 * PARAM_ALPHA - contains only English ascii letters [a-zA-Z].
84
 */
85
define('PARAM_ALPHA', \core\param::ALPHA->value);
86
 
87
/**
88
 * PARAM_ALPHAEXT the same contents as PARAM_ALPHA (English ascii letters [a-zA-Z]) plus the chars in quotes: "_-" allowed
89
 * NOTE: originally this allowed "/" too, please use PARAM_SAFEPATH if "/" needed
90
 */
91
define('PARAM_ALPHAEXT', \core\param::ALPHAEXT->value);
92
 
93
/**
94
 * PARAM_ALPHANUM - expected numbers 0-9 and English ascii letters [a-zA-Z] only.
95
 */
96
define('PARAM_ALPHANUM', \core\param::ALPHANUM->value);
97
 
98
/**
99
 * PARAM_ALPHANUMEXT - expected numbers 0-9, letters (English ascii letters [a-zA-Z]) and _- only.
100
 */
101
define('PARAM_ALPHANUMEXT', \core\param::ALPHANUMEXT->value);
102
 
103
/**
104
 * PARAM_AUTH - actually checks to make sure the string is a valid auth plugin
105
 */
106
define('PARAM_AUTH', \core\param::AUTH->value);
107
 
108
/**
109
 * PARAM_BASE64 - Base 64 encoded format
110
 */
111
define('PARAM_BASE64', \core\param::BASE64->value);
112
 
113
/**
114
 * PARAM_BOOL - converts input into 0 or 1, use for switches in forms and urls.
115
 */
116
define('PARAM_BOOL', \core\param::BOOL->value);
117
 
118
/**
119
 * PARAM_CAPABILITY - A capability name, like 'moodle/role:manage'. Actually
120
 * checked against the list of capabilities in the database.
121
 */
122
define('PARAM_CAPABILITY', \core\param::CAPABILITY->value);
123
 
124
/**
125
 * PARAM_CLEANHTML - cleans submitted HTML code. Note that you almost never want
126
 * to use this. The normal mode of operation is to use PARAM_RAW when receiving
127
 * the input (required/optional_param or formslib) and then sanitise the HTML
128
 * using format_text on output. This is for the rare cases when you want to
129
 * sanitise the HTML on input. This cleaning may also fix xhtml strictness.
130
 */
131
define('PARAM_CLEANHTML', \core\param::CLEANHTML->value);
132
 
133
/**
134
 * PARAM_EMAIL - an email address following the RFC
135
 */
136
define('PARAM_EMAIL', \core\param::EMAIL->value);
137
 
138
/**
139
 * PARAM_FILE - safe file name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
140
 */
141
define('PARAM_FILE', \core\param::FILE->value);
142
 
143
/**
144
 * PARAM_FLOAT - a real/floating point number.
145
 *
146
 * Note that you should not use PARAM_FLOAT for numbers typed in by the user.
147
 * It does not work for languages that use , as a decimal separator.
148
 * Use PARAM_LOCALISEDFLOAT instead.
149
 */
150
define('PARAM_FLOAT', \core\param::FLOAT->value);
151
 
152
/**
153
 * PARAM_LOCALISEDFLOAT - a localised real/floating point number.
154
 * This is preferred over PARAM_FLOAT for numbers typed in by the user.
155
 * Cleans localised numbers to computer readable numbers; false for invalid numbers.
156
 */
157
define('PARAM_LOCALISEDFLOAT', \core\param::LOCALISEDFLOAT->value);
158
 
159
/**
160
 * PARAM_HOST - expected fully qualified domain name (FQDN) or an IPv4 dotted quad (IP address)
161
 */
162
define('PARAM_HOST', \core\param::HOST->value);
163
 
164
/**
165
 * PARAM_INT - integers only, use when expecting only numbers.
166
 */
167
define('PARAM_INT', \core\param::INT->value);
168
 
169
/**
170
 * PARAM_LANG - checks to see if the string is a valid installed language in the current site.
171
 */
172
define('PARAM_LANG', \core\param::LANG->value);
173
 
174
/**
175
 * PARAM_LOCALURL - expected properly formatted URL as well as one that refers to the local server itself. (NOT orthogonal to the
176
 * others! Implies PARAM_URL!)
177
 */
178
define('PARAM_LOCALURL', \core\param::LOCALURL->value);
179
 
180
/**
181
 * PARAM_NOTAGS - all html tags are stripped from the text. Do not abuse this type.
182
 */
183
define('PARAM_NOTAGS', \core\param::NOTAGS->value);
184
 
185
/**
186
 * PARAM_PATH - safe relative path name, all dangerous chars are stripped, protects against XSS, SQL injections and directory
187
 * traversals note: the leading slash is not removed, window drive letter is not allowed
188
 */
189
define('PARAM_PATH', \core\param::PATH->value);
190
 
191
/**
192
 * PARAM_PEM - Privacy Enhanced Mail format
193
 */
194
define('PARAM_PEM', \core\param::PEM->value);
195
 
196
/**
197
 * PARAM_PERMISSION - A permission, one of CAP_INHERIT, CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT.
198
 */
199
define('PARAM_PERMISSION', \core\param::PERMISSION->value);
200
 
201
/**
202
 * PARAM_RAW specifies a parameter that is not cleaned/processed in any way except the discarding of the invalid utf-8 characters
203
 */
204
define('PARAM_RAW', \core\param::RAW->value);
205
 
206
/**
207
 * PARAM_RAW_TRIMMED like PARAM_RAW but leading and trailing whitespace is stripped.
208
 */
209
define('PARAM_RAW_TRIMMED', \core\param::RAW_TRIMMED->value);
210
 
211
/**
212
 * PARAM_SAFEDIR - safe directory name, suitable for include() and require()
213
 */
214
define('PARAM_SAFEDIR', \core\param::SAFEDIR->value);
215
 
216
/**
217
 * PARAM_SAFEPATH - several PARAM_SAFEDIR joined by "/", suitable for include() and require(), plugin paths
218
 * and other references to Moodle code files.
219
 *
220
 * This is NOT intended to be used for absolute paths or any user uploaded files.
221
 */
222
define('PARAM_SAFEPATH', \core\param::SAFEPATH->value);
223
 
224
/**
225
 * PARAM_SEQUENCE - expects a sequence of numbers like 8 to 1,5,6,4,6,8,9.  Numbers and comma only.
226
 */
227
define('PARAM_SEQUENCE', \core\param::SEQUENCE->value);
228
 
229
/**
230
 * PARAM_TAG - one tag (interests, blogs, etc.) - mostly international characters and space, <> not supported
231
 */
232
define('PARAM_TAG', \core\param::TAG->value);
233
 
234
/**
235
 * PARAM_TAGLIST - list of tags separated by commas (interests, blogs, etc.)
236
 */
237
define('PARAM_TAGLIST', \core\param::TAGLIST->value);
238
 
239
/**
240
 * PARAM_TEXT - general plain text compatible with multilang filter, no other html tags. Please note '<', or '>' are allowed here.
241
 */
242
define('PARAM_TEXT', \core\param::TEXT->value);
243
 
244
/**
245
 * PARAM_THEME - Checks to see if the string is a valid theme name in the current site
246
 */
247
define('PARAM_THEME', \core\param::THEME->value);
248
 
249
/**
250
 * PARAM_URL - expected properly formatted URL. Please note that domain part is required, http://localhost/ is not accepted but
251
 * http://localhost.localdomain/ is ok.
252
 */
253
define('PARAM_URL', \core\param::URL->value);
254
 
255
/**
256
 * PARAM_USERNAME - Clean username to only contains allowed characters. This is to be used ONLY when manually creating user
257
 * accounts, do NOT use when syncing with external systems!!
258
 */
259
define('PARAM_USERNAME', \core\param::USERNAME->value);
260
 
261
/**
262
 * PARAM_STRINGID - used to check if the given string is valid string identifier for get_string()
263
 */
264
define('PARAM_STRINGID', \core\param::STRINGID->value);
265
 
266
// DEPRECATED PARAM TYPES OR ALIASES - DO NOT USE FOR NEW CODE.
267
/**
268
 * PARAM_CLEAN - obsoleted, please use a more specific type of parameter.
269
 * It was one of the first types, that is why it is abused so much ;-)
270
 * @deprecated since 2.0
271
 */
272
define('PARAM_CLEAN', \core\param::CLEAN->value);
273
 
274
/**
275
 * PARAM_INTEGER - deprecated alias for PARAM_INT
276
 * @deprecated since 2.0
277
 */
278
define('PARAM_INTEGER', \core\param::INT->value);
279
 
280
/**
281
 * PARAM_NUMBER - deprecated alias of PARAM_FLOAT
282
 * @deprecated since 2.0
283
 */
284
define('PARAM_NUMBER', \core\param::FLOAT->value);
285
 
286
/**
287
 * PARAM_ACTION - deprecated alias for PARAM_ALPHANUMEXT, use for various actions in forms and urls
288
 * NOTE: originally alias for PARAM_APLHA
289
 * @deprecated since 2.0
290
 */
291
define('PARAM_ACTION', \core\param::ALPHANUMEXT->value);
292
 
293
/**
294
 * PARAM_FORMAT - deprecated alias for PARAM_ALPHANUMEXT, use for names of plugins, formats, etc.
295
 * NOTE: originally alias for PARAM_APLHA
296
 * @deprecated since 2.0
297
 */
298
define('PARAM_FORMAT', \core\param::ALPHANUMEXT->value);
299
 
300
/**
301
 * PARAM_MULTILANG - deprecated alias of PARAM_TEXT.
302
 * @deprecated since 2.0
303
 */
304
define('PARAM_MULTILANG', \core\param::TEXT->value);
305
 
306
/**
307
 * PARAM_TIMEZONE - expected timezone. Timezone can be int +-(0-13) or float +-(0.5-12.5) or
308
 * string separated by '/' and can have '-' &/ '_' (eg. America/North_Dakota/New_Salem
309
 * America/Port-au-Prince)
310
 */
311
define('PARAM_TIMEZONE', \core\param::TIMEZONE->value);
312
 
313
/**
314
 * PARAM_CLEANFILE - deprecated alias of PARAM_FILE; originally was removing regional chars too
315
 * @deprecated since 2.0
316
 */
317
define('PARAM_CLEANFILE', \core\param::CLEANFILE->value);
318
 
319
/**
320
 * PARAM_COMPONENT is used for full component names (aka frankenstyle) such as 'mod_forum', 'core_rating', 'auth_ldap'.
321
 * Short legacy subsystem names and module names are accepted too ex: 'forum', 'rating', 'user'.
322
 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
323
 * NOTE: numbers and underscores are strongly discouraged in plugin names!
324
 */
325
define('PARAM_COMPONENT', \core\param::COMPONENT->value);
326
 
327
/**
328
 * PARAM_AREA is a name of area used when addressing files, comments, ratings, etc.
329
 * It is usually used together with context id and component.
330
 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
331
 */
332
define('PARAM_AREA', \core\param::AREA->value);
333
 
334
/**
335
 * PARAM_PLUGIN is used for plugin names such as 'forum', 'glossary', 'ldap', 'paypal', 'completionstatus'.
336
 * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
337
 * NOTE: numbers and underscores are strongly discouraged in plugin names! Underscores are forbidden in module names.
338
 */
339
define('PARAM_PLUGIN', \core\param::PLUGIN->value);
340
 
341
 
342
// Web Services.
343
 
344
/**
345
 * VALUE_REQUIRED - if the parameter is not supplied, there is an error
346
 */
347
define('VALUE_REQUIRED', 1);
348
 
349
/**
350
 * VALUE_OPTIONAL - if the parameter is not supplied, then the param has no value
351
 */
352
define('VALUE_OPTIONAL', 2);
353
 
354
/**
355
 * VALUE_DEFAULT - if the parameter is not supplied, then the default value is used
356
 */
357
define('VALUE_DEFAULT', 0);
358
 
359
/**
360
 * NULL_NOT_ALLOWED - the parameter can not be set to null in the database
361
 */
362
define('NULL_NOT_ALLOWED', false);
363
 
364
/**
365
 * NULL_ALLOWED - the parameter can be set to null in the database
366
 */
367
define('NULL_ALLOWED', true);
368
 
369
// Page types.
370
 
371
/**
372
 * PAGE_COURSE_VIEW is a definition of a page type. For more information on the page class see moodle/lib/pagelib.php.
373
 */
374
define('PAGE_COURSE_VIEW', 'course-view');
375
 
376
/** Get remote addr constant */
377
define('GETREMOTEADDR_SKIP_HTTP_CLIENT_IP', '1');
378
/** Get remote addr constant */
379
define('GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR', '2');
380
/**
381
 * GETREMOTEADDR_SKIP_DEFAULT defines the default behavior remote IP address validation.
382
 */
383
define('GETREMOTEADDR_SKIP_DEFAULT', GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR|GETREMOTEADDR_SKIP_HTTP_CLIENT_IP);
384
 
385
// Blog access level constant declaration.
386
define ('BLOG_USER_LEVEL', 1);
387
define ('BLOG_GROUP_LEVEL', 2);
388
define ('BLOG_COURSE_LEVEL', 3);
389
define ('BLOG_SITE_LEVEL', 4);
390
define ('BLOG_GLOBAL_LEVEL', 5);
391
 
392
 
393
// Tag constants.
394
/**
395
 * To prevent problems with multibytes strings,Flag updating in nav not working on the review page. this should not exceed the
396
 * length of "varchar(255) / 3 (bytes / utf-8 character) = 85".
397
 * TODO: this is not correct, varchar(255) are 255 unicode chars ;-)
398
 *
399
 * @todo define(TAG_MAX_LENGTH) this is not correct, varchar(255) are 255 unicode chars ;-)
400
 */
401
define('TAG_MAX_LENGTH', 50);
402
 
403
// Password policy constants.
404
define ('PASSWORD_LOWER', 'abcdefghijklmnopqrstuvwxyz');
405
define ('PASSWORD_UPPER', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
406
define ('PASSWORD_DIGITS', '0123456789');
407
define ('PASSWORD_NONALPHANUM', '.,;:!?_-+/*@#&$');
408
 
409
/**
410
 * Required password pepper entropy.
411
 */
412
define ('PEPPER_ENTROPY', 112);
413
 
414
// Feature constants.
415
// Used for plugin_supports() to report features that are, or are not, supported by a module.
416
 
417
/** True if module can provide a grade */
418
define('FEATURE_GRADE_HAS_GRADE', 'grade_has_grade');
419
/** True if module supports outcomes */
420
define('FEATURE_GRADE_OUTCOMES', 'outcomes');
421
/** True if module supports advanced grading methods */
422
define('FEATURE_ADVANCED_GRADING', 'grade_advanced_grading');
423
/** True if module controls the grade visibility over the gradebook */
424
define('FEATURE_CONTROLS_GRADE_VISIBILITY', 'controlsgradevisbility');
425
/** True if module supports plagiarism plugins */
426
define('FEATURE_PLAGIARISM', 'plagiarism');
427
 
428
/** True if module has code to track whether somebody viewed it */
429
define('FEATURE_COMPLETION_TRACKS_VIEWS', 'completion_tracks_views');
430
/** True if module has custom completion rules */
431
define('FEATURE_COMPLETION_HAS_RULES', 'completion_has_rules');
432
 
433
/** True if module has no 'view' page (like label) */
434
define('FEATURE_NO_VIEW_LINK', 'viewlink');
435
/** True (which is default) if the module wants support for setting the ID number for grade calculation purposes. */
436
define('FEATURE_IDNUMBER', 'idnumber');
437
/** True if module supports groups */
438
define('FEATURE_GROUPS', 'groups');
439
/** True if module supports groupings */
440
define('FEATURE_GROUPINGS', 'groupings');
441
/**
442
 * True if module supports groupmembersonly (which no longer exists)
443
 * @deprecated Since Moodle 2.8
444
 */
445
define('FEATURE_GROUPMEMBERSONLY', 'groupmembersonly');
446
 
447
/** Type of module */
448
define('FEATURE_MOD_ARCHETYPE', 'mod_archetype');
449
/** True if module supports intro editor */
450
define('FEATURE_MOD_INTRO', 'mod_intro');
451
/** True if module has default completion */
452
define('FEATURE_MODEDIT_DEFAULT_COMPLETION', 'modedit_default_completion');
453
 
454
define('FEATURE_COMMENT', 'comment');
455
 
456
define('FEATURE_RATE', 'rate');
457
/** True if module supports backup/restore of moodle2 format */
458
define('FEATURE_BACKUP_MOODLE2', 'backup_moodle2');
459
 
460
/** True if module can show description on course main page */
461
define('FEATURE_SHOW_DESCRIPTION', 'showdescription');
462
 
463
/** True if module uses the question bank */
464
define('FEATURE_USES_QUESTIONS', 'usesquestions');
465
 
466
/**
467
 * Maximum filename char size
468
 */
469
define('MAX_FILENAME_SIZE', 100);
470
 
471
/** Unspecified module archetype */
472
define('MOD_ARCHETYPE_OTHER', 0);
473
/** Resource-like type module */
474
define('MOD_ARCHETYPE_RESOURCE', 1);
475
/** Assignment module archetype */
476
define('MOD_ARCHETYPE_ASSIGNMENT', 2);
477
/** System (not user-addable) module archetype */
478
define('MOD_ARCHETYPE_SYSTEM', 3);
479
 
480
/** Type of module */
481
define('FEATURE_MOD_PURPOSE', 'mod_purpose');
482
/** Module purpose administration */
483
define('MOD_PURPOSE_ADMINISTRATION', 'administration');
484
/** Module purpose assessment */
485
define('MOD_PURPOSE_ASSESSMENT', 'assessment');
486
/** Module purpose communication */
487
define('MOD_PURPOSE_COLLABORATION', 'collaboration');
488
/** Module purpose communication */
489
define('MOD_PURPOSE_COMMUNICATION', 'communication');
490
/** Module purpose content */
491
define('MOD_PURPOSE_CONTENT', 'content');
492
/** Module purpose interactive content */
493
define('MOD_PURPOSE_INTERACTIVECONTENT', 'interactivecontent');
494
/** Module purpose other */
495
define('MOD_PURPOSE_OTHER', 'other');
496
/**
497
 * Module purpose interface
498
 * @deprecated since Moodle 4.4
499
 * @todo MDL-80701 Remove in Moodle 4.8
500
*/
501
define('MOD_PURPOSE_INTERFACE', 'interface');
502
 
503
/**
504
 * Security token used for allowing access
505
 * from external application such as web services.
506
 * Scripts do not use any session, performance is relatively
507
 * low because we need to load access info in each request.
508
 * Scripts are executed in parallel.
509
 */
510
define('EXTERNAL_TOKEN_PERMANENT', 0);
511
 
512
/**
513
 * Security token used for allowing access
514
 * of embedded applications, the code is executed in the
515
 * active user session. Token is invalidated after user logs out.
516
 * Scripts are executed serially - normal session locking is used.
517
 */
518
define('EXTERNAL_TOKEN_EMBEDDED', 1);
519
 
520
/**
521
 * The home page should be the site home
522
 */
523
define('HOMEPAGE_SITE', 0);
524
/**
525
 * The home page should be the users my page
526
 */
527
define('HOMEPAGE_MY', 1);
528
/**
529
 * The home page can be chosen by the user
530
 */
531
define('HOMEPAGE_USER', 2);
532
/**
533
 * The home page should be the users my courses page
534
 */
535
define('HOMEPAGE_MYCOURSES', 3);
536
 
537
/**
538
 * URL of the Moodle sites registration portal.
539
 */
540
defined('HUB_MOODLEORGHUBURL') || define('HUB_MOODLEORGHUBURL', 'https://stats.moodle.org');
541
 
542
/**
543
 * URL of main Moodle site for marketing, products and services.
544
 */
545
defined('MOODLE_PRODUCTURL') || define('MOODLE_PRODUCTURL', 'https://moodle.com');
546
 
547
/**
548
 * URL of the statistic server public key.
549
 */
550
defined('HUB_STATSPUBLICKEY') || define('HUB_STATSPUBLICKEY', 'https://moodle.org/static/statspubkey.pem');
551
 
552
/**
553
 * Moodle mobile app service name
554
 */
555
define('MOODLE_OFFICIAL_MOBILE_SERVICE', 'moodle_mobile_app');
556
 
557
/**
558
 * Indicates the user has the capabilities required to ignore activity and course file size restrictions
559
 */
560
define('USER_CAN_IGNORE_FILE_SIZE_LIMITS', -1);
561
 
562
/**
563
 * Course display settings: display all sections on one page.
564
 */
565
define('COURSE_DISPLAY_SINGLEPAGE', 0);
566
/**
567
 * Course display settings: split pages into a page per section.
568
 */
569
define('COURSE_DISPLAY_MULTIPAGE', 1);
570
 
571
/**
572
 * Authentication constant: String used in password field when password is not stored.
573
 */
574
define('AUTH_PASSWORD_NOT_CACHED', 'not cached');
575
 
576
/**
577
 * Email from header to never include via information.
578
 */
579
define('EMAIL_VIA_NEVER', 0);
580
 
581
/**
582
 * Email from header to always include via information.
583
 */
584
define('EMAIL_VIA_ALWAYS', 1);
585
 
586
/**
587
 * Email from header to only include via information if the address is no-reply.
588
 */
589
define('EMAIL_VIA_NO_REPLY_ONLY', 2);
590
 
591
/**
592
 * Contact site support form/link disabled.
593
 */
594
define('CONTACT_SUPPORT_DISABLED', 0);
595
 
596
/**
597
 * Contact site support form/link only available to authenticated users.
598
 */
599
define('CONTACT_SUPPORT_AUTHENTICATED', 1);
600
 
601
/**
602
 * Contact site support form/link available to anyone visiting the site.
603
 */
604
define('CONTACT_SUPPORT_ANYONE', 2);
605
 
606
/**
607
 * Maximum number of characters for password.
608
 */
609
define('MAX_PASSWORD_CHARACTERS', 128);
610
 
611
/**
612
 * Toggle sensitive feature is disabled. Used for sensitive inputs (passwords, tokens, keys).
613
 */
614
define('TOGGLE_SENSITIVE_DISABLED', 0);
615
 
616
/**
617
 * Toggle sensitive feature is enabled. Used for sensitive inputs (passwords, tokens, keys).
618
 */
619
define('TOGGLE_SENSITIVE_ENABLED', 1);
620
 
621
/**
622
 * Toggle sensitive feature is enabled for small screens only. Used for sensitive inputs (passwords, tokens, keys).
623
 */
624
define('TOGGLE_SENSITIVE_SMALL_SCREENS_ONLY', 2);
625
 
626
// PARAMETER HANDLING.
627
 
628
/**
629
 * Returns a particular value for the named variable, taken from
630
 * POST or GET.  If the parameter doesn't exist then an error is
631
 * thrown because we require this variable.
632
 *
633
 * This function should be used to initialise all required values
634
 * in a script that are based on parameters.  Usually it will be
635
 * used like this:
636
 *    $id = required_param('id', PARAM_INT);
637
 *
638
 * Please note the $type parameter is now required and the value can not be array.
639
 *
640
 * @param string $parname the name of the page parameter we want
641
 * @param string $type expected type of parameter
642
 * @return mixed
643
 * @throws coding_exception
644
 */
645
function required_param($parname, $type) {
646
    return \core\param::from_type($type)->required_param($parname);
647
}
648
 
649
/**
650
 * Returns a particular array value for the named variable, taken from
651
 * POST or GET.  If the parameter doesn't exist then an error is
652
 * thrown because we require this variable.
653
 *
654
 * This function should be used to initialise all required values
655
 * in a script that are based on parameters.  Usually it will be
656
 * used like this:
657
 *    $ids = required_param_array('ids', PARAM_INT);
658
 *
659
 *  Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
660
 *
661
 * @param string $parname the name of the page parameter we want
662
 * @param string $type expected type of parameter
663
 * @return array
664
 * @throws coding_exception
665
 */
666
function required_param_array($parname, $type) {
667
    return \core\param::from_type($type)->required_param_array($parname);
668
}
669
 
670
/**
671
 * Returns a particular value for the named variable, taken from
672
 * POST or GET, otherwise returning a given default.
673
 *
674
 * This function should be used to initialise all optional values
675
 * in a script that are based on parameters.  Usually it will be
676
 * used like this:
677
 *    $name = optional_param('name', 'Fred', PARAM_TEXT);
678
 *
679
 * Please note the $type parameter is now required and the value can not be array.
680
 *
681
 * @param string $parname the name of the page parameter we want
682
 * @param mixed  $default the default value to return if nothing is found
683
 * @param string $type expected type of parameter
684
 * @return mixed
685
 * @throws coding_exception
686
 */
687
function optional_param($parname, $default, $type) {
688
    return \core\param::from_type($type)->optional_param(
689
        paramname: $parname,
690
        default: $default,
691
    );
692
}
693
 
694
/**
695
 * Returns a particular array value for the named variable, taken from
696
 * POST or GET, otherwise returning a given default.
697
 *
698
 * This function should be used to initialise all optional values
699
 * in a script that are based on parameters.  Usually it will be
700
 * used like this:
701
 *    $ids = optional_param('id', array(), PARAM_INT);
702
 *
703
 * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
704
 *
705
 * @param string $parname the name of the page parameter we want
706
 * @param mixed $default the default value to return if nothing is found
707
 * @param string $type expected type of parameter
708
 * @return array
709
 * @throws coding_exception
710
 */
711
function optional_param_array($parname, $default, $type) {
712
    return \core\param::from_type($type)->optional_param_array(
713
        paramname: $parname,
714
        default: $default,
715
    );
716
}
717
 
718
/**
719
 * Strict validation of parameter values, the values are only converted
720
 * to requested PHP type. Internally it is using clean_param, the values
721
 * before and after cleaning must be equal - otherwise
722
 * an invalid_parameter_exception is thrown.
723
 * Objects and classes are not accepted.
724
 *
725
 * @param mixed $param
726
 * @param string $type PARAM_ constant
727
 * @param bool $allownull are nulls valid value?
728
 * @param string $debuginfo optional debug information
729
 * @return mixed the $param value converted to PHP type
730
 * @throws invalid_parameter_exception if $param is not of given type
731
 */
732
function validate_param($param, $type, $allownull = NULL_NOT_ALLOWED, $debuginfo = '') {
733
    return \core\param::from_type($type)->validate_param(
734
        param: $param,
735
        allownull: $allownull,
736
        debuginfo: $debuginfo,
737
    );
738
}
739
 
740
/**
741
 * Makes sure array contains only the allowed types, this function does not validate array key names!
742
 *
743
 * <code>
744
 * $options = clean_param($options, PARAM_INT);
745
 * </code>
746
 *
747
 * @param array|null $param the variable array we are cleaning
748
 * @param string $type expected format of param after cleaning.
749
 * @param bool $recursive clean recursive arrays
750
 * @return array
751
 * @throws coding_exception
752
 */
753
function clean_param_array(?array $param, $type, $recursive = false) {
754
    return \core\param::from_type($type)->clean_param_array(
755
        param: $param,
756
        recursive: $recursive,
757
    );
758
}
759
 
760
/**
761
 * Used by {@link optional_param()} and {@link required_param()} to
762
 * clean the variables and/or cast to specific types, based on
763
 * an options field.
764
 * <code>
765
 * $course->format = clean_param($course->format, PARAM_ALPHA);
766
 * $selectedgradeitem = clean_param($selectedgradeitem, PARAM_INT);
767
 * </code>
768
 *
769
 * @param mixed $param the variable we are cleaning
770
 * @param string $type expected format of param after cleaning.
771
 * @return mixed
772
 * @throws coding_exception
773
 */
774
function clean_param($param, $type) {
775
    return \core\param::from_type($type)->clean($param);
776
}
777
 
778
/**
779
 * Whether the PARAM_* type is compatible in RTL.
780
 *
781
 * Being compatible with RTL means that the data they contain can flow
782
 * from right-to-left or left-to-right without compromising the user experience.
783
 *
784
 * Take URLs for example, they are not RTL compatible as they should always
785
 * flow from the left to the right. This also applies to numbers, email addresses,
786
 * configuration snippets, base64 strings, etc...
787
 *
788
 * This function tries to best guess which parameters can contain localised strings.
789
 *
790
 * @param string $paramtype Constant PARAM_*.
791
 * @return bool
792
 */
793
function is_rtl_compatible($paramtype) {
794
    return $paramtype == PARAM_TEXT || $paramtype == PARAM_NOTAGS;
795
}
796
 
797
/**
798
 * Makes sure the data is using valid utf8, invalid characters are discarded.
799
 *
800
 * Note: this function is not intended for full objects with methods and private properties.
801
 *
802
 * @param mixed $value
803
 * @return mixed with proper utf-8 encoding
804
 */
805
function fix_utf8($value) {
806
    if (is_null($value) or $value === '') {
807
        return $value;
808
 
809
    } else if (is_string($value)) {
810
        if ((string)(int)$value === $value) {
811
            // Shortcut.
812
            return $value;
813
        }
814
 
815
        // Remove null bytes or invalid Unicode sequences from value.
816
        $value = str_replace(["\0", "\xef\xbf\xbe", "\xef\xbf\xbf"], '', $value);
817
 
818
        // Note: this duplicates min_fix_utf8() intentionally.
819
        static $buggyiconv = null;
820
        if ($buggyiconv === null) {
821
            $buggyiconv = (!function_exists('iconv') or @iconv('UTF-8', 'UTF-8//IGNORE', '100'.chr(130).'€') !== '100€');
822
        }
823
 
824
        if ($buggyiconv) {
825
            if (function_exists('mb_convert_encoding')) {
826
                $subst = mb_substitute_character();
827
                mb_substitute_character('none');
828
                $result = mb_convert_encoding($value, 'utf-8', 'utf-8');
829
                mb_substitute_character($subst);
830
 
831
            } else {
832
                // Warn admins on admin/index.php page.
833
                $result = $value;
834
            }
835
 
836
        } else {
837
            $result = @iconv('UTF-8', 'UTF-8//IGNORE', $value);
838
        }
839
 
840
        return $result;
841
 
842
    } else if (is_array($value)) {
843
        foreach ($value as $k => $v) {
844
            $value[$k] = fix_utf8($v);
845
        }
846
        return $value;
847
 
848
    } else if (is_object($value)) {
849
        // Do not modify original.
850
        $value = clone($value);
851
        foreach ($value as $k => $v) {
852
            $value->$k = fix_utf8($v);
853
        }
854
        return $value;
855
 
856
    } else {
857
        // This is some other type, no utf-8 here.
858
        return $value;
859
    }
860
}
861
 
862
/**
863
 * Return true if given value is integer or string with integer value
864
 *
865
 * @param mixed $value String or Int
866
 * @return bool true if number, false if not
867
 */
868
function is_number($value) {
869
    if (is_int($value)) {
870
        return true;
871
    } else if (is_string($value)) {
872
        return ((string)(int)$value) === $value;
873
    } else {
874
        return false;
875
    }
876
}
877
 
878
/**
879
 * Returns host part from url.
880
 *
881
 * @param string $url full url
882
 * @return string host, null if not found
883
 */
884
function get_host_from_url($url) {
885
    preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
886
    if ($matches) {
887
        return $matches[1];
888
    }
889
    return null;
890
}
891
 
892
/**
893
 * Tests whether anything was returned by text editor
894
 *
895
 * This function is useful for testing whether something you got back from
896
 * the HTML editor actually contains anything. Sometimes the HTML editor
897
 * appear to be empty, but actually you get back a <br> tag or something.
898
 *
899
 * @param string $string a string containing HTML.
900
 * @return boolean does the string contain any actual content - that is text,
901
 * images, objects, etc.
902
 */
903
function html_is_blank($string) {
904
    return trim(strip_tags((string)$string, '<img><object><applet><input><select><textarea><hr>')) == '';
905
}
906
 
907
/**
908
 * Set a key in global configuration
909
 *
910
 * Set a key/value pair in both this session's {@link $CFG} global variable
911
 * and in the 'config' database table for future sessions.
912
 *
913
 * Can also be used to update keys for plugin-scoped configs in config_plugin table.
914
 * In that case it doesn't affect $CFG.
915
 *
916
 * A NULL value will delete the entry.
917
 *
918
 * NOTE: this function is called from lib/db/upgrade.php
919
 *
920
 * @param string $name the key to set
921
 * @param string|int|bool|null $value the value to set (without magic quotes),
922
 *               null to unset the value
923
 * @param string $plugin (optional) the plugin scope, default null
924
 * @return bool true or exception
925
 */
926
function set_config($name, $value, $plugin = null) {
927
    global $CFG, $DB;
928
 
929
    // Redirect to appropriate handler when value is null.
930
    if ($value === null) {
931
        return unset_config($name, $plugin);
932
    }
933
 
934
    // Set variables determining conditions and where to store the new config.
935
    // Plugin config goes to {config_plugins}, core config goes to {config}.
936
    $iscore = empty($plugin);
937
    if ($iscore) {
938
        // If it's for core config.
939
        $table = 'config';
940
        $conditions = ['name' => $name];
941
        $invalidatecachekey = 'core';
942
    } else {
943
        // If it's a plugin.
944
        $table = 'config_plugins';
945
        $conditions = ['name' => $name, 'plugin' => $plugin];
946
        $invalidatecachekey = $plugin;
947
    }
948
 
949
    // DB handling - checks for existing config, updating or inserting only if necessary.
950
    $invalidatecache = true;
951
    $inserted = false;
952
    $record = $DB->get_record($table, $conditions, 'id, value');
953
    if ($record === false) {
954
        // Inserts a new config record.
955
        $config = new stdClass();
956
        $config->name  = $name;
957
        $config->value = $value;
958
        if (!$iscore) {
959
            $config->plugin = $plugin;
960
        }
961
        $inserted = $DB->insert_record($table, $config, false);
962
    } else if ($invalidatecache = ($record->value !== $value)) {
963
        // Record exists - Check and only set new value if it has changed.
964
        $DB->set_field($table, 'value', $value, ['id' => $record->id]);
965
    }
966
 
967
    if ($iscore && !isset($CFG->config_php_settings[$name])) {
968
        // So it's defined for this invocation at least.
969
        // Settings from db are always strings.
970
        $CFG->$name = (string) $value;
971
    }
972
 
973
    // When setting config during a Behat test (in the CLI script, not in the web browser
974
    // requests), remember which ones are set so that we can clear them later.
975
    if ($iscore && $inserted && defined('BEHAT_TEST')) {
976
        $CFG->behat_cli_added_config[$name] = true;
977
    }
978
 
979
    // Update siteidentifier cache, if required.
980
    if ($iscore && $name === 'siteidentifier') {
981
        cache_helper::update_site_identifier($value);
982
    }
983
 
984
    // Invalidate cache, if required.
985
    if ($invalidatecache) {
986
        cache_helper::invalidate_by_definition('core', 'config', [], $invalidatecachekey);
987
    }
988
 
989
    return true;
990
}
991
 
992
/**
993
 * Get configuration values from the global config table
994
 * or the config_plugins table.
995
 *
996
 * If called with one parameter, it will load all the config
997
 * variables for one plugin, and return them as an object.
998
 *
999
 * If called with 2 parameters it will return a string single
1000
 * value or false if the value is not found.
1001
 *
1002
 * NOTE: this function is called from lib/db/upgrade.php
1003
 *
1004
 * @param string $plugin full component name
1005
 * @param string $name default null
1006
 * @return mixed hash-like object or single value, return false no config found
1007
 * @throws dml_exception
1008
 */
1009
function get_config($plugin, $name = null) {
1010
    global $CFG, $DB;
1011
 
1012
    if ($plugin === 'moodle' || $plugin === 'core' || empty($plugin)) {
1013
        $forced =& $CFG->config_php_settings;
1014
        $iscore = true;
1015
        $plugin = 'core';
1016
    } else {
1017
        if (array_key_exists($plugin, $CFG->forced_plugin_settings)) {
1018
            $forced =& $CFG->forced_plugin_settings[$plugin];
1019
        } else {
1020
            $forced = array();
1021
        }
1022
        $iscore = false;
1023
    }
1024
 
1025
    if (!isset($CFG->siteidentifier)) {
1026
        try {
1027
            // This may throw an exception during installation, which is how we detect the
1028
            // need to install the database. For more details see {@see initialise_cfg()}.
1029
            $CFG->siteidentifier = $DB->get_field('config', 'value', array('name' => 'siteidentifier'));
1030
        } catch (dml_exception $ex) {
1031
            // Set siteidentifier to false. We don't want to trip this continually.
1032
            $siteidentifier = false;
1033
            throw $ex;
1034
        }
1035
    }
1036
 
1037
    if (!empty($name)) {
1038
        if (array_key_exists($name, $forced)) {
1039
            return (string)$forced[$name];
1040
        } else if ($name === 'siteidentifier' && $plugin == 'core') {
1041
            return $CFG->siteidentifier;
1042
        }
1043
    }
1044
 
1045
    $cache = cache::make('core', 'config');
1046
    $result = $cache->get($plugin);
1047
    if ($result === false) {
1048
        // The user is after a recordset.
1049
        if (!$iscore) {
1050
            $result = $DB->get_records_menu('config_plugins', array('plugin' => $plugin), '', 'name,value');
1051
        } else {
1052
            // This part is not really used any more, but anyway...
1053
            $result = $DB->get_records_menu('config', array(), '', 'name,value');;
1054
        }
1055
        $cache->set($plugin, $result);
1056
    }
1057
 
1058
    if (!empty($name)) {
1059
        if (array_key_exists($name, $result)) {
1060
            return $result[$name];
1061
        }
1062
        return false;
1063
    }
1064
 
1065
    if ($plugin === 'core') {
1066
        $result['siteidentifier'] = $CFG->siteidentifier;
1067
    }
1068
 
1069
    foreach ($forced as $key => $value) {
1070
        if (is_null($value) or is_array($value) or is_object($value)) {
1071
            // We do not want any extra mess here, just real settings that could be saved in db.
1072
            unset($result[$key]);
1073
        } else {
1074
            // Convert to string as if it went through the DB.
1075
            $result[$key] = (string)$value;
1076
        }
1077
    }
1078
 
1079
    return (object)$result;
1080
}
1081
 
1082
/**
1083
 * Removes a key from global configuration.
1084
 *
1085
 * NOTE: this function is called from lib/db/upgrade.php
1086
 *
1087
 * @param string $name the key to set
1088
 * @param string $plugin (optional) the plugin scope
1089
 * @return boolean whether the operation succeeded.
1090
 */
1091
function unset_config($name, $plugin=null) {
1092
    global $CFG, $DB;
1093
 
1094
    if (empty($plugin)) {
1095
        unset($CFG->$name);
1096
        $DB->delete_records('config', array('name' => $name));
1097
        cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1098
    } else {
1099
        $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1100
        cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1101
    }
1102
 
1103
    return true;
1104
}
1105
 
1106
/**
1107
 * Remove all the config variables for a given plugin.
1108
 *
1109
 * NOTE: this function is called from lib/db/upgrade.php
1110
 *
1111
 * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
1112
 * @return boolean whether the operation succeeded.
1113
 */
1114
function unset_all_config_for_plugin($plugin) {
1115
    global $DB;
1116
    // Delete from the obvious config_plugins first.
1117
    $DB->delete_records('config_plugins', array('plugin' => $plugin));
1118
    // Next delete any suspect settings from config.
1119
    $like = $DB->sql_like('name', '?', true, true, false, '|');
1120
    $params = array($DB->sql_like_escape($plugin.'_', '|') . '%');
1121
    $DB->delete_records_select('config', $like, $params);
1122
    // Finally clear both the plugin cache and the core cache (suspect settings now removed from core).
1123
    cache_helper::invalidate_by_definition('core', 'config', array(), array('core', $plugin));
1124
 
1125
    return true;
1126
}
1127
 
1128
/**
1129
 * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
1130
 *
1131
 * All users are verified if they still have the necessary capability.
1132
 *
1133
 * @param string $value the value of the config setting.
1134
 * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
1135
 * @param bool $includeadmins include administrators.
1136
 * @return array of user objects.
1137
 */
1138
function get_users_from_config($value, $capability, $includeadmins = true) {
1139
    if (empty($value) or $value === '$@NONE@$') {
1140
        return array();
1141
    }
1142
 
1143
    // We have to make sure that users still have the necessary capability,
1144
    // it should be faster to fetch them all first and then test if they are present
1145
    // instead of validating them one-by-one.
1146
    $users = get_users_by_capability(context_system::instance(), $capability);
1147
    if ($includeadmins) {
1148
        $admins = get_admins();
1149
        foreach ($admins as $admin) {
1150
            $users[$admin->id] = $admin;
1151
        }
1152
    }
1153
 
1154
    if ($value === '$@ALL@$') {
1155
        return $users;
1156
    }
1157
 
1158
    $result = array(); // Result in correct order.
1159
    $allowed = explode(',', $value);
1160
    foreach ($allowed as $uid) {
1161
        if (isset($users[$uid])) {
1162
            $user = $users[$uid];
1163
            $result[$user->id] = $user;
1164
        }
1165
    }
1166
 
1167
    return $result;
1168
}
1169
 
1170
 
1171
/**
1172
 * Invalidates browser caches and cached data in temp.
1173
 *
1174
 * @return void
1175
 */
1176
function purge_all_caches() {
1177
    purge_caches();
1178
}
1179
 
1180
/**
1181
 * Selectively invalidate different types of cache.
1182
 *
1183
 * Purges the cache areas specified.  By default, this will purge all caches but can selectively purge specific
1184
 * areas alone or in combination.
1185
 *
1186
 * @param bool[] $options Specific parts of the cache to purge. Valid options are:
1187
 *        'muc'    Purge MUC caches?
1188
 *        'theme'  Purge theme cache?
1189
 *        'lang'   Purge language string cache?
1190
 *        'js'     Purge javascript cache?
1191
 *        'filter' Purge text filter cache?
1192
 *        'other'  Purge all other caches?
1193
 */
1194
function purge_caches($options = []) {
1195
    $defaults = array_fill_keys(['muc', 'courses', 'theme', 'lang', 'js', 'template', 'filter', 'other'], false);
1196
    if (empty(array_filter($options))) {
1197
        $options = array_fill_keys(array_keys($defaults), true); // Set all options to true.
1198
    } else {
1199
        $options = array_merge($defaults, array_intersect_key($options, $defaults)); // Override defaults with specified options.
1200
    }
1201
    if ($options['muc']) {
1202
        cache_helper::purge_all();
1203
    }
1204
    if ($options['courses']) {
1205
        if ($options['courses'] === true) {
1206
            $courseids = [];
1207
        } else {
1208
            $courseids = preg_split('/\s*,\s*/', $options['courses'], -1, PREG_SPLIT_NO_EMPTY);
1209
        }
1210
        course_modinfo::purge_course_caches($courseids);
1211
    }
1212
    if ($options['theme']) {
1213
        theme_reset_all_caches();
1214
    }
1215
    if ($options['lang']) {
1216
        get_string_manager()->reset_caches();
1217
    }
1218
    if ($options['js']) {
1219
        js_reset_all_caches();
1220
    }
1221
    if ($options['template']) {
1222
        template_reset_all_caches();
1223
    }
1224
    if ($options['filter']) {
1225
        reset_text_filters_cache();
1226
    }
1227
    if ($options['other']) {
1228
        purge_other_caches();
1229
    }
1230
}
1231
 
1232
/**
1233
 * Purge all non-MUC caches not otherwise purged in purge_caches.
1234
 *
1235
 * IMPORTANT - If you are adding anything here to do with the cache directory you should also have a look at
1236
 * {@link phpunit_util::reset_dataroot()}
1237
 */
1238
function purge_other_caches() {
1239
    global $DB, $CFG;
1240
    if (class_exists('core_plugin_manager')) {
1241
        core_plugin_manager::reset_caches();
1242
    }
1243
 
1244
    // Bump up cacherev field for all courses.
1245
    try {
1246
        increment_revision_number('course', 'cacherev', '');
1247
    } catch (moodle_exception $e) {
1248
        // Ignore exception since this function is also called before upgrade script when field course.cacherev does not exist yet.
1249
    }
1250
 
1251
    $DB->reset_caches();
1252
 
1253
    // Purge all other caches: rss, simplepie, etc.
1254
    clearstatcache();
1255
    remove_dir($CFG->cachedir.'', true);
1256
 
1257
    // Make sure cache dir is writable, throws exception if not.
1258
    make_cache_directory('');
1259
 
1260
    // This is the only place where we purge local caches, we are only adding files there.
1261
    // The $CFG->localcachedirpurged flag forces local directories to be purged on cluster nodes.
1262
    remove_dir($CFG->localcachedir, true);
1263
    set_config('localcachedirpurged', time());
1264
    make_localcache_directory('', true);
1265
    \core\task\manager::clear_static_caches();
1266
}
1267
 
1268
/**
1269
 * Get volatile flags
1270
 *
1271
 * @param string $type
1272
 * @param int $changedsince default null
1273
 * @return array records array
1274
 */
1275
function get_cache_flags($type, $changedsince = null) {
1276
    global $DB;
1277
 
1278
    $params = array('type' => $type, 'expiry' => time());
1279
    $sqlwhere = "flagtype = :type AND expiry >= :expiry";
1280
    if ($changedsince !== null) {
1281
        $params['changedsince'] = $changedsince;
1282
        $sqlwhere .= " AND timemodified > :changedsince";
1283
    }
1284
    $cf = array();
1285
    if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1286
        foreach ($flags as $flag) {
1287
            $cf[$flag->name] = $flag->value;
1288
        }
1289
    }
1290
    return $cf;
1291
}
1292
 
1293
/**
1294
 * Get volatile flags
1295
 *
1296
 * @param string $type
1297
 * @param string $name
1298
 * @param int $changedsince default null
1299
 * @return string|false The cache flag value or false
1300
 */
1301
function get_cache_flag($type, $name, $changedsince=null) {
1302
    global $DB;
1303
 
1304
    $params = array('type' => $type, 'name' => $name, 'expiry' => time());
1305
 
1306
    $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
1307
    if ($changedsince !== null) {
1308
        $params['changedsince'] = $changedsince;
1309
        $sqlwhere .= " AND timemodified > :changedsince";
1310
    }
1311
 
1312
    return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
1313
}
1314
 
1315
/**
1316
 * Set a volatile flag
1317
 *
1318
 * @param string $type the "type" namespace for the key
1319
 * @param string $name the key to set
1320
 * @param string $value the value to set (without magic quotes) - null will remove the flag
1321
 * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
1322
 * @return bool Always returns true
1323
 */
1324
function set_cache_flag($type, $name, $value, $expiry = null) {
1325
    global $DB;
1326
 
1327
    $timemodified = time();
1328
    if ($expiry === null || $expiry < $timemodified) {
1329
        $expiry = $timemodified + 24 * 60 * 60;
1330
    } else {
1331
        $expiry = (int)$expiry;
1332
    }
1333
 
1334
    if ($value === null) {
1335
        unset_cache_flag($type, $name);
1336
        return true;
1337
    }
1338
 
1339
    if ($f = $DB->get_record('cache_flags', array('name' => $name, 'flagtype' => $type), '*', IGNORE_MULTIPLE)) {
1340
        // This is a potential problem in DEBUG_DEVELOPER.
1341
        if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
1342
            return true; // No need to update.
1343
        }
1344
        $f->value        = $value;
1345
        $f->expiry       = $expiry;
1346
        $f->timemodified = $timemodified;
1347
        $DB->update_record('cache_flags', $f);
1348
    } else {
1349
        $f = new stdClass();
1350
        $f->flagtype     = $type;
1351
        $f->name         = $name;
1352
        $f->value        = $value;
1353
        $f->expiry       = $expiry;
1354
        $f->timemodified = $timemodified;
1355
        $DB->insert_record('cache_flags', $f);
1356
    }
1357
    return true;
1358
}
1359
 
1360
/**
1361
 * Removes a single volatile flag
1362
 *
1363
 * @param string $type the "type" namespace for the key
1364
 * @param string $name the key to set
1365
 * @return bool
1366
 */
1367
function unset_cache_flag($type, $name) {
1368
    global $DB;
1369
    $DB->delete_records('cache_flags', array('name' => $name, 'flagtype' => $type));
1370
    return true;
1371
}
1372
 
1373
/**
1374
 * Garbage-collect volatile flags
1375
 *
1376
 * @return bool Always returns true
1377
 */
1378
function gc_cache_flags() {
1379
    global $DB;
1380
    $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1381
    return true;
1382
}
1383
 
1384
// USER PREFERENCE API.
1385
 
1386
/**
1387
 * Refresh user preference cache. This is used most often for $USER
1388
 * object that is stored in session, but it also helps with performance in cron script.
1389
 *
1390
 * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
1391
 *
1392
 * @package  core
1393
 * @category preference
1394
 * @access   public
1395
 * @param    stdClass         $user          User object. Preferences are preloaded into 'preference' property
1396
 * @param    int              $cachelifetime Cache life time on the current page (in seconds)
1397
 * @throws   coding_exception
1398
 * @return   null
1399
 */
1400
function check_user_preferences_loaded(stdClass $user, $cachelifetime = 120) {
1401
    global $DB;
1402
    // Static cache, we need to check on each page load, not only every 2 minutes.
1403
    static $loadedusers = array();
1404
 
1405
    if (!isset($user->id)) {
1406
        throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
1407
    }
1408
 
1409
    if (empty($user->id) or isguestuser($user->id)) {
1410
        // No permanent storage for not-logged-in users and guest.
1411
        if (!isset($user->preference)) {
1412
            $user->preference = array();
1413
        }
1414
        return;
1415
    }
1416
 
1417
    $timenow = time();
1418
 
1419
    if (isset($loadedusers[$user->id]) and isset($user->preference) and isset($user->preference['_lastloaded'])) {
1420
        // Already loaded at least once on this page. Are we up to date?
1421
        if ($user->preference['_lastloaded'] + $cachelifetime > $timenow) {
1422
            // No need to reload - we are on the same page and we loaded prefs just a moment ago.
1423
            return;
1424
 
1425
        } else if (!get_cache_flag('userpreferenceschanged', $user->id, $user->preference['_lastloaded'])) {
1426
            // No change since the lastcheck on this page.
1427
            $user->preference['_lastloaded'] = $timenow;
1428
            return;
1429
        }
1430
    }
1431
 
1432
    // OK, so we have to reload all preferences.
1433
    $loadedusers[$user->id] = true;
1434
    $user->preference = $DB->get_records_menu('user_preferences', array('userid' => $user->id), '', 'name,value'); // All values.
1435
    $user->preference['_lastloaded'] = $timenow;
1436
}
1437
 
1438
/**
1439
 * Called from set/unset_user_preferences, so that the prefs can be correctly reloaded in different sessions.
1440
 *
1441
 * NOTE: internal function, do not call from other code.
1442
 *
1443
 * @package core
1444
 * @access private
1445
 * @param integer $userid the user whose prefs were changed.
1446
 */
1447
function mark_user_preferences_changed($userid) {
1448
    global $CFG;
1449
 
1450
    if (empty($userid) or isguestuser($userid)) {
1451
        // No cache flags for guest and not-logged-in users.
1452
        return;
1453
    }
1454
 
1455
    set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
1456
}
1457
 
1458
/**
1459
 * Sets a preference for the specified user.
1460
 *
1461
 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1462
 *
1463
 * When additional validation/permission check is needed it is better to use {@see useredit_update_user_preference()}
1464
 *
1465
 * @package  core
1466
 * @category preference
1467
 * @access   public
1468
 * @param    string            $name  The key to set as preference for the specified user
1469
 * @param    string|int|bool|null $value The value to set for the $name key in the specified user's
1470
 *                                    record, null means delete current value.
1471
 * @param    stdClass|int|null $user  A moodle user object or id, null means current user
1472
 * @throws   coding_exception
1473
 * @return   bool                     Always true or exception
1474
 */
1475
function set_user_preference($name, $value, $user = null) {
1476
    global $USER, $DB;
1477
 
1478
    if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1479
        throw new coding_exception('Invalid preference name in set_user_preference() call');
1480
    }
1481
 
1482
    if (is_null($value)) {
1483
        // Null means delete current.
1484
        return unset_user_preference($name, $user);
1485
    } else if (is_object($value)) {
1486
        throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
1487
    } else if (is_array($value)) {
1488
        throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
1489
    }
1490
    // Value column maximum length is 1333 characters.
1491
    $value = (string)$value;
1492
    if (core_text::strlen($value) > 1333) {
1493
        throw new coding_exception('Invalid value in set_user_preference() call, value is is too long for the value column');
1494
    }
1495
 
1496
    if (is_null($user)) {
1497
        $user = $USER;
1498
    } else if (isset($user->id)) {
1499
        // It is a valid object.
1500
    } else if (is_numeric($user)) {
1501
        $user = (object)array('id' => (int)$user);
1502
    } else {
1503
        throw new coding_exception('Invalid $user parameter in set_user_preference() call');
1504
    }
1505
 
1506
    check_user_preferences_loaded($user);
1507
 
1508
    if (empty($user->id) or isguestuser($user->id)) {
1509
        // No permanent storage for not-logged-in users and guest.
1510
        $user->preference[$name] = $value;
1511
        return true;
1512
    }
1513
 
1514
    if ($preference = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => $name))) {
1515
        if ($preference->value === $value and isset($user->preference[$name]) and $user->preference[$name] === $value) {
1516
            // Preference already set to this value.
1517
            return true;
1518
        }
1519
        $DB->set_field('user_preferences', 'value', $value, array('id' => $preference->id));
1520
 
1521
    } else {
1522
        $preference = new stdClass();
1523
        $preference->userid = $user->id;
1524
        $preference->name   = $name;
1525
        $preference->value  = $value;
1526
        $DB->insert_record('user_preferences', $preference);
1527
    }
1528
 
1529
    // Update value in cache.
1530
    $user->preference[$name] = $value;
1531
    // Update the $USER in case where we've not a direct reference to $USER.
1532
    if ($user !== $USER && $user->id == $USER->id) {
1533
        $USER->preference[$name] = $value;
1534
    }
1535
 
1536
    // Set reload flag for other sessions.
1537
    mark_user_preferences_changed($user->id);
1538
 
1539
    return true;
1540
}
1541
 
1542
/**
1543
 * Sets a whole array of preferences for the current user
1544
 *
1545
 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1546
 *
1547
 * @package  core
1548
 * @category preference
1549
 * @access   public
1550
 * @param    array             $prefarray An array of key/value pairs to be set
1551
 * @param    stdClass|int|null $user      A moodle user object or id, null means current user
1552
 * @return   bool                         Always true or exception
1553
 */
1554
function set_user_preferences(array $prefarray, $user = null) {
1555
    foreach ($prefarray as $name => $value) {
1556
        set_user_preference($name, $value, $user);
1557
    }
1558
    return true;
1559
}
1560
 
1561
/**
1562
 * Unsets a preference completely by deleting it from the database
1563
 *
1564
 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1565
 *
1566
 * @package  core
1567
 * @category preference
1568
 * @access   public
1569
 * @param    string            $name The key to unset as preference for the specified user
1570
 * @param    stdClass|int|null $user A moodle user object or id, null means current user
1571
 * @throws   coding_exception
1572
 * @return   bool                    Always true or exception
1573
 */
1574
function unset_user_preference($name, $user = null) {
1575
    global $USER, $DB;
1576
 
1577
    if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1578
        throw new coding_exception('Invalid preference name in unset_user_preference() call');
1579
    }
1580
 
1581
    if (is_null($user)) {
1582
        $user = $USER;
1583
    } else if (isset($user->id)) {
1584
        // It is a valid object.
1585
    } else if (is_numeric($user)) {
1586
        $user = (object)array('id' => (int)$user);
1587
    } else {
1588
        throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
1589
    }
1590
 
1591
    check_user_preferences_loaded($user);
1592
 
1593
    if (empty($user->id) or isguestuser($user->id)) {
1594
        // No permanent storage for not-logged-in user and guest.
1595
        unset($user->preference[$name]);
1596
        return true;
1597
    }
1598
 
1599
    // Delete from DB.
1600
    $DB->delete_records('user_preferences', array('userid' => $user->id, 'name' => $name));
1601
 
1602
    // Delete the preference from cache.
1603
    unset($user->preference[$name]);
1604
    // Update the $USER in case where we've not a direct reference to $USER.
1605
    if ($user !== $USER && $user->id == $USER->id) {
1606
        unset($USER->preference[$name]);
1607
    }
1608
 
1609
    // Set reload flag for other sessions.
1610
    mark_user_preferences_changed($user->id);
1611
 
1612
    return true;
1613
}
1614
 
1615
/**
1616
 * Used to fetch user preference(s)
1617
 *
1618
 * If no arguments are supplied this function will return
1619
 * all of the current user preferences as an array.
1620
 *
1621
 * If a name is specified then this function
1622
 * attempts to return that particular preference value.  If
1623
 * none is found, then the optional value $default is returned,
1624
 * otherwise null.
1625
 *
1626
 * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1627
 *
1628
 * @package  core
1629
 * @category preference
1630
 * @access   public
1631
 * @param    string            $name    Name of the key to use in finding a preference value
1632
 * @param    mixed|null        $default Value to be returned if the $name key is not set in the user preferences
1633
 * @param    stdClass|int|null $user    A moodle user object or id, null means current user
1634
 * @throws   coding_exception
1635
 * @return   string|mixed|null          A string containing the value of a single preference. An
1636
 *                                      array with all of the preferences or null
1637
 */
1638
function get_user_preferences($name = null, $default = null, $user = null) {
1639
    global $USER;
1640
 
1641
    if (is_null($name)) {
1642
        // All prefs.
1643
    } else if (is_numeric($name) or $name === '_lastloaded') {
1644
        throw new coding_exception('Invalid preference name in get_user_preferences() call');
1645
    }
1646
 
1647
    if (is_null($user)) {
1648
        $user = $USER;
1649
    } else if (isset($user->id)) {
1650
        // Is a valid object.
1651
    } else if (is_numeric($user)) {
1652
        if ($USER->id == $user) {
1653
            $user = $USER;
1654
        } else {
1655
            $user = (object)array('id' => (int)$user);
1656
        }
1657
    } else {
1658
        throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
1659
    }
1660
 
1661
    check_user_preferences_loaded($user);
1662
 
1663
    if (empty($name)) {
1664
        // All values.
1665
        return $user->preference;
1666
    } else if (isset($user->preference[$name])) {
1667
        // The single string value.
1668
        return $user->preference[$name];
1669
    } else {
1670
        // Default value (null if not specified).
1671
        return $default;
1672
    }
1673
}
1674
 
1675
// FUNCTIONS FOR HANDLING TIME.
1676
 
1677
/**
1678
 * Given Gregorian date parts in user time produce a GMT timestamp.
1679
 *
1680
 * @package core
1681
 * @category time
1682
 * @param int $year The year part to create timestamp of
1683
 * @param int $month The month part to create timestamp of
1684
 * @param int $day The day part to create timestamp of
1685
 * @param int $hour The hour part to create timestamp of
1686
 * @param int $minute The minute part to create timestamp of
1687
 * @param int $second The second part to create timestamp of
1688
 * @param int|float|string $timezone Timezone modifier, used to calculate GMT time offset.
1689
 *             if 99 then default user's timezone is used {@link https://moodledev.io/docs/apis/subsystems/time#timezone}
1690
 * @param bool $applydst Toggle Daylight Saving Time, default true, will be
1691
 *             applied only if timezone is 99 or string.
1692
 * @return int GMT timestamp
1693
 */
1694
function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
1695
    $date = new DateTime('now', core_date::get_user_timezone_object($timezone));
1696
    $date->setDate((int)$year, (int)$month, (int)$day);
1697
    $date->setTime((int)$hour, (int)$minute, (int)$second);
1698
 
1699
    $time = $date->getTimestamp();
1700
 
1701
    if ($time === false) {
1702
        throw new coding_exception('getTimestamp() returned false, please ensure you have passed correct values.'.
1703
            ' This can fail if year is more than 2038 and OS is 32 bit windows');
1704
    }
1705
 
1706
    // Moodle BC DST stuff.
1707
    if (!$applydst) {
1708
        $time += dst_offset_on($time, $timezone);
1709
    }
1710
 
1711
    return $time;
1712
 
1713
}
1714
 
1715
/**
1716
 * Format a date/time (seconds) as weeks, days, hours etc as needed
1717
 *
1718
 * Given an amount of time in seconds, returns string
1719
 * formatted nicely as years, days, hours etc as needed
1720
 *
1721
 * @package core
1722
 * @category time
1723
 * @uses MINSECS
1724
 * @uses HOURSECS
1725
 * @uses DAYSECS
1726
 * @uses YEARSECS
1727
 * @param int $totalsecs Time in seconds
1728
 * @param stdClass $str Should be a time object
1729
 * @return string A nicely formatted date/time string
1730
 */
1731
function format_time($totalsecs, $str = null) {
1732
 
1733
    $totalsecs = abs($totalsecs);
1734
 
1735
    if (!$str) {
1736
        // Create the str structure the slow way.
1737
        $str = new stdClass();
1738
        $str->day   = get_string('day');
1739
        $str->days  = get_string('days');
1740
        $str->hour  = get_string('hour');
1741
        $str->hours = get_string('hours');
1742
        $str->min   = get_string('min');
1743
        $str->mins  = get_string('mins');
1744
        $str->sec   = get_string('sec');
1745
        $str->secs  = get_string('secs');
1746
        $str->year  = get_string('year');
1747
        $str->years = get_string('years');
1748
    }
1749
 
1750
    $years     = floor($totalsecs/YEARSECS);
1751
    $remainder = $totalsecs - ($years*YEARSECS);
1752
    $days      = floor($remainder/DAYSECS);
1753
    $remainder = $totalsecs - ($days*DAYSECS);
1754
    $hours     = floor($remainder/HOURSECS);
1755
    $remainder = $remainder - ($hours*HOURSECS);
1756
    $mins      = floor($remainder/MINSECS);
1757
    $secs      = $remainder - ($mins*MINSECS);
1758
 
1759
    $ss = ($secs == 1)  ? $str->sec  : $str->secs;
1760
    $sm = ($mins == 1)  ? $str->min  : $str->mins;
1761
    $sh = ($hours == 1) ? $str->hour : $str->hours;
1762
    $sd = ($days == 1)  ? $str->day  : $str->days;
1763
    $sy = ($years == 1)  ? $str->year  : $str->years;
1764
 
1765
    $oyears = '';
1766
    $odays = '';
1767
    $ohours = '';
1768
    $omins = '';
1769
    $osecs = '';
1770
 
1771
    if ($years) {
1772
        $oyears  = $years .' '. $sy;
1773
    }
1774
    if ($days) {
1775
        $odays  = $days .' '. $sd;
1776
    }
1777
    if ($hours) {
1778
        $ohours = $hours .' '. $sh;
1779
    }
1780
    if ($mins) {
1781
        $omins  = $mins .' '. $sm;
1782
    }
1783
    if ($secs) {
1784
        $osecs  = $secs .' '. $ss;
1785
    }
1786
 
1787
    if ($years) {
1788
        return trim($oyears .' '. $odays);
1789
    }
1790
    if ($days) {
1791
        return trim($odays .' '. $ohours);
1792
    }
1793
    if ($hours) {
1794
        return trim($ohours .' '. $omins);
1795
    }
1796
    if ($mins) {
1797
        return trim($omins .' '. $osecs);
1798
    }
1799
    if ($secs) {
1800
        return $osecs;
1801
    }
1802
    return get_string('now');
1803
}
1804
 
1805
/**
1806
 * Returns a formatted string that represents a date in user time.
1807
 *
1808
 * @package core
1809
 * @category time
1810
 * @param int $date the timestamp in UTC, as obtained from the database.
1811
 * @param string $format strftime format. You should probably get this using
1812
 *        get_string('strftime...', 'langconfig');
1813
 * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
1814
 *        not 99 then daylight saving will not be added.
1815
 *        {@link https://moodledev.io/docs/apis/subsystems/time#timezone}
1816
 * @param bool $fixday If true (default) then the leading zero from %d is removed.
1817
 *        If false then the leading zero is maintained.
1818
 * @param bool $fixhour If true (default) then the leading zero from %I is removed.
1819
 * @return string the formatted date/time.
1820
 */
1821
function userdate($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
1822
    $calendartype = \core_calendar\type_factory::get_calendar_instance();
1823
    return $calendartype->timestamp_to_date_string($date, $format, $timezone, $fixday, $fixhour);
1824
}
1825
 
1826
/**
1827
 * Returns a html "time" tag with both the exact user date with timezone information
1828
 * as a datetime attribute in the W3C format, and the user readable date and time as text.
1829
 *
1830
 * @package core
1831
 * @category time
1832
 * @param int $date the timestamp in UTC, as obtained from the database.
1833
 * @param string $format strftime format. You should probably get this using
1834
 *        get_string('strftime...', 'langconfig');
1835
 * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
1836
 *        not 99 then daylight saving will not be added.
1837
 *        {@link https://moodledev.io/docs/apis/subsystems/time#timezone}
1838
 * @param bool $fixday If true (default) then the leading zero from %d is removed.
1839
 *        If false then the leading zero is maintained.
1840
 * @param bool $fixhour If true (default) then the leading zero from %I is removed.
1841
 * @return string the formatted date/time.
1842
 */
1843
function userdate_htmltime($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
1844
    $userdatestr = userdate($date, $format, $timezone, $fixday, $fixhour);
1845
    if (CLI_SCRIPT && !PHPUNIT_TEST) {
1846
        return $userdatestr;
1847
    }
1848
    $machinedate = new DateTime();
1849
    $machinedate->setTimestamp(intval($date));
1850
    $machinedate->setTimezone(core_date::get_user_timezone_object());
1851
 
1852
    return html_writer::tag('time', $userdatestr, ['datetime' => $machinedate->format(DateTime::W3C)]);
1853
}
1854
 
1855
/**
1856
 * Returns a formatted date ensuring it is UTF-8.
1857
 *
1858
 * If we are running under Windows convert to Windows encoding and then back to UTF-8
1859
 * (because it's impossible to specify UTF-8 to fetch locale info in Win32).
1860
 *
1861
 * @param int $date the timestamp - since Moodle 2.9 this is a real UTC timestamp
1862
 * @param string $format strftime format.
1863
 * @param int|float|string $tz the user timezone
1864
 * @return string the formatted date/time.
1865
 * @since Moodle 2.3.3
1866
 */
1867
function date_format_string($date, $format, $tz = 99) {
1868
 
1869
    date_default_timezone_set(core_date::get_user_timezone($tz));
1870
 
1871
    if (date('A', 0) === date('A', HOURSECS * 18)) {
1872
        $datearray = getdate($date);
1873
        $format = str_replace([
1874
            '%P',
1875
            '%p',
1876
        ], [
1877
            $datearray['hours'] < 12 ? get_string('am', 'langconfig') : get_string('pm', 'langconfig'),
1878
            $datearray['hours'] < 12 ? get_string('amcaps', 'langconfig') : get_string('pmcaps', 'langconfig'),
1879
        ], $format);
1880
    }
1881
 
1882
    $datestring = core_date::strftime($format, $date);
1883
    core_date::set_default_server_timezone();
1884
 
1885
    return $datestring;
1886
}
1887
 
1888
/**
1889
 * Given a $time timestamp in GMT (seconds since epoch),
1890
 * returns an array that represents the Gregorian date in user time
1891
 *
1892
 * @package core
1893
 * @category time
1894
 * @param int $time Timestamp in GMT
1895
 * @param float|int|string $timezone user timezone
1896
 * @return array An array that represents the date in user time
1897
 */
1898
function usergetdate($time, $timezone=99) {
1899
    if ($time === null) {
1900
        // PHP8 and PHP7 return different results when getdate(null) is called.
1901
        // Display warning and cast to 0 to make sure the usergetdate() behaves consistently on all versions of PHP.
1902
        // In the future versions of Moodle we may consider adding a strict typehint.
1903
        debugging('usergetdate() expects parameter $time to be int, null given', DEBUG_DEVELOPER);
1904
        $time = 0;
1905
    }
1906
 
1907
    date_default_timezone_set(core_date::get_user_timezone($timezone));
1908
    $result = getdate($time);
1909
    core_date::set_default_server_timezone();
1910
 
1911
    return $result;
1912
}
1913
 
1914
/**
1915
 * Given a GMT timestamp (seconds since epoch), offsets it by
1916
 * the timezone.  eg 3pm in India is 3pm GMT - 7 * 3600 seconds
1917
 *
1918
 * NOTE: this function does not include DST properly,
1919
 *       you should use the PHP date stuff instead!
1920
 *
1921
 * @package core
1922
 * @category time
1923
 * @param int $date Timestamp in GMT
1924
 * @param float|int|string $timezone user timezone
1925
 * @return int
1926
 */
1927
function usertime($date, $timezone=99) {
1928
    $userdate = new DateTime('@' . $date);
1929
    $userdate->setTimezone(core_date::get_user_timezone_object($timezone));
1930
    $dst = dst_offset_on($date, $timezone);
1931
 
1932
    return $date - $userdate->getOffset() + $dst;
1933
}
1934
 
1935
/**
1936
 * Get a formatted string representation of an interval between two unix timestamps.
1937
 *
1938
 * E.g.
1939
 * $intervalstring = get_time_interval_string(12345600, 12345660);
1940
 * Will produce the string:
1941
 * '0d 0h 1m'
1942
 *
1943
 * @param int $time1 unix timestamp
1944
 * @param int $time2 unix timestamp
1945
 * @param string $format string (can be lang string) containing format chars: https://www.php.net/manual/en/dateinterval.format.php.
1946
 * @param bool $dropzeroes If format is not provided and this is set to true, do not include zero time units.
1947
 *                         e.g. a duration of 3 days and 2 hours will be displayed as '3d 2h' instead of '3d 2h 0s'
1948
 * @param bool $fullformat If format is not provided and this is set to true, display time units in full format.
1949
 *                         e.g. instead of showing "3d", "3 days" will be returned.
1950
 * @return string the formatted string describing the time difference, e.g. '10d 11h 45m'.
1951
 */
1952
function get_time_interval_string(int $time1, int $time2, string $format = '',
1953
        bool $dropzeroes = false, bool $fullformat = false): string {
1954
    $dtdate = new DateTime();
1955
    $dtdate->setTimeStamp($time1);
1956
    $dtdate2 = new DateTime();
1957
    $dtdate2->setTimeStamp($time2);
1958
    $interval = $dtdate2->diff($dtdate);
1959
 
1960
    if (empty(trim($format))) {
1961
        // Default to this key.
1962
        $formatkey = 'dateintervaldayhrmin';
1963
 
1964
        if ($dropzeroes) {
1965
            $units = [
1966
                'y' => 'yr',
1967
                'm' => 'mo',
1968
                'd' => 'day',
1969
                'h' => 'hr',
1970
                'i' => 'min',
1971
                's' => 'sec',
1972
            ];
1973
            $formatunits = [];
1974
            foreach ($units as $key => $unit) {
1975
                if (empty($interval->$key)) {
1976
                    continue;
1977
                }
1978
                $formatunits[] = $unit;
1979
            }
1980
            if (!empty($formatunits)) {
1981
                $formatkey = 'dateinterval' . implode("", $formatunits);
1982
            }
1983
        }
1984
 
1985
        if ($fullformat) {
1986
            $formatkey .= 'full';
1987
        }
1988
        $format = get_string($formatkey, 'langconfig');
1989
    }
1990
    return $interval->format($format);
1991
}
1992
 
1993
/**
1994
 * Given a time, return the GMT timestamp of the most recent midnight
1995
 * for the current user.
1996
 *
1997
 * @package core
1998
 * @category time
1999
 * @param int $date Timestamp in GMT
2000
 * @param float|int|string $timezone user timezone
2001
 * @return int Returns a GMT timestamp
2002
 */
2003
function usergetmidnight($date, $timezone=99) {
2004
 
2005
    $userdate = usergetdate($date, $timezone);
2006
 
2007
    // Time of midnight of this user's day, in GMT.
2008
    return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
2009
 
2010
}
2011
 
2012
/**
2013
 * Returns a string that prints the user's timezone
2014
 *
2015
 * @package core
2016
 * @category time
2017
 * @param float|int|string $timezone user timezone
2018
 * @return string
2019
 */
2020
function usertimezone($timezone=99) {
2021
    $tz = core_date::get_user_timezone($timezone);
2022
    return core_date::get_localised_timezone($tz);
2023
}
2024
 
2025
/**
2026
 * Returns a float or a string which denotes the user's timezone
2027
 * A float value means that a simple offset from GMT is used, while a string (it will be the name of a timezone in the database)
2028
 * means that for this timezone there are also DST rules to be taken into account
2029
 * Checks various settings and picks the most dominant of those which have a value
2030
 *
2031
 * @package core
2032
 * @category time
2033
 * @param float|int|string $tz timezone to calculate GMT time offset before
2034
 *        calculating user timezone, 99 is default user timezone
2035
 *        {@link https://moodledev.io/docs/apis/subsystems/time#timezone}
2036
 * @return float|string
2037
 */
2038
function get_user_timezone($tz = 99) {
2039
    global $USER, $CFG;
2040
 
2041
    $timezones = array(
2042
        $tz,
2043
        isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
2044
        isset($USER->timezone) ? $USER->timezone : 99,
2045
        isset($CFG->timezone) ? $CFG->timezone : 99,
2046
        );
2047
 
2048
    $tz = 99;
2049
 
2050
    // Loop while $tz is, empty but not zero, or 99, and there is another timezone is the array.
2051
    foreach ($timezones as $nextvalue) {
2052
        if ((empty($tz) && !is_numeric($tz)) || $tz == 99) {
2053
            $tz = $nextvalue;
2054
        }
2055
    }
2056
    return is_numeric($tz) ? (float) $tz : $tz;
2057
}
2058
 
2059
/**
2060
 * Calculates the Daylight Saving Offset for a given date/time (timestamp)
2061
 * - Note: Daylight saving only works for string timezones and not for float.
2062
 *
2063
 * @package core
2064
 * @category time
2065
 * @param int $time must NOT be compensated at all, it has to be a pure timestamp
2066
 * @param int|float|string $strtimezone user timezone
2067
 * @return int
2068
 */
2069
function dst_offset_on($time, $strtimezone = null) {
2070
    $tz = core_date::get_user_timezone($strtimezone);
2071
    $date = new DateTime('@' . $time);
2072
    $date->setTimezone(new DateTimeZone($tz));
2073
    if ($date->format('I') == '1') {
2074
        if ($tz === 'Australia/Lord_Howe') {
2075
            return 1800;
2076
        }
2077
        return 3600;
2078
    }
2079
    return 0;
2080
}
2081
 
2082
/**
2083
 * Calculates when the day appears in specific month
2084
 *
2085
 * @package core
2086
 * @category time
2087
 * @param int $startday starting day of the month
2088
 * @param int $weekday The day when week starts (normally taken from user preferences)
2089
 * @param int $month The month whose day is sought
2090
 * @param int $year The year of the month whose day is sought
2091
 * @return int
2092
 */
2093
function find_day_in_month($startday, $weekday, $month, $year) {
2094
    $calendartype = \core_calendar\type_factory::get_calendar_instance();
2095
 
2096
    $daysinmonth = days_in_month($month, $year);
2097
    $daysinweek = count($calendartype->get_weekdays());
2098
 
2099
    if ($weekday == -1) {
2100
        // Don't care about weekday, so return:
2101
        //    abs($startday) if $startday != -1
2102
        //    $daysinmonth otherwise.
2103
        return ($startday == -1) ? $daysinmonth : abs($startday);
2104
    }
2105
 
2106
    // From now on we 're looking for a specific weekday.
2107
    // Give "end of month" its actual value, since we know it.
2108
    if ($startday == -1) {
2109
        $startday = -1 * $daysinmonth;
2110
    }
2111
 
2112
    // Starting from day $startday, the sign is the direction.
2113
    if ($startday < 1) {
2114
        $startday = abs($startday);
2115
        $lastmonthweekday = dayofweek($daysinmonth, $month, $year);
2116
 
2117
        // This is the last such weekday of the month.
2118
        $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
2119
        if ($lastinmonth > $daysinmonth) {
2120
            $lastinmonth -= $daysinweek;
2121
        }
2122
 
2123
        // Find the first such weekday <= $startday.
2124
        while ($lastinmonth > $startday) {
2125
            $lastinmonth -= $daysinweek;
2126
        }
2127
 
2128
        return $lastinmonth;
2129
    } else {
2130
        $indexweekday = dayofweek($startday, $month, $year);
2131
 
2132
        $diff = $weekday - $indexweekday;
2133
        if ($diff < 0) {
2134
            $diff += $daysinweek;
2135
        }
2136
 
2137
        // This is the first such weekday of the month equal to or after $startday.
2138
        $firstfromindex = $startday + $diff;
2139
 
2140
        return $firstfromindex;
2141
    }
2142
}
2143
 
2144
/**
2145
 * Calculate the number of days in a given month
2146
 *
2147
 * @package core
2148
 * @category time
2149
 * @param int $month The month whose day count is sought
2150
 * @param int $year The year of the month whose day count is sought
2151
 * @return int
2152
 */
2153
function days_in_month($month, $year) {
2154
    $calendartype = \core_calendar\type_factory::get_calendar_instance();
2155
    return $calendartype->get_num_days_in_month($year, $month);
2156
}
2157
 
2158
/**
2159
 * Calculate the position in the week of a specific calendar day
2160
 *
2161
 * @package core
2162
 * @category time
2163
 * @param int $day The day of the date whose position in the week is sought
2164
 * @param int $month The month of the date whose position in the week is sought
2165
 * @param int $year The year of the date whose position in the week is sought
2166
 * @return int
2167
 */
2168
function dayofweek($day, $month, $year) {
2169
    $calendartype = \core_calendar\type_factory::get_calendar_instance();
2170
    return $calendartype->get_weekday($year, $month, $day);
2171
}
2172
 
2173
// USER AUTHENTICATION AND LOGIN.
2174
 
2175
/**
2176
 * Returns full login url.
2177
 *
2178
 * Any form submissions for authentication to this URL must include username,
2179
 * password as well as a logintoken generated by \core\session\manager::get_login_token().
2180
 *
2181
 * @return string login url
2182
 */
2183
function get_login_url() {
2184
    global $CFG;
2185
 
2186
    return "$CFG->wwwroot/login/index.php";
2187
}
2188
 
2189
/**
2190
 * This function checks that the current user is logged in and has the
2191
 * required privileges
2192
 *
2193
 * This function checks that the current user is logged in, and optionally
2194
 * whether they are allowed to be in a particular course and view a particular
2195
 * course module.
2196
 * If they are not logged in, then it redirects them to the site login unless
2197
 * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2198
 * case they are automatically logged in as guests.
2199
 * If $courseid is given and the user is not enrolled in that course then the
2200
 * user is redirected to the course enrolment page.
2201
 * If $cm is given and the course module is hidden and the user is not a teacher
2202
 * in the course then the user is redirected to the course home page.
2203
 *
2204
 * When $cm parameter specified, this function sets page layout to 'module'.
2205
 * You need to change it manually later if some other layout needed.
2206
 *
2207
 * @package    core_access
2208
 * @category   access
2209
 *
2210
 * @param mixed $courseorid id of the course or course object
2211
 * @param bool $autologinguest default true
2212
 * @param object $cm course module object
2213
 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2214
 *             true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2215
 *             in order to keep redirects working properly. MDL-14495
2216
 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2217
 * @return mixed Void, exit, and die depending on path
2218
 * @throws coding_exception
2219
 * @throws require_login_exception
2220
 * @throws moodle_exception
2221
 */
2222
function require_login($courseorid = null, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
2223
    global $CFG, $SESSION, $USER, $PAGE, $SITE, $DB, $OUTPUT;
2224
 
2225
    // Must not redirect when byteserving already started.
2226
    if (!empty($_SERVER['HTTP_RANGE'])) {
2227
        $preventredirect = true;
2228
    }
2229
 
2230
    if (AJAX_SCRIPT) {
2231
        // We cannot redirect for AJAX scripts either.
2232
        $preventredirect = true;
2233
    }
2234
 
2235
    // Setup global $COURSE, themes, language and locale.
2236
    if (!empty($courseorid)) {
2237
        if (is_object($courseorid)) {
2238
            $course = $courseorid;
2239
        } else if ($courseorid == SITEID) {
2240
            $course = clone($SITE);
2241
        } else {
2242
            $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
2243
        }
2244
        if ($cm) {
2245
            if ($cm->course != $course->id) {
2246
                throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2247
            }
2248
            // Make sure we have a $cm from get_fast_modinfo as this contains activity access details.
2249
            if (!($cm instanceof cm_info)) {
2250
                // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
2251
                // db queries so this is not really a performance concern, however it is obviously
2252
                // better if you use get_fast_modinfo to get the cm before calling this.
2253
                $modinfo = get_fast_modinfo($course);
2254
                $cm = $modinfo->get_cm($cm->id);
2255
            }
2256
        }
2257
    } else {
2258
        // Do not touch global $COURSE via $PAGE->set_course(),
2259
        // the reasons is we need to be able to call require_login() at any time!!
2260
        $course = $SITE;
2261
        if ($cm) {
2262
            throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2263
        }
2264
    }
2265
 
2266
    // If this is an AJAX request and $setwantsurltome is true then we need to override it and set it to false.
2267
    // Otherwise the AJAX request URL will be set to $SESSION->wantsurl and events such as self enrolment in the future
2268
    // risk leading the user back to the AJAX request URL.
2269
    if ($setwantsurltome && defined('AJAX_SCRIPT') && AJAX_SCRIPT) {
2270
        $setwantsurltome = false;
2271
    }
2272
 
2273
    // Redirect to the login page if session has expired, only with dbsessions enabled (MDL-35029) to maintain current behaviour.
2274
    if ((!isloggedin() or isguestuser()) && !empty($SESSION->has_timed_out) && !empty($CFG->dbsessions)) {
2275
        if ($preventredirect) {
2276
            throw new require_login_session_timeout_exception();
2277
        } else {
2278
            if ($setwantsurltome) {
2279
                $SESSION->wantsurl = qualified_me();
2280
            }
2281
            redirect(get_login_url());
2282
        }
2283
    }
2284
 
2285
    // If the user is not even logged in yet then make sure they are.
2286
    if (!isloggedin()) {
2287
        if ($autologinguest && !empty($CFG->autologinguests)) {
2288
            if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
2289
                // Misconfigured site guest, just redirect to login page.
2290
                redirect(get_login_url());
2291
                exit; // Never reached.
2292
            }
2293
            $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
2294
            complete_user_login($guest);
2295
            $USER->autologinguest = true;
2296
            $SESSION->lang = $lang;
2297
        } else {
2298
            // NOTE: $USER->site check was obsoleted by session test cookie, $USER->confirmed test is in login/index.php.
2299
            if ($preventredirect) {
2300
                throw new require_login_exception('You are not logged in');
2301
            }
2302
 
2303
            if ($setwantsurltome) {
2304
                $SESSION->wantsurl = qualified_me();
2305
            }
2306
 
2307
            // Give auth plugins an opportunity to authenticate or redirect to an external login page
2308
            $authsequence = get_enabled_auth_plugins(); // Auths, in sequence.
2309
            foreach($authsequence as $authname) {
2310
                $authplugin = get_auth_plugin($authname);
2311
                $authplugin->pre_loginpage_hook();
2312
                if (isloggedin()) {
2313
                    if ($cm) {
2314
                        $modinfo = get_fast_modinfo($course);
2315
                        $cm = $modinfo->get_cm($cm->id);
2316
                    }
2317
                    set_access_log_user();
2318
                    break;
2319
                }
2320
            }
2321
 
2322
            // If we're still not logged in then go to the login page
2323
            if (!isloggedin()) {
2324
                redirect(get_login_url());
2325
                exit; // Never reached.
2326
            }
2327
        }
2328
    }
2329
 
2330
    // Loginas as redirection if needed.
2331
    if ($course->id != SITEID and \core\session\manager::is_loggedinas()) {
2332
        if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
2333
            if ($USER->loginascontext->instanceid != $course->id) {
2334
                throw new \moodle_exception('loginasonecourse', '',
2335
                    $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
2336
            }
2337
        }
2338
    }
2339
 
2340
    // Check whether the user should be changing password (but only if it is REALLY them).
2341
    if (get_user_preferences('auth_forcepasswordchange') && !\core\session\manager::is_loggedinas()) {
2342
        $userauth = get_auth_plugin($USER->auth);
2343
        if ($userauth->can_change_password() and !$preventredirect) {
2344
            if ($setwantsurltome) {
2345
                $SESSION->wantsurl = qualified_me();
2346
            }
2347
            if ($changeurl = $userauth->change_password_url()) {
2348
                // Use plugin custom url.
2349
                redirect($changeurl);
2350
            } else {
2351
                // Use moodle internal method.
2352
                redirect($CFG->wwwroot .'/login/change_password.php');
2353
            }
2354
        } else if ($userauth->can_change_password()) {
2355
            throw new moodle_exception('forcepasswordchangenotice');
2356
        } else {
2357
            throw new moodle_exception('nopasswordchangeforced', 'auth');
2358
        }
2359
    }
2360
 
2361
    // Check that the user account is properly set up. If we can't redirect to
2362
    // edit their profile and this is not a WS request, perform just the lax check.
2363
    // It will allow them to use filepicker on the profile edit page.
2364
 
2365
    if ($preventredirect && !WS_SERVER) {
2366
        $usernotfullysetup = user_not_fully_set_up($USER, false);
2367
    } else {
2368
        $usernotfullysetup = user_not_fully_set_up($USER, true);
2369
    }
2370
 
2371
    if ($usernotfullysetup) {
2372
        if ($preventredirect) {
2373
            throw new moodle_exception('usernotfullysetup');
2374
        }
2375
        if ($setwantsurltome) {
2376
            $SESSION->wantsurl = qualified_me();
2377
        }
2378
        redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&amp;course='. SITEID);
2379
    }
2380
 
2381
    // Make sure the USER has a sesskey set up. Used for CSRF protection.
2382
    sesskey();
2383
 
2384
    if (\core\session\manager::is_loggedinas()) {
2385
        // During a "logged in as" session we should force all content to be cleaned because the
2386
        // logged in user will be viewing potentially malicious user generated content.
2387
        // See MDL-63786 for more details.
2388
        $CFG->forceclean = true;
2389
    }
2390
 
2391
    $afterlogins = get_plugins_with_function('after_require_login', 'lib.php');
2392
 
2393
    // Do not bother admins with any formalities, except for activities pending deletion.
2394
    if (is_siteadmin() && !($cm && $cm->deletioninprogress)) {
2395
        // Set the global $COURSE.
2396
        if ($cm) {
2397
            $PAGE->set_cm($cm, $course);
2398
            $PAGE->set_pagelayout('incourse');
2399
        } else if (!empty($courseorid)) {
2400
            $PAGE->set_course($course);
2401
        }
2402
        // Set accesstime or the user will appear offline which messes up messaging.
2403
        // Do not update access time for webservice or ajax requests.
2404
        if (!WS_SERVER && !AJAX_SCRIPT) {
2405
            user_accesstime_log($course->id);
2406
        }
2407
 
2408
        foreach ($afterlogins as $plugintype => $plugins) {
2409
            foreach ($plugins as $pluginfunction) {
2410
                $pluginfunction($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2411
            }
2412
        }
2413
        return;
2414
    }
2415
 
2416
    // Scripts have a chance to declare that $USER->policyagreed should not be checked.
2417
    // This is mostly for places where users are actually accepting the policies, to avoid the redirect loop.
2418
    if (!defined('NO_SITEPOLICY_CHECK')) {
2419
        define('NO_SITEPOLICY_CHECK', false);
2420
    }
2421
 
2422
    // Check that the user has agreed to a site policy if there is one - do not test in case of admins.
2423
    // Do not test if the script explicitly asked for skipping the site policies check.
2424
    // Or if the user auth type is webservice.
2425
    if (!$USER->policyagreed && !is_siteadmin() && !NO_SITEPOLICY_CHECK && $USER->auth !== 'webservice') {
2426
        $manager = new \core_privacy\local\sitepolicy\manager();
2427
        if ($policyurl = $manager->get_redirect_url(isguestuser())) {
2428
            if ($preventredirect) {
2429
                throw new moodle_exception('sitepolicynotagreed', 'error', '', $policyurl->out());
2430
            }
2431
            if ($setwantsurltome) {
2432
                $SESSION->wantsurl = qualified_me();
2433
            }
2434
            redirect($policyurl);
2435
        }
2436
    }
2437
 
2438
    // Fetch the system context, the course context, and prefetch its child contexts.
2439
    $sysctx = context_system::instance();
2440
    $coursecontext = context_course::instance($course->id, MUST_EXIST);
2441
    if ($cm) {
2442
        $cmcontext = context_module::instance($cm->id, MUST_EXIST);
2443
    } else {
2444
        $cmcontext = null;
2445
    }
2446
 
2447
    // If the site is currently under maintenance, then print a message.
2448
    if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:maintenanceaccess', $sysctx)) {
2449
        if ($preventredirect) {
2450
            throw new require_login_exception('Maintenance in progress');
2451
        }
2452
        $PAGE->set_context(null);
2453
        print_maintenance_message();
2454
    }
2455
 
2456
    // Make sure the course itself is not hidden.
2457
    if ($course->id == SITEID) {
2458
        // Frontpage can not be hidden.
2459
    } else {
2460
        if (is_role_switched($course->id)) {
2461
            // When switching roles ignore the hidden flag - user had to be in course to do the switch.
2462
        } else {
2463
            if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2464
                // Originally there was also test of parent category visibility, BUT is was very slow in complex queries
2465
                // involving "my courses" now it is also possible to simply hide all courses user is not enrolled in :-).
2466
                if ($preventredirect) {
2467
                    throw new require_login_exception('Course is hidden');
2468
                }
2469
                $PAGE->set_context(null);
2470
                // We need to override the navigation URL as the course won't have been added to the navigation and thus
2471
                // the navigation will mess up when trying to find it.
2472
                navigation_node::override_active_url(new moodle_url('/'));
2473
                notice(get_string('coursehidden'), $CFG->wwwroot .'/');
2474
            }
2475
        }
2476
    }
2477
 
2478
    // Is the user enrolled?
2479
    if ($course->id == SITEID) {
2480
        // Everybody is enrolled on the frontpage.
2481
    } else {
2482
        if (\core\session\manager::is_loggedinas()) {
2483
            // Make sure the REAL person can access this course first.
2484
            $realuser = \core\session\manager::get_realuser();
2485
            if (!is_enrolled($coursecontext, $realuser->id, '', true) and
2486
                !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
2487
                if ($preventredirect) {
2488
                    throw new require_login_exception('Invalid course login-as access');
2489
                }
2490
                $PAGE->set_context(null);
2491
                echo $OUTPUT->header();
2492
                notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
2493
            }
2494
        }
2495
 
2496
        $access = false;
2497
 
2498
        if (is_role_switched($course->id)) {
2499
            // Ok, user had to be inside this course before the switch.
2500
            $access = true;
2501
 
2502
        } else if (is_viewing($coursecontext, $USER)) {
2503
            // Ok, no need to mess with enrol.
2504
            $access = true;
2505
 
2506
        } else {
2507
            if (isset($USER->enrol['enrolled'][$course->id])) {
2508
                if ($USER->enrol['enrolled'][$course->id] > time()) {
2509
                    $access = true;
2510
                    if (isset($USER->enrol['tempguest'][$course->id])) {
2511
                        unset($USER->enrol['tempguest'][$course->id]);
2512
                        remove_temp_course_roles($coursecontext);
2513
                    }
2514
                } else {
2515
                    // Expired.
2516
                    unset($USER->enrol['enrolled'][$course->id]);
2517
                }
2518
            }
2519
            if (isset($USER->enrol['tempguest'][$course->id])) {
2520
                if ($USER->enrol['tempguest'][$course->id] == 0) {
2521
                    $access = true;
2522
                } else if ($USER->enrol['tempguest'][$course->id] > time()) {
2523
                    $access = true;
2524
                } else {
2525
                    // Expired.
2526
                    unset($USER->enrol['tempguest'][$course->id]);
2527
                    remove_temp_course_roles($coursecontext);
2528
                }
2529
            }
2530
 
2531
            if (!$access) {
2532
                // Cache not ok.
2533
                $until = enrol_get_enrolment_end($coursecontext->instanceid, $USER->id);
2534
                if ($until !== false) {
2535
                    // Active participants may always access, a timestamp in the future, 0 (always) or false.
2536
                    if ($until == 0) {
2537
                        $until = ENROL_MAX_TIMESTAMP;
2538
                    }
2539
                    $USER->enrol['enrolled'][$course->id] = $until;
2540
                    $access = true;
2541
 
2542
                } else if (core_course_category::can_view_course_info($course)) {
2543
                    $params = array('courseid' => $course->id, 'status' => ENROL_INSTANCE_ENABLED);
2544
                    $instances = $DB->get_records('enrol', $params, 'sortorder, id ASC');
2545
                    $enrols = enrol_get_plugins(true);
2546
                    // First ask all enabled enrol instances in course if they want to auto enrol user.
2547
                    foreach ($instances as $instance) {
2548
                        if (!isset($enrols[$instance->enrol])) {
2549
                            continue;
2550
                        }
2551
                        // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
2552
                        $until = $enrols[$instance->enrol]->try_autoenrol($instance);
2553
                        if ($until !== false) {
2554
                            if ($until == 0) {
2555
                                $until = ENROL_MAX_TIMESTAMP;
2556
                            }
2557
                            $USER->enrol['enrolled'][$course->id] = $until;
2558
                            $access = true;
2559
                            break;
2560
                        }
2561
                    }
2562
                    // If not enrolled yet try to gain temporary guest access.
2563
                    if (!$access) {
2564
                        foreach ($instances as $instance) {
2565
                            if (!isset($enrols[$instance->enrol])) {
2566
                                continue;
2567
                            }
2568
                            // Get a duration for the guest access, a timestamp in the future or false.
2569
                            $until = $enrols[$instance->enrol]->try_guestaccess($instance);
2570
                            if ($until !== false and $until > time()) {
2571
                                $USER->enrol['tempguest'][$course->id] = $until;
2572
                                $access = true;
2573
                                break;
2574
                            }
2575
                        }
2576
                    }
2577
                } else {
2578
                    // User is not enrolled and is not allowed to browse courses here.
2579
                    if ($preventredirect) {
2580
                        throw new require_login_exception('Course is not available');
2581
                    }
2582
                    $PAGE->set_context(null);
2583
                    // We need to override the navigation URL as the course won't have been added to the navigation and thus
2584
                    // the navigation will mess up when trying to find it.
2585
                    navigation_node::override_active_url(new moodle_url('/'));
2586
                    notice(get_string('coursehidden'), $CFG->wwwroot .'/');
2587
                }
2588
            }
2589
        }
2590
 
2591
        if (!$access) {
2592
            if ($preventredirect) {
2593
                throw new require_login_exception('Not enrolled');
2594
            }
2595
            if ($setwantsurltome) {
2596
                $SESSION->wantsurl = qualified_me();
2597
            }
2598
            redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
2599
        }
2600
    }
2601
 
2602
    // Check whether the activity has been scheduled for deletion. If so, then deny access, even for admins.
2603
    if ($cm && $cm->deletioninprogress) {
2604
        if ($preventredirect) {
2605
            throw new moodle_exception('activityisscheduledfordeletion');
2606
        }
2607
        require_once($CFG->dirroot . '/course/lib.php');
2608
        redirect(course_get_url($course), get_string('activityisscheduledfordeletion', 'error'));
2609
    }
2610
 
2611
    // Check visibility of activity to current user; includes visible flag, conditional availability, etc.
2612
    if ($cm && !$cm->uservisible) {
2613
        if ($preventredirect) {
2614
            throw new require_login_exception('Activity is hidden');
2615
        }
2616
        // Get the error message that activity is not available and why (if explanation can be shown to the user).
2617
        $PAGE->set_course($course);
2618
        $renderer = $PAGE->get_renderer('course');
2619
        $message = $renderer->course_section_cm_unavailable_error_message($cm);
2620
        redirect(course_get_url($course), $message, null, \core\output\notification::NOTIFY_ERROR);
2621
    }
2622
 
2623
    // Set the global $COURSE.
2624
    if ($cm) {
2625
        $PAGE->set_cm($cm, $course);
2626
        $PAGE->set_pagelayout('incourse');
2627
    } else if (!empty($courseorid)) {
2628
        $PAGE->set_course($course);
2629
    }
2630
 
2631
    foreach ($afterlogins as $plugintype => $plugins) {
2632
        foreach ($plugins as $pluginfunction) {
2633
            $pluginfunction($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2634
        }
2635
    }
2636
 
2637
    // Finally access granted, update lastaccess times.
2638
    // Do not update access time for webservice or ajax requests.
2639
    if (!WS_SERVER && !AJAX_SCRIPT) {
2640
        user_accesstime_log($course->id);
2641
    }
2642
}
2643
 
2644
/**
2645
 * A convenience function for where we must be logged in as admin
2646
 * @return void
2647
 */
2648
function require_admin() {
2649
    require_login(null, false);
2650
    require_capability('moodle/site:config', context_system::instance());
2651
}
2652
 
2653
/**
2654
 * This function just makes sure a user is logged out.
2655
 *
2656
 * @package    core_access
2657
 * @category   access
2658
 */
2659
function require_logout() {
2660
    global $USER, $DB;
2661
 
2662
    if (!isloggedin()) {
2663
        // This should not happen often, no need for hooks or events here.
2664
        \core\session\manager::terminate_current();
2665
        return;
2666
    }
2667
 
2668
    // Execute hooks before action.
2669
    $authplugins = array();
2670
    $authsequence = get_enabled_auth_plugins();
2671
    foreach ($authsequence as $authname) {
2672
        $authplugins[$authname] = get_auth_plugin($authname);
2673
        $authplugins[$authname]->prelogout_hook();
2674
    }
2675
 
2676
    // Store info that gets removed during logout.
2677
    $sid = session_id();
2678
    $event = \core\event\user_loggedout::create(
2679
        array(
2680
            'userid' => $USER->id,
2681
            'objectid' => $USER->id,
2682
            'other' => array('sessionid' => $sid),
2683
        )
2684
    );
2685
    if ($session = $DB->get_record('sessions', array('sid'=>$sid))) {
2686
        $event->add_record_snapshot('sessions', $session);
2687
    }
2688
 
2689
    // Clone of $USER object to be used by auth plugins.
2690
    $user = fullclone($USER);
2691
 
2692
    // Delete session record and drop $_SESSION content.
2693
    \core\session\manager::terminate_current();
2694
 
2695
    // Trigger event AFTER action.
2696
    $event->trigger();
2697
 
2698
    // Hook to execute auth plugins redirection after event trigger.
2699
    foreach ($authplugins as $authplugin) {
2700
        $authplugin->postlogout_hook($user);
2701
    }
2702
}
2703
 
2704
/**
2705
 * Weaker version of require_login()
2706
 *
2707
 * This is a weaker version of {@link require_login()} which only requires login
2708
 * when called from within a course rather than the site page, unless
2709
 * the forcelogin option is turned on.
2710
 * @see require_login()
2711
 *
2712
 * @package    core_access
2713
 * @category   access
2714
 *
2715
 * @param mixed $courseorid The course object or id in question
2716
 * @param bool $autologinguest Allow autologin guests if that is wanted
2717
 * @param object $cm Course activity module if known
2718
 * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2719
 *             true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2720
 *             in order to keep redirects working properly. MDL-14495
2721
 * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2722
 * @return void
2723
 * @throws coding_exception
2724
 */
2725
function require_course_login($courseorid, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
2726
    global $CFG, $PAGE, $SITE;
2727
    $issite = ((is_object($courseorid) and $courseorid->id == SITEID)
2728
          or (!is_object($courseorid) and $courseorid == SITEID));
2729
    if ($issite && !empty($cm) && !($cm instanceof cm_info)) {
2730
        // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
2731
        // db queries so this is not really a performance concern, however it is obviously
2732
        // better if you use get_fast_modinfo to get the cm before calling this.
2733
        if (is_object($courseorid)) {
2734
            $course = $courseorid;
2735
        } else {
2736
            $course = clone($SITE);
2737
        }
2738
        $modinfo = get_fast_modinfo($course);
2739
        $cm = $modinfo->get_cm($cm->id);
2740
    }
2741
    if (!empty($CFG->forcelogin)) {
2742
        // Login required for both SITE and courses.
2743
        require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2744
 
2745
    } else if ($issite && !empty($cm) and !$cm->uservisible) {
2746
        // Always login for hidden activities.
2747
        require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2748
 
2749
    } else if (isloggedin() && !isguestuser()) {
2750
        // User is already logged in. Make sure the login is complete (user is fully setup, policies agreed).
2751
        require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2752
 
2753
    } else if ($issite) {
2754
        // Login for SITE not required.
2755
        // We still need to instatiate PAGE vars properly so that things that rely on it like navigation function correctly.
2756
        if (!empty($courseorid)) {
2757
            if (is_object($courseorid)) {
2758
                $course = $courseorid;
2759
            } else {
2760
                $course = clone $SITE;
2761
            }
2762
            if ($cm) {
2763
                if ($cm->course != $course->id) {
2764
                    throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
2765
                }
2766
                $PAGE->set_cm($cm, $course);
2767
                $PAGE->set_pagelayout('incourse');
2768
            } else {
2769
                $PAGE->set_course($course);
2770
            }
2771
        } else {
2772
            // If $PAGE->course, and hence $PAGE->context, have not already been set up properly, set them up now.
2773
            $PAGE->set_course($PAGE->course);
2774
        }
2775
        // Do not update access time for webservice or ajax requests.
2776
        if (!WS_SERVER && !AJAX_SCRIPT) {
2777
            user_accesstime_log(SITEID);
2778
        }
2779
        return;
2780
 
2781
    } else {
2782
        // Course login always required.
2783
        require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2784
    }
2785
}
2786
 
2787
/**
2788
 * Validates a user key, checking if the key exists, is not expired and the remote ip is correct.
2789
 *
2790
 * @param  string $keyvalue the key value
2791
 * @param  string $script   unique script identifier
2792
 * @param  int $instance    instance id
2793
 * @return stdClass the key entry in the user_private_key table
2794
 * @since Moodle 3.2
2795
 * @throws moodle_exception
2796
 */
2797
function validate_user_key($keyvalue, $script, $instance) {
2798
    global $DB;
2799
 
2800
    if (!$key = $DB->get_record('user_private_key', array('script' => $script, 'value' => $keyvalue, 'instance' => $instance))) {
2801
        throw new \moodle_exception('invalidkey');
2802
    }
2803
 
2804
    if (!empty($key->validuntil) and $key->validuntil < time()) {
2805
        throw new \moodle_exception('expiredkey');
2806
    }
2807
 
2808
    if ($key->iprestriction) {
2809
        $remoteaddr = getremoteaddr(null);
2810
        if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction)) {
2811
            throw new \moodle_exception('ipmismatch');
2812
        }
2813
    }
2814
    return $key;
2815
}
2816
 
2817
/**
2818
 * Require key login. Function terminates with error if key not found or incorrect.
2819
 *
2820
 * @uses NO_MOODLE_COOKIES
2821
 * @uses PARAM_ALPHANUM
2822
 * @param string $script unique script identifier
2823
 * @param int $instance optional instance id
2824
 * @param string $keyvalue The key. If not supplied, this will be fetched from the current session.
2825
 * @return int Instance ID
2826
 */
2827
function require_user_key_login($script, $instance = null, $keyvalue = null) {
2828
    global $DB;
2829
 
2830
    if (!NO_MOODLE_COOKIES) {
2831
        throw new \moodle_exception('sessioncookiesdisable');
2832
    }
2833
 
2834
    // Extra safety.
2835
    \core\session\manager::write_close();
2836
 
2837
    if (null === $keyvalue) {
2838
        $keyvalue = required_param('key', PARAM_ALPHANUM);
2839
    }
2840
 
2841
    $key = validate_user_key($keyvalue, $script, $instance);
2842
 
2843
    if (!$user = $DB->get_record('user', array('id' => $key->userid))) {
2844
        throw new \moodle_exception('invaliduserid');
2845
    }
2846
 
2847
    core_user::require_active_user($user, true, true);
2848
 
2849
    // Emulate normal session.
2850
    enrol_check_plugins($user, false);
2851
    \core\session\manager::set_user($user);
2852
 
2853
    // Note we are not using normal login.
2854
    if (!defined('USER_KEY_LOGIN')) {
2855
        define('USER_KEY_LOGIN', true);
2856
    }
2857
 
2858
    // Return instance id - it might be empty.
2859
    return $key->instance;
2860
}
2861
 
2862
/**
2863
 * Creates a new private user access key.
2864
 *
2865
 * @param string $script unique target identifier
2866
 * @param int $userid
2867
 * @param int $instance optional instance id
2868
 * @param string $iprestriction optional ip restricted access
2869
 * @param int $validuntil key valid only until given data
2870
 * @return string access key value
2871
 */
2872
function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
2873
    global $DB;
2874
 
2875
    $key = new stdClass();
2876
    $key->script        = $script;
2877
    $key->userid        = $userid;
2878
    $key->instance      = $instance;
2879
    $key->iprestriction = $iprestriction;
2880
    $key->validuntil    = $validuntil;
2881
    $key->timecreated   = time();
2882
 
2883
    // Something long and unique.
2884
    $key->value         = md5($userid.'_'.time().random_string(40));
2885
    while ($DB->record_exists('user_private_key', array('value' => $key->value))) {
2886
        // Must be unique.
2887
        $key->value     = md5($userid.'_'.time().random_string(40));
2888
    }
2889
    $DB->insert_record('user_private_key', $key);
2890
    return $key->value;
2891
}
2892
 
2893
/**
2894
 * Delete the user's new private user access keys for a particular script.
2895
 *
2896
 * @param string $script unique target identifier
2897
 * @param int $userid
2898
 * @return void
2899
 */
2900
function delete_user_key($script, $userid) {
2901
    global $DB;
2902
    $DB->delete_records('user_private_key', array('script' => $script, 'userid' => $userid));
2903
}
2904
 
2905
/**
2906
 * Gets a private user access key (and creates one if one doesn't exist).
2907
 *
2908
 * @param string $script unique target identifier
2909
 * @param int $userid
2910
 * @param int $instance optional instance id
2911
 * @param string $iprestriction optional ip restricted access
2912
 * @param int $validuntil key valid only until given date
2913
 * @return string access key value
2914
 */
2915
function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
2916
    global $DB;
2917
 
2918
    if ($key = $DB->get_record('user_private_key', array('script' => $script, 'userid' => $userid,
2919
                                                         'instance' => $instance, 'iprestriction' => $iprestriction,
2920
                                                         'validuntil' => $validuntil))) {
2921
        return $key->value;
2922
    } else {
2923
        return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
2924
    }
2925
}
2926
 
2927
 
2928
/**
2929
 * Modify the user table by setting the currently logged in user's last login to now.
2930
 *
2931
 * @return bool Always returns true
2932
 */
2933
function update_user_login_times() {
2934
    global $USER, $DB, $SESSION;
2935
 
2936
    if (isguestuser()) {
2937
        // Do not update guest access times/ips for performance.
2938
        return true;
2939
    }
2940
 
2941
    if (defined('USER_KEY_LOGIN') && USER_KEY_LOGIN === true) {
2942
        // Do not update user login time when using user key login.
2943
        return true;
2944
    }
2945
 
2946
    $now = time();
2947
 
2948
    $user = new stdClass();
2949
    $user->id = $USER->id;
2950
 
2951
    // Make sure all users that logged in have some firstaccess.
2952
    if ($USER->firstaccess == 0) {
2953
        $USER->firstaccess = $user->firstaccess = $now;
2954
    }
2955
 
2956
    // Store the previous current as lastlogin.
2957
    $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
2958
 
2959
    $USER->currentlogin = $user->currentlogin = $now;
2960
 
2961
    // Function user_accesstime_log() may not update immediately, better do it here.
2962
    $USER->lastaccess = $user->lastaccess = $now;
2963
    $SESSION->userpreviousip = $USER->lastip;
2964
    $USER->lastip = $user->lastip = getremoteaddr();
2965
 
2966
    // Note: do not call user_update_user() here because this is part of the login process,
2967
    //       the login event means that these fields were updated.
2968
    $DB->update_record('user', $user);
2969
    return true;
2970
}
2971
 
2972
/**
2973
 * Determines if a user has completed setting up their account.
2974
 *
2975
 * The lax mode (with $strict = false) has been introduced for special cases
2976
 * only where we want to skip certain checks intentionally. This is valid in
2977
 * certain mnet or ajax scenarios when the user cannot / should not be
2978
 * redirected to edit their profile. In most cases, you should perform the
2979
 * strict check.
2980
 *
2981
 * @param stdClass $user A {@link $USER} object to test for the existence of a valid name and email
2982
 * @param bool $strict Be more strict and assert id and custom profile fields set, too
2983
 * @return bool
2984
 */
2985
function user_not_fully_set_up($user, $strict = true) {
2986
    global $CFG, $SESSION, $USER;
2987
    require_once($CFG->dirroot.'/user/profile/lib.php');
2988
 
2989
    // If the user is setup then store this in the session to avoid re-checking.
2990
    // Some edge cases are when the users email starts to bounce or the
2991
    // configuration for custom fields has changed while they are logged in so
2992
    // we re-check this fully every hour for the rare cases it has changed.
2993
    if (isset($USER->id) && isset($user->id) && $USER->id === $user->id &&
2994
         isset($SESSION->fullysetupstrict) && (time() - $SESSION->fullysetupstrict) < HOURSECS) {
2995
        return false;
2996
    }
2997
 
2998
    if (isguestuser($user)) {
2999
        return false;
3000
    }
3001
 
3002
    if (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user)) {
3003
        return true;
3004
    }
3005
 
3006
    if ($strict) {
3007
        if (empty($user->id)) {
3008
            // Strict mode can be used with existing accounts only.
3009
            return true;
3010
        }
3011
        if (!profile_has_required_custom_fields_set($user->id)) {
3012
            return true;
3013
        }
3014
        if (isset($USER->id) && isset($user->id) && $USER->id === $user->id) {
3015
            $SESSION->fullysetupstrict = time();
3016
        }
3017
    }
3018
 
3019
    return false;
3020
}
3021
 
3022
/**
3023
 * Check whether the user has exceeded the bounce threshold
3024
 *
3025
 * @param stdClass $user A {@link $USER} object
3026
 * @return bool true => User has exceeded bounce threshold
3027
 */
3028
function over_bounce_threshold($user) {
3029
    global $CFG, $DB;
3030
 
3031
    if (empty($CFG->handlebounces)) {
3032
        return false;
3033
    }
3034
 
3035
    if (empty($user->id)) {
3036
        // No real (DB) user, nothing to do here.
3037
        return false;
3038
    }
3039
 
3040
    // Set sensible defaults.
3041
    if (empty($CFG->minbounces)) {
3042
        $CFG->minbounces = 10;
3043
    }
3044
    if (empty($CFG->bounceratio)) {
3045
        $CFG->bounceratio = .20;
3046
    }
3047
    $bouncecount = 0;
3048
    $sendcount = 0;
3049
    if ($bounce = $DB->get_record('user_preferences', array ('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3050
        $bouncecount = $bounce->value;
3051
    }
3052
    if ($send = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3053
        $sendcount = $send->value;
3054
    }
3055
    return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
3056
}
3057
 
3058
/**
3059
 * Used to increment or reset email sent count
3060
 *
3061
 * @param stdClass $user object containing an id
3062
 * @param bool $reset will reset the count to 0
3063
 * @return void
3064
 */
3065
function set_send_count($user, $reset=false) {
3066
    global $DB;
3067
 
3068
    if (empty($user->id)) {
3069
        // No real (DB) user, nothing to do here.
3070
        return;
3071
    }
3072
 
3073
    if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3074
        $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3075
        $DB->update_record('user_preferences', $pref);
3076
    } else if (!empty($reset)) {
3077
        // If it's not there and we're resetting, don't bother. Make a new one.
3078
        $pref = new stdClass();
3079
        $pref->name   = 'email_send_count';
3080
        $pref->value  = 1;
3081
        $pref->userid = $user->id;
3082
        $DB->insert_record('user_preferences', $pref, false);
3083
    }
3084
}
3085
 
3086
/**
3087
 * Increment or reset user's email bounce count
3088
 *
3089
 * @param stdClass $user object containing an id
3090
 * @param bool $reset will reset the count to 0
3091
 */
3092
function set_bounce_count($user, $reset=false) {
3093
    global $DB;
3094
 
3095
    if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3096
        $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3097
        $DB->update_record('user_preferences', $pref);
3098
    } else if (!empty($reset)) {
3099
        // If it's not there and we're resetting, don't bother. Make a new one.
3100
        $pref = new stdClass();
3101
        $pref->name   = 'email_bounce_count';
3102
        $pref->value  = 1;
3103
        $pref->userid = $user->id;
3104
        $DB->insert_record('user_preferences', $pref, false);
3105
    }
3106
}
3107
 
3108
/**
3109
 * Determines if the logged in user is currently moving an activity
3110
 *
3111
 * @param int $courseid The id of the course being tested
3112
 * @return bool
3113
 */
3114
function ismoving($courseid) {
3115
    global $USER;
3116
 
3117
    if (!empty($USER->activitycopy)) {
3118
        return ($USER->activitycopycourse == $courseid);
3119
    }
3120
    return false;
3121
}
3122
 
3123
/**
3124
 * Returns a persons full name
3125
 *
3126
 * Given an object containing all of the users name values, this function returns a string with the full name of the person.
3127
 * The result may depend on system settings or language. 'override' will force the alternativefullnameformat to be used. In
3128
 * English, fullname as well as alternativefullnameformat is set to 'firstname lastname' by default. But you could have
3129
 * fullname set to 'firstname lastname' and alternativefullnameformat set to 'firstname middlename alternatename lastname'.
3130
 *
3131
 * @param stdClass $user A {@link $USER} object to get full name of.
3132
 * @param bool $override If true then the alternativefullnameformat format rather than fullnamedisplay format will be used.
3133
 * @return string
3134
 */
3135
function fullname($user, $override=false) {
3136
    // Note: We do not intend to deprecate this function any time soon as it is too widely used at this time.
3137
    // Uses of it should be updated to use the new API and pass updated arguments.
3138
 
3139
    // Return an empty string if there is no user.
3140
    if (empty($user)) {
3141
        return '';
3142
    }
3143
 
3144
    $options = ['override' => $override];
3145
    return core_user::get_fullname($user, null, $options);
3146
}
3147
 
3148
/**
3149
 * Reduces lines of duplicated code for getting user name fields.
3150
 *
3151
 * See also {@link user_picture::unalias()}
3152
 *
3153
 * @param object $addtoobject Object to add user name fields to.
3154
 * @param object $secondobject Object that contains user name field information.
3155
 * @param string $prefix prefix to be added to all fields (including $additionalfields) e.g. authorfirstname.
3156
 * @param array $additionalfields Additional fields to be matched with data in the second object.
3157
 * The key can be set to the user table field name.
3158
 * @return object User name fields.
3159
 */
3160
function username_load_fields_from_object($addtoobject, $secondobject, $prefix = null, $additionalfields = null) {
3161
    $fields = [];
3162
    foreach (\core_user\fields::get_name_fields() as $field) {
3163
        $fields[$field] = $prefix . $field;
3164
    }
3165
    if ($additionalfields) {
3166
        // Additional fields can specify their own 'alias' such as 'id' => 'userid'. This checks to see if
3167
        // the key is a number and then sets the key to the array value.
3168
        foreach ($additionalfields as $key => $value) {
3169
            if (is_numeric($key)) {
3170
                $additionalfields[$value] = $prefix . $value;
3171
                unset($additionalfields[$key]);
3172
            } else {
3173
                $additionalfields[$key] = $prefix . $value;
3174
            }
3175
        }
3176
        $fields = array_merge($fields, $additionalfields);
3177
    }
3178
    foreach ($fields as $key => $field) {
3179
        // Important that we have all of the user name fields present in the object that we are sending back.
3180
        $addtoobject->$key = '';
3181
        if (isset($secondobject->$field)) {
3182
            $addtoobject->$key = $secondobject->$field;
3183
        }
3184
    }
3185
    return $addtoobject;
3186
}
3187
 
3188
/**
3189
 * Returns an array of values in order of occurance in a provided string.
3190
 * The key in the result is the character postion in the string.
3191
 *
3192
 * @param array $values Values to be found in the string format
3193
 * @param string $stringformat The string which may contain values being searched for.
3194
 * @return array An array of values in order according to placement in the string format.
3195
 */
3196
function order_in_string($values, $stringformat) {
3197
    $valuearray = array();
3198
    foreach ($values as $value) {
3199
        $pattern = "/$value\b/";
3200
        // Using preg_match as strpos() may match values that are similar e.g. firstname and firstnamephonetic.
3201
        if (preg_match($pattern, $stringformat)) {
3202
            $replacement = "thing";
3203
            // Replace the value with something more unique to ensure we get the right position when using strpos().
3204
            $newformat = preg_replace($pattern, $replacement, $stringformat);
3205
            $position = strpos($newformat, $replacement);
3206
            $valuearray[$position] = $value;
3207
        }
3208
    }
3209
    ksort($valuearray);
3210
    return $valuearray;
3211
}
3212
 
3213
/**
3214
 * Returns whether a given authentication plugin exists.
3215
 *
3216
 * @param string $auth Form of authentication to check for. Defaults to the global setting in {@link $CFG}.
3217
 * @return boolean Whether the plugin is available.
3218
 */
3219
function exists_auth_plugin($auth) {
3220
    global $CFG;
3221
 
3222
    if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
3223
        return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
3224
    }
3225
    return false;
3226
}
3227
 
3228
/**
3229
 * Checks if a given plugin is in the list of enabled authentication plugins.
3230
 *
3231
 * @param string $auth Authentication plugin.
3232
 * @return boolean Whether the plugin is enabled.
3233
 */
3234
function is_enabled_auth($auth) {
3235
    if (empty($auth)) {
3236
        return false;
3237
    }
3238
 
3239
    $enabled = get_enabled_auth_plugins();
3240
 
3241
    return in_array($auth, $enabled);
3242
}
3243
 
3244
/**
3245
 * Returns an authentication plugin instance.
3246
 *
3247
 * @param string $auth name of authentication plugin
3248
 * @return auth_plugin_base An instance of the required authentication plugin.
3249
 */
3250
function get_auth_plugin($auth) {
3251
    global $CFG;
3252
 
3253
    // Check the plugin exists first.
3254
    if (! exists_auth_plugin($auth)) {
3255
        throw new \moodle_exception('authpluginnotfound', 'debug', '', $auth);
3256
    }
3257
 
3258
    // Return auth plugin instance.
3259
    require_once("{$CFG->dirroot}/auth/$auth/auth.php");
3260
    $class = "auth_plugin_$auth";
3261
    return new $class;
3262
}
3263
 
3264
/**
3265
 * Returns array of active auth plugins.
3266
 *
3267
 * @param bool $fix fix $CFG->auth if needed. Only set if logged in as admin.
3268
 * @return array
3269
 */
3270
function get_enabled_auth_plugins($fix=false) {
3271
    global $CFG;
3272
 
3273
    $default = array('manual', 'nologin');
3274
 
3275
    if (empty($CFG->auth)) {
3276
        $auths = array();
3277
    } else {
3278
        $auths = explode(',', $CFG->auth);
3279
    }
3280
 
3281
    $auths = array_unique($auths);
3282
    $oldauthconfig = implode(',', $auths);
3283
    foreach ($auths as $k => $authname) {
3284
        if (in_array($authname, $default)) {
3285
            // The manual and nologin plugin never need to be stored.
3286
            unset($auths[$k]);
3287
        } else if (!exists_auth_plugin($authname)) {
3288
            debugging(get_string('authpluginnotfound', 'debug', $authname));
3289
            unset($auths[$k]);
3290
        }
3291
    }
3292
 
3293
    // Ideally only explicit interaction from a human admin should trigger a
3294
    // change in auth config, see MDL-70424 for details.
3295
    if ($fix) {
3296
        $newconfig = implode(',', $auths);
3297
        if (!isset($CFG->auth) or $newconfig != $CFG->auth) {
3298
            add_to_config_log('auth', $oldauthconfig, $newconfig, 'core');
3299
            set_config('auth', $newconfig);
3300
        }
3301
    }
3302
 
3303
    return (array_merge($default, $auths));
3304
}
3305
 
3306
/**
3307
 * Returns true if an internal authentication method is being used.
3308
 * if method not specified then, global default is assumed
3309
 *
3310
 * @param string $auth Form of authentication required
3311
 * @return bool
3312
 */
3313
function is_internal_auth($auth) {
3314
    // Throws error if bad $auth.
3315
    $authplugin = get_auth_plugin($auth);
3316
    return $authplugin->is_internal();
3317
}
3318
 
3319
/**
3320
 * Returns true if the user is a 'restored' one.
3321
 *
3322
 * Used in the login process to inform the user and allow him/her to reset the password
3323
 *
3324
 * @param string $username username to be checked
3325
 * @return bool
3326
 */
3327
function is_restored_user($username) {
3328
    global $CFG, $DB;
3329
 
3330
    return $DB->record_exists('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'password' => 'restored'));
3331
}
3332
 
3333
/**
3334
 * Returns an array of user fields
3335
 *
3336
 * @return array User field/column names
3337
 */
3338
function get_user_fieldnames() {
3339
    global $DB;
3340
 
3341
    $fieldarray = $DB->get_columns('user');
3342
    unset($fieldarray['id']);
3343
    $fieldarray = array_keys($fieldarray);
3344
 
3345
    return $fieldarray;
3346
}
3347
 
3348
/**
3349
 * Returns the string of the language for the new user.
3350
 *
3351
 * @return string language for the new user
3352
 */
3353
function get_newuser_language() {
3354
    global $CFG, $SESSION;
3355
    return (!empty($CFG->autolangusercreation) && !empty($SESSION->lang)) ? $SESSION->lang : $CFG->lang;
3356
}
3357
 
3358
/**
3359
 * Creates a bare-bones user record
3360
 *
3361
 * @todo Outline auth types and provide code example
3362
 *
3363
 * @param string $username New user's username to add to record
3364
 * @param string $password New user's password to add to record
3365
 * @param string $auth Form of authentication required
3366
 * @return stdClass A complete user object
3367
 */
3368
function create_user_record($username, $password, $auth = 'manual') {
3369
    global $CFG, $DB, $SESSION;
3370
    require_once($CFG->dirroot.'/user/profile/lib.php');
3371
    require_once($CFG->dirroot.'/user/lib.php');
3372
 
3373
    // Just in case check text case.
3374
    $username = trim(core_text::strtolower($username));
3375
 
3376
    $authplugin = get_auth_plugin($auth);
3377
    $customfields = $authplugin->get_custom_user_profile_fields();
3378
    $newuser = new stdClass();
3379
    if ($newinfo = $authplugin->get_userinfo($username)) {
3380
        $newinfo = truncate_userinfo($newinfo);
3381
        foreach ($newinfo as $key => $value) {
3382
            if (in_array($key, $authplugin->userfields) || (in_array($key, $customfields))) {
3383
                $newuser->$key = $value;
3384
            }
3385
        }
3386
    }
3387
 
3388
    if (!empty($newuser->email)) {
3389
        if (email_is_not_allowed($newuser->email)) {
3390
            unset($newuser->email);
3391
        }
3392
    }
3393
 
3394
    $newuser->auth = $auth;
3395
    $newuser->username = $username;
3396
 
3397
    // Fix for MDL-8480
3398
    // user CFG lang for user if $newuser->lang is empty
3399
    // or $user->lang is not an installed language.
3400
    if (empty($newuser->lang) || !get_string_manager()->translation_exists($newuser->lang)) {
3401
        $newuser->lang = get_newuser_language();
3402
    }
3403
    $newuser->confirmed = 1;
3404
    $newuser->lastip = getremoteaddr();
3405
    $newuser->timecreated = time();
3406
    $newuser->timemodified = $newuser->timecreated;
3407
    $newuser->mnethostid = $CFG->mnet_localhost_id;
3408
 
3409
    $newuser->id = user_create_user($newuser, false, false);
3410
 
3411
    // Save user profile data.
3412
    profile_save_data($newuser);
3413
 
3414
    $user = get_complete_user_data('id', $newuser->id);
3415
    if (!empty($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'})) {
3416
        set_user_preference('auth_forcepasswordchange', 1, $user);
3417
    }
3418
    // Set the password.
3419
    update_internal_user_password($user, $password);
3420
 
3421
    // Trigger event.
3422
    \core\event\user_created::create_from_userid($newuser->id)->trigger();
3423
 
3424
    return $user;
3425
}
3426
 
3427
/**
3428
 * Will update a local user record from an external source (MNET users can not be updated using this method!).
3429
 *
3430
 * @param string $username user's username to update the record
3431
 * @return stdClass A complete user object
3432
 */
3433
function update_user_record($username) {
3434
    global $DB, $CFG;
3435
    // Just in case check text case.
3436
    $username = trim(core_text::strtolower($username));
3437
 
3438
    $oldinfo = $DB->get_record('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id), '*', MUST_EXIST);
3439
    return update_user_record_by_id($oldinfo->id);
3440
}
3441
 
3442
/**
3443
 * Will update a local user record from an external source (MNET users can not be updated using this method!).
3444
 *
3445
 * @param int $id user id
3446
 * @return stdClass A complete user object
3447
 */
3448
function update_user_record_by_id($id) {
3449
    global $DB, $CFG;
3450
    require_once($CFG->dirroot."/user/profile/lib.php");
3451
    require_once($CFG->dirroot.'/user/lib.php');
3452
 
3453
    $params = array('mnethostid' => $CFG->mnet_localhost_id, 'id' => $id, 'deleted' => 0);
3454
    $oldinfo = $DB->get_record('user', $params, '*', MUST_EXIST);
3455
 
3456
    $newuser = array();
3457
    $userauth = get_auth_plugin($oldinfo->auth);
3458
 
3459
    if ($newinfo = $userauth->get_userinfo($oldinfo->username)) {
3460
        $newinfo = truncate_userinfo($newinfo);
3461
        $customfields = $userauth->get_custom_user_profile_fields();
3462
 
3463
        foreach ($newinfo as $key => $value) {
3464
            $iscustom = in_array($key, $customfields);
3465
            if (!$iscustom) {
3466
                $key = strtolower($key);
3467
            }
3468
            if ((!property_exists($oldinfo, $key) && !$iscustom) or $key === 'username' or $key === 'id'
3469
                    or $key === 'auth' or $key === 'mnethostid' or $key === 'deleted') {
3470
                // Unknown or must not be changed.
3471
                continue;
3472
            }
3473
            if (empty($userauth->config->{'field_updatelocal_' . $key}) || empty($userauth->config->{'field_lock_' . $key})) {
3474
                continue;
3475
            }
3476
            $confval = $userauth->config->{'field_updatelocal_' . $key};
3477
            $lockval = $userauth->config->{'field_lock_' . $key};
3478
            if ($confval === 'onlogin') {
3479
                // MDL-4207 Don't overwrite modified user profile values with
3480
                // empty LDAP values when 'unlocked if empty' is set. The purpose
3481
                // of the setting 'unlocked if empty' is to allow the user to fill
3482
                // in a value for the selected field _if LDAP is giving
3483
                // nothing_ for this field. Thus it makes sense to let this value
3484
                // stand in until LDAP is giving a value for this field.
3485
                if (!(empty($value) && $lockval === 'unlockedifempty')) {
3486
                    if ($iscustom || (in_array($key, $userauth->userfields) &&
3487
                            ((string)$oldinfo->$key !== (string)$value))) {
3488
                        $newuser[$key] = (string)$value;
3489
                    }
3490
                }
3491
            }
3492
        }
3493
        if ($newuser) {
3494
            $newuser['id'] = $oldinfo->id;
3495
            $newuser['timemodified'] = time();
3496
            user_update_user((object) $newuser, false, false);
3497
 
3498
            // Save user profile data.
3499
            profile_save_data((object) $newuser);
3500
 
3501
            // Trigger event.
3502
            \core\event\user_updated::create_from_userid($newuser['id'])->trigger();
3503
        }
3504
    }
3505
 
3506
    return get_complete_user_data('id', $oldinfo->id);
3507
}
3508
 
3509
/**
3510
 * Will truncate userinfo as it comes from auth_get_userinfo (from external auth) which may have large fields.
3511
 *
3512
 * @param array $info Array of user properties to truncate if needed
3513
 * @return array The now truncated information that was passed in
3514
 */
3515
function truncate_userinfo(array $info) {
3516
    // Define the limits.
3517
    $limit = array(
3518
        'username'    => 100,
3519
        'idnumber'    => 255,
3520
        'firstname'   => 100,
3521
        'lastname'    => 100,
3522
        'email'       => 100,
3523
        'phone1'      =>  20,
3524
        'phone2'      =>  20,
3525
        'institution' => 255,
3526
        'department'  => 255,
3527
        'address'     => 255,
3528
        'city'        => 120,
3529
        'country'     =>   2,
3530
    );
3531
 
3532
    // Apply where needed.
3533
    foreach (array_keys($info) as $key) {
3534
        if (!empty($limit[$key])) {
3535
            $info[$key] = trim(core_text::substr($info[$key], 0, $limit[$key]));
3536
        }
3537
    }
3538
 
3539
    return $info;
3540
}
3541
 
3542
/**
3543
 * Marks user deleted in internal user database and notifies the auth plugin.
3544
 * Also unenrols user from all roles and does other cleanup.
3545
 *
3546
 * Any plugin that needs to purge user data should register the 'user_deleted' event.
3547
 *
3548
 * @param stdClass $user full user object before delete
3549
 * @return boolean success
3550
 * @throws coding_exception if invalid $user parameter detected
3551
 */
3552
function delete_user(stdClass $user) {
3553
    global $CFG, $DB, $SESSION;
3554
    require_once($CFG->libdir.'/grouplib.php');
3555
    require_once($CFG->libdir.'/gradelib.php');
3556
    require_once($CFG->dirroot.'/message/lib.php');
3557
    require_once($CFG->dirroot.'/user/lib.php');
3558
 
3559
    // Make sure nobody sends bogus record type as parameter.
3560
    if (!property_exists($user, 'id') or !property_exists($user, 'username')) {
3561
        throw new coding_exception('Invalid $user parameter in delete_user() detected');
3562
    }
3563
 
3564
    // Better not trust the parameter and fetch the latest info this will be very expensive anyway.
3565
    if (!$user = $DB->get_record('user', array('id' => $user->id))) {
3566
        debugging('Attempt to delete unknown user account.');
3567
        return false;
3568
    }
3569
 
3570
    // There must be always exactly one guest record, originally the guest account was identified by username only,
3571
    // now we use $CFG->siteguest for performance reasons.
3572
    if ($user->username === 'guest' or isguestuser($user)) {
3573
        debugging('Guest user account can not be deleted.');
3574
        return false;
3575
    }
3576
 
3577
    // Admin can be theoretically from different auth plugin, but we want to prevent deletion of internal accoutns only,
3578
    // if anything goes wrong ppl may force somebody to be admin via config.php setting $CFG->siteadmins.
3579
    if ($user->auth === 'manual' and is_siteadmin($user)) {
3580
        debugging('Local administrator accounts can not be deleted.');
3581
        return false;
3582
    }
3583
    // Allow plugins to use this user object before we completely delete it.
3584
    if ($pluginsfunction = get_plugins_with_function('pre_user_delete')) {
3585
        foreach ($pluginsfunction as $plugintype => $plugins) {
3586
            foreach ($plugins as $pluginfunction) {
3587
                $pluginfunction($user);
3588
            }
3589
        }
3590
    }
3591
 
3592
    // Dispatch the hook for pre user update actions.
3593
    $hook = new \core_user\hook\before_user_deleted(
3594
        user: $user,
3595
    );
3596
    di::get(hook\manager::class)->dispatch($hook);
3597
 
3598
    // Keep user record before updating it, as we have to pass this to user_deleted event.
3599
    $olduser = clone $user;
3600
 
3601
    // Keep a copy of user context, we need it for event.
3602
    $usercontext = context_user::instance($user->id);
3603
 
3604
    // Delete all grades - backup is kept in grade_grades_history table.
3605
    grade_user_delete($user->id);
3606
 
3607
    // TODO: remove from cohorts using standard API here.
3608
 
3609
    // Remove user tags.
3610
    core_tag_tag::remove_all_item_tags('core', 'user', $user->id);
3611
 
3612
    // Unconditionally unenrol from all courses.
3613
    enrol_user_delete($user);
3614
 
3615
    // Unenrol from all roles in all contexts.
3616
    // This might be slow but it is really needed - modules might do some extra cleanup!
3617
    role_unassign_all(array('userid' => $user->id));
3618
 
3619
    // Notify the competency subsystem.
3620
    \core_competency\api::hook_user_deleted($user->id);
3621
 
3622
    // Now do a brute force cleanup.
3623
 
3624
    // Delete all user events and subscription events.
3625
    $DB->delete_records_select('event', 'userid = :userid AND subscriptionid IS NOT NULL', ['userid' => $user->id]);
3626
 
3627
    // Now, delete all calendar subscription from the user.
3628
    $DB->delete_records('event_subscriptions', ['userid' => $user->id]);
3629
 
3630
    // Remove from all cohorts.
3631
    $DB->delete_records('cohort_members', array('userid' => $user->id));
3632
 
3633
    // Remove from all groups.
3634
    $DB->delete_records('groups_members', array('userid' => $user->id));
3635
 
3636
    // Brute force unenrol from all courses.
3637
    $DB->delete_records('user_enrolments', array('userid' => $user->id));
3638
 
3639
    // Purge user preferences.
3640
    $DB->delete_records('user_preferences', array('userid' => $user->id));
3641
 
3642
    // Purge user extra profile info.
3643
    $DB->delete_records('user_info_data', array('userid' => $user->id));
3644
 
3645
    // Purge log of previous password hashes.
3646
    $DB->delete_records('user_password_history', array('userid' => $user->id));
3647
 
3648
    // Last course access not necessary either.
3649
    $DB->delete_records('user_lastaccess', array('userid' => $user->id));
3650
    // Remove all user tokens.
3651
    $DB->delete_records('external_tokens', array('userid' => $user->id));
3652
 
3653
    // Unauthorise the user for all services.
3654
    $DB->delete_records('external_services_users', array('userid' => $user->id));
3655
 
3656
    // Remove users private keys.
3657
    $DB->delete_records('user_private_key', array('userid' => $user->id));
3658
 
3659
    // Remove users customised pages.
3660
    $DB->delete_records('my_pages', array('userid' => $user->id, 'private' => 1));
3661
 
3662
    // Remove user's oauth2 refresh tokens, if present.
3663
    $DB->delete_records('oauth2_refresh_token', array('userid' => $user->id));
3664
 
3665
    // Delete user from $SESSION->bulk_users.
3666
    if (isset($SESSION->bulk_users[$user->id])) {
3667
        unset($SESSION->bulk_users[$user->id]);
3668
    }
3669
 
3670
    // Force logout - may fail if file based sessions used, sorry.
3671
    \core\session\manager::kill_user_sessions($user->id);
3672
 
3673
    // Generate username from email address, or a fake email.
3674
    $delemail = !empty($user->email) ? $user->email : $user->username . '.' . $user->id . '@unknownemail.invalid';
3675
 
3676
    $deltime = time();
3677
 
3678
    // Max username length is 100 chars. Select up to limit - (length of current time + 1 [period character]) from users email.
3679
    $delnameprefix = clean_param($delemail, PARAM_USERNAME);
3680
    $delnamesuffix = $deltime;
3681
    $delnamesuffixlength = 10;
3682
    do {
3683
        // Workaround for bulk deletes of users with the same email address.
3684
        $delname = sprintf(
3685
            "%s.%10d",
3686
            core_text::substr(
3687
                $delnameprefix,
3688
                0,
3689
                // 100 Character maximum, with a '.' character, and a 10-digit timestamp.
3690
                100 - 1 - $delnamesuffixlength,
3691
            ),
3692
            $delnamesuffix,
3693
        );
3694
        $delnamesuffix++;
3695
 
3696
        // No need to use mnethostid here.
3697
    } while ($DB->record_exists('user', ['username' => $delname]));
3698
 
3699
    // Mark internal user record as "deleted".
3700
    $updateuser = new stdClass();
3701
    $updateuser->id           = $user->id;
3702
    $updateuser->deleted      = 1;
3703
    $updateuser->username     = $delname;            // Remember it just in case.
3704
    $updateuser->email        = md5($user->username);// Store hash of username, useful importing/restoring users.
3705
    $updateuser->idnumber     = '';                  // Clear this field to free it up.
3706
    $updateuser->picture      = 0;
3707
    $updateuser->timemodified = $deltime;
3708
 
3709
    // Don't trigger update event, as user is being deleted.
3710
    user_update_user($updateuser, false, false);
3711
 
3712
    // Delete all content associated with the user context, but not the context itself.
3713
    $usercontext->delete_content();
3714
 
3715
    // Delete any search data.
3716
    \core_search\manager::context_deleted($usercontext);
3717
 
3718
    // Any plugin that needs to cleanup should register this event.
3719
    // Trigger event.
3720
    $event = \core\event\user_deleted::create(
3721
            array(
3722
                'objectid' => $user->id,
3723
                'relateduserid' => $user->id,
3724
                'context' => $usercontext,
3725
                'other' => array(
3726
                    'username' => $user->username,
3727
                    'email' => $user->email,
3728
                    'idnumber' => $user->idnumber,
3729
                    'picture' => $user->picture,
3730
                    'mnethostid' => $user->mnethostid
3731
                    )
3732
                )
3733
            );
3734
    $event->add_record_snapshot('user', $olduser);
3735
    $event->trigger();
3736
 
3737
    // We will update the user's timemodified, as it will be passed to the user_deleted event, which
3738
    // should know about this updated property persisted to the user's table.
3739
    $user->timemodified = $updateuser->timemodified;
3740
 
3741
    // Notify auth plugin - do not block the delete even when plugin fails.
3742
    $authplugin = get_auth_plugin($user->auth);
3743
    $authplugin->user_delete($user);
3744
 
3745
    return true;
3746
}
3747
 
3748
/**
3749
 * Retrieve the guest user object.
3750
 *
3751
 * @return stdClass A {@link $USER} object
3752
 */
3753
function guest_user() {
3754
    global $CFG, $DB;
3755
 
3756
    if ($newuser = $DB->get_record('user', array('id' => $CFG->siteguest))) {
3757
        $newuser->confirmed = 1;
3758
        $newuser->lang = get_newuser_language();
3759
        $newuser->lastip = getremoteaddr();
3760
    }
3761
 
3762
    return $newuser;
3763
}
3764
 
3765
/**
3766
 * Authenticates a user against the chosen authentication mechanism
3767
 *
3768
 * Given a username and password, this function looks them
3769
 * up using the currently selected authentication mechanism,
3770
 * and if the authentication is successful, it returns a
3771
 * valid $user object from the 'user' table.
3772
 *
3773
 * Uses auth_ functions from the currently active auth module
3774
 *
3775
 * After authenticate_user_login() returns success, you will need to
3776
 * log that the user has logged in, and call complete_user_login() to set
3777
 * the session up.
3778
 *
3779
 * Note: this function works only with non-mnet accounts!
3780
 *
3781
 * @param string $username  User's username (or also email if $CFG->authloginviaemail enabled)
3782
 * @param string $password  User's password
3783
 * @param bool $ignorelockout useful when guessing is prevented by other mechanism such as captcha or SSO
3784
 * @param int $failurereason login failure reason, can be used in renderers (it may disclose if account exists)
3785
 * @param string|bool $logintoken If this is set to a string it is validated against the login token for the session.
3786
 * @param string|bool $loginrecaptcha If this is set to a string it is validated against Google reCaptcha.
3787
 * @return stdClass|false A {@link $USER} object or false if error
3788
 */
3789
function authenticate_user_login(
3790
    $username,
3791
    $password,
3792
    $ignorelockout = false,
3793
    &$failurereason = null,
3794
    $logintoken = false,
3795
    string|bool $loginrecaptcha = false,
3796
) {
3797
    global $CFG, $DB, $PAGE, $SESSION;
3798
    require_once("$CFG->libdir/authlib.php");
3799
 
3800
    if ($user = get_complete_user_data('username', $username, $CFG->mnet_localhost_id)) {
3801
        // we have found the user
3802
 
3803
    } else if (!empty($CFG->authloginviaemail)) {
3804
        if ($email = clean_param($username, PARAM_EMAIL)) {
3805
            $select = "mnethostid = :mnethostid AND LOWER(email) = LOWER(:email) AND deleted = 0";
3806
            $params = array('mnethostid' => $CFG->mnet_localhost_id, 'email' => $email);
3807
            $users = $DB->get_records_select('user', $select, $params, 'id', 'id', 0, 2);
3808
            if (count($users) === 1) {
3809
                // Use email for login only if unique.
3810
                $user = reset($users);
3811
                $user = get_complete_user_data('id', $user->id);
3812
                $username = $user->username;
3813
            }
3814
            unset($users);
3815
        }
3816
    }
3817
 
3818
    // Make sure this request came from the login form.
3819
    if (!\core\session\manager::validate_login_token($logintoken)) {
3820
        $failurereason = AUTH_LOGIN_FAILED;
3821
 
3822
        // Trigger login failed event (specifying the ID of the found user, if available).
3823
        \core\event\user_login_failed::create([
3824
            'userid' => ($user->id ?? 0),
3825
            'other' => [
3826
                'username' => $username,
3827
                'reason' => $failurereason,
3828
            ],
3829
        ])->trigger();
3830
 
3831
        error_log('[client '.getremoteaddr()."]  $CFG->wwwroot  Invalid Login Token:  $username  ".$_SERVER['HTTP_USER_AGENT']);
3832
        return false;
3833
    }
3834
 
3835
    // Login reCaptcha.
3836
    if (login_captcha_enabled() && !validate_login_captcha($loginrecaptcha)) {
3837
        $failurereason = AUTH_LOGIN_FAILED_RECAPTCHA;
3838
        // Trigger login failed event (specifying the ID of the found user, if available).
3839
        \core\event\user_login_failed::create([
3840
            'userid' => ($user->id ?? 0),
3841
            'other' => [
3842
                'username' => $username,
3843
                'reason' => $failurereason,
3844
            ],
3845
        ])->trigger();
3846
        return false;
3847
    }
3848
 
3849
    $authsenabled = get_enabled_auth_plugins();
3850
 
3851
    if ($user) {
3852
        // Use manual if auth not set.
3853
        $auth = empty($user->auth) ? 'manual' : $user->auth;
3854
 
3855
        if (in_array($user->auth, $authsenabled)) {
3856
            $authplugin = get_auth_plugin($user->auth);
3857
            $authplugin->pre_user_login_hook($user);
3858
        }
3859
 
3860
        if (!empty($user->suspended)) {
3861
            $failurereason = AUTH_LOGIN_SUSPENDED;
3862
 
3863
            // Trigger login failed event.
3864
            $event = \core\event\user_login_failed::create(array('userid' => $user->id,
3865
                    'other' => array('username' => $username, 'reason' => $failurereason)));
3866
            $event->trigger();
3867
            error_log('[client '.getremoteaddr()."]  $CFG->wwwroot  Suspended Login:  $username  ".$_SERVER['HTTP_USER_AGENT']);
3868
            return false;
3869
        }
3870
        if ($auth=='nologin' or !is_enabled_auth($auth)) {
3871
            // Legacy way to suspend user.
3872
            $failurereason = AUTH_LOGIN_SUSPENDED;
3873
 
3874
            // Trigger login failed event.
3875
            $event = \core\event\user_login_failed::create(array('userid' => $user->id,
3876
                    'other' => array('username' => $username, 'reason' => $failurereason)));
3877
            $event->trigger();
3878
            error_log('[client '.getremoteaddr()."]  $CFG->wwwroot  Disabled Login:  $username  ".$_SERVER['HTTP_USER_AGENT']);
3879
            return false;
3880
        }
3881
        $auths = array($auth);
3882
 
3883
    } else {
3884
        // Check if there's a deleted record (cheaply), this should not happen because we mangle usernames in delete_user().
3885
        if ($DB->get_field('user', 'id', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id,  'deleted' => 1))) {
3886
            $failurereason = AUTH_LOGIN_NOUSER;
3887
 
3888
            // Trigger login failed event.
3889
            $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
3890
                    'reason' => $failurereason)));
3891
            $event->trigger();
3892
            error_log('[client '.getremoteaddr()."]  $CFG->wwwroot  Deleted Login:  $username  ".$_SERVER['HTTP_USER_AGENT']);
3893
            return false;
3894
        }
3895
 
3896
        // User does not exist.
3897
        $auths = $authsenabled;
3898
        $user = new stdClass();
3899
        $user->id = 0;
3900
    }
3901
 
3902
    if ($ignorelockout) {
3903
        // Some other mechanism protects against brute force password guessing, for example login form might include reCAPTCHA
3904
        // or this function is called from a SSO script.
3905
    } else if ($user->id) {
3906
        // Verify login lockout after other ways that may prevent user login.
3907
        if (login_is_lockedout($user)) {
3908
            $failurereason = AUTH_LOGIN_LOCKOUT;
3909
 
3910
            // Trigger login failed event.
3911
            $event = \core\event\user_login_failed::create(array('userid' => $user->id,
3912
                    'other' => array('username' => $username, 'reason' => $failurereason)));
3913
            $event->trigger();
3914
 
3915
            error_log('[client '.getremoteaddr()."]  $CFG->wwwroot  Login lockout:  $username  ".$_SERVER['HTTP_USER_AGENT']);
3916
            $SESSION->loginerrormsg = get_string('accountlocked', 'admin');
3917
 
3918
            return false;
3919
        }
3920
    } else {
3921
        // We can not lockout non-existing accounts.
3922
    }
3923
 
3924
    foreach ($auths as $auth) {
3925
        $authplugin = get_auth_plugin($auth);
3926
 
3927
        // On auth fail fall through to the next plugin.
3928
        if (!$authplugin->user_login($username, $password)) {
3929
            continue;
3930
        }
3931
 
3932
        // Before performing login actions, check if user still passes password policy, if admin setting is enabled.
3933
        if (!empty($CFG->passwordpolicycheckonlogin)) {
3934
            $errmsg = '';
3935
            $passed = check_password_policy($password, $errmsg, $user);
3936
            if (!$passed) {
3937
                // First trigger event for failure.
3938
                $failedevent = \core\event\user_password_policy_failed::create_from_user($user);
3939
                $failedevent->trigger();
3940
 
3941
                // If able to change password, set flag and move on.
3942
                if ($authplugin->can_change_password()) {
3943
                    // Check if we are on internal change password page, or service is external, don't show notification.
3944
                    $internalchangeurl = new moodle_url('/login/change_password.php');
3945
                    if (!($PAGE->has_set_url() && $internalchangeurl->compare($PAGE->url)) && $authplugin->is_internal()) {
3946
                        \core\notification::error(get_string('passwordpolicynomatch', '', $errmsg));
3947
                    }
3948
                    set_user_preference('auth_forcepasswordchange', 1, $user);
3949
                } else if ($authplugin->can_reset_password()) {
3950
                    // Else force a reset if possible.
3951
                    \core\notification::error(get_string('forcepasswordresetnotice', '', $errmsg));
3952
                    redirect(new moodle_url('/login/forgot_password.php'));
3953
                } else {
3954
                    $notifymsg = get_string('forcepasswordresetfailurenotice', '', $errmsg);
3955
                    // If support page is set, add link for help.
3956
                    if (!empty($CFG->supportpage)) {
3957
                        $link = \html_writer::link($CFG->supportpage, $CFG->supportpage);
3958
                        $link = \html_writer::tag('p', $link);
3959
                        $notifymsg .= $link;
3960
                    }
3961
 
3962
                    // If no change or reset is possible, add a notification for user.
3963
                    \core\notification::error($notifymsg);
3964
                }
3965
            }
3966
        }
3967
 
3968
        // Successful authentication.
3969
        if ($user->id) {
3970
            // User already exists in database.
3971
            if (empty($user->auth)) {
3972
                // For some reason auth isn't set yet.
3973
                $DB->set_field('user', 'auth', $auth, array('id' => $user->id));
3974
                $user->auth = $auth;
3975
            }
3976
 
3977
            // If the existing hash is using an out-of-date algorithm (or the legacy md5 algorithm), then we should update to
3978
            // the current hash algorithm while we have access to the user's password.
3979
            update_internal_user_password($user, $password);
3980
 
3981
            if ($authplugin->is_synchronised_with_external()) {
3982
                // Update user record from external DB.
3983
                $user = update_user_record_by_id($user->id);
3984
            }
3985
        } else {
3986
            // The user is authenticated but user creation may be disabled.
3987
            if (!empty($CFG->authpreventaccountcreation)) {
3988
                $failurereason = AUTH_LOGIN_UNAUTHORISED;
3989
 
3990
                // Trigger login failed event.
3991
                $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
3992
                        'reason' => $failurereason)));
3993
                $event->trigger();
3994
 
3995
                error_log('[client '.getremoteaddr()."]  $CFG->wwwroot  Unknown user, can not create new accounts:  $username  ".
3996
                        $_SERVER['HTTP_USER_AGENT']);
3997
                return false;
3998
            } else {
3999
                $user = create_user_record($username, $password, $auth);
4000
            }
4001
        }
4002
 
4003
        $authplugin->sync_roles($user);
4004
 
4005
        foreach ($authsenabled as $hau) {
4006
            $hauth = get_auth_plugin($hau);
4007
            $hauth->user_authenticated_hook($user, $username, $password);
4008
        }
4009
 
4010
        if (empty($user->id)) {
4011
            $failurereason = AUTH_LOGIN_NOUSER;
4012
            // Trigger login failed event.
4013
            $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4014
                    'reason' => $failurereason)));
4015
            $event->trigger();
4016
            return false;
4017
        }
4018
 
4019
        if (!empty($user->suspended)) {
4020
            // Just in case some auth plugin suspended account.
4021
            $failurereason = AUTH_LOGIN_SUSPENDED;
4022
            // Trigger login failed event.
4023
            $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4024
                    'other' => array('username' => $username, 'reason' => $failurereason)));
4025
            $event->trigger();
4026
            error_log('[client '.getremoteaddr()."]  $CFG->wwwroot  Suspended Login:  $username  ".$_SERVER['HTTP_USER_AGENT']);
4027
            return false;
4028
        }
4029
 
4030
        login_attempt_valid($user);
4031
        $failurereason = AUTH_LOGIN_OK;
4032
        return $user;
4033
    }
4034
 
4035
    // Failed if all the plugins have failed.
4036
    if (debugging('', DEBUG_ALL)) {
4037
        error_log('[client '.getremoteaddr()."]  $CFG->wwwroot  Failed Login:  $username  ".$_SERVER['HTTP_USER_AGENT']);
4038
    }
4039
 
4040
    if ($user->id) {
4041
        login_attempt_failed($user);
4042
        $failurereason = AUTH_LOGIN_FAILED;
4043
        // Trigger login failed event.
4044
        $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4045
                'other' => array('username' => $username, 'reason' => $failurereason)));
4046
        $event->trigger();
4047
    } else {
4048
        $failurereason = AUTH_LOGIN_NOUSER;
4049
        // Trigger login failed event.
4050
        $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4051
                'reason' => $failurereason)));
4052
        $event->trigger();
4053
    }
4054
 
4055
    return false;
4056
}
4057
 
4058
/**
4059
 * Call to complete the user login process after authenticate_user_login()
4060
 * has succeeded. It will setup the $USER variable and other required bits
4061
 * and pieces.
4062
 *
4063
 * NOTE:
4064
 * - It will NOT log anything -- up to the caller to decide what to log.
4065
 * - this function does not set any cookies any more!
4066
 *
4067
 * @param stdClass $user
4068
 * @param array $extrauserinfo
4069
 * @return stdClass A {@link $USER} object - BC only, do not use
4070
 */
4071
function complete_user_login($user, array $extrauserinfo = []) {
4072
    global $CFG, $DB, $USER, $SESSION;
4073
 
4074
    \core\session\manager::login_user($user);
4075
 
4076
    // Reload preferences from DB.
4077
    unset($USER->preference);
4078
    check_user_preferences_loaded($USER);
4079
 
4080
    // Update login times.
4081
    update_user_login_times();
4082
 
4083
    // Extra session prefs init.
4084
    set_login_session_preferences();
4085
 
4086
    // Trigger login event.
4087
    $event = \core\event\user_loggedin::create(
4088
        array(
4089
            'userid' => $USER->id,
4090
            'objectid' => $USER->id,
4091
            'other' => [
4092
                'username' => $USER->username,
4093
                'extrauserinfo' => $extrauserinfo
4094
            ]
4095
        )
4096
    );
4097
    $event->trigger();
4098
 
4099
    // Allow plugins to callback as soon possible after user has completed login.
4100
    di::get(\core\hook\manager::class)->dispatch(new \core_user\hook\after_login_completed());
4101
 
4102
    // Check if the user is using a new browser or session (a new MoodleSession cookie is set in that case).
4103
    // If the user is accessing from the same IP, ignore everything (most of the time will be a new session in the same browser).
4104
    // Skip Web Service requests, CLI scripts, AJAX scripts, and request from the mobile app itself.
4105
    $loginip = getremoteaddr();
4106
    $isnewip = isset($SESSION->userpreviousip) && $SESSION->userpreviousip != $loginip;
4107
    $isvalidenv = (!WS_SERVER && !CLI_SCRIPT && !NO_MOODLE_COOKIES) || PHPUNIT_TEST;
4108
 
4109
    if (!empty($SESSION->isnewsessioncookie) && $isnewip && $isvalidenv && !\core_useragent::is_moodle_app()) {
4110
 
4111
        $logintime = time();
4112
        $ismoodleapp = false;
4113
        $useragent = \core_useragent::get_user_agent_string();
4114
 
4115
        $sitepreferences = get_message_output_default_preferences();
4116
        // Check if new login notification is disabled at system level.
4117
        $newlogindisabled = $sitepreferences->moodle_newlogin_disable ?? 0;
4118
        // Check if message providers (web, email, mobile) are enabled at system level.
4119
        $msgproviderenabled = isset($sitepreferences->message_provider_moodle_newlogin_enabled);
4120
        // Get message providers enabled for a user.
4121
        $userpreferences = get_user_preferences('message_provider_moodle_newlogin_enabled');
4122
        // Check if notification processor plugins (web, email, mobile) are enabled at system level.
4123
        $msgprocessorsready = !empty(get_message_processors(true));
4124
        // If new login notification is enabled at system level then go for other conditions check.
4125
        $newloginenabled = $newlogindisabled ? 0 : ($userpreferences != 'none' && $msgproviderenabled);
4126
 
4127
        if ($newloginenabled && $msgprocessorsready) {
4128
            // Schedule adhoc task to send a login notification to the user.
4129
            $task = new \core\task\send_login_notifications();
4130
            $task->set_userid($USER->id);
4131
            $task->set_custom_data(compact('ismoodleapp', 'useragent', 'loginip', 'logintime'));
4132
            $task->set_component('core');
4133
            \core\task\manager::queue_adhoc_task($task);
4134
        }
4135
    }
4136
 
4137
    // Queue migrating the messaging data, if we need to.
4138
    if (!get_user_preferences('core_message_migrate_data', false, $USER->id)) {
4139
        // Check if there are any legacy messages to migrate.
4140
        if (\core_message\helper::legacy_messages_exist($USER->id)) {
4141
            \core_message\task\migrate_message_data::queue_task($USER->id);
4142
        } else {
4143
            set_user_preference('core_message_migrate_data', true, $USER->id);
4144
        }
4145
    }
4146
 
4147
    if (isguestuser()) {
4148
        // No need to continue when user is THE guest.
4149
        return $USER;
4150
    }
4151
 
4152
    if (CLI_SCRIPT) {
4153
        // We can redirect to password change URL only in browser.
4154
        return $USER;
4155
    }
4156
 
4157
    // Select password change url.
4158
    $userauth = get_auth_plugin($USER->auth);
4159
 
4160
    // Check whether the user should be changing password.
4161
    if (get_user_preferences('auth_forcepasswordchange', false)) {
4162
        if ($userauth->can_change_password()) {
4163
            if ($changeurl = $userauth->change_password_url()) {
4164
                redirect($changeurl);
4165
            } else {
4166
                require_once($CFG->dirroot . '/login/lib.php');
4167
                $SESSION->wantsurl = core_login_get_return_url();
4168
                redirect($CFG->wwwroot.'/login/change_password.php');
4169
            }
4170
        } else {
4171
            throw new \moodle_exception('nopasswordchangeforced', 'auth');
4172
        }
4173
    }
4174
    return $USER;
4175
}
4176
 
4177
/**
4178
 * Check a password hash to see if it was hashed using the legacy hash algorithm (bcrypt).
4179
 *
4180
 * @param string $password String to check.
4181
 * @return bool True if the $password matches the format of a bcrypt hash.
4182
 */
4183
function password_is_legacy_hash(#[\SensitiveParameter] string $password): bool {
4184
    return (bool) preg_match('/^\$2y\$[\d]{2}\$[A-Za-z0-9\.\/]{53}$/', $password);
4185
}
4186
 
4187
/**
4188
 * Calculate the Shannon entropy of a string.
4189
 *
4190
 * @param string $pepper The pepper to calculate the entropy of.
4191
 * @return float The Shannon entropy of the string.
4192
 */
4193
function calculate_entropy(#[\SensitiveParameter] string $pepper): float {
4194
    // Initialize entropy.
4195
    $h = 0;
4196
 
4197
    // Calculate the length of the string.
4198
    $size = strlen($pepper);
4199
 
4200
    // For each unique character in the string.
4201
    foreach (count_chars($pepper, 1) as $v) {
4202
        // Calculate the probability of the character.
4203
        $p = $v / $size;
4204
 
4205
        // Add the character's contribution to the total entropy.
4206
        // This uses the formula for the entropy of a discrete random variable.
4207
        $h -= $p * log($p) / log(2);
4208
    }
4209
 
4210
    // Instead of returning the average entropy per symbol (Shannon entropy),
4211
    // we multiply by the length of the string to get total entropy.
4212
    return $h * $size;
4213
}
4214
 
4215
/**
4216
 * Get the available password peppers.
4217
 * The latest pepper is checked for minimum entropy as part of this function.
4218
 * We only calculate the entropy of the most recent pepper,
4219
 * because passwords are always updated to the latest pepper,
4220
 * and in the past we may have enforced a lower minimum entropy.
4221
 * Also, we allow the latest pepper to be empty, to allow admins to migrate off peppers.
4222
 *
4223
 * @return array The password peppers.
4224
 * @throws coding_exception If the entropy of the password pepper is less than the recommended minimum.
4225
 */
4226
function get_password_peppers(): array {
4227
    global $CFG;
4228
 
4229
    // Get all available peppers.
4230
    if (isset($CFG->passwordpeppers) && is_array($CFG->passwordpeppers)) {
4231
        // Sort the array in descending order of keys (numerical).
4232
        $peppers = $CFG->passwordpeppers;
4233
        krsort($peppers, SORT_NUMERIC);
4234
    } else {
4235
        $peppers = [];  // Set an empty array if no peppers are found.
4236
    }
4237
 
4238
    // Check if the entropy of the most recent pepper is less than the minimum.
4239
    // Also, we allow the most recent pepper to be empty, to allow admins to migrate off peppers.
4240
    $lastpepper = reset($peppers);
4241
    if (!empty($peppers) && $lastpepper !== '' && calculate_entropy($lastpepper) < PEPPER_ENTROPY) {
4242
        throw new coding_exception(
4243
                'password pepper below minimum',
4244
                'The entropy of the password pepper is less than the recommended minimum.');
4245
    }
4246
    return $peppers;
4247
}
4248
 
4249
/**
4250
 * Compare password against hash stored in user object to determine if it is valid.
4251
 *
4252
 * If necessary it also updates the stored hash to the current format.
4253
 *
4254
 * @param stdClass $user (Password property may be updated).
4255
 * @param string $password Plain text password.
4256
 * @return bool True if password is valid.
4257
 */
4258
function validate_internal_user_password(stdClass $user, #[\SensitiveParameter] string $password): bool {
4259
 
4260
    if (exceeds_password_length($password)) {
4261
        // Password cannot be more than MAX_PASSWORD_CHARACTERS characters.
4262
        return false;
4263
    }
4264
 
4265
    if ($user->password === AUTH_PASSWORD_NOT_CACHED) {
4266
        // Internal password is not used at all, it can not validate.
4267
        return false;
4268
    }
4269
 
4270
    $peppers = get_password_peppers(); // Get the array of available peppers.
4271
    $islegacy = password_is_legacy_hash($user->password); // Check if the password is a legacy bcrypt hash.
4272
 
4273
    // If the password is a legacy hash, no peppers were used, so verify and update directly.
4274
    if ($islegacy && password_verify($password, $user->password)) {
4275
        update_internal_user_password($user, $password);
4276
        return true;
4277
    }
4278
 
4279
    // If the password is not a legacy hash, iterate through the peppers.
4280
    $latestpepper = reset($peppers);
4281
    // Add an empty pepper to the beginning of the array. To make it easier to check if the password matches without any pepper.
4282
    $peppers = [-1 => ''] + $peppers;
4283
    foreach ($peppers as $pepper) {
4284
        $pepperedpassword = $password . $pepper;
4285
 
4286
        // If the peppered password is correct, update (if necessary) and return true.
4287
        if (password_verify($pepperedpassword, $user->password)) {
4288
            // If the pepper used is not the latest one, update the password.
4289
            if ($pepper !== $latestpepper) {
4290
                update_internal_user_password($user, $password);
4291
            }
4292
            return true;
4293
        }
4294
    }
4295
 
4296
    // If no peppered password was correct, the password is wrong.
4297
    return false;
4298
}
4299
 
4300
/**
4301
 * Calculate hash for a plain text password.
4302
 *
4303
 * @param string $password Plain text password to be hashed.
4304
 * @param bool $fasthash If true, use a low number of rounds when generating the hash
4305
 *                       This is faster to generate but makes the hash less secure.
4306
 *                       It is used when lots of hashes need to be generated quickly.
4307
 * @param int $pepperlength Lenght of the peppers
4308
 * @return string The hashed password.
4309
 *
4310
 * @throws moodle_exception If a problem occurs while generating the hash.
4311
 */
4312
function hash_internal_user_password(#[\SensitiveParameter] string $password, $fasthash = false, $pepperlength = 0): string {
4313
    if (exceeds_password_length($password, $pepperlength)) {
4314
        // Password cannot be more than MAX_PASSWORD_CHARACTERS.
4315
        throw new \moodle_exception(get_string("passwordexceeded", 'error', MAX_PASSWORD_CHARACTERS));
4316
    }
4317
 
4318
    // Set the cost factor to 5000 for fast hashing, otherwise use default cost.
4319
    $rounds = $fasthash ? 5000 : 10000;
4320
 
4321
    // First generate a cryptographically suitable salt.
4322
    $randombytes = random_bytes(16);
4323
    $salt = substr(strtr(base64_encode($randombytes), '+', '.'), 0, 16);
4324
 
4325
    // Now construct the password string with the salt and number of rounds.
4326
    // The password string is in the format $algorithm$rounds$salt$hash. ($6 is the SHA512 algorithm).
4327
    $generatedhash = crypt($password, implode('$', [
4328
        '',
4329
        // The SHA512 Algorithm
4330
        '6',
4331
        "rounds={$rounds}",
4332
        $salt,
4333
        '',
4334
    ]));
4335
 
4336
    if ($generatedhash === false || $generatedhash === null) {
4337
        throw new moodle_exception('Failed to generate password hash.');
4338
    }
4339
 
4340
    return $generatedhash;
4341
}
4342
 
4343
/**
4344
 * Update password hash in user object (if necessary).
4345
 *
4346
 * The password is updated if:
4347
 * 1. The password has changed (the hash of $user->password is different
4348
 *    to the hash of $password).
4349
 * 2. The existing hash is using an out-of-date algorithm (or the legacy
4350
 *    md5 algorithm).
4351
 *
4352
 * The password is peppered with the latest pepper before hashing,
4353
 * if peppers are available.
4354
 * Updating the password will modify the $user object and the database
4355
 * record to use the current hashing algorithm.
4356
 * It will remove Web Services user tokens too.
4357
 *
4358
 * @param stdClass $user User object (password property may be updated).
4359
 * @param string $password Plain text password.
4360
 * @param bool $fasthash If true, use a low cost factor when generating the hash
4361
 *                       This is much faster to generate but makes the hash
4362
 *                       less secure. It is used when lots of hashes need to
4363
 *                       be generated quickly.
4364
 * @return bool Always returns true.
4365
 */
4366
function update_internal_user_password(
4367
        stdClass $user,
4368
        #[\SensitiveParameter] string $password,
4369
        bool $fasthash = false
4370
): bool {
4371
    global $CFG, $DB;
4372
 
4373
    // Add the latest password pepper to the password before further processing.
4374
    $peppers = get_password_peppers();
4375
    if (!empty($peppers)) {
4376
        $password = $password . reset($peppers);
4377
    }
4378
 
4379
    // Figure out what the hashed password should be.
4380
    if (!isset($user->auth)) {
4381
        debugging('User record in update_internal_user_password() must include field auth',
4382
                DEBUG_DEVELOPER);
4383
        $user->auth = $DB->get_field('user', 'auth', array('id' => $user->id));
4384
    }
4385
    $authplugin = get_auth_plugin($user->auth);
4386
    if ($authplugin->prevent_local_passwords()) {
4387
        $hashedpassword = AUTH_PASSWORD_NOT_CACHED;
4388
    } else {
4389
        $hashedpassword = hash_internal_user_password($password, $fasthash);
4390
    }
4391
 
4392
    $algorithmchanged = false;
4393
 
4394
    if ($hashedpassword === AUTH_PASSWORD_NOT_CACHED) {
4395
        // Password is not cached, update it if not set to AUTH_PASSWORD_NOT_CACHED.
4396
        $passwordchanged = ($user->password !== $hashedpassword);
4397
 
4398
    } else if (isset($user->password)) {
4399
        // If verification fails then it means the password has changed.
4400
        $passwordchanged = !password_verify($password, $user->password);
4401
        $algorithmchanged = password_is_legacy_hash($user->password);
4402
    } else {
4403
        // While creating new user, password in unset in $user object, to avoid
4404
        // saving it with user_create()
4405
        $passwordchanged = true;
4406
    }
4407
 
4408
    if ($passwordchanged || $algorithmchanged) {
4409
        $DB->set_field('user', 'password',  $hashedpassword, array('id' => $user->id));
4410
        $user->password = $hashedpassword;
4411
 
4412
        // Trigger event.
4413
        $user = $DB->get_record('user', array('id' => $user->id));
4414
        \core\event\user_password_updated::create_from_user($user)->trigger();
4415
 
4416
        // Remove WS user tokens.
4417
        if (!empty($CFG->passwordchangetokendeletion)) {
4418
            require_once($CFG->dirroot.'/webservice/lib.php');
4419
            webservice::delete_user_ws_tokens($user->id);
4420
        }
4421
    }
4422
 
4423
    return true;
4424
}
4425
 
4426
/**
4427
 * Get a complete user record, which includes all the info in the user record.
4428
 *
4429
 * Intended for setting as $USER session variable
4430
 *
4431
 * @param string $field The user field to be checked for a given value.
4432
 * @param string $value The value to match for $field.
4433
 * @param int $mnethostid
4434
 * @param bool $throwexception If true, it will throw an exception when there's no record found or when there are multiple records
4435
 *                              found. Otherwise, it will just return false.
4436
 * @return mixed False, or A {@link $USER} object.
4437
 */
4438
function get_complete_user_data($field, $value, $mnethostid = null, $throwexception = false) {
4439
    global $CFG, $DB;
4440
 
4441
    if (!$field || !$value) {
4442
        return false;
4443
    }
4444
 
4445
    // Change the field to lowercase.
4446
    $field = core_text::strtolower($field);
4447
 
4448
    // List of case insensitive fields.
4449
    $caseinsensitivefields = ['email'];
4450
 
4451
    // Username input is forced to lowercase and should be case sensitive.
4452
    if ($field == 'username') {
4453
        $value = core_text::strtolower($value);
4454
    }
4455
 
4456
    // Build the WHERE clause for an SQL query.
4457
    $params = array('fieldval' => $value);
4458
 
4459
    // Do a case-insensitive query, if necessary. These are generally very expensive. The performance can be improved on some DBs
4460
    // such as MySQL by pre-filtering users with accent-insensitive subselect.
4461
    if (in_array($field, $caseinsensitivefields)) {
4462
        $fieldselect = $DB->sql_equal($field, ':fieldval', false);
4463
        $idsubselect = $DB->sql_equal($field, ':fieldval2', false, false);
4464
        $params['fieldval2'] = $value;
4465
    } else {
4466
        $fieldselect = "$field = :fieldval";
4467
        $idsubselect = '';
4468
    }
4469
    $constraints = "$fieldselect AND deleted <> 1";
4470
 
4471
    // If we are loading user data based on anything other than id,
4472
    // we must also restrict our search based on mnet host.
4473
    if ($field != 'id') {
4474
        if (empty($mnethostid)) {
4475
            // If empty, we restrict to local users.
4476
            $mnethostid = $CFG->mnet_localhost_id;
4477
        }
4478
    }
4479
    if (!empty($mnethostid)) {
4480
        $params['mnethostid'] = $mnethostid;
4481
        $constraints .= " AND mnethostid = :mnethostid";
4482
    }
4483
 
4484
    if ($idsubselect) {
4485
        $constraints .= " AND id IN (SELECT id FROM {user} WHERE {$idsubselect})";
4486
    }
4487
 
4488
    // Get all the basic user data.
4489
    try {
4490
        // Make sure that there's only a single record that matches our query.
4491
        // For example, when fetching by email, multiple records might match the query as there's no guarantee that email addresses
4492
        // are unique. Therefore we can't reliably tell whether the user profile data that we're fetching is the correct one.
4493
        $user = $DB->get_record_select('user', $constraints, $params, '*', MUST_EXIST);
4494
    } catch (dml_exception $exception) {
4495
        if ($throwexception) {
4496
            throw $exception;
4497
        } else {
4498
            // Return false when no records or multiple records were found.
4499
            return false;
4500
        }
4501
    }
4502
 
4503
    // Get various settings and preferences.
4504
 
4505
    // Preload preference cache.
4506
    check_user_preferences_loaded($user);
4507
 
4508
    // Load course enrolment related stuff.
4509
    $user->lastcourseaccess    = array(); // During last session.
4510
    $user->currentcourseaccess = array(); // During current session.
4511
    if ($lastaccesses = $DB->get_records('user_lastaccess', array('userid' => $user->id))) {
4512
        foreach ($lastaccesses as $lastaccess) {
4513
            $user->lastcourseaccess[$lastaccess->courseid] = $lastaccess->timeaccess;
4514
        }
4515
    }
4516
 
4517
    // Add cohort theme.
4518
    if (!empty($CFG->allowcohortthemes)) {
4519
        require_once($CFG->dirroot . '/cohort/lib.php');
4520
        if ($cohorttheme = cohort_get_user_cohort_theme($user->id)) {
4521
            $user->cohorttheme = $cohorttheme;
4522
        }
4523
    }
4524
 
4525
    // Add the custom profile fields to the user record.
4526
    $user->profile = array();
4527
    if (!isguestuser($user)) {
4528
        require_once($CFG->dirroot.'/user/profile/lib.php');
4529
        profile_load_custom_fields($user);
4530
    }
4531
 
4532
    // Rewrite some variables if necessary.
4533
    if (!empty($user->description)) {
4534
        // No need to cart all of it around.
4535
        $user->description = true;
4536
    }
4537
    if (isguestuser($user)) {
4538
        // Guest language always same as site.
4539
        $user->lang = get_newuser_language();
4540
        // Name always in current language.
4541
        $user->firstname = get_string('guestuser');
4542
        $user->lastname = ' ';
4543
    }
4544
 
4545
    return $user;
4546
}
4547
 
4548
/**
4549
 * Validate a password against the configured password policy
4550
 *
4551
 * @param string $password the password to be checked against the password policy
4552
 * @param string|null $errmsg the error message to display when the password doesn't comply with the policy.
4553
 * @param stdClass|null $user the user object to perform password validation against. Defaults to null if not provided.
4554
 *
4555
 * @return bool true if the password is valid according to the policy. false otherwise.
4556
 */
4557
function check_password_policy(string $password, ?string &$errmsg, ?stdClass $user = null) {
4558
    global $CFG;
4559
    if (!empty($CFG->passwordpolicy) && !isguestuser($user)) {
4560
        $errors = get_password_policy_errors($password, $user);
4561
 
4562
        foreach ($errors as $error) {
4563
            $errmsg .= '<div>' . $error . '</div>';
4564
        }
4565
    }
4566
 
4567
    return $errmsg == '';
4568
}
4569
 
4570
/**
4571
 * Validate a password against the configured password policy.
4572
 * Note: This function is unaffected by whether the password policy is enabled or not.
4573
 *
4574
 * @param string $password the password to be checked against the password policy
4575
 * @param stdClass|null $user the user object to perform password validation against. Defaults to null if not provided.
4576
 *
4577
 * @return string[] Array of error messages.
4578
 */
4579
function get_password_policy_errors(string $password, ?stdClass $user = null) : array {
4580
    global $CFG;
4581
 
4582
    $errors = [];
4583
 
4584
    if (core_text::strlen($password) < $CFG->minpasswordlength) {
4585
        $errors[] = get_string('errorminpasswordlength', 'auth', $CFG->minpasswordlength);
4586
    }
4587
    if (preg_match_all('/[[:digit:]]/u', $password, $matches) < $CFG->minpassworddigits) {
4588
        $errors[] = get_string('errorminpassworddigits', 'auth', $CFG->minpassworddigits);
4589
    }
4590
    if (preg_match_all('/[[:lower:]]/u', $password, $matches) < $CFG->minpasswordlower) {
4591
        $errors[] = get_string('errorminpasswordlower', 'auth', $CFG->minpasswordlower);
4592
    }
4593
    if (preg_match_all('/[[:upper:]]/u', $password, $matches) < $CFG->minpasswordupper) {
4594
        $errors[] = get_string('errorminpasswordupper', 'auth', $CFG->minpasswordupper);
4595
    }
4596
    if (preg_match_all('/[^[:upper:][:lower:][:digit:]]/u', $password, $matches) < $CFG->minpasswordnonalphanum) {
4597
        $errors[] = get_string('errorminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum);
4598
    }
4599
    if (!check_consecutive_identical_characters($password, $CFG->maxconsecutiveidentchars)) {
4600
        $errors[] = get_string('errormaxconsecutiveidentchars', 'auth', $CFG->maxconsecutiveidentchars);
4601
    }
4602
 
4603
    // Fire any additional password policy functions from plugins.
4604
    // Plugin functions should output an error message string or empty string for success.
4605
    $pluginsfunction = get_plugins_with_function('check_password_policy');
4606
    foreach ($pluginsfunction as $plugintype => $plugins) {
4607
        foreach ($plugins as $pluginfunction) {
4608
            $pluginerr = $pluginfunction($password, $user);
4609
            if ($pluginerr) {
4610
                $errors[] = $pluginerr;
4611
            }
4612
        }
4613
    }
4614
 
4615
    return $errors;
4616
}
4617
 
4618
/**
4619
 * When logging in, this function is run to set certain preferences for the current SESSION.
4620
 */
4621
function set_login_session_preferences() {
4622
    global $SESSION;
4623
 
4624
    $SESSION->justloggedin = true;
4625
 
4626
    unset($SESSION->lang);
4627
    unset($SESSION->forcelang);
4628
    unset($SESSION->load_navigation_admin);
4629
}
4630
 
4631
 
4632
/**
4633
 * Delete a course, including all related data from the database, and any associated files.
4634
 *
4635
 * @param mixed $courseorid The id of the course or course object to delete.
4636
 * @param bool $showfeedback Whether to display notifications of each action the function performs.
4637
 * @return bool true if all the removals succeeded. false if there were any failures. If this
4638
 *             method returns false, some of the removals will probably have succeeded, and others
4639
 *             failed, but you have no way of knowing which.
4640
 */
4641
function delete_course($courseorid, $showfeedback = true) {
4642
    global $DB, $CFG;
4643
 
4644
    if (is_object($courseorid)) {
4645
        $courseid = $courseorid->id;
4646
        $course   = $courseorid;
4647
    } else {
4648
        $courseid = $courseorid;
4649
        if (!$course = $DB->get_record('course', array('id' => $courseid))) {
4650
            return false;
4651
        }
4652
    }
4653
    $context = context_course::instance($courseid);
4654
 
4655
    // Frontpage course can not be deleted!!
4656
    if ($courseid == SITEID) {
4657
        return false;
4658
    }
4659
 
4660
    // Allow plugins to use this course before we completely delete it.
4661
    if ($pluginsfunction = get_plugins_with_function('pre_course_delete')) {
4662
        foreach ($pluginsfunction as $plugintype => $plugins) {
4663
            foreach ($plugins as $pluginfunction) {
4664
                $pluginfunction($course);
4665
            }
4666
        }
4667
    }
4668
 
4669
    // Dispatch the hook for pre course delete actions.
4670
    $hook = new \core_course\hook\before_course_deleted(
4671
        course: $course,
4672
    );
4673
    \core\di::get(\core\hook\manager::class)->dispatch($hook);
4674
 
4675
    // Tell the search manager we are about to delete a course. This prevents us sending updates
4676
    // for each individual context being deleted.
4677
    \core_search\manager::course_deleting_start($courseid);
4678
 
4679
    $handler = core_course\customfield\course_handler::create();
4680
    $handler->delete_instance($courseid);
4681
 
4682
    // Make the course completely empty.
4683
    remove_course_contents($courseid, $showfeedback);
4684
 
4685
    // Delete the course and related context instance.
4686
    context_helper::delete_instance(CONTEXT_COURSE, $courseid);
4687
 
4688
    $DB->delete_records("course", array("id" => $courseid));
4689
    $DB->delete_records("course_format_options", array("courseid" => $courseid));
4690
 
4691
    // Reset all course related caches here.
4692
    core_courseformat\base::reset_course_cache($courseid);
4693
 
4694
    // Tell search that we have deleted the course so it can delete course data from the index.
4695
    \core_search\manager::course_deleting_finish($courseid);
4696
 
4697
    // Trigger a course deleted event.
4698
    $event = \core\event\course_deleted::create(array(
4699
        'objectid' => $course->id,
4700
        'context' => $context,
4701
        'other' => array(
4702
            'shortname' => $course->shortname,
4703
            'fullname' => $course->fullname,
4704
            'idnumber' => $course->idnumber
4705
            )
4706
    ));
4707
    $event->add_record_snapshot('course', $course);
4708
    $event->trigger();
4709
 
4710
    return true;
4711
}
4712
 
4713
/**
4714
 * Clear a course out completely, deleting all content but don't delete the course itself.
4715
 *
4716
 * This function does not verify any permissions.
4717
 *
4718
 * Please note this function also deletes all user enrolments,
4719
 * enrolment instances and role assignments by default.
4720
 *
4721
 * $options:
4722
 *  - 'keep_roles_and_enrolments' - false by default
4723
 *  - 'keep_groups_and_groupings' - false by default
4724
 *
4725
 * @param int $courseid The id of the course that is being deleted
4726
 * @param bool $showfeedback Whether to display notifications of each action the function performs.
4727
 * @param array $options extra options
4728
 * @return bool true if all the removals succeeded. false if there were any failures. If this
4729
 *             method returns false, some of the removals will probably have succeeded, and others
4730
 *             failed, but you have no way of knowing which.
4731
 */
4732
function remove_course_contents($courseid, $showfeedback = true, array $options = null) {
4733
    global $CFG, $DB, $OUTPUT;
4734
 
4735
    require_once($CFG->libdir.'/badgeslib.php');
4736
    require_once($CFG->libdir.'/completionlib.php');
4737
    require_once($CFG->libdir.'/questionlib.php');
4738
    require_once($CFG->libdir.'/gradelib.php');
4739
    require_once($CFG->dirroot.'/group/lib.php');
4740
    require_once($CFG->dirroot.'/comment/lib.php');
4741
    require_once($CFG->dirroot.'/rating/lib.php');
4742
    require_once($CFG->dirroot.'/notes/lib.php');
4743
 
4744
    // Handle course badges.
4745
    badges_handle_course_deletion($courseid);
4746
 
4747
    // NOTE: these concatenated strings are suboptimal, but it is just extra info...
4748
    $strdeleted = get_string('deleted').' - ';
4749
 
4750
    // Some crazy wishlist of stuff we should skip during purging of course content.
4751
    $options = (array)$options;
4752
 
4753
    $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
4754
    $coursecontext = context_course::instance($courseid);
4755
    $fs = get_file_storage();
4756
 
4757
    // Delete course completion information, this has to be done before grades and enrols.
4758
    $cc = new completion_info($course);
4759
    $cc->clear_criteria();
4760
    if ($showfeedback) {
4761
        echo $OUTPUT->notification($strdeleted.get_string('completion', 'completion'), 'notifysuccess');
4762
    }
4763
 
4764
    // Remove all data from gradebook - this needs to be done before course modules
4765
    // because while deleting this information, the system may need to reference
4766
    // the course modules that own the grades.
4767
    remove_course_grades($courseid, $showfeedback);
4768
    remove_grade_letters($coursecontext, $showfeedback);
4769
 
4770
    // Delete course blocks in any all child contexts,
4771
    // they may depend on modules so delete them first.
4772
    $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
4773
    foreach ($childcontexts as $childcontext) {
4774
        blocks_delete_all_for_context($childcontext->id);
4775
    }
4776
    unset($childcontexts);
4777
    blocks_delete_all_for_context($coursecontext->id);
4778
    if ($showfeedback) {
4779
        echo $OUTPUT->notification($strdeleted.get_string('type_block_plural', 'plugin'), 'notifysuccess');
4780
    }
4781
 
4782
    $DB->set_field('course_modules', 'deletioninprogress', '1', ['course' => $courseid]);
4783
    rebuild_course_cache($courseid, true);
4784
 
4785
    // Get the list of all modules that are properly installed.
4786
    $allmodules = $DB->get_records_menu('modules', array(), '', 'name, id');
4787
 
4788
    // Delete every instance of every module,
4789
    // this has to be done before deleting of course level stuff.
4790
    $locations = core_component::get_plugin_list('mod');
4791
    foreach ($locations as $modname => $moddir) {
4792
        if ($modname === 'NEWMODULE') {
4793
            continue;
4794
        }
4795
        if (array_key_exists($modname, $allmodules)) {
4796
            $sql = "SELECT cm.*, m.id AS modinstance, m.name, '$modname' AS modname
4797
              FROM {".$modname."} m
4798
                   LEFT JOIN {course_modules} cm ON cm.instance = m.id AND cm.module = :moduleid
4799
             WHERE m.course = :courseid";
4800
            $instances = $DB->get_records_sql($sql, array('courseid' => $course->id,
4801
                'modulename' => $modname, 'moduleid' => $allmodules[$modname]));
4802
 
4803
            include_once("$moddir/lib.php");                 // Shows php warning only if plugin defective.
4804
            $moddelete = $modname .'_delete_instance';       // Delete everything connected to an instance.
4805
 
4806
            if ($instances) {
4807
                foreach ($instances as $cm) {
4808
                    if ($cm->id) {
4809
                        // Delete activity context questions and question categories.
4810
                        question_delete_activity($cm);
4811
                        // Notify the competency subsystem.
4812
                        \core_competency\api::hook_course_module_deleted($cm);
4813
 
4814
                        // Delete all tag instances associated with the instance of this module.
4815
                        core_tag_tag::delete_instances("mod_{$modname}", null, context_module::instance($cm->id)->id);
4816
                        core_tag_tag::remove_all_item_tags('core', 'course_modules', $cm->id);
4817
                    }
4818
                    if (function_exists($moddelete)) {
4819
                        // This purges all module data in related tables, extra user prefs, settings, etc.
4820
                        $moddelete($cm->modinstance);
4821
                    } else {
4822
                        // NOTE: we should not allow installation of modules with missing delete support!
4823
                        debugging("Defective module '$modname' detected when deleting course contents: missing function $moddelete()!");
4824
                        $DB->delete_records($modname, array('id' => $cm->modinstance));
4825
                    }
4826
 
4827
                    if ($cm->id) {
4828
                        // Delete cm and its context - orphaned contexts are purged in cron in case of any race condition.
4829
                        context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
4830
                        $DB->delete_records('course_modules_completion', ['coursemoduleid' => $cm->id]);
4831
                        $DB->delete_records('course_modules_viewed', ['coursemoduleid' => $cm->id]);
4832
                        $DB->delete_records('course_modules', array('id' => $cm->id));
4833
                        rebuild_course_cache($cm->course, true);
4834
                    }
4835
                }
4836
            }
4837
            if ($instances and $showfeedback) {
4838
                echo $OUTPUT->notification($strdeleted.get_string('pluginname', $modname), 'notifysuccess');
4839
            }
4840
        } else {
4841
            // Ooops, this module is not properly installed, force-delete it in the next block.
4842
        }
4843
    }
4844
 
4845
    // We have tried to delete everything the nice way - now let's force-delete any remaining module data.
4846
 
4847
    // Delete completion defaults.
4848
    $DB->delete_records("course_completion_defaults", array("course" => $courseid));
4849
 
4850
    // Remove all data from availability and completion tables that is associated
4851
    // with course-modules belonging to this course. Note this is done even if the
4852
    // features are not enabled now, in case they were enabled previously.
4853
    $DB->delete_records_subquery('course_modules_completion', 'coursemoduleid', 'id',
4854
            'SELECT id from {course_modules} WHERE course = ?', [$courseid]);
4855
    $DB->delete_records_subquery('course_modules_viewed', 'coursemoduleid', 'id',
4856
        'SELECT id from {course_modules} WHERE course = ?', [$courseid]);
4857
 
4858
    // Remove course-module data that has not been removed in modules' _delete_instance callbacks.
4859
    $cms = $DB->get_records('course_modules', array('course' => $course->id));
4860
    $allmodulesbyid = array_flip($allmodules);
4861
    foreach ($cms as $cm) {
4862
        if (array_key_exists($cm->module, $allmodulesbyid)) {
4863
            try {
4864
                $DB->delete_records($allmodulesbyid[$cm->module], array('id' => $cm->instance));
4865
            } catch (Exception $e) {
4866
                // Ignore weird or missing table problems.
4867
            }
4868
        }
4869
        context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
4870
        $DB->delete_records('course_modules', array('id' => $cm->id));
4871
        rebuild_course_cache($cm->course, true);
4872
    }
4873
 
4874
    if ($showfeedback) {
4875
        echo $OUTPUT->notification($strdeleted.get_string('type_mod_plural', 'plugin'), 'notifysuccess');
4876
    }
4877
 
4878
    // Delete questions and question categories.
4879
    question_delete_course($course);
4880
    if ($showfeedback) {
4881
        echo $OUTPUT->notification($strdeleted.get_string('questions', 'question'), 'notifysuccess');
4882
    }
4883
 
4884
    // Delete content bank contents.
4885
    $cb = new \core_contentbank\contentbank();
4886
    $cbdeleted = $cb->delete_contents($coursecontext);
4887
    if ($showfeedback && $cbdeleted) {
4888
        echo $OUTPUT->notification($strdeleted.get_string('contentbank', 'contentbank'), 'notifysuccess');
4889
    }
4890
 
4891
    // Make sure there are no subcontexts left - all valid blocks and modules should be already gone.
4892
    $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
4893
    foreach ($childcontexts as $childcontext) {
4894
        $childcontext->delete();
4895
    }
4896
    unset($childcontexts);
4897
 
4898
    // Remove roles and enrolments by default.
4899
    if (empty($options['keep_roles_and_enrolments'])) {
4900
        // This hack is used in restore when deleting contents of existing course.
4901
        // During restore, we should remove only enrolment related data that the user performing the restore has a
4902
        // permission to remove.
4903
        $userid = $options['userid'] ?? null;
4904
        enrol_course_delete($course, $userid);
4905
        role_unassign_all(array('contextid' => $coursecontext->id, 'component' => ''), true);
4906
        if ($showfeedback) {
4907
            echo $OUTPUT->notification($strdeleted.get_string('type_enrol_plural', 'plugin'), 'notifysuccess');
4908
        }
4909
    }
4910
 
4911
    // Delete any groups, removing members and grouping/course links first.
4912
    if (empty($options['keep_groups_and_groupings'])) {
4913
        groups_delete_groupings($course->id, $showfeedback);
4914
        groups_delete_groups($course->id, $showfeedback);
4915
    }
4916
 
4917
    // Filters be gone!
4918
    filter_delete_all_for_context($coursecontext->id);
4919
 
4920
    // Notes, you shall not pass!
4921
    note_delete_all($course->id);
4922
 
4923
    // Die comments!
4924
    comment::delete_comments($coursecontext->id);
4925
 
4926
    // Ratings are history too.
4927
    $delopt = new stdclass();
4928
    $delopt->contextid = $coursecontext->id;
4929
    $rm = new rating_manager();
4930
    $rm->delete_ratings($delopt);
4931
 
4932
    // Delete course tags.
4933
    core_tag_tag::remove_all_item_tags('core', 'course', $course->id);
4934
 
4935
    // Give the course format the opportunity to remove its obscure data.
4936
    $format = course_get_format($course);
4937
    $format->delete_format_data();
4938
 
4939
    // Notify the competency subsystem.
4940
    \core_competency\api::hook_course_deleted($course);
4941
 
4942
    // Delete calendar events.
4943
    $DB->delete_records('event', array('courseid' => $course->id));
4944
    $fs->delete_area_files($coursecontext->id, 'calendar');
4945
 
4946
    // Delete all related records in other core tables that may have a courseid
4947
    // This array stores the tables that need to be cleared, as
4948
    // table_name => column_name that contains the course id.
4949
    $tablestoclear = array(
4950
        'backup_courses' => 'courseid',  // Scheduled backup stuff.
4951
        'user_lastaccess' => 'courseid', // User access info.
4952
    );
4953
    foreach ($tablestoclear as $table => $col) {
4954
        $DB->delete_records($table, array($col => $course->id));
4955
    }
4956
 
4957
    // Delete all course backup files.
4958
    $fs->delete_area_files($coursecontext->id, 'backup');
4959
 
4960
    // Cleanup course record - remove links to deleted stuff.
4961
    // Do not wipe cacherev, as this course might be reused and we need to ensure that it keeps
4962
    // increasing.
4963
    $oldcourse = new stdClass();
4964
    $oldcourse->id               = $course->id;
4965
    $oldcourse->summary          = '';
4966
    $oldcourse->legacyfiles      = 0;
4967
    if (!empty($options['keep_groups_and_groupings'])) {
4968
        $oldcourse->defaultgroupingid = 0;
4969
    }
4970
    $DB->update_record('course', $oldcourse);
4971
 
4972
    // Delete course sections.
4973
    $DB->delete_records('course_sections', array('course' => $course->id));
4974
 
4975
    // Delete legacy, section and any other course files.
4976
    $fs->delete_area_files($coursecontext->id, 'course'); // Files from summary and section.
4977
 
4978
    // Delete all remaining stuff linked to context such as files, comments, ratings, etc.
4979
    if (empty($options['keep_roles_and_enrolments']) and empty($options['keep_groups_and_groupings'])) {
4980
        // Easy, do not delete the context itself...
4981
        $coursecontext->delete_content();
4982
    } else {
4983
        // Hack alert!!!!
4984
        // We can not drop all context stuff because it would bork enrolments and roles,
4985
        // there might be also files used by enrol plugins...
4986
    }
4987
 
4988
    // Delete legacy files - just in case some files are still left there after conversion to new file api,
4989
    // also some non-standard unsupported plugins may try to store something there.
4990
    fulldelete($CFG->dataroot.'/'.$course->id);
4991
 
4992
    // Delete from cache to reduce the cache size especially makes sense in case of bulk course deletion.
4993
    course_modinfo::purge_course_cache($courseid);
4994
 
4995
    // Trigger a course content deleted event.
4996
    $event = \core\event\course_content_deleted::create(array(
4997
        'objectid' => $course->id,
4998
        'context' => $coursecontext,
4999
        'other' => array('shortname' => $course->shortname,
5000
                         'fullname' => $course->fullname,
5001
                         'options' => $options) // Passing this for legacy reasons.
5002
    ));
5003
    $event->add_record_snapshot('course', $course);
5004
    $event->trigger();
5005
 
5006
    return true;
5007
}
5008
 
5009
/**
5010
 * Change dates in module - used from course reset.
5011
 *
5012
 * @param string $modname forum, assignment, etc
5013
 * @param array $fields array of date fields from mod table
5014
 * @param int $timeshift time difference
5015
 * @param int $courseid
5016
 * @param int $modid (Optional) passed if specific mod instance in course needs to be updated.
5017
 * @return bool success
5018
 */
5019
function shift_course_mod_dates($modname, $fields, $timeshift, $courseid, $modid = 0) {
5020
    global $CFG, $DB;
5021
    include_once($CFG->dirroot.'/mod/'.$modname.'/lib.php');
5022
 
5023
    $return = true;
5024
    $params = array($timeshift, $courseid);
5025
    foreach ($fields as $field) {
5026
        $updatesql = "UPDATE {".$modname."}
5027
                          SET $field = $field + ?
5028
                        WHERE course=? AND $field<>0";
5029
        if ($modid) {
5030
            $updatesql .= ' AND id=?';
5031
            $params[] = $modid;
5032
        }
5033
        $return = $DB->execute($updatesql, $params) && $return;
5034
    }
5035
 
5036
    return $return;
5037
}
5038
 
5039
/**
5040
 * This function will empty a course of user data.
5041
 * It will retain the activities and the structure of the course.
5042
 *
5043
 * @param object $data an object containing all the settings including courseid (without magic quotes)
5044
 * @return array status array of array component, item, error
5045
 */
5046
function reset_course_userdata($data) {
5047
    global $CFG, $DB;
5048
    require_once($CFG->libdir.'/gradelib.php');
5049
    require_once($CFG->libdir.'/completionlib.php');
5050
    require_once($CFG->dirroot.'/completion/criteria/completion_criteria_date.php');
5051
    require_once($CFG->dirroot.'/group/lib.php');
5052
 
5053
    $data->courseid = $data->id;
5054
    $context = context_course::instance($data->courseid);
5055
 
5056
    $eventparams = array(
5057
        'context' => $context,
5058
        'courseid' => $data->id,
5059
        'other' => array(
5060
            'reset_options' => (array) $data
5061
        )
5062
    );
5063
    $event = \core\event\course_reset_started::create($eventparams);
5064
    $event->trigger();
5065
 
5066
    // Calculate the time shift of dates.
5067
    if (!empty($data->reset_start_date)) {
5068
        // Time part of course startdate should be zero.
5069
        $data->timeshift = $data->reset_start_date - usergetmidnight($data->reset_start_date_old);
5070
    } else {
5071
        $data->timeshift = 0;
5072
    }
5073
 
5074
    // Result array: component, item, error.
5075
    $status = array();
5076
 
5077
    // Start the resetting.
5078
    $componentstr = get_string('general');
5079
 
5080
    // Move the course start time.
5081
    if (!empty($data->reset_start_date) and $data->timeshift) {
5082
        // Change course start data.
5083
        $DB->set_field('course', 'startdate', $data->reset_start_date, array('id' => $data->courseid));
5084
        // Update all course and group events - do not move activity events.
5085
        $updatesql = "UPDATE {event}
5086
                         SET timestart = timestart + ?
5087
                       WHERE courseid=? AND instance=0";
5088
        $DB->execute($updatesql, array($data->timeshift, $data->courseid));
5089
 
5090
        // Update any date activity restrictions.
5091
        if ($CFG->enableavailability) {
5092
            \availability_date\condition::update_all_dates($data->courseid, $data->timeshift);
5093
        }
5094
 
5095
        // Update completion expected dates.
5096
        if ($CFG->enablecompletion) {
5097
            $modinfo = get_fast_modinfo($data->courseid);
5098
            $changed = false;
5099
            foreach ($modinfo->get_cms() as $cm) {
5100
                if ($cm->completion && !empty($cm->completionexpected)) {
5101
                    $DB->set_field('course_modules', 'completionexpected', $cm->completionexpected + $data->timeshift,
5102
                        array('id' => $cm->id));
5103
                    $changed = true;
5104
                }
5105
            }
5106
 
5107
            // Clear course cache if changes made.
5108
            if ($changed) {
5109
                rebuild_course_cache($data->courseid, true);
5110
            }
5111
 
5112
            // Update course date completion criteria.
5113
            \completion_criteria_date::update_date($data->courseid, $data->timeshift);
5114
        }
5115
 
5116
        $status[] = array('component' => $componentstr, 'item' => get_string('datechanged'), 'error' => false);
5117
    }
5118
 
5119
    if (!empty($data->reset_end_date)) {
5120
        // If the user set a end date value respect it.
5121
        $DB->set_field('course', 'enddate', $data->reset_end_date, array('id' => $data->courseid));
5122
    } else if ($data->timeshift > 0 && $data->reset_end_date_old) {
5123
        // If there is a time shift apply it to the end date as well.
5124
        $enddate = $data->reset_end_date_old + $data->timeshift;
5125
        $DB->set_field('course', 'enddate', $enddate, array('id' => $data->courseid));
5126
    }
5127
 
5128
    if (!empty($data->reset_events)) {
5129
        $DB->delete_records('event', array('courseid' => $data->courseid));
5130
        $status[] = array('component' => $componentstr, 'item' => get_string('deleteevents', 'calendar'), 'error' => false);
5131
    }
5132
 
5133
    if (!empty($data->reset_notes)) {
5134
        require_once($CFG->dirroot.'/notes/lib.php');
5135
        note_delete_all($data->courseid);
5136
        $status[] = array('component' => $componentstr, 'item' => get_string('deletenotes', 'notes'), 'error' => false);
5137
    }
5138
 
5139
    if (!empty($data->delete_blog_associations)) {
5140
        require_once($CFG->dirroot.'/blog/lib.php');
5141
        blog_remove_associations_for_course($data->courseid);
5142
        $status[] = array('component' => $componentstr, 'item' => get_string('deleteblogassociations', 'blog'), 'error' => false);
5143
    }
5144
 
5145
    if (!empty($data->reset_completion)) {
5146
        // Delete course and activity completion information.
5147
        $course = $DB->get_record('course', array('id' => $data->courseid));
5148
        $cc = new completion_info($course);
5149
        $cc->delete_all_completion_data();
5150
        $status[] = array('component' => $componentstr,
5151
                'item' => get_string('deletecompletiondata', 'completion'), 'error' => false);
5152
    }
5153
 
5154
    if (!empty($data->reset_competency_ratings)) {
5155
        \core_competency\api::hook_course_reset_competency_ratings($data->courseid);
5156
        $status[] = array('component' => $componentstr,
5157
            'item' => get_string('deletecompetencyratings', 'core_competency'), 'error' => false);
5158
    }
5159
 
5160
    $componentstr = get_string('roles');
5161
 
5162
    if (!empty($data->reset_roles_overrides)) {
5163
        $children = $context->get_child_contexts();
5164
        foreach ($children as $child) {
5165
            $child->delete_capabilities();
5166
        }
5167
        $context->delete_capabilities();
5168
        $status[] = array('component' => $componentstr, 'item' => get_string('deletecourseoverrides', 'role'), 'error' => false);
5169
    }
5170
 
5171
    if (!empty($data->reset_roles_local)) {
5172
        $children = $context->get_child_contexts();
5173
        foreach ($children as $child) {
5174
            role_unassign_all(array('contextid' => $child->id));
5175
        }
5176
        $status[] = array('component' => $componentstr, 'item' => get_string('deletelocalroles', 'role'), 'error' => false);
5177
    }
5178
 
5179
    // First unenrol users - this cleans some of related user data too, such as forum subscriptions, tracking, etc.
5180
    $data->unenrolled = array();
5181
    if (!empty($data->unenrol_users)) {
5182
        $plugins = enrol_get_plugins(true);
5183
        $instances = enrol_get_instances($data->courseid, true);
5184
        foreach ($instances as $key => $instance) {
5185
            if (!isset($plugins[$instance->enrol])) {
5186
                unset($instances[$key]);
5187
                continue;
5188
            }
5189
        }
5190
 
5191
        $usersroles = enrol_get_course_users_roles($data->courseid);
5192
        foreach ($data->unenrol_users as $withroleid) {
5193
            if ($withroleid) {
5194
                $sql = "SELECT ue.*
5195
                          FROM {user_enrolments} ue
5196
                          JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5197
                          JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5198
                          JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.roleid = :roleid AND ra.userid = ue.userid)";
5199
                $params = array('courseid' => $data->courseid, 'roleid' => $withroleid, 'courselevel' => CONTEXT_COURSE);
5200
 
5201
            } else {
5202
                // Without any role assigned at course context.
5203
                $sql = "SELECT ue.*
5204
                          FROM {user_enrolments} ue
5205
                          JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5206
                          JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5207
                     LEFT JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.userid = ue.userid)
5208
                         WHERE ra.id IS null";
5209
                $params = array('courseid' => $data->courseid, 'courselevel' => CONTEXT_COURSE);
5210
            }
5211
 
5212
            $rs = $DB->get_recordset_sql($sql, $params);
5213
            foreach ($rs as $ue) {
5214
                if (!isset($instances[$ue->enrolid])) {
5215
                    continue;
5216
                }
5217
                $instance = $instances[$ue->enrolid];
5218
                $plugin = $plugins[$instance->enrol];
5219
                if (!$plugin->allow_unenrol($instance) and !$plugin->allow_unenrol_user($instance, $ue)) {
5220
                    continue;
5221
                }
5222
 
5223
                if ($withroleid && count($usersroles[$ue->userid]) > 1) {
5224
                    // If we don't remove all roles and user has more than one role, just remove this role.
5225
                    role_unassign($withroleid, $ue->userid, $context->id);
5226
 
5227
                    unset($usersroles[$ue->userid][$withroleid]);
5228
                } else {
5229
                    // If we remove all roles or user has only one role, unenrol user from course.
5230
                    $plugin->unenrol_user($instance, $ue->userid);
5231
                }
5232
                $data->unenrolled[$ue->userid] = $ue->userid;
5233
            }
5234
            $rs->close();
5235
        }
5236
    }
5237
    if (!empty($data->unenrolled)) {
5238
        $status[] = array(
5239
            'component' => $componentstr,
5240
            'item' => get_string('unenrol', 'enrol').' ('.count($data->unenrolled).')',
5241
            'error' => false
5242
        );
5243
    }
5244
 
5245
    $componentstr = get_string('groups');
5246
 
5247
    // Remove all group members.
5248
    if (!empty($data->reset_groups_members)) {
5249
        groups_delete_group_members($data->courseid);
5250
        $status[] = array('component' => $componentstr, 'item' => get_string('removegroupsmembers', 'group'), 'error' => false);
5251
    }
5252
 
5253
    // Remove all groups.
5254
    if (!empty($data->reset_groups_remove)) {
5255
        groups_delete_groups($data->courseid, false);
5256
        $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroups', 'group'), 'error' => false);
5257
    }
5258
 
5259
    // Remove all grouping members.
5260
    if (!empty($data->reset_groupings_members)) {
5261
        groups_delete_groupings_groups($data->courseid, false);
5262
        $status[] = array('component' => $componentstr, 'item' => get_string('removegroupingsmembers', 'group'), 'error' => false);
5263
    }
5264
 
5265
    // Remove all groupings.
5266
    if (!empty($data->reset_groupings_remove)) {
5267
        groups_delete_groupings($data->courseid, false);
5268
        $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroupings', 'group'), 'error' => false);
5269
    }
5270
 
5271
    // Look in every instance of every module for data to delete.
5272
    $unsupportedmods = array();
5273
    if ($allmods = $DB->get_records('modules') ) {
5274
        foreach ($allmods as $mod) {
5275
            $modname = $mod->name;
5276
            $modfile = $CFG->dirroot.'/mod/'. $modname.'/lib.php';
5277
            $moddeleteuserdata = $modname.'_reset_userdata';   // Function to delete user data.
5278
            if (file_exists($modfile)) {
5279
                if (!$DB->count_records($modname, array('course' => $data->courseid))) {
5280
                    continue; // Skip mods with no instances.
5281
                }
5282
                include_once($modfile);
5283
                if (function_exists($moddeleteuserdata)) {
5284
                    $modstatus = $moddeleteuserdata($data);
5285
                    if (is_array($modstatus)) {
5286
                        $status = array_merge($status, $modstatus);
5287
                    } else {
5288
                        debugging('Module '.$modname.' returned incorrect staus - must be an array!');
5289
                    }
5290
                } else {
5291
                    $unsupportedmods[] = $mod;
5292
                }
5293
            } else {
5294
                debugging('Missing lib.php in '.$modname.' module!');
5295
            }
5296
            // Update calendar events for all modules.
5297
            course_module_bulk_update_calendar_events($modname, $data->courseid);
5298
        }
5299
        // Purge the course cache after resetting course start date. MDL-76936
5300
        if ($data->timeshift) {
5301
            course_modinfo::purge_course_cache($data->courseid);
5302
        }
5303
    }
5304
 
5305
    // Mention unsupported mods.
5306
    if (!empty($unsupportedmods)) {
5307
        foreach ($unsupportedmods as $mod) {
5308
            $status[] = array(
5309
                'component' => get_string('modulenameplural', $mod->name),
5310
                'item' => '',
5311
                'error' => get_string('resetnotimplemented')
5312
            );
5313
        }
5314
    }
5315
 
5316
    $componentstr = get_string('gradebook', 'grades');
5317
    // Reset gradebook,.
5318
    if (!empty($data->reset_gradebook_items)) {
5319
        remove_course_grades($data->courseid, false);
5320
        grade_grab_course_grades($data->courseid);
5321
        grade_regrade_final_grades($data->courseid);
5322
        $status[] = array('component' => $componentstr, 'item' => get_string('removeallcourseitems', 'grades'), 'error' => false);
5323
 
5324
    } else if (!empty($data->reset_gradebook_grades)) {
5325
        grade_course_reset($data->courseid);
5326
        $status[] = array('component' => $componentstr, 'item' => get_string('removeallcoursegrades', 'grades'), 'error' => false);
5327
    }
5328
    // Reset comments.
5329
    if (!empty($data->reset_comments)) {
5330
        require_once($CFG->dirroot.'/comment/lib.php');
5331
        comment::reset_course_page_comments($context);
5332
    }
5333
 
5334
    $event = \core\event\course_reset_ended::create($eventparams);
5335
    $event->trigger();
5336
 
5337
    return $status;
5338
}
5339
 
5340
/**
5341
 * Generate an email processing address.
5342
 *
5343
 * @param int $modid
5344
 * @param string $modargs
5345
 * @return string Returns email processing address
5346
 */
5347
function generate_email_processing_address($modid, $modargs) {
5348
    global $CFG;
5349
 
5350
    $header = $CFG->mailprefix . substr(base64_encode(pack('C', $modid)), 0, 2).$modargs;
5351
    return $header . substr(md5($header.get_site_identifier()), 0, 16).'@'.$CFG->maildomain;
5352
}
5353
 
5354
/**
5355
 * ?
5356
 *
5357
 * @todo Finish documenting this function
5358
 *
5359
 * @param string $modargs
5360
 * @param string $body Currently unused
5361
 */
5362
function moodle_process_email($modargs, $body) {
5363
    global $DB;
5364
 
5365
    // The first char should be an unencoded letter. We'll take this as an action.
5366
    switch ($modargs[0]) {
5367
        case 'B': { // Bounce.
5368
            list(, $userid) = unpack('V', base64_decode(substr($modargs, 1, 8)));
5369
            if ($user = $DB->get_record("user", array('id' => $userid), "id,email")) {
5370
                // Check the half md5 of their email.
5371
                $md5check = substr(md5($user->email), 0, 16);
5372
                if ($md5check == substr($modargs, -16)) {
5373
                    set_bounce_count($user);
5374
                }
5375
                // Else maybe they've already changed it?
5376
            }
5377
        }
5378
        break;
5379
        // Maybe more later?
5380
    }
5381
}
5382
 
5383
// CORRESPONDENCE.
5384
 
5385
/**
5386
 * Get mailer instance, enable buffering, flush buffer or disable buffering.
5387
 *
5388
 * @param string $action 'get', 'buffer', 'close' or 'flush'
5389
 * @return moodle_phpmailer|null mailer instance if 'get' used or nothing
5390
 */
5391
function get_mailer($action='get') {
5392
    global $CFG;
5393
 
5394
    /** @var moodle_phpmailer $mailer */
5395
    static $mailer  = null;
5396
    static $counter = 0;
5397
 
5398
    if (!isset($CFG->smtpmaxbulk)) {
5399
        $CFG->smtpmaxbulk = 1;
5400
    }
5401
 
5402
    if ($action == 'get') {
5403
        $prevkeepalive = false;
5404
 
5405
        if (isset($mailer) and $mailer->Mailer == 'smtp') {
5406
            if ($counter < $CFG->smtpmaxbulk and !$mailer->isError()) {
5407
                $counter++;
5408
                // Reset the mailer.
5409
                $mailer->Priority         = 3;
5410
                $mailer->CharSet          = 'UTF-8'; // Our default.
5411
                $mailer->ContentType      = "text/plain";
5412
                $mailer->Encoding         = "8bit";
5413
                $mailer->From             = "root@localhost";
5414
                $mailer->FromName         = "Root User";
5415
                $mailer->Sender           = "";
5416
                $mailer->Subject          = "";
5417
                $mailer->Body             = "";
5418
                $mailer->AltBody          = "";
5419
                $mailer->ConfirmReadingTo = "";
5420
 
5421
                $mailer->clearAllRecipients();
5422
                $mailer->clearReplyTos();
5423
                $mailer->clearAttachments();
5424
                $mailer->clearCustomHeaders();
5425
                return $mailer;
5426
            }
5427
 
5428
            $prevkeepalive = $mailer->SMTPKeepAlive;
5429
            get_mailer('flush');
5430
        }
5431
 
5432
        require_once($CFG->libdir.'/phpmailer/moodle_phpmailer.php');
5433
        $mailer = new moodle_phpmailer();
5434
 
5435
        $counter = 1;
5436
 
5437
        if ($CFG->smtphosts == 'qmail') {
5438
            // Use Qmail system.
5439
            $mailer->isQmail();
5440
 
5441
        } else if (empty($CFG->smtphosts)) {
5442
            // Use PHP mail() = sendmail.
5443
            $mailer->isMail();
5444
 
5445
        } else {
5446
            // Use SMTP directly.
5447
            $mailer->isSMTP();
5448
            if (!empty($CFG->debugsmtp) && (!empty($CFG->debugdeveloper))) {
5449
                $mailer->SMTPDebug = 3;
5450
            }
5451
            // Specify main and backup servers.
5452
            $mailer->Host          = $CFG->smtphosts;
5453
            // Specify secure connection protocol.
5454
            $mailer->SMTPSecure    = $CFG->smtpsecure;
5455
            // Use previous keepalive.
5456
            $mailer->SMTPKeepAlive = $prevkeepalive;
5457
 
5458
            if ($CFG->smtpuser) {
5459
                // Use SMTP authentication.
5460
                $mailer->SMTPAuth = true;
5461
                $mailer->Username = $CFG->smtpuser;
5462
                $mailer->Password = $CFG->smtppass;
5463
            }
5464
        }
5465
 
5466
        return $mailer;
5467
    }
5468
 
5469
    $nothing = null;
5470
 
5471
    // Keep smtp session open after sending.
5472
    if ($action == 'buffer') {
5473
        if (!empty($CFG->smtpmaxbulk)) {
5474
            get_mailer('flush');
5475
            $m = get_mailer();
5476
            if ($m->Mailer == 'smtp') {
5477
                $m->SMTPKeepAlive = true;
5478
            }
5479
        }
5480
        return $nothing;
5481
    }
5482
 
5483
    // Close smtp session, but continue buffering.
5484
    if ($action == 'flush') {
5485
        if (isset($mailer) and $mailer->Mailer == 'smtp') {
5486
            if (!empty($mailer->SMTPDebug)) {
5487
                echo '<pre>'."\n";
5488
            }
5489
            $mailer->SmtpClose();
5490
            if (!empty($mailer->SMTPDebug)) {
5491
                echo '</pre>';
5492
            }
5493
        }
5494
        return $nothing;
5495
    }
5496
 
5497
    // Close smtp session, do not buffer anymore.
5498
    if ($action == 'close') {
5499
        if (isset($mailer) and $mailer->Mailer == 'smtp') {
5500
            get_mailer('flush');
5501
            $mailer->SMTPKeepAlive = false;
5502
        }
5503
        $mailer = null; // Better force new instance.
5504
        return $nothing;
5505
    }
5506
}
5507
 
5508
/**
5509
 * A helper function to test for email diversion
5510
 *
5511
 * @param string $email
5512
 * @return bool Returns true if the email should be diverted
5513
 */
5514
function email_should_be_diverted($email) {
5515
    global $CFG;
5516
 
5517
    if (empty($CFG->divertallemailsto)) {
5518
        return false;
5519
    }
5520
 
5521
    if (empty($CFG->divertallemailsexcept)) {
5522
        return true;
5523
    }
5524
 
5525
    $patterns = array_map('trim', preg_split("/[\s,]+/", $CFG->divertallemailsexcept, -1, PREG_SPLIT_NO_EMPTY));
5526
    foreach ($patterns as $pattern) {
5527
        if (preg_match("/{$pattern}/i", $email)) {
5528
            return false;
5529
        }
5530
    }
5531
 
5532
    return true;
5533
}
5534
 
5535
/**
5536
 * Generate a unique email Message-ID using the moodle domain and install path
5537
 *
5538
 * @param string $localpart An optional unique message id prefix.
5539
 * @return string The formatted ID ready for appending to the email headers.
5540
 */
5541
function generate_email_messageid($localpart = null) {
5542
    global $CFG;
5543
 
5544
    $urlinfo = parse_url($CFG->wwwroot);
5545
    $base = '@' . $urlinfo['host'];
5546
 
5547
    // If multiple moodles are on the same domain we want to tell them
5548
    // apart so we add the install path to the local part. This means
5549
    // that the id local part should never contain a / character so
5550
    // we can correctly parse the id to reassemble the wwwroot.
5551
    if (isset($urlinfo['path'])) {
5552
        $base = $urlinfo['path'] . $base;
5553
    }
5554
 
5555
    if (empty($localpart)) {
5556
        $localpart = uniqid('', true);
5557
    }
5558
 
5559
    // Because we may have an option /installpath suffix to the local part
5560
    // of the id we need to escape any / chars which are in the $localpart.
5561
    $localpart = str_replace('/', '%2F', $localpart);
5562
 
5563
    return '<' . $localpart . $base . '>';
5564
}
5565
 
5566
/**
5567
 * Send an email to a specified user
5568
 *
5569
 * @param stdClass $user  A {@link $USER} object
5570
 * @param stdClass $from A {@link $USER} object
5571
 * @param string $subject plain text subject line of the email
5572
 * @param string $messagetext plain text version of the message
5573
 * @param string $messagehtml complete html version of the message (optional)
5574
 * @param string $attachment a file on the filesystem, either relative to $CFG->dataroot or a full path to a file in one of
5575
 *          the following directories: $CFG->cachedir, $CFG->dataroot, $CFG->dirroot, $CFG->localcachedir, $CFG->tempdir
5576
 * @param string $attachname the name of the file (extension indicates MIME)
5577
 * @param bool $usetrueaddress determines whether $from email address should
5578
 *          be sent out. Will be overruled by user profile setting for maildisplay
5579
 * @param string $replyto Email address to reply to
5580
 * @param string $replytoname Name of reply to recipient
5581
 * @param int $wordwrapwidth custom word wrap width, default 79
5582
 * @return bool Returns true if mail was sent OK and false if there was an error.
5583
 */
5584
function email_to_user($user, $from, $subject, $messagetext, $messagehtml = '', $attachment = '', $attachname = '',
5585
                       $usetrueaddress = true, $replyto = '', $replytoname = '', $wordwrapwidth = 79) {
5586
 
5587
    global $CFG, $PAGE, $SITE;
5588
 
5589
    if (empty($user) or empty($user->id)) {
5590
        debugging('Can not send email to null user', DEBUG_DEVELOPER);
5591
        return false;
5592
    }
5593
 
5594
    if (empty($user->email)) {
5595
        debugging('Can not send email to user without email: '.$user->id, DEBUG_DEVELOPER);
5596
        return false;
5597
    }
5598
 
5599
    if (!empty($user->deleted)) {
5600
        debugging('Can not send email to deleted user: '.$user->id, DEBUG_DEVELOPER);
5601
        return false;
5602
    }
5603
 
5604
    if (defined('BEHAT_SITE_RUNNING')) {
5605
        // Fake email sending in behat.
5606
        return true;
5607
    }
5608
 
5609
    if (!empty($CFG->noemailever)) {
5610
        // Hidden setting for development sites, set in config.php if needed.
5611
        debugging('Not sending email due to $CFG->noemailever config setting', DEBUG_NORMAL);
5612
        return true;
5613
    }
5614
 
5615
    if (email_should_be_diverted($user->email)) {
5616
        $subject = "[DIVERTED {$user->email}] $subject";
5617
        $user = clone($user);
5618
        $user->email = $CFG->divertallemailsto;
5619
    }
5620
 
5621
    // Skip mail to suspended users.
5622
    if ((isset($user->auth) && $user->auth=='nologin') or (isset($user->suspended) && $user->suspended)) {
5623
        return true;
5624
    }
5625
 
5626
    if (!validate_email($user->email)) {
5627
        // We can not send emails to invalid addresses - it might create security issue or confuse the mailer.
5628
        debugging("email_to_user: User $user->id (".fullname($user).") email ($user->email) is invalid! Not sending.");
5629
        return false;
5630
    }
5631
 
5632
    if (over_bounce_threshold($user)) {
5633
        debugging("email_to_user: User $user->id (".fullname($user).") is over bounce threshold! Not sending.");
5634
        return false;
5635
    }
5636
 
5637
    // TLD .invalid  is specifically reserved for invalid domain names.
5638
    // For More information, see {@link http://tools.ietf.org/html/rfc2606#section-2}.
5639
    if (substr($user->email, -8) == '.invalid') {
5640
        debugging("email_to_user: User $user->id (".fullname($user).") email domain ($user->email) is invalid! Not sending.");
5641
        return true; // This is not an error.
5642
    }
5643
 
5644
    // If the user is a remote mnet user, parse the email text for URL to the
5645
    // wwwroot and modify the url to direct the user's browser to login at their
5646
    // home site (identity provider - idp) before hitting the link itself.
5647
    if (is_mnet_remote_user($user)) {
5648
        require_once($CFG->dirroot.'/mnet/lib.php');
5649
 
5650
        $jumpurl = mnet_get_idp_jump_url($user);
5651
        $callback = partial('mnet_sso_apply_indirection', $jumpurl);
5652
 
5653
        $messagetext = preg_replace_callback("%($CFG->wwwroot[^[:space:]]*)%",
5654
                $callback,
5655
                $messagetext);
5656
        $messagehtml = preg_replace_callback("%href=[\"'`]($CFG->wwwroot[\w_:\?=#&@/;.~-]*)[\"'`]%",
5657
                $callback,
5658
                $messagehtml);
5659
    }
5660
    $mail = get_mailer();
5661
 
5662
    if (!empty($mail->SMTPDebug)) {
5663
        echo '<pre>' . "\n";
5664
    }
5665
 
5666
    $temprecipients = array();
5667
    $tempreplyto = array();
5668
 
5669
    // Make sure that we fall back onto some reasonable no-reply address.
5670
    $noreplyaddressdefault = 'noreply@' . get_host_from_url($CFG->wwwroot);
5671
    $noreplyaddress = empty($CFG->noreplyaddress) ? $noreplyaddressdefault : $CFG->noreplyaddress;
5672
 
5673
    if (!validate_email($noreplyaddress)) {
5674
        debugging('email_to_user: Invalid noreply-email '.s($noreplyaddress));
5675
        $noreplyaddress = $noreplyaddressdefault;
5676
    }
5677
 
5678
    // Make up an email address for handling bounces.
5679
    if (!empty($CFG->handlebounces)) {
5680
        $modargs = 'B'.base64_encode(pack('V', $user->id)).substr(md5($user->email), 0, 16);
5681
        $mail->Sender = generate_email_processing_address(0, $modargs);
5682
    } else {
5683
        $mail->Sender = $noreplyaddress;
5684
    }
5685
 
5686
    // Make sure that the explicit replyto is valid, fall back to the implicit one.
5687
    if (!empty($replyto) && !validate_email($replyto)) {
5688
        debugging('email_to_user: Invalid replyto-email '.s($replyto));
5689
        $replyto = $noreplyaddress;
5690
    }
5691
 
5692
    if (is_string($from)) { // So we can pass whatever we want if there is need.
5693
        $mail->From     = $noreplyaddress;
5694
        $mail->FromName = $from;
5695
    // Check if using the true address is true, and the email is in the list of allowed domains for sending email,
5696
    // and that the senders email setting is either displayed to everyone, or display to only other users that are enrolled
5697
    // in a course with the sender.
5698
    } else if ($usetrueaddress && can_send_from_real_email_address($from, $user)) {
5699
        if (!validate_email($from->email)) {
5700
            debugging('email_to_user: Invalid from-email '.s($from->email).' - not sending');
5701
            // Better not to use $noreplyaddress in this case.
5702
            return false;
5703
        }
5704
        $mail->From = $from->email;
5705
        $fromdetails = new stdClass();
5706
        $fromdetails->name = fullname($from);
5707
        $fromdetails->url = preg_replace('#^https?://#', '', $CFG->wwwroot);
5708
        $fromdetails->siteshortname = format_string($SITE->shortname);
5709
        $fromstring = $fromdetails->name;
5710
        if ($CFG->emailfromvia == EMAIL_VIA_ALWAYS) {
5711
            $fromstring = get_string('emailvia', 'core', $fromdetails);
5712
        }
5713
        $mail->FromName = $fromstring;
5714
        if (empty($replyto)) {
5715
            $tempreplyto[] = array($from->email, fullname($from));
5716
        }
5717
    } else {
5718
        $mail->From = $noreplyaddress;
5719
        $fromdetails = new stdClass();
5720
        $fromdetails->name = fullname($from);
5721
        $fromdetails->url = preg_replace('#^https?://#', '', $CFG->wwwroot);
5722
        $fromdetails->siteshortname = format_string($SITE->shortname);
5723
        $fromstring = $fromdetails->name;
5724
        if ($CFG->emailfromvia != EMAIL_VIA_NEVER) {
5725
            $fromstring = get_string('emailvia', 'core', $fromdetails);
5726
        }
5727
        $mail->FromName = $fromstring;
5728
        if (empty($replyto)) {
5729
            $tempreplyto[] = array($noreplyaddress, get_string('noreplyname'));
5730
        }
5731
    }
5732
 
5733
    if (!empty($replyto)) {
5734
        $tempreplyto[] = array($replyto, $replytoname);
5735
    }
5736
 
5737
    $temprecipients[] = array($user->email, fullname($user));
5738
 
5739
    // Set word wrap.
5740
    $mail->WordWrap = $wordwrapwidth;
5741
 
5742
    if (!empty($from->customheaders)) {
5743
        // Add custom headers.
5744
        if (is_array($from->customheaders)) {
5745
            foreach ($from->customheaders as $customheader) {
5746
                $mail->addCustomHeader($customheader);
5747
            }
5748
        } else {
5749
            $mail->addCustomHeader($from->customheaders);
5750
        }
5751
    }
5752
 
5753
    // If the X-PHP-Originating-Script email header is on then also add an additional
5754
    // header with details of where exactly in moodle the email was triggered from,
5755
    // either a call to message_send() or to email_to_user().
5756
    if (ini_get('mail.add_x_header')) {
5757
 
5758
        $stack = debug_backtrace(false);
5759
        $origin = $stack[0];
5760
 
5761
        foreach ($stack as $depth => $call) {
5762
            if ($call['function'] == 'message_send') {
5763
                $origin = $call;
5764
            }
5765
        }
5766
 
5767
        $originheader = $CFG->wwwroot . ' => ' . gethostname() . ':'
5768
             . str_replace($CFG->dirroot . '/', '', $origin['file']) . ':' . $origin['line'];
5769
        $mail->addCustomHeader('X-Moodle-Originating-Script: ' . $originheader);
5770
    }
5771
 
5772
    if (!empty($CFG->emailheaders)) {
5773
        $headers = array_map('trim', explode("\n", $CFG->emailheaders));
5774
        foreach ($headers as $header) {
5775
            if (!empty($header)) {
5776
                $mail->addCustomHeader($header);
5777
            }
5778
        }
5779
    }
5780
 
5781
    if (!empty($from->priority)) {
5782
        $mail->Priority = $from->priority;
5783
    }
5784
 
5785
    $renderer = $PAGE->get_renderer('core');
5786
    $context = array(
5787
        'sitefullname' => $SITE->fullname,
5788
        'siteshortname' => $SITE->shortname,
5789
        'sitewwwroot' => $CFG->wwwroot,
5790
        'subject' => $subject,
5791
        'prefix' => $CFG->emailsubjectprefix,
5792
        'to' => $user->email,
5793
        'toname' => fullname($user),
5794
        'from' => $mail->From,
5795
        'fromname' => $mail->FromName,
5796
    );
5797
    if (!empty($tempreplyto[0])) {
5798
        $context['replyto'] = $tempreplyto[0][0];
5799
        $context['replytoname'] = $tempreplyto[0][1];
5800
    }
5801
    if ($user->id > 0) {
5802
        $context['touserid'] = $user->id;
5803
        $context['tousername'] = $user->username;
5804
    }
5805
 
5806
    if (!empty($user->mailformat) && $user->mailformat == 1) {
5807
        // Only process html templates if the user preferences allow html email.
5808
 
5809
        if (!$messagehtml) {
5810
            // If no html has been given, BUT there is an html wrapping template then
5811
            // auto convert the text to html and then wrap it.
5812
            $messagehtml = trim(text_to_html($messagetext));
5813
        }
5814
        $context['body'] = $messagehtml;
5815
        $messagehtml = $renderer->render_from_template('core/email_html', $context);
5816
    }
5817
 
5818
    $context['body'] = html_to_text(nl2br($messagetext));
5819
    $mail->Subject = $renderer->render_from_template('core/email_subject', $context);
5820
    $mail->FromName = $renderer->render_from_template('core/email_fromname', $context);
5821
    $messagetext = $renderer->render_from_template('core/email_text', $context);
5822
 
5823
    // Autogenerate a MessageID if it's missing.
5824
    if (empty($mail->MessageID)) {
5825
        $mail->MessageID = generate_email_messageid();
5826
    }
5827
 
5828
    if ($messagehtml && !empty($user->mailformat) && $user->mailformat == 1) {
5829
        // Don't ever send HTML to users who don't want it.
5830
        $mail->isHTML(true);
5831
        $mail->Encoding = 'quoted-printable';
5832
        $mail->Body    =  $messagehtml;
5833
        $mail->AltBody =  "\n$messagetext\n";
5834
    } else {
5835
        $mail->IsHTML(false);
5836
        $mail->Body =  "\n$messagetext\n";
5837
    }
5838
 
5839
    if ($attachment && $attachname) {
5840
        if (preg_match( "~\\.\\.~" , $attachment )) {
5841
            // Security check for ".." in dir path.
5842
            $supportuser = core_user::get_support_user();
5843
            $temprecipients[] = array($supportuser->email, fullname($supportuser, true));
5844
            $mail->addStringAttachment('Error in attachment.  User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
5845
        } else {
5846
            require_once($CFG->libdir.'/filelib.php');
5847
            $mimetype = mimeinfo('type', $attachname);
5848
 
5849
            // Before doing the comparison, make sure that the paths are correct (Windows uses slashes in the other direction).
5850
            // The absolute (real) path is also fetched to ensure that comparisons to allowed paths are compared equally.
5851
            $attachpath = str_replace('\\', '/', realpath($attachment));
5852
 
5853
            // Build an array of all filepaths from which attachments can be added (normalised slashes, absolute/real path).
5854
            $allowedpaths = array_map(function(string $path): string {
5855
                return str_replace('\\', '/', realpath($path));
5856
            }, [
5857
                $CFG->cachedir,
5858
                $CFG->dataroot,
5859
                $CFG->dirroot,
5860
                $CFG->localcachedir,
5861
                $CFG->tempdir,
5862
                $CFG->localrequestdir,
5863
            ]);
5864
 
5865
            // Set addpath to true.
5866
            $addpath = true;
5867
 
5868
            // Check if attachment includes one of the allowed paths.
5869
            foreach (array_filter($allowedpaths) as $allowedpath) {
5870
                // Set addpath to false if the attachment includes one of the allowed paths.
5871
                if (strpos($attachpath, $allowedpath) === 0) {
5872
                    $addpath = false;
5873
                    break;
5874
                }
5875
            }
5876
 
5877
            // If the attachment is a full path to a file in the multiple allowed paths, use it as is,
5878
            // otherwise assume it is a relative path from the dataroot (for backwards compatibility reasons).
5879
            if ($addpath == true) {
5880
                $attachment = $CFG->dataroot . '/' . $attachment;
5881
            }
5882
 
5883
            $mail->addAttachment($attachment, $attachname, 'base64', $mimetype);
5884
        }
5885
    }
5886
 
5887
    // Check if the email should be sent in an other charset then the default UTF-8.
5888
    if ((!empty($CFG->sitemailcharset) || !empty($CFG->allowusermailcharset))) {
5889
 
5890
        // Use the defined site mail charset or eventually the one preferred by the recipient.
5891
        $charset = $CFG->sitemailcharset;
5892
        if (!empty($CFG->allowusermailcharset)) {
5893
            if ($useremailcharset = get_user_preferences('mailcharset', '0', $user->id)) {
5894
                $charset = $useremailcharset;
5895
            }
5896
        }
5897
 
5898
        // Convert all the necessary strings if the charset is supported.
5899
        $charsets = get_list_of_charsets();
5900
        unset($charsets['UTF-8']);
5901
        if (in_array($charset, $charsets)) {
5902
            $mail->CharSet  = $charset;
5903
            $mail->FromName = core_text::convert($mail->FromName, 'utf-8', strtolower($charset));
5904
            $mail->Subject  = core_text::convert($mail->Subject, 'utf-8', strtolower($charset));
5905
            $mail->Body     = core_text::convert($mail->Body, 'utf-8', strtolower($charset));
5906
            $mail->AltBody  = core_text::convert($mail->AltBody, 'utf-8', strtolower($charset));
5907
 
5908
            foreach ($temprecipients as $key => $values) {
5909
                $temprecipients[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
5910
            }
5911
            foreach ($tempreplyto as $key => $values) {
5912
                $tempreplyto[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
5913
            }
5914
        }
5915
    }
5916
 
5917
    foreach ($temprecipients as $values) {
5918
        $mail->addAddress($values[0], $values[1]);
5919
    }
5920
    foreach ($tempreplyto as $values) {
5921
        $mail->addReplyTo($values[0], $values[1]);
5922
    }
5923
 
5924
    if (!empty($CFG->emaildkimselector)) {
5925
        $domain = substr(strrchr($mail->From, "@"), 1);
5926
        $pempath = "{$CFG->dataroot}/dkim/{$domain}/{$CFG->emaildkimselector}.private";
5927
        if (file_exists($pempath)) {
5928
            $mail->DKIM_domain      = $domain;
5929
            $mail->DKIM_private     = $pempath;
5930
            $mail->DKIM_selector    = $CFG->emaildkimselector;
5931
            $mail->DKIM_identity    = $mail->From;
5932
        } else {
5933
            debugging("Email DKIM selector chosen due to {$mail->From} but no certificate found at $pempath", DEBUG_DEVELOPER);
5934
        }
5935
    }
5936
 
5937
    if ($mail->send()) {
5938
        set_send_count($user);
5939
        if (!empty($mail->SMTPDebug)) {
5940
            echo '</pre>';
5941
        }
5942
        return true;
5943
    } else {
5944
        // Trigger event for failing to send email.
5945
        $event = \core\event\email_failed::create(array(
5946
            'context' => context_system::instance(),
5947
            'userid' => $from->id,
5948
            'relateduserid' => $user->id,
5949
            'other' => array(
5950
                'subject' => $subject,
5951
                'message' => $messagetext,
5952
                'errorinfo' => $mail->ErrorInfo
5953
            )
5954
        ));
5955
        $event->trigger();
5956
        if (CLI_SCRIPT) {
5957
            mtrace('Error: lib/moodlelib.php email_to_user(): '.$mail->ErrorInfo);
5958
        }
5959
        if (!empty($mail->SMTPDebug)) {
5960
            echo '</pre>';
5961
        }
5962
        return false;
5963
    }
5964
}
5965
 
5966
/**
5967
 * Check to see if a user's real email address should be used for the "From" field.
5968
 *
5969
 * @param  object $from The user object for the user we are sending the email from.
5970
 * @param  object $user The user object that we are sending the email to.
5971
 * @param  array $unused No longer used.
5972
 * @return bool Returns true if we can use the from user's email adress in the "From" field.
5973
 */
5974
function can_send_from_real_email_address($from, $user, $unused = null) {
5975
    global $CFG;
5976
    if (!isset($CFG->allowedemaildomains) || empty(trim($CFG->allowedemaildomains))) {
5977
        return false;
5978
    }
5979
    $alloweddomains = array_map('trim', explode("\n", $CFG->allowedemaildomains));
5980
    // Email is in the list of allowed domains for sending email,
5981
    // and the senders email setting is either displayed to everyone, or display to only other users that are enrolled
5982
    // in a course with the sender.
5983
    if (\core\ip_utils::is_domain_in_allowed_list(substr($from->email, strpos($from->email, '@') + 1), $alloweddomains)
5984
                && ($from->maildisplay == core_user::MAILDISPLAY_EVERYONE
5985
                || ($from->maildisplay == core_user::MAILDISPLAY_COURSE_MEMBERS_ONLY
5986
                && enrol_get_shared_courses($user, $from, false, true)))) {
5987
        return true;
5988
    }
5989
    return false;
5990
}
5991
 
5992
/**
5993
 * Generate a signoff for emails based on support settings
5994
 *
5995
 * @return string
5996
 */
5997
function generate_email_signoff() {
5998
    global $CFG, $OUTPUT;
5999
 
6000
    $signoff = "\n";
6001
    if (!empty($CFG->supportname)) {
6002
        $signoff .= $CFG->supportname."\n";
6003
    }
6004
 
6005
    $supportemail = $OUTPUT->supportemail(['class' => 'font-weight-bold']);
6006
 
6007
    if ($supportemail) {
6008
        $signoff .= "\n" . $supportemail . "\n";
6009
    }
6010
 
6011
    return $signoff;
6012
}
6013
 
6014
/**
6015
 * Sets specified user's password and send the new password to the user via email.
6016
 *
6017
 * @param stdClass $user A {@link $USER} object
6018
 * @param bool $fasthash If true, use a low cost factor when generating the hash for speed.
6019
 * @return bool|string Returns "true" if mail was sent OK and "false" if there was an error
6020
 */
6021
function setnew_password_and_mail($user, $fasthash = false) {
6022
    global $CFG, $DB;
6023
 
6024
    // We try to send the mail in language the user understands,
6025
    // unfortunately the filter_string() does not support alternative langs yet
6026
    // so multilang will not work properly for site->fullname.
6027
    $lang = empty($user->lang) ? get_newuser_language() : $user->lang;
6028
 
6029
    $site  = get_site();
6030
 
6031
    $supportuser = core_user::get_support_user();
6032
 
6033
    $newpassword = generate_password();
6034
 
6035
    update_internal_user_password($user, $newpassword, $fasthash);
6036
 
6037
    $a = new stdClass();
6038
    $a->firstname   = fullname($user, true);
6039
    $a->sitename    = format_string($site->fullname);
6040
    $a->username    = $user->username;
6041
    $a->newpassword = $newpassword;
6042
    $a->link        = $CFG->wwwroot .'/login/?lang='.$lang;
6043
    $a->signoff     = generate_email_signoff();
6044
 
6045
    $message = (string)new lang_string('newusernewpasswordtext', '', $a, $lang);
6046
 
6047
    $subject = format_string($site->fullname) .': '. (string)new lang_string('newusernewpasswordsubj', '', $a, $lang);
6048
 
6049
    // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6050
    return email_to_user($user, $supportuser, $subject, $message);
6051
 
6052
}
6053
 
6054
/**
6055
 * Resets specified user's password and send the new password to the user via email.
6056
 *
6057
 * @param stdClass $user A {@link $USER} object
6058
 * @return bool Returns true if mail was sent OK and false if there was an error.
6059
 */
6060
function reset_password_and_mail($user) {
6061
    global $CFG;
6062
 
6063
    $site  = get_site();
6064
    $supportuser = core_user::get_support_user();
6065
 
6066
    $userauth = get_auth_plugin($user->auth);
6067
    if (!$userauth->can_reset_password() or !is_enabled_auth($user->auth)) {
6068
        trigger_error("Attempt to reset user password for user $user->username with Auth $user->auth.");
6069
        return false;
6070
    }
6071
 
6072
    $newpassword = generate_password();
6073
 
6074
    if (!$userauth->user_update_password($user, $newpassword)) {
6075
        throw new \moodle_exception("cannotsetpassword");
6076
    }
6077
 
6078
    $a = new stdClass();
6079
    $a->firstname   = $user->firstname;
6080
    $a->lastname    = $user->lastname;
6081
    $a->sitename    = format_string($site->fullname);
6082
    $a->username    = $user->username;
6083
    $a->newpassword = $newpassword;
6084
    $a->link        = $CFG->wwwroot .'/login/change_password.php';
6085
    $a->signoff     = generate_email_signoff();
6086
 
6087
    $message = get_string('newpasswordtext', '', $a);
6088
 
6089
    $subject  = format_string($site->fullname) .': '. get_string('changedpassword');
6090
 
6091
    unset_user_preference('create_password', $user); // Prevent cron from generating the password.
6092
 
6093
    // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6094
    return email_to_user($user, $supportuser, $subject, $message);
6095
}
6096
 
6097
/**
6098
 * Send email to specified user with confirmation text and activation link.
6099
 *
6100
 * @param stdClass $user A {@link $USER} object
6101
 * @param string $confirmationurl user confirmation URL
6102
 * @return bool Returns true if mail was sent OK and false if there was an error.
6103
 */
6104
function send_confirmation_email($user, $confirmationurl = null) {
6105
    global $CFG;
6106
 
6107
    $site = get_site();
6108
    $supportuser = core_user::get_support_user();
6109
 
6110
    $data = new stdClass();
6111
    $data->sitename  = format_string($site->fullname);
6112
    $data->admin     = generate_email_signoff();
6113
 
6114
    $subject = get_string('emailconfirmationsubject', '', format_string($site->fullname));
6115
 
6116
    if (empty($confirmationurl)) {
6117
        $confirmationurl = '/login/confirm.php';
6118
    }
6119
 
6120
    $confirmationurl = new moodle_url($confirmationurl);
6121
    // Remove data parameter just in case it was included in the confirmation so we can add it manually later.
6122
    $confirmationurl->remove_params('data');
6123
    $confirmationpath = $confirmationurl->out(false);
6124
 
6125
    // We need to custom encode the username to include trailing dots in the link.
6126
    // Because of this custom encoding we can't use moodle_url directly.
6127
    // Determine if a query string is present in the confirmation url.
6128
    $hasquerystring = strpos($confirmationpath, '?') !== false;
6129
    // Perform normal url encoding of the username first.
6130
    $username = urlencode($user->username);
6131
    // Prevent problems with trailing dots not being included as part of link in some mail clients.
6132
    $username = str_replace('.', '%2E', $username);
6133
 
6134
    $data->link = $confirmationpath . ( $hasquerystring ? '&' : '?') . 'data='. $user->secret .'/'. $username;
6135
 
6136
    $message     = get_string('emailconfirmation', '', $data);
6137
    $messagehtml = text_to_html(get_string('emailconfirmation', '', $data), false, false, true);
6138
 
6139
    // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6140
    return email_to_user($user, $supportuser, $subject, $message, $messagehtml);
6141
}
6142
 
6143
/**
6144
 * Sends a password change confirmation email.
6145
 *
6146
 * @param stdClass $user A {@link $USER} object
6147
 * @param stdClass $resetrecord An object tracking metadata regarding password reset request
6148
 * @return bool Returns true if mail was sent OK and false if there was an error.
6149
 */
6150
function send_password_change_confirmation_email($user, $resetrecord) {
6151
    global $CFG;
6152
 
6153
    $site = get_site();
6154
    $supportuser = core_user::get_support_user();
6155
    $pwresetmins = isset($CFG->pwresettime) ? floor($CFG->pwresettime / MINSECS) : 30;
6156
 
6157
    $data = new stdClass();
6158
    $data->firstname = $user->firstname;
6159
    $data->lastname  = $user->lastname;
6160
    $data->username  = $user->username;
6161
    $data->sitename  = format_string($site->fullname);
6162
    $data->link      = $CFG->wwwroot .'/login/forgot_password.php?token='. $resetrecord->token;
6163
    $data->admin     = generate_email_signoff();
6164
    $data->resetminutes = $pwresetmins;
6165
 
6166
    $message = get_string('emailresetconfirmation', '', $data);
6167
    $subject = get_string('emailresetconfirmationsubject', '', format_string($site->fullname));
6168
 
6169
    // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6170
    return email_to_user($user, $supportuser, $subject, $message);
6171
 
6172
}
6173
 
6174
/**
6175
 * Sends an email containing information on how to change your password.
6176
 *
6177
 * @param stdClass $user A {@link $USER} object
6178
 * @return bool Returns true if mail was sent OK and false if there was an error.
6179
 */
6180
function send_password_change_info($user) {
6181
    $site = get_site();
6182
    $supportuser = core_user::get_support_user();
6183
 
6184
    $data = new stdClass();
6185
    $data->firstname = $user->firstname;
6186
    $data->lastname  = $user->lastname;
6187
    $data->username  = $user->username;
6188
    $data->sitename  = format_string($site->fullname);
6189
    $data->admin     = generate_email_signoff();
6190
 
6191
    if (!is_enabled_auth($user->auth)) {
6192
        $message = get_string('emailpasswordchangeinfodisabled', '', $data);
6193
        $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
6194
        // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6195
        return email_to_user($user, $supportuser, $subject, $message);
6196
    }
6197
 
6198
    $userauth = get_auth_plugin($user->auth);
6199
    ['subject' => $subject, 'message' => $message] = $userauth->get_password_change_info($user);
6200
 
6201
    // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6202
    return email_to_user($user, $supportuser, $subject, $message);
6203
}
6204
 
6205
/**
6206
 * Check that an email is allowed.  It returns an error message if there was a problem.
6207
 *
6208
 * @param string $email Content of email
6209
 * @return string|false
6210
 */
6211
function email_is_not_allowed($email) {
6212
    global $CFG;
6213
 
6214
    // Comparing lowercase domains.
6215
    $email = strtolower($email);
6216
    if (!empty($CFG->allowemailaddresses)) {
6217
        $allowed = explode(' ', strtolower($CFG->allowemailaddresses));
6218
        foreach ($allowed as $allowedpattern) {
6219
            $allowedpattern = trim($allowedpattern);
6220
            if (!$allowedpattern) {
6221
                continue;
6222
            }
6223
            if (strpos($allowedpattern, '.') === 0) {
6224
                if (strpos(strrev($email), strrev($allowedpattern)) === 0) {
6225
                    // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6226
                    return false;
6227
                }
6228
 
6229
            } else if (strpos(strrev($email), strrev('@'.$allowedpattern)) === 0) {
6230
                return false;
6231
            }
6232
        }
6233
        return get_string('emailonlyallowed', '', $CFG->allowemailaddresses);
6234
 
6235
    } else if (!empty($CFG->denyemailaddresses)) {
6236
        $denied = explode(' ', strtolower($CFG->denyemailaddresses));
6237
        foreach ($denied as $deniedpattern) {
6238
            $deniedpattern = trim($deniedpattern);
6239
            if (!$deniedpattern) {
6240
                continue;
6241
            }
6242
            if (strpos($deniedpattern, '.') === 0) {
6243
                if (strpos(strrev($email), strrev($deniedpattern)) === 0) {
6244
                    // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6245
                    return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
6246
                }
6247
 
6248
            } else if (strpos(strrev($email), strrev('@'.$deniedpattern)) === 0) {
6249
                return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
6250
            }
6251
        }
6252
    }
6253
 
6254
    return false;
6255
}
6256
 
6257
// FILE HANDLING.
6258
 
6259
/**
6260
 * Returns local file storage instance
6261
 *
6262
 * @return ?file_storage
6263
 */
6264
function get_file_storage($reset = false) {
6265
    global $CFG;
6266
 
6267
    static $fs = null;
6268
 
6269
    if ($reset) {
6270
        $fs = null;
6271
        return;
6272
    }
6273
 
6274
    if ($fs) {
6275
        return $fs;
6276
    }
6277
 
6278
    require_once("$CFG->libdir/filelib.php");
6279
 
6280
    $fs = new file_storage();
6281
 
6282
    return $fs;
6283
}
6284
 
6285
/**
6286
 * Returns local file storage instance
6287
 *
6288
 * @return file_browser
6289
 */
6290
function get_file_browser() {
6291
    global $CFG;
6292
 
6293
    static $fb = null;
6294
 
6295
    if ($fb) {
6296
        return $fb;
6297
    }
6298
 
6299
    require_once("$CFG->libdir/filelib.php");
6300
 
6301
    $fb = new file_browser();
6302
 
6303
    return $fb;
6304
}
6305
 
6306
/**
6307
 * Returns file packer
6308
 *
6309
 * @param string $mimetype default application/zip
6310
 * @return file_packer|false
6311
 */
6312
function get_file_packer($mimetype='application/zip') {
6313
    global $CFG;
6314
 
6315
    static $fp = array();
6316
 
6317
    if (isset($fp[$mimetype])) {
6318
        return $fp[$mimetype];
6319
    }
6320
 
6321
    switch ($mimetype) {
6322
        case 'application/zip':
6323
        case 'application/vnd.moodle.profiling':
6324
            $classname = 'zip_packer';
6325
            break;
6326
 
6327
        case 'application/x-gzip' :
6328
            $classname = 'tgz_packer';
6329
            break;
6330
 
6331
        case 'application/vnd.moodle.backup':
6332
            $classname = 'mbz_packer';
6333
            break;
6334
 
6335
        default:
6336
            return false;
6337
    }
6338
 
6339
    require_once("$CFG->libdir/filestorage/$classname.php");
6340
    $fp[$mimetype] = new $classname();
6341
 
6342
    return $fp[$mimetype];
6343
}
6344
 
6345
/**
6346
 * Returns current name of file on disk if it exists.
6347
 *
6348
 * @param string $newfile File to be verified
6349
 * @return string Current name of file on disk if true
6350
 */
6351
function valid_uploaded_file($newfile) {
6352
    if (empty($newfile)) {
6353
        return '';
6354
    }
6355
    if (is_uploaded_file($newfile['tmp_name']) and $newfile['size'] > 0) {
6356
        return $newfile['tmp_name'];
6357
    } else {
6358
        return '';
6359
    }
6360
}
6361
 
6362
/**
6363
 * Returns the maximum size for uploading files.
6364
 *
6365
 * There are seven possible upload limits:
6366
 * 1. in Apache using LimitRequestBody (no way of checking or changing this)
6367
 * 2. in php.ini for 'upload_max_filesize' (can not be changed inside PHP)
6368
 * 3. in .htaccess for 'upload_max_filesize' (can not be changed inside PHP)
6369
 * 4. in php.ini for 'post_max_size' (can not be changed inside PHP)
6370
 * 5. by the Moodle admin in $CFG->maxbytes
6371
 * 6. by the teacher in the current course $course->maxbytes
6372
 * 7. by the teacher for the current module, eg $assignment->maxbytes
6373
 *
6374
 * These last two are passed to this function as arguments (in bytes).
6375
 * Anything defined as 0 is ignored.
6376
 * The smallest of all the non-zero numbers is returned.
6377
 *
6378
 * @todo Finish documenting this function
6379
 *
6380
 * @param int $sitebytes Set maximum size
6381
 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6382
 * @param int $modulebytes Current module ->maxbytes (in bytes)
6383
 * @param bool $unused This parameter has been deprecated and is not used any more.
6384
 * @return int The maximum size for uploading files.
6385
 */
6386
function get_max_upload_file_size($sitebytes=0, $coursebytes=0, $modulebytes=0, $unused = false) {
6387
 
6388
    if (! $filesize = ini_get('upload_max_filesize')) {
6389
        $filesize = '5M';
6390
    }
6391
    $minimumsize = get_real_size($filesize);
6392
 
6393
    if ($postsize = ini_get('post_max_size')) {
6394
        $postsize = get_real_size($postsize);
6395
        if ($postsize < $minimumsize) {
6396
            $minimumsize = $postsize;
6397
        }
6398
    }
6399
 
6400
    if (($sitebytes > 0) and ($sitebytes < $minimumsize)) {
6401
        $minimumsize = $sitebytes;
6402
    }
6403
 
6404
    if (($coursebytes > 0) and ($coursebytes < $minimumsize)) {
6405
        $minimumsize = $coursebytes;
6406
    }
6407
 
6408
    if (($modulebytes > 0) and ($modulebytes < $minimumsize)) {
6409
        $minimumsize = $modulebytes;
6410
    }
6411
 
6412
    return $minimumsize;
6413
}
6414
 
6415
/**
6416
 * Returns the maximum size for uploading files for the current user
6417
 *
6418
 * This function takes in account {@link get_max_upload_file_size()} the user's capabilities
6419
 *
6420
 * @param context $context The context in which to check user capabilities
6421
 * @param int $sitebytes Set maximum size
6422
 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6423
 * @param int $modulebytes Current module ->maxbytes (in bytes)
6424
 * @param stdClass|int|null $user The user
6425
 * @param bool $unused This parameter has been deprecated and is not used any more.
6426
 * @return int The maximum size for uploading files.
6427
 */
6428
function get_user_max_upload_file_size($context, $sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $user = null,
6429
        $unused = false) {
6430
    global $USER;
6431
 
6432
    if (empty($user)) {
6433
        $user = $USER;
6434
    }
6435
 
6436
    if (has_capability('moodle/course:ignorefilesizelimits', $context, $user)) {
6437
        return USER_CAN_IGNORE_FILE_SIZE_LIMITS;
6438
    }
6439
 
6440
    return get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes);
6441
}
6442
 
6443
/**
6444
 * Returns an array of possible sizes in local language
6445
 *
6446
 * Related to {@link get_max_upload_file_size()} - this function returns an
6447
 * array of possible sizes in an array, translated to the
6448
 * local language.
6449
 *
6450
 * The list of options will go up to the minimum of $sitebytes, $coursebytes or $modulebytes.
6451
 *
6452
 * If $coursebytes or $sitebytes is not 0, an option will be included for "Course/Site upload limit (X)"
6453
 * with the value set to 0. This option will be the first in the list.
6454
 *
6455
 * @uses SORT_NUMERIC
6456
 * @param int $sitebytes Set maximum size
6457
 * @param int $coursebytes Current course $course->maxbytes (in bytes)
6458
 * @param int $modulebytes Current module ->maxbytes (in bytes)
6459
 * @param int|array $custombytes custom upload size/s which will be added to list,
6460
 *        Only value/s smaller then maxsize will be added to list.
6461
 * @return array
6462
 */
6463
function get_max_upload_sizes($sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $custombytes = null) {
6464
    global $CFG;
6465
 
6466
    if (!$maxsize = get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes)) {
6467
        return array();
6468
    }
6469
 
6470
    if ($sitebytes == 0) {
6471
        // Will get the minimum of upload_max_filesize or post_max_size.
6472
        $sitebytes = get_max_upload_file_size();
6473
    }
6474
 
6475
    $filesize = array();
6476
    $sizelist = array(10240, 51200, 102400, 512000, 1048576, 2097152,
6477
                      5242880, 10485760, 20971520, 52428800, 104857600,
6478
                      262144000, 524288000, 786432000, 1073741824,
6479
                      2147483648, 4294967296, 8589934592);
6480
 
6481
    // If custombytes is given and is valid then add it to the list.
6482
    if (is_number($custombytes) and $custombytes > 0) {
6483
        $custombytes = (int)$custombytes;
6484
        if (!in_array($custombytes, $sizelist)) {
6485
            $sizelist[] = $custombytes;
6486
        }
6487
    } else if (is_array($custombytes)) {
6488
        $sizelist = array_unique(array_merge($sizelist, $custombytes));
6489
    }
6490
 
6491
    // Allow maxbytes to be selected if it falls outside the above boundaries.
6492
    if (isset($CFG->maxbytes) && !in_array(get_real_size($CFG->maxbytes), $sizelist)) {
6493
        // Note: get_real_size() is used in order to prevent problems with invalid values.
6494
        $sizelist[] = get_real_size($CFG->maxbytes);
6495
    }
6496
 
6497
    foreach ($sizelist as $sizebytes) {
6498
        if ($sizebytes < $maxsize && $sizebytes > 0) {
6499
            $filesize[(string)intval($sizebytes)] = display_size($sizebytes, 0);
6500
        }
6501
    }
6502
 
6503
    $limitlevel = '';
6504
    $displaysize = '';
6505
    if ($modulebytes &&
6506
        (($modulebytes < $coursebytes || $coursebytes == 0) &&
6507
         ($modulebytes < $sitebytes || $sitebytes == 0))) {
6508
        $limitlevel = get_string('activity', 'core');
6509
        $displaysize = display_size($modulebytes, 0);
6510
        $filesize[$modulebytes] = $displaysize; // Make sure the limit is also included in the list.
6511
 
6512
    } else if ($coursebytes && ($coursebytes < $sitebytes || $sitebytes == 0)) {
6513
        $limitlevel = get_string('course', 'core');
6514
        $displaysize = display_size($coursebytes, 0);
6515
        $filesize[$coursebytes] = $displaysize; // Make sure the limit is also included in the list.
6516
 
6517
    } else if ($sitebytes) {
6518
        $limitlevel = get_string('site', 'core');
6519
        $displaysize = display_size($sitebytes, 0);
6520
        $filesize[$sitebytes] = $displaysize; // Make sure the limit is also included in the list.
6521
    }
6522
 
6523
    krsort($filesize, SORT_NUMERIC);
6524
    if ($limitlevel) {
6525
        $params = (object) array('contextname' => $limitlevel, 'displaysize' => $displaysize);
6526
        $filesize  = array('0' => get_string('uploadlimitwithsize', 'core', $params)) + $filesize;
6527
    }
6528
 
6529
    return $filesize;
6530
}
6531
 
6532
/**
6533
 * Returns an array with all the filenames in all subdirectories, relative to the given rootdir.
6534
 *
6535
 * If excludefiles is defined, then that file/directory is ignored
6536
 * If getdirs is true, then (sub)directories are included in the output
6537
 * If getfiles is true, then files are included in the output
6538
 * (at least one of these must be true!)
6539
 *
6540
 * @todo Finish documenting this function. Add examples of $excludefile usage.
6541
 *
6542
 * @param string $rootdir A given root directory to start from
6543
 * @param string|array $excludefiles If defined then the specified file/directory is ignored
6544
 * @param bool $descend If true then subdirectories are recursed as well
6545
 * @param bool $getdirs If true then (sub)directories are included in the output
6546
 * @param bool $getfiles  If true then files are included in the output
6547
 * @return array An array with all the filenames in all subdirectories, relative to the given rootdir
6548
 */
6549
function get_directory_list($rootdir, $excludefiles='', $descend=true, $getdirs=false, $getfiles=true) {
6550
 
6551
    $dirs = array();
6552
 
6553
    if (!$getdirs and !$getfiles) {   // Nothing to show.
6554
        return $dirs;
6555
    }
6556
 
6557
    if (!is_dir($rootdir)) {          // Must be a directory.
6558
        return $dirs;
6559
    }
6560
 
6561
    if (!$dir = opendir($rootdir)) {  // Can't open it for some reason.
6562
        return $dirs;
6563
    }
6564
 
6565
    if (!is_array($excludefiles)) {
6566
        $excludefiles = array($excludefiles);
6567
    }
6568
 
6569
    while (false !== ($file = readdir($dir))) {
6570
        $firstchar = substr($file, 0, 1);
6571
        if ($firstchar == '.' or $file == 'CVS' or in_array($file, $excludefiles)) {
6572
            continue;
6573
        }
6574
        $fullfile = $rootdir .'/'. $file;
6575
        if (filetype($fullfile) == 'dir') {
6576
            if ($getdirs) {
6577
                $dirs[] = $file;
6578
            }
6579
            if ($descend) {
6580
                $subdirs = get_directory_list($fullfile, $excludefiles, $descend, $getdirs, $getfiles);
6581
                foreach ($subdirs as $subdir) {
6582
                    $dirs[] = $file .'/'. $subdir;
6583
                }
6584
            }
6585
        } else if ($getfiles) {
6586
            $dirs[] = $file;
6587
        }
6588
    }
6589
    closedir($dir);
6590
 
6591
    asort($dirs);
6592
 
6593
    return $dirs;
6594
}
6595
 
6596
 
6597
/**
6598
 * Adds up all the files in a directory and works out the size.
6599
 *
6600
 * @param string $rootdir  The directory to start from
6601
 * @param string $excludefile A file to exclude when summing directory size
6602
 * @return int The summed size of all files and subfiles within the root directory
6603
 */
6604
function get_directory_size($rootdir, $excludefile='') {
6605
    global $CFG;
6606
 
6607
    // Do it this way if we can, it's much faster.
6608
    if (!empty($CFG->pathtodu) && is_executable(trim($CFG->pathtodu))) {
6609
        $command = trim($CFG->pathtodu).' -sk '.escapeshellarg($rootdir);
6610
        $output = null;
6611
        $return = null;
6612
        exec($command, $output, $return);
6613
        if (is_array($output)) {
6614
            // We told it to return k.
6615
            return get_real_size(intval($output[0]).'k');
6616
        }
6617
    }
6618
 
6619
    if (!is_dir($rootdir)) {
6620
        // Must be a directory.
6621
        return 0;
6622
    }
6623
 
6624
    if (!$dir = @opendir($rootdir)) {
6625
        // Can't open it for some reason.
6626
        return 0;
6627
    }
6628
 
6629
    $size = 0;
6630
 
6631
    while (false !== ($file = readdir($dir))) {
6632
        $firstchar = substr($file, 0, 1);
6633
        if ($firstchar == '.' or $file == 'CVS' or $file == $excludefile) {
6634
            continue;
6635
        }
6636
        $fullfile = $rootdir .'/'. $file;
6637
        if (filetype($fullfile) == 'dir') {
6638
            $size += get_directory_size($fullfile, $excludefile);
6639
        } else {
6640
            $size += filesize($fullfile);
6641
        }
6642
    }
6643
    closedir($dir);
6644
 
6645
    return $size;
6646
}
6647
 
6648
/**
6649
 * Converts bytes into display form
6650
 *
6651
 * @param int $size  The size to convert to human readable form
6652
 * @param int $decimalplaces If specified, uses fixed number of decimal places
6653
 * @param string $fixedunits If specified, uses fixed units (e.g. 'KB')
6654
 * @return string Display version of size
6655
 */
6656
function display_size($size, int $decimalplaces = 1, string $fixedunits = ''): string {
6657
 
6658
    static $units;
6659
 
6660
    if ($size === USER_CAN_IGNORE_FILE_SIZE_LIMITS) {
6661
        return get_string('unlimited');
6662
    }
6663
 
6664
    if (empty($units)) {
6665
        $units[] = get_string('sizeb');
6666
        $units[] = get_string('sizekb');
6667
        $units[] = get_string('sizemb');
6668
        $units[] = get_string('sizegb');
6669
        $units[] = get_string('sizetb');
6670
        $units[] = get_string('sizepb');
6671
    }
6672
 
6673
    switch ($fixedunits) {
6674
        case 'PB' :
6675
            $magnitude = 5;
6676
            break;
6677
        case 'TB' :
6678
            $magnitude = 4;
6679
            break;
6680
        case 'GB' :
6681
            $magnitude = 3;
6682
            break;
6683
        case 'MB' :
6684
            $magnitude = 2;
6685
            break;
6686
        case 'KB' :
6687
            $magnitude = 1;
6688
            break;
6689
        case 'B' :
6690
            $magnitude = 0;
6691
            break;
6692
        case '':
6693
            $magnitude = floor(log($size, 1024));
6694
            $magnitude = max(0, min(5, $magnitude));
6695
            break;
6696
        default:
6697
            throw new coding_exception('Unknown fixed units value: ' . $fixedunits);
6698
    }
6699
 
6700
    // Special case for magnitude 0 (bytes) - never use decimal places.
6701
    $nbsp = "\xc2\xa0";
6702
    if ($magnitude === 0) {
6703
        return round($size) . $nbsp . $units[$magnitude];
6704
    }
6705
 
6706
    // Convert to specified units.
6707
    $sizeinunit = $size / 1024 ** $magnitude;
6708
 
6709
    // Fixed decimal places.
6710
    return sprintf('%.' . $decimalplaces . 'f', $sizeinunit) . $nbsp . $units[$magnitude];
6711
}
6712
 
6713
/**
6714
 * Cleans a given filename by removing suspicious or troublesome characters
6715
 *
6716
 * @see clean_param()
6717
 * @param string $string file name
6718
 * @return string cleaned file name
6719
 */
6720
function clean_filename($string) {
6721
    return clean_param($string, PARAM_FILE);
6722
}
6723
 
6724
// STRING TRANSLATION.
6725
 
6726
/**
6727
 * Returns the code for the current language
6728
 *
6729
 * @category string
6730
 * @return string
6731
 */
6732
function current_language() {
6733
    global $CFG, $PAGE, $SESSION, $USER;
6734
 
6735
    if (!empty($SESSION->forcelang)) {
6736
        // Allows overriding course-forced language (useful for admins to check
6737
        // issues in courses whose language they don't understand).
6738
        // Also used by some code to temporarily get language-related information in a
6739
        // specific language (see force_current_language()).
6740
        $return = $SESSION->forcelang;
6741
 
6742
    } else if (!empty($PAGE->cm->lang)) {
6743
        // Activity language, if set.
6744
        $return = $PAGE->cm->lang;
6745
 
6746
    } else if (!empty($PAGE->course->id) && $PAGE->course->id != SITEID && !empty($PAGE->course->lang)) {
6747
        // Course language can override all other settings for this page.
6748
        $return = $PAGE->course->lang;
6749
 
6750
    } else if (!empty($SESSION->lang)) {
6751
        // Session language can override other settings.
6752
        $return = $SESSION->lang;
6753
 
6754
    } else if (!empty($USER->lang)) {
6755
        $return = $USER->lang;
6756
 
6757
    } else if (isset($CFG->lang)) {
6758
        $return = $CFG->lang;
6759
 
6760
    } else {
6761
        $return = 'en';
6762
    }
6763
 
6764
    // Just in case this slipped in from somewhere by accident.
6765
    $return = str_replace('_utf8', '', $return);
6766
 
6767
    return $return;
6768
}
6769
 
6770
/**
6771
 * Fix the current language to the given language code.
6772
 *
6773
 * @param string $lang The language code to use.
6774
 * @return void
6775
 */
6776
function fix_current_language(string $lang): void {
6777
    global $CFG, $COURSE, $SESSION, $USER;
6778
 
6779
    if (!get_string_manager()->translation_exists($lang)) {
6780
        throw new coding_exception("The language pack for $lang is not available");
6781
    }
6782
 
6783
    $fixglobal = '';
6784
    $fixlang = 'lang';
6785
    if (!empty($SESSION->forcelang)) {
6786
        $fixglobal = $SESSION;
6787
        $fixlang = 'forcelang';
6788
    } else if (!empty($COURSE->id) && $COURSE->id != SITEID && !empty($COURSE->lang)) {
6789
        $fixglobal = $COURSE;
6790
    } else if (!empty($SESSION->lang)) {
6791
        $fixglobal = $SESSION;
6792
    } else if (!empty($USER->lang)) {
6793
        $fixglobal = $USER;
6794
    } else if (isset($CFG->lang)) {
6795
        set_config('lang', $lang);
6796
    }
6797
 
6798
    if ($fixglobal) {
6799
        $fixglobal->$fixlang = $lang;
6800
    }
6801
}
6802
 
6803
/**
6804
 * Returns parent language of current active language if defined
6805
 *
6806
 * @category string
6807
 * @param string $lang null means current language
6808
 * @return string
6809
 */
6810
function get_parent_language($lang=null) {
6811
 
6812
    $parentlang = get_string_manager()->get_string('parentlanguage', 'langconfig', null, $lang);
6813
 
6814
    if ($parentlang === 'en') {
6815
        $parentlang = '';
6816
    }
6817
 
6818
    return $parentlang;
6819
}
6820
 
6821
/**
6822
 * Force the current language to get strings and dates localised in the given language.
6823
 *
6824
 * After calling this function, all strings will be provided in the given language
6825
 * until this function is called again, or equivalent code is run.
6826
 *
6827
 * @param string $language
6828
 * @return string previous $SESSION->forcelang value
6829
 */
6830
function force_current_language($language) {
6831
    global $SESSION;
6832
    $sessionforcelang = isset($SESSION->forcelang) ? $SESSION->forcelang : '';
6833
    if ($language !== $sessionforcelang) {
6834
        // Setting forcelang to null or an empty string disables its effect.
6835
        if (empty($language) || get_string_manager()->translation_exists($language, false)) {
6836
            $SESSION->forcelang = $language;
6837
            moodle_setlocale();
6838
        }
6839
    }
6840
    return $sessionforcelang;
6841
}
6842
 
6843
/**
6844
 * Returns current string_manager instance.
6845
 *
6846
 * The param $forcereload is needed for CLI installer only where the string_manager instance
6847
 * must be replaced during the install.php script life time.
6848
 *
6849
 * @category string
6850
 * @param bool $forcereload shall the singleton be released and new instance created instead?
6851
 * @return core_string_manager
6852
 */
6853
function get_string_manager($forcereload=false) {
6854
    global $CFG;
6855
 
6856
    static $singleton = null;
6857
 
6858
    if ($forcereload) {
6859
        $singleton = null;
6860
    }
6861
    if ($singleton === null) {
6862
        if (empty($CFG->early_install_lang)) {
6863
 
6864
            $transaliases = array();
6865
            if (empty($CFG->langlist)) {
6866
                 $translist = array();
6867
            } else {
6868
                $translist = explode(',', $CFG->langlist);
6869
                $translist = array_map('trim', $translist);
6870
                // Each language in the $CFG->langlist can has an "alias" that would substitute the default language name.
6871
                foreach ($translist as $i => $value) {
6872
                    $parts = preg_split('/\s*\|\s*/', $value, 2);
6873
                    if (count($parts) == 2) {
6874
                        $transaliases[$parts[0]] = $parts[1];
6875
                        $translist[$i] = $parts[0];
6876
                    }
6877
                }
6878
            }
6879
 
6880
            if (!empty($CFG->config_php_settings['customstringmanager'])) {
6881
                $classname = $CFG->config_php_settings['customstringmanager'];
6882
 
6883
                if (class_exists($classname)) {
6884
                    $implements = class_implements($classname);
6885
 
6886
                    if (isset($implements['core_string_manager'])) {
6887
                        $singleton = new $classname($CFG->langotherroot, $CFG->langlocalroot, $translist, $transaliases);
6888
                        return $singleton;
6889
 
6890
                    } else {
6891
                        debugging('Unable to instantiate custom string manager: class '.$classname.
6892
                            ' does not implement the core_string_manager interface.');
6893
                    }
6894
 
6895
                } else {
6896
                    debugging('Unable to instantiate custom string manager: class '.$classname.' can not be found.');
6897
                }
6898
            }
6899
 
6900
            $singleton = new core_string_manager_standard($CFG->langotherroot, $CFG->langlocalroot, $translist, $transaliases);
6901
 
6902
        } else {
6903
            $singleton = new core_string_manager_install();
6904
        }
6905
    }
6906
 
6907
    return $singleton;
6908
}
6909
 
6910
/**
6911
 * Returns a localized string.
6912
 *
6913
 * Returns the translated string specified by $identifier as
6914
 * for $module.  Uses the same format files as STphp.
6915
 * $a is an object, string or number that can be used
6916
 * within translation strings
6917
 *
6918
 * eg 'hello {$a->firstname} {$a->lastname}'
6919
 * or 'hello {$a}'
6920
 *
6921
 * If you would like to directly echo the localized string use
6922
 * the function {@link print_string()}
6923
 *
6924
 * Example usage of this function involves finding the string you would
6925
 * like a local equivalent of and using its identifier and module information
6926
 * to retrieve it.<br/>
6927
 * If you open moodle/lang/en/moodle.php and look near line 278
6928
 * you will find a string to prompt a user for their word for 'course'
6929
 * <code>
6930
 * $string['course'] = 'Course';
6931
 * </code>
6932
 * So if you want to display the string 'Course'
6933
 * in any language that supports it on your site
6934
 * you just need to use the identifier 'course'
6935
 * <code>
6936
 * $mystring = '<strong>'. get_string('course') .'</strong>';
6937
 * or
6938
 * </code>
6939
 * If the string you want is in another file you'd take a slightly
6940
 * different approach. Looking in moodle/lang/en/calendar.php you find
6941
 * around line 75:
6942
 * <code>
6943
 * $string['typecourse'] = 'Course event';
6944
 * </code>
6945
 * If you want to display the string "Course event" in any language
6946
 * supported you would use the identifier 'typecourse' and the module 'calendar'
6947
 * (because it is in the file calendar.php):
6948
 * <code>
6949
 * $mystring = '<h1>'. get_string('typecourse', 'calendar') .'</h1>';
6950
 * </code>
6951
 *
6952
 * As a last resort, should the identifier fail to map to a string
6953
 * the returned string will be [[ $identifier ]]
6954
 *
6955
 * In Moodle 2.3 there is a new argument to this function $lazyload.
6956
 * Setting $lazyload to true causes get_string to return a lang_string object
6957
 * rather than the string itself. The fetching of the string is then put off until
6958
 * the string object is first used. The object can be used by calling it's out
6959
 * method or by casting the object to a string, either directly e.g.
6960
 *     (string)$stringobject
6961
 * or indirectly by using the string within another string or echoing it out e.g.
6962
 *     echo $stringobject
6963
 *     return "<p>{$stringobject}</p>";
6964
 * It is worth noting that using $lazyload and attempting to use the string as an
6965
 * array key will cause a fatal error as objects cannot be used as array keys.
6966
 * But you should never do that anyway!
6967
 * For more information {@link lang_string}
6968
 *
6969
 * @category string
6970
 * @param string $identifier The key identifier for the localized string
6971
 * @param string $component The module where the key identifier is stored,
6972
 *      usually expressed as the filename in the language pack without the
6973
 *      .php on the end but can also be written as mod/forum or grade/export/xls.
6974
 *      If none is specified then moodle.php is used.
6975
 * @param string|object|array|int $a An object, string or number that can be used
6976
 *      within translation strings
6977
 * @param bool $lazyload If set to true a string object is returned instead of
6978
 *      the string itself. The string then isn't calculated until it is first used.
6979
 * @return string The localized string.
6980
 * @throws coding_exception
6981
 */
6982
function get_string($identifier, $component = '', $a = null, $lazyload = false) {
6983
    global $CFG;
6984
 
6985
    // If the lazy load argument has been supplied return a lang_string object
6986
    // instead.
6987
    // We need to make sure it is true (and a bool) as you will see below there
6988
    // used to be a forth argument at one point.
6989
    if ($lazyload === true) {
6990
        return new lang_string($identifier, $component, $a);
6991
    }
6992
 
6993
    if ($CFG->debugdeveloper && clean_param($identifier, PARAM_STRINGID) === '') {
6994
        throw new coding_exception('Invalid string identifier. The identifier cannot be empty. Please fix your get_string() call.', DEBUG_DEVELOPER);
6995
    }
6996
 
6997
    // There is now a forth argument again, this time it is a boolean however so
6998
    // we can still check for the old extralocations parameter.
6999
    if (!is_bool($lazyload) && !empty($lazyload)) {
7000
        debugging('extralocations parameter in get_string() is not supported any more, please use standard lang locations only.');
7001
    }
7002
 
7003
    if (strpos((string)$component, '/') !== false) {
7004
        debugging('The module name you passed to get_string is the deprecated format ' .
7005
                'like mod/mymod or block/myblock. The correct form looks like mymod, or block_myblock.' , DEBUG_DEVELOPER);
7006
        $componentpath = explode('/', $component);
7007
 
7008
        switch ($componentpath[0]) {
7009
            case 'mod':
7010
                $component = $componentpath[1];
7011
                break;
7012
            case 'blocks':
7013
            case 'block':
7014
                $component = 'block_'.$componentpath[1];
7015
                break;
7016
            case 'enrol':
7017
                $component = 'enrol_'.$componentpath[1];
7018
                break;
7019
            case 'format':
7020
                $component = 'format_'.$componentpath[1];
7021
                break;
7022
            case 'grade':
7023
                $component = 'grade'.$componentpath[1].'_'.$componentpath[2];
7024
                break;
7025
        }
7026
    }
7027
 
7028
    $result = get_string_manager()->get_string($identifier, $component, $a);
7029
 
7030
    // Debugging feature lets you display string identifier and component.
7031
    if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
7032
        $result .= ' {' . $identifier . '/' . $component . '}';
7033
    }
7034
    return $result;
7035
}
7036
 
7037
/**
7038
 * Converts an array of strings to their localized value.
7039
 *
7040
 * @param array $array An array of strings
7041
 * @param string $component The language module that these strings can be found in.
7042
 * @return stdClass translated strings.
7043
 */
7044
function get_strings($array, $component = '') {
7045
    $string = new stdClass;
7046
    foreach ($array as $item) {
7047
        $string->$item = get_string($item, $component);
7048
    }
7049
    return $string;
7050
}
7051
 
7052
/**
7053
 * Prints out a translated string.
7054
 *
7055
 * Prints out a translated string using the return value from the {@link get_string()} function.
7056
 *
7057
 * Example usage of this function when the string is in the moodle.php file:<br/>
7058
 * <code>
7059
 * echo '<strong>';
7060
 * print_string('course');
7061
 * echo '</strong>';
7062
 * </code>
7063
 *
7064
 * Example usage of this function when the string is not in the moodle.php file:<br/>
7065
 * <code>
7066
 * echo '<h1>';
7067
 * print_string('typecourse', 'calendar');
7068
 * echo '</h1>';
7069
 * </code>
7070
 *
7071
 * @category string
7072
 * @param string $identifier The key identifier for the localized string
7073
 * @param string $component The module where the key identifier is stored. If none is specified then moodle.php is used.
7074
 * @param string|object|array $a An object, string or number that can be used within translation strings
7075
 */
7076
function print_string($identifier, $component = '', $a = null) {
7077
    echo get_string($identifier, $component, $a);
7078
}
7079
 
7080
/**
7081
 * Returns a list of charset codes
7082
 *
7083
 * Returns a list of charset codes. It's hardcoded, so they should be added manually
7084
 * (checking that such charset is supported by the texlib library!)
7085
 *
7086
 * @return array And associative array with contents in the form of charset => charset
7087
 */
7088
function get_list_of_charsets() {
7089
 
7090
    $charsets = array(
7091
        'EUC-JP'     => 'EUC-JP',
7092
        'ISO-2022-JP'=> 'ISO-2022-JP',
7093
        'ISO-8859-1' => 'ISO-8859-1',
7094
        'SHIFT-JIS'  => 'SHIFT-JIS',
7095
        'GB2312'     => 'GB2312',
7096
        'GB18030'    => 'GB18030', // GB18030 not supported by typo and mbstring.
7097
        'UTF-8'      => 'UTF-8');
7098
 
7099
    asort($charsets);
7100
 
7101
    return $charsets;
7102
}
7103
 
7104
/**
7105
 * Returns a list of valid and compatible themes
7106
 *
7107
 * @return array
7108
 */
7109
function get_list_of_themes() {
7110
    global $CFG;
7111
 
7112
    $themes = array();
7113
 
7114
    if (!empty($CFG->themelist)) {       // Use admin's list of themes.
7115
        $themelist = explode(',', $CFG->themelist);
7116
    } else {
7117
        $themelist = array_keys(core_component::get_plugin_list("theme"));
7118
    }
7119
 
7120
    foreach ($themelist as $key => $themename) {
7121
        $theme = theme_config::load($themename);
7122
        $themes[$themename] = $theme;
7123
    }
7124
 
7125
    core_collator::asort_objects_by_method($themes, 'get_theme_name');
7126
 
7127
    return $themes;
7128
}
7129
 
7130
/**
7131
 * Factory function for emoticon_manager
7132
 *
7133
 * @return emoticon_manager singleton
7134
 */
7135
function get_emoticon_manager() {
7136
    static $singleton = null;
7137
 
7138
    if (is_null($singleton)) {
7139
        $singleton = new emoticon_manager();
7140
    }
7141
 
7142
    return $singleton;
7143
}
7144
 
7145
/**
7146
 * Provides core support for plugins that have to deal with emoticons (like HTML editor or emoticon filter).
7147
 *
7148
 * Whenever this manager mentiones 'emoticon object', the following data
7149
 * structure is expected: stdClass with properties text, imagename, imagecomponent,
7150
 * altidentifier and altcomponent
7151
 *
7152
 * @see admin_setting_emoticons
7153
 *
7154
 * @copyright 2010 David Mudrak
7155
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7156
 */
7157
class emoticon_manager {
7158
 
7159
    /**
7160
     * Returns the currently enabled emoticons
7161
     *
7162
     * @param boolean $selectable - If true, only return emoticons that should be selectable from a list.
7163
     * @return array of emoticon objects
7164
     */
7165
    public function get_emoticons($selectable = false) {
7166
        global $CFG;
7167
        $notselectable = ['martin', 'egg'];
7168
 
7169
        if (empty($CFG->emoticons)) {
7170
            return array();
7171
        }
7172
 
7173
        $emoticons = $this->decode_stored_config($CFG->emoticons);
7174
 
7175
        if (!is_array($emoticons)) {
7176
            // Something is wrong with the format of stored setting.
7177
            debugging('Invalid format of emoticons setting, please resave the emoticons settings form', DEBUG_NORMAL);
7178
            return array();
7179
        }
7180
        if ($selectable) {
7181
            foreach ($emoticons as $index => $emote) {
7182
                if (in_array($emote->altidentifier, $notselectable)) {
7183
                    // Skip this one.
7184
                    unset($emoticons[$index]);
7185
                }
7186
            }
7187
        }
7188
 
7189
        return $emoticons;
7190
    }
7191
 
7192
    /**
7193
     * Converts emoticon object into renderable pix_emoticon object
7194
     *
7195
     * @param stdClass $emoticon emoticon object
7196
     * @param array $attributes explicit HTML attributes to set
7197
     * @return pix_emoticon
7198
     */
7199
    public function prepare_renderable_emoticon(stdClass $emoticon, array $attributes = array()) {
7200
        $stringmanager = get_string_manager();
7201
        if ($stringmanager->string_exists($emoticon->altidentifier, $emoticon->altcomponent)) {
7202
            $alt = get_string($emoticon->altidentifier, $emoticon->altcomponent);
7203
        } else {
7204
            $alt = s($emoticon->text);
7205
        }
7206
        return new pix_emoticon($emoticon->imagename, $alt, $emoticon->imagecomponent, $attributes);
7207
    }
7208
 
7209
    /**
7210
     * Encodes the array of emoticon objects into a string storable in config table
7211
     *
7212
     * @see self::decode_stored_config()
7213
     * @param array $emoticons array of emtocion objects
7214
     * @return string
7215
     */
7216
    public function encode_stored_config(array $emoticons) {
7217
        return json_encode($emoticons);
7218
    }
7219
 
7220
    /**
7221
     * Decodes the string into an array of emoticon objects
7222
     *
7223
     * @see self::encode_stored_config()
7224
     * @param string $encoded
7225
     * @return array|null
7226
     */
7227
    public function decode_stored_config($encoded) {
7228
        $decoded = json_decode($encoded);
7229
        if (!is_array($decoded)) {
7230
            return null;
7231
        }
7232
        return $decoded;
7233
    }
7234
 
7235
    /**
7236
     * Returns default set of emoticons supported by Moodle
7237
     *
7238
     * @return array of sdtClasses
7239
     */
7240
    public function default_emoticons() {
7241
        return array(
7242
            $this->prepare_emoticon_object(":-)", 's/smiley', 'smiley'),
7243
            $this->prepare_emoticon_object(":)", 's/smiley', 'smiley'),
7244
            $this->prepare_emoticon_object(":-D", 's/biggrin', 'biggrin'),
7245
            $this->prepare_emoticon_object(";-)", 's/wink', 'wink'),
7246
            $this->prepare_emoticon_object(":-/", 's/mixed', 'mixed'),
7247
            $this->prepare_emoticon_object("V-.", 's/thoughtful', 'thoughtful'),
7248
            $this->prepare_emoticon_object(":-P", 's/tongueout', 'tongueout'),
7249
            $this->prepare_emoticon_object(":-p", 's/tongueout', 'tongueout'),
7250
            $this->prepare_emoticon_object("B-)", 's/cool', 'cool'),
7251
            $this->prepare_emoticon_object("^-)", 's/approve', 'approve'),
7252
            $this->prepare_emoticon_object("8-)", 's/wideeyes', 'wideeyes'),
7253
            $this->prepare_emoticon_object(":o)", 's/clown', 'clown'),
7254
            $this->prepare_emoticon_object(":-(", 's/sad', 'sad'),
7255
            $this->prepare_emoticon_object(":(", 's/sad', 'sad'),
7256
            $this->prepare_emoticon_object("8-.", 's/shy', 'shy'),
7257
            $this->prepare_emoticon_object(":-I", 's/blush', 'blush'),
7258
            $this->prepare_emoticon_object(":-X", 's/kiss', 'kiss'),
7259
            $this->prepare_emoticon_object("8-o", 's/surprise', 'surprise'),
7260
            $this->prepare_emoticon_object("P-|", 's/blackeye', 'blackeye'),
7261
            $this->prepare_emoticon_object("8-[", 's/angry', 'angry'),
7262
            $this->prepare_emoticon_object("(grr)", 's/angry', 'angry'),
7263
            $this->prepare_emoticon_object("xx-P", 's/dead', 'dead'),
7264
            $this->prepare_emoticon_object("|-.", 's/sleepy', 'sleepy'),
7265
            $this->prepare_emoticon_object("}-]", 's/evil', 'evil'),
7266
            $this->prepare_emoticon_object("(h)", 's/heart', 'heart'),
7267
            $this->prepare_emoticon_object("(heart)", 's/heart', 'heart'),
7268
            $this->prepare_emoticon_object("(y)", 's/yes', 'yes', 'core'),
7269
            $this->prepare_emoticon_object("(n)", 's/no', 'no', 'core'),
7270
            $this->prepare_emoticon_object("(martin)", 's/martin', 'martin'),
7271
            $this->prepare_emoticon_object("( )", 's/egg', 'egg'),
7272
        );
7273
    }
7274
 
7275
    /**
7276
     * Helper method preparing the stdClass with the emoticon properties
7277
     *
7278
     * @param string|array $text or array of strings
7279
     * @param string $imagename to be used by {@link pix_emoticon}
7280
     * @param string $altidentifier alternative string identifier, null for no alt
7281
     * @param string $altcomponent where the alternative string is defined
7282
     * @param string $imagecomponent to be used by {@link pix_emoticon}
7283
     * @return stdClass
7284
     */
7285
    protected function prepare_emoticon_object($text, $imagename, $altidentifier = null,
7286
                                               $altcomponent = 'core_pix', $imagecomponent = 'core') {
7287
        return (object)array(
7288
            'text'           => $text,
7289
            'imagename'      => $imagename,
7290
            'imagecomponent' => $imagecomponent,
7291
            'altidentifier'  => $altidentifier,
7292
            'altcomponent'   => $altcomponent,
7293
        );
7294
    }
7295
}
7296
 
7297
// ENCRYPTION.
7298
 
7299
/**
7300
 * rc4encrypt
7301
 *
7302
 * @param string $data        Data to encrypt.
7303
 * @return string             The now encrypted data.
7304
 */
7305
function rc4encrypt($data) {
7306
    return endecrypt(get_site_identifier(), $data, '');
7307
}
7308
 
7309
/**
7310
 * rc4decrypt
7311
 *
7312
 * @param string $data        Data to decrypt.
7313
 * @return string             The now decrypted data.
7314
 */
7315
function rc4decrypt($data) {
7316
    return endecrypt(get_site_identifier(), $data, 'de');
7317
}
7318
 
7319
/**
7320
 * Based on a class by Mukul Sabharwal [mukulsabharwal @ yahoo.com]
7321
 *
7322
 * @todo Finish documenting this function
7323
 *
7324
 * @param string $pwd The password to use when encrypting or decrypting
7325
 * @param string $data The data to be decrypted/encrypted
7326
 * @param string $case Either 'de' for decrypt or '' for encrypt
7327
 * @return string
7328
 */
7329
function endecrypt ($pwd, $data, $case) {
7330
 
7331
    if ($case == 'de') {
7332
        $data = urldecode($data);
7333
    }
7334
 
7335
    $key[] = '';
7336
    $box[] = '';
7337
    $pwdlength = strlen($pwd);
7338
 
7339
    for ($i = 0; $i <= 255; $i++) {
7340
        $key[$i] = ord(substr($pwd, ($i % $pwdlength), 1));
7341
        $box[$i] = $i;
7342
    }
7343
 
7344
    $x = 0;
7345
 
7346
    for ($i = 0; $i <= 255; $i++) {
7347
        $x = ($x + $box[$i] + $key[$i]) % 256;
7348
        $tempswap = $box[$i];
7349
        $box[$i] = $box[$x];
7350
        $box[$x] = $tempswap;
7351
    }
7352
 
7353
    $cipher = '';
7354
 
7355
    $a = 0;
7356
    $j = 0;
7357
 
7358
    for ($i = 0; $i < strlen($data); $i++) {
7359
        $a = ($a + 1) % 256;
7360
        $j = ($j + $box[$a]) % 256;
7361
        $temp = $box[$a];
7362
        $box[$a] = $box[$j];
7363
        $box[$j] = $temp;
7364
        $k = $box[(($box[$a] + $box[$j]) % 256)];
7365
        $cipherby = ord(substr($data, $i, 1)) ^ $k;
7366
        $cipher .= chr($cipherby);
7367
    }
7368
 
7369
    if ($case == 'de') {
7370
        $cipher = urldecode(urlencode($cipher));
7371
    } else {
7372
        $cipher = urlencode($cipher);
7373
    }
7374
 
7375
    return $cipher;
7376
}
7377
 
7378
// ENVIRONMENT CHECKING.
7379
 
7380
/**
7381
 * This method validates a plug name. It is much faster than calling clean_param.
7382
 *
7383
 * @param string $name a string that might be a plugin name.
7384
 * @return bool if this string is a valid plugin name.
7385
 */
7386
function is_valid_plugin_name($name) {
7387
    // This does not work for 'mod', bad luck, use any other type.
7388
    return core_component::is_valid_plugin_name('tool', $name);
7389
}
7390
 
7391
/**
7392
 * Get a list of all the plugins of a given type that define a certain API function
7393
 * in a certain file. The plugin component names and function names are returned.
7394
 *
7395
 * @param string $plugintype the type of plugin, e.g. 'mod' or 'report'.
7396
 * @param string $function the part of the name of the function after the
7397
 *      frankenstyle prefix. e.g 'hook' if you are looking for functions with
7398
 *      names like report_courselist_hook.
7399
 * @param string $file the name of file within the plugin that defines the
7400
 *      function. Defaults to lib.php.
7401
 * @return array with frankenstyle plugin names as keys (e.g. 'report_courselist', 'mod_forum')
7402
 *      and the function names as values (e.g. 'report_courselist_hook', 'forum_hook').
7403
 */
7404
function get_plugin_list_with_function($plugintype, $function, $file = 'lib.php') {
7405
    global $CFG;
7406
 
7407
    // We don't include here as all plugin types files would be included.
7408
    $plugins = get_plugins_with_function($function, $file, false);
7409
 
7410
    if (empty($plugins[$plugintype])) {
7411
        return array();
7412
    }
7413
 
7414
    $allplugins = core_component::get_plugin_list($plugintype);
7415
 
7416
    // Reformat the array and include the files.
7417
    $pluginfunctions = array();
7418
    foreach ($plugins[$plugintype] as $pluginname => $functionname) {
7419
 
7420
        // Check that it has not been removed and the file is still available.
7421
        if (!empty($allplugins[$pluginname])) {
7422
 
7423
            $filepath = $allplugins[$pluginname] . DIRECTORY_SEPARATOR . $file;
7424
            if (file_exists($filepath)) {
7425
                include_once($filepath);
7426
 
7427
                // Now that the file is loaded, we must verify the function still exists.
7428
                if (function_exists($functionname)) {
7429
                    $pluginfunctions[$plugintype . '_' . $pluginname] = $functionname;
7430
                } else {
7431
                    // Invalidate the cache for next run.
7432
                    \cache_helper::invalidate_by_definition('core', 'plugin_functions');
7433
                }
7434
            }
7435
        }
7436
    }
7437
 
7438
    return $pluginfunctions;
7439
}
7440
 
7441
/**
7442
 * Get a list of all the plugins that define a certain API function in a certain file.
7443
 *
7444
 * @param string $function the part of the name of the function after the
7445
 *      frankenstyle prefix. e.g 'hook' if you are looking for functions with
7446
 *      names like report_courselist_hook.
7447
 * @param string $file the name of file within the plugin that defines the
7448
 *      function. Defaults to lib.php.
7449
 * @param bool $include Whether to include the files that contain the functions or not.
7450
 * @param bool $migratedtohook if true this is a deprecated lib.php callback, if hook callback is present then do nothing
7451
 * @return array with [plugintype][plugin] = functionname
7452
 */
7453
function get_plugins_with_function($function, $file = 'lib.php', $include = true, bool $migratedtohook = false) {
7454
    global $CFG;
7455
 
7456
    if (during_initial_install() || isset($CFG->upgraderunning)) {
7457
        // API functions _must not_ be called during an installation or upgrade.
7458
        return [];
7459
    }
7460
 
7461
    $plugincallback = $function;
7462
    $filtermigrated = function($plugincallback, $pluginfunctions): array {
7463
        foreach ($pluginfunctions as $plugintype => $plugins) {
7464
            foreach ($plugins as $plugin => $unusedfunction) {
7465
                $component = $plugintype . '_' . $plugin;
7466
                if ($hooks = di::get(hook\manager::class)->get_hooks_deprecating_plugin_callback($plugincallback)) {
7467
                    if (di::get(hook\manager::class)->is_deprecating_hook_present($component, $plugincallback)) {
7468
                        // Ignore the old callback, it is there only for older Moodle versions.
7469
                        unset($pluginfunctions[$plugintype][$plugin]);
7470
                    } else {
7471
                        $hookmessage = count($hooks) == 1 ? reset($hooks) : 'one of  ' . implode(', ', $hooks);
7472
                        debugging(
7473
                            "Callback $plugincallback in $component component should be migrated to new " .
7474
                                "hook callback for $hookmessage",
7475
                            DEBUG_DEVELOPER
7476
                        );
7477
                    }
7478
                }
7479
            }
7480
        }
7481
        return $pluginfunctions;
7482
    };
7483
 
7484
    $cache = \cache::make('core', 'plugin_functions');
7485
 
7486
    // Including both although I doubt that we will find two functions definitions with the same name.
7487
    // Clean the filename as cache_helper::hash_key only allows a-zA-Z0-9_.
7488
    $pluginfunctions = false;
7489
    if (!empty($CFG->allversionshash)) {
7490
        $key = $CFG->allversionshash . '_' . $function . '_' . clean_param($file, PARAM_ALPHA);
7491
        $pluginfunctions = $cache->get($key);
7492
    }
7493
    $dirty = false;
7494
 
7495
    // Use the plugin manager to check that plugins are currently installed.
7496
    $pluginmanager = \core_plugin_manager::instance();
7497
 
7498
    if ($pluginfunctions !== false) {
7499
 
7500
        // Checking that the files are still available.
7501
        foreach ($pluginfunctions as $plugintype => $plugins) {
7502
 
7503
            $allplugins = \core_component::get_plugin_list($plugintype);
7504
            $installedplugins = $pluginmanager->get_installed_plugins($plugintype);
7505
            foreach ($plugins as $plugin => $function) {
7506
                if (!isset($installedplugins[$plugin])) {
7507
                    // Plugin code is still present on disk but it is not installed.
7508
                    $dirty = true;
7509
                    break 2;
7510
                }
7511
 
7512
                // Cache might be out of sync with the codebase, skip the plugin if it is not available.
7513
                if (empty($allplugins[$plugin])) {
7514
                    $dirty = true;
7515
                    break 2;
7516
                }
7517
 
7518
                $fileexists = file_exists($allplugins[$plugin] . DIRECTORY_SEPARATOR . $file);
7519
                if ($include && $fileexists) {
7520
                    // Include the files if it was requested.
7521
                    include_once($allplugins[$plugin] . DIRECTORY_SEPARATOR . $file);
7522
                } else if (!$fileexists) {
7523
                    // If the file is not available any more it should not be returned.
7524
                    $dirty = true;
7525
                    break 2;
7526
                }
7527
 
7528
                // Check if the function still exists in the file.
7529
                if ($include && !function_exists($function)) {
7530
                    $dirty = true;
7531
                    break 2;
7532
                }
7533
            }
7534
        }
7535
 
7536
        // If the cache is dirty, we should fall through and let it rebuild.
7537
        if (!$dirty) {
7538
            if ($migratedtohook && $file === 'lib.php') {
7539
                $pluginfunctions = $filtermigrated($plugincallback, $pluginfunctions);
7540
            }
7541
            return $pluginfunctions;
7542
        }
7543
    }
7544
 
7545
    $pluginfunctions = array();
7546
 
7547
    // To fill the cached. Also, everything should continue working with cache disabled.
7548
    $plugintypes = \core_component::get_plugin_types();
7549
    foreach ($plugintypes as $plugintype => $unused) {
7550
 
7551
        // We need to include files here.
7552
        $pluginswithfile = \core_component::get_plugin_list_with_file($plugintype, $file, true);
7553
        $installedplugins = $pluginmanager->get_installed_plugins($plugintype);
7554
        foreach ($pluginswithfile as $plugin => $notused) {
7555
 
7556
            if (!isset($installedplugins[$plugin])) {
7557
                continue;
7558
            }
7559
 
7560
            $fullfunction = $plugintype . '_' . $plugin . '_' . $function;
7561
 
7562
            $pluginfunction = false;
7563
            if (function_exists($fullfunction)) {
7564
                // Function exists with standard name. Store, indexed by frankenstyle name of plugin.
7565
                $pluginfunction = $fullfunction;
7566
 
7567
            } else if ($plugintype === 'mod') {
7568
                // For modules, we also allow plugin without full frankenstyle but just starting with the module name.
7569
                $shortfunction = $plugin . '_' . $function;
7570
                if (function_exists($shortfunction)) {
7571
                    $pluginfunction = $shortfunction;
7572
                }
7573
            }
7574
 
7575
            if ($pluginfunction) {
7576
                if (empty($pluginfunctions[$plugintype])) {
7577
                    $pluginfunctions[$plugintype] = array();
7578
                }
7579
                $pluginfunctions[$plugintype][$plugin] = $pluginfunction;
7580
            }
7581
 
7582
        }
7583
    }
7584
    if (!empty($CFG->allversionshash)) {
7585
        $cache->set($key, $pluginfunctions);
7586
    }
7587
 
7588
    if ($migratedtohook && $file === 'lib.php') {
7589
        $pluginfunctions = $filtermigrated($plugincallback, $pluginfunctions);
7590
    }
7591
 
7592
    return $pluginfunctions;
7593
 
7594
}
7595
 
7596
/**
7597
 * Lists plugin-like directories within specified directory
7598
 *
7599
 * This function was originally used for standard Moodle plugins, please use
7600
 * new core_component::get_plugin_list() now.
7601
 *
7602
 * This function is used for general directory listing and backwards compatility.
7603
 *
7604
 * @param string $directory relative directory from root
7605
 * @param string $exclude dir name to exclude from the list (defaults to none)
7606
 * @param string $basedir full path to the base dir where $plugin resides (defaults to $CFG->dirroot)
7607
 * @return array Sorted array of directory names found under the requested parameters
7608
 */
7609
function get_list_of_plugins($directory='mod', $exclude='', $basedir='') {
7610
    global $CFG;
7611
 
7612
    $plugins = array();
7613
 
7614
    if (empty($basedir)) {
7615
        $basedir = $CFG->dirroot .'/'. $directory;
7616
 
7617
    } else {
7618
        $basedir = $basedir .'/'. $directory;
7619
    }
7620
 
7621
    if ($CFG->debugdeveloper and empty($exclude)) {
7622
        // Make sure devs do not use this to list normal plugins,
7623
        // this is intended for general directories that are not plugins!
7624
 
7625
        $subtypes = core_component::get_plugin_types();
7626
        if (in_array($basedir, $subtypes)) {
7627
            debugging('get_list_of_plugins() should not be used to list real plugins, use core_component::get_plugin_list() instead!', DEBUG_DEVELOPER);
7628
        }
7629
        unset($subtypes);
7630
    }
7631
 
7632
    $ignorelist = array_flip(array_filter([
7633
        'CVS',
7634
        '_vti_cnf',
7635
        'amd',
7636
        'classes',
7637
        'simpletest',
7638
        'tests',
7639
        'templates',
7640
        'yui',
7641
        $exclude,
7642
    ]));
7643
 
7644
    if (file_exists($basedir) && filetype($basedir) == 'dir') {
7645
        if (!$dirhandle = opendir($basedir)) {
7646
            debugging("Directory permission error for plugin ({$directory}). Directory exists but cannot be read.", DEBUG_DEVELOPER);
7647
            return array();
7648
        }
7649
        while (false !== ($dir = readdir($dirhandle))) {
7650
            if (strpos($dir, '.') === 0) {
7651
                // Ignore directories starting with .
7652
                // These are treated as hidden directories.
7653
                continue;
7654
            }
7655
            if (array_key_exists($dir, $ignorelist)) {
7656
                // This directory features on the ignore list.
7657
                continue;
7658
            }
7659
            if (filetype($basedir .'/'. $dir) != 'dir') {
7660
                continue;
7661
            }
7662
            $plugins[] = $dir;
7663
        }
7664
        closedir($dirhandle);
7665
    }
7666
    if ($plugins) {
7667
        asort($plugins);
7668
    }
7669
    return $plugins;
7670
}
7671
 
7672
/**
7673
 * Invoke plugin's callback functions
7674
 *
7675
 * @param string $type plugin type e.g. 'mod'
7676
 * @param string $name plugin name
7677
 * @param string $feature feature name
7678
 * @param string $action feature's action
7679
 * @param array $params parameters of callback function, should be an array
7680
 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7681
 * @param bool $migratedtohook if true this is a deprecated callback, if hook callback is present then do nothing
7682
 * @return mixed
7683
 *
7684
 * @todo Decide about to deprecate and drop plugin_callback() - MDL-30743
7685
 */
7686
function plugin_callback($type, $name, $feature, $action, $params = null, $default = null, bool $migratedtohook = false) {
7687
    return component_callback($type . '_' . $name, $feature . '_' . $action, (array) $params, $default, $migratedtohook);
7688
}
7689
 
7690
/**
7691
 * Invoke component's callback functions
7692
 *
7693
 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7694
 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7695
 * @param array $params parameters of callback function
7696
 * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7697
 * @param bool $migratedtohook if true this is a deprecated callback, if hook callback is present then do nothing
7698
 * @return mixed
7699
 */
7700
function component_callback($component, $function, array $params = array(), $default = null, bool $migratedtohook = false) {
7701
    $functionname = component_callback_exists($component, $function);
7702
 
7703
    if ($functionname) {
7704
        if ($migratedtohook) {
7705
            $hookmanager = di::get(hook\manager::class);
7706
            if ($hooks = $hookmanager->get_hooks_deprecating_plugin_callback($function)) {
7707
                if ($hookmanager->is_deprecating_hook_present($component, $function)) {
7708
                    // Do not call the old lib.php callback,
7709
                    // it is there for compatibility with older Moodle versions only.
7710
                    return null;
7711
                } else {
7712
                    $hookmessage = count($hooks) == 1 ? reset($hooks) : 'one of  ' . implode(', ', $hooks);
7713
                    debugging(
7714
                        "Callback $function in $component component should be migrated to new hook callback for $hookmessage",
7715
                        DEBUG_DEVELOPER);
7716
                }
7717
            }
7718
        }
7719
 
7720
        // Function exists, so just return function result.
7721
        $ret = call_user_func_array($functionname, $params);
7722
        if (is_null($ret)) {
7723
            return $default;
7724
        } else {
7725
            return $ret;
7726
        }
7727
    }
7728
    return $default;
7729
}
7730
 
7731
/**
7732
 * Determine if a component callback exists and return the function name to call. Note that this
7733
 * function will include the required library files so that the functioname returned can be
7734
 * called directly.
7735
 *
7736
 * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7737
 * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7738
 * @return mixed Complete function name to call if the callback exists or false if it doesn't.
7739
 * @throws coding_exception if invalid component specfied
7740
 */
7741
function component_callback_exists($component, $function) {
7742
    global $CFG; // This is needed for the inclusions.
7743
 
7744
    $cleancomponent = clean_param($component, PARAM_COMPONENT);
7745
    if (empty($cleancomponent)) {
7746
        throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
7747
    }
7748
    $component = $cleancomponent;
7749
 
7750
    list($type, $name) = core_component::normalize_component($component);
7751
    $component = $type . '_' . $name;
7752
 
7753
    $oldfunction = $name.'_'.$function;
7754
    $function = $component.'_'.$function;
7755
 
7756
    $dir = core_component::get_component_directory($component);
7757
    if (empty($dir)) {
7758
        throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
7759
    }
7760
 
7761
    // Load library and look for function.
7762
    if (file_exists($dir.'/lib.php')) {
7763
        require_once($dir.'/lib.php');
7764
    }
7765
 
7766
    if (!function_exists($function) and function_exists($oldfunction)) {
7767
        if ($type !== 'mod' and $type !== 'core') {
7768
            debugging("Please use new function name $function instead of legacy $oldfunction", DEBUG_DEVELOPER);
7769
        }
7770
        $function = $oldfunction;
7771
    }
7772
 
7773
    if (function_exists($function)) {
7774
        return $function;
7775
    }
7776
    return false;
7777
}
7778
 
7779
/**
7780
 * Call the specified callback method on the provided class.
7781
 *
7782
 * If the callback returns null, then the default value is returned instead.
7783
 * If the class does not exist, then the default value is returned.
7784
 *
7785
 * @param   string      $classname The name of the class to call upon.
7786
 * @param   string      $methodname The name of the staticically defined method on the class.
7787
 * @param   array       $params The arguments to pass into the method.
7788
 * @param   mixed       $default The default value.
7789
 * @param   bool        $migratedtohook True if the callback has been migrated to a hook.
7790
 * @return  mixed       The return value.
7791
 */
7792
function component_class_callback($classname, $methodname, array $params, $default = null, bool $migratedtohook = false) {
7793
    if (!class_exists($classname)) {
7794
        return $default;
7795
    }
7796
 
7797
    if (!method_exists($classname, $methodname)) {
7798
        return $default;
7799
    }
7800
 
7801
    $fullfunction = $classname . '::' . $methodname;
7802
 
7803
    if ($migratedtohook) {
7804
        $functionparts = explode('\\', trim($fullfunction, '\\'));
7805
        $component = $functionparts[0];
7806
        $callback = end($functionparts);
7807
        $hookmanager = di::get(hook\manager::class);
7808
        if ($hooks = $hookmanager->get_hooks_deprecating_plugin_callback($callback)) {
7809
            if ($hookmanager->is_deprecating_hook_present($component, $callback)) {
7810
                // Do not call the old class callback,
7811
                // it is there for compatibility with older Moodle versions only.
7812
                return null;
7813
            } else {
7814
                $hookmessage = count($hooks) == 1 ? reset($hooks) : 'one of  ' . implode(', ', $hooks);
7815
                debugging("Callback $callback in $component component should be migrated to new hook callback for $hookmessage",
7816
                        DEBUG_DEVELOPER);
7817
            }
7818
        }
7819
    }
7820
 
7821
    $result = call_user_func_array($fullfunction, $params);
7822
 
7823
    if (null === $result) {
7824
        return $default;
7825
    } else {
7826
        return $result;
7827
    }
7828
}
7829
 
7830
/**
7831
 * Checks whether a plugin supports a specified feature.
7832
 *
7833
 * @param string $type Plugin type e.g. 'mod'
7834
 * @param string $name Plugin name e.g. 'forum'
7835
 * @param string $feature Feature code (FEATURE_xx constant)
7836
 * @param mixed $default default value if feature support unknown
7837
 * @return mixed Feature result (false if not supported, null if feature is unknown,
7838
 *         otherwise usually true but may have other feature-specific value such as array)
7839
 * @throws coding_exception
7840
 */
7841
function plugin_supports($type, $name, $feature, $default = null) {
7842
    global $CFG;
7843
 
7844
    if ($type === 'mod' and $name === 'NEWMODULE') {
7845
        // Somebody forgot to rename the module template.
7846
        return false;
7847
    }
7848
 
7849
    $component = clean_param($type . '_' . $name, PARAM_COMPONENT);
7850
    if (empty($component)) {
7851
        throw new coding_exception('Invalid component used in plugin_supports():' . $type . '_' . $name);
7852
    }
7853
 
7854
    $function = null;
7855
 
7856
    if ($type === 'mod') {
7857
        // We need this special case because we support subplugins in modules,
7858
        // otherwise it would end up in infinite loop.
7859
        if (file_exists("$CFG->dirroot/mod/$name/lib.php")) {
7860
            include_once("$CFG->dirroot/mod/$name/lib.php");
7861
            $function = $component.'_supports';
7862
            if (!function_exists($function)) {
7863
                // Legacy non-frankenstyle function name.
7864
                $function = $name.'_supports';
7865
            }
7866
        }
7867
 
7868
    } else {
7869
        if (!$path = core_component::get_plugin_directory($type, $name)) {
7870
            // Non existent plugin type.
7871
            return false;
7872
        }
7873
        if (file_exists("$path/lib.php")) {
7874
            include_once("$path/lib.php");
7875
            $function = $component.'_supports';
7876
        }
7877
    }
7878
 
7879
    if ($function and function_exists($function)) {
7880
        $supports = $function($feature);
7881
        if (is_null($supports)) {
7882
            // Plugin does not know - use default.
7883
            return $default;
7884
        } else {
7885
            return $supports;
7886
        }
7887
    }
7888
 
7889
    // Plugin does not care, so use default.
7890
    return $default;
7891
}
7892
 
7893
/**
7894
 * Returns true if the current version of PHP is greater that the specified one.
7895
 *
7896
 * @todo Check PHP version being required here is it too low?
7897
 *
7898
 * @param string $version The version of php being tested.
7899
 * @return bool
7900
 */
7901
function check_php_version($version='5.2.4') {
7902
    return (version_compare(phpversion(), $version) >= 0);
7903
}
7904
 
7905
/**
7906
 * Determine if moodle installation requires update.
7907
 *
7908
 * Checks version numbers of main code and all plugins to see
7909
 * if there are any mismatches.
7910
 *
7911
 * @param bool $checkupgradeflag check the outagelessupgrade flag to see if an upgrade is running.
7912
 * @return bool
7913
 */
7914
function moodle_needs_upgrading($checkupgradeflag = true) {
7915
    global $CFG, $DB;
7916
 
7917
    // Say no if there is already an upgrade running.
7918
    if ($checkupgradeflag) {
7919
        $lock = $DB->get_field('config', 'value', ['name' => 'outagelessupgrade']);
7920
        $currentprocessrunningupgrade = (defined('CLI_UPGRADE_RUNNING') && CLI_UPGRADE_RUNNING);
7921
        // If we ARE locked, but this PHP process is NOT the process running the upgrade,
7922
        // We should always return false.
7923
        // This means the upgrade is running from CLI somewhere, or about to.
7924
        if (!empty($lock) && !$currentprocessrunningupgrade) {
7925
            return false;
7926
        }
7927
    }
7928
 
7929
    if (empty($CFG->version)) {
7930
        return true;
7931
    }
7932
 
7933
    // There is no need to purge plugininfo caches here because
7934
    // these caches are not used during upgrade and they are purged after
7935
    // every upgrade.
7936
 
7937
    if (empty($CFG->allversionshash)) {
7938
        return true;
7939
    }
7940
 
7941
    $hash = core_component::get_all_versions_hash();
7942
 
7943
    return ($hash !== $CFG->allversionshash);
7944
}
7945
 
7946
/**
7947
 * Returns the major version of this site
7948
 *
7949
 * Moodle version numbers consist of three numbers separated by a dot, for
7950
 * example 1.9.11 or 2.0.2. The first two numbers, like 1.9 or 2.0, represent so
7951
 * called major version. This function extracts the major version from either
7952
 * $CFG->release (default) or eventually from the $release variable defined in
7953
 * the main version.php.
7954
 *
7955
 * @param bool $fromdisk should the version if source code files be used
7956
 * @return string|false the major version like '2.3', false if could not be determined
7957
 */
7958
function moodle_major_version($fromdisk = false) {
7959
    global $CFG;
7960
 
7961
    if ($fromdisk) {
7962
        $release = null;
7963
        require($CFG->dirroot.'/version.php');
7964
        if (empty($release)) {
7965
            return false;
7966
        }
7967
 
7968
    } else {
7969
        if (empty($CFG->release)) {
7970
            return false;
7971
        }
7972
        $release = $CFG->release;
7973
    }
7974
 
7975
    if (preg_match('/^[0-9]+\.[0-9]+/', $release, $matches)) {
7976
        return $matches[0];
7977
    } else {
7978
        return false;
7979
    }
7980
}
7981
 
7982
// MISCELLANEOUS.
7983
 
7984
/**
7985
 * Gets the system locale
7986
 *
7987
 * @return string Retuns the current locale.
7988
 */
7989
function moodle_getlocale() {
7990
    global $CFG;
7991
 
7992
    // Fetch the correct locale based on ostype.
7993
    if ($CFG->ostype == 'WINDOWS') {
7994
        $stringtofetch = 'localewin';
7995
    } else {
7996
        $stringtofetch = 'locale';
7997
    }
7998
 
7999
    if (!empty($CFG->locale)) { // Override locale for all language packs.
8000
        return $CFG->locale;
8001
    }
8002
 
8003
    return get_string($stringtofetch, 'langconfig');
8004
}
8005
 
8006
/**
8007
 * Sets the system locale
8008
 *
8009
 * @category string
8010
 * @param string $locale Can be used to force a locale
8011
 */
8012
function moodle_setlocale($locale='') {
8013
    global $CFG;
8014
 
8015
    static $currentlocale = ''; // Last locale caching.
8016
 
8017
    $oldlocale = $currentlocale;
8018
 
8019
    // The priority is the same as in get_string() - parameter, config, course, session, user, global language.
8020
    if (!empty($locale)) {
8021
        $currentlocale = $locale;
8022
    } else {
8023
        $currentlocale = moodle_getlocale();
8024
    }
8025
 
8026
    // Do nothing if locale already set up.
8027
    if ($oldlocale == $currentlocale) {
8028
        return;
8029
    }
8030
 
8031
    // Due to some strange BUG we cannot set the LC_TIME directly, so we fetch current values,
8032
    // set LC_ALL and then set values again. Just wondering why we cannot set LC_ALL only??? - stronk7
8033
    // Some day, numeric, monetary and other categories should be set too, I think. :-/.
8034
 
8035
    // Get current values.
8036
    $monetary= setlocale (LC_MONETARY, 0);
8037
    $numeric = setlocale (LC_NUMERIC, 0);
8038
    $ctype   = setlocale (LC_CTYPE, 0);
8039
    if ($CFG->ostype != 'WINDOWS') {
8040
        $messages= setlocale (LC_MESSAGES, 0);
8041
    }
8042
    // Set locale to all.
8043
    $result = setlocale (LC_ALL, $currentlocale);
8044
    // If setting of locale fails try the other utf8 or utf-8 variant,
8045
    // some operating systems support both (Debian), others just one (OSX).
8046
    if ($result === false) {
8047
        if (stripos($currentlocale, '.UTF-8') !== false) {
8048
            $newlocale = str_ireplace('.UTF-8', '.UTF8', $currentlocale);
8049
            setlocale (LC_ALL, $newlocale);
8050
        } else if (stripos($currentlocale, '.UTF8') !== false) {
8051
            $newlocale = str_ireplace('.UTF8', '.UTF-8', $currentlocale);
8052
            setlocale (LC_ALL, $newlocale);
8053
        }
8054
    }
8055
    // Set old values.
8056
    setlocale (LC_MONETARY, $monetary);
8057
    setlocale (LC_NUMERIC, $numeric);
8058
    if ($CFG->ostype != 'WINDOWS') {
8059
        setlocale (LC_MESSAGES, $messages);
8060
    }
8061
    if ($currentlocale == 'tr_TR' or $currentlocale == 'tr_TR.UTF-8') {
8062
        // To workaround a well-known PHP problem with Turkish letter Ii.
8063
        setlocale (LC_CTYPE, $ctype);
8064
    }
8065
}
8066
 
8067
/**
8068
 * Count words in a string.
8069
 *
8070
 * Words are defined as things between whitespace.
8071
 *
8072
 * @category string
8073
 * @param string $string The text to be searched for words. May be HTML.
8074
 * @param int|null $format
8075
 * @return int The count of words in the specified string
8076
 */
8077
function count_words($string, $format = null) {
8078
    // Before stripping tags, add a space after the close tag of anything that is not obviously inline.
8079
    // Also, br is a special case because it definitely delimits a word, but has no close tag.
8080
    $string = preg_replace('~
8081
            (                                   # Capture the tag we match.
8082
                </                              # Start of close tag.
8083
                (?!                             # Do not match any of these specific close tag names.
8084
                    a> | b> | del> | em> | i> |
8085
                    ins> | s> | small> | span> |
8086
                    strong> | sub> | sup> | u>
8087
                )
8088
                \w+                             # But, apart from those execptions, match any tag name.
8089
                >                               # End of close tag.
8090
            |
8091
                <br> | <br\s*/>                 # Special cases that are not close tags.
8092
            )
8093
            ~x', '$1 ', $string); // Add a space after the close tag.
8094
    if ($format !== null && $format != FORMAT_PLAIN) {
8095
        // Match the usual text cleaning before display.
8096
        // Ideally we should apply multilang filter only here, other filters might add extra text.
8097
        $string = format_text($string, $format, ['filter' => false, 'noclean' => false, 'para' => false]);
8098
    }
8099
    // Now remove HTML tags.
8100
    $string = strip_tags($string);
8101
    // Decode HTML entities.
8102
    $string = html_entity_decode($string, ENT_COMPAT);
8103
 
8104
    // Now, the word count is the number of blocks of characters separated
8105
    // by any sort of space. That seems to be the definition used by all other systems.
8106
    // To be precise about what is considered to separate words:
8107
    // * Anything that Unicode considers a 'Separator'
8108
    // * Anything that Unicode considers a 'Control character'
8109
    // * An em- or en- dash.
8110
    return count(preg_split('~[\p{Z}\p{Cc}—–]+~u', $string, -1, PREG_SPLIT_NO_EMPTY));
8111
}
8112
 
8113
/**
8114
 * Count letters in a string.
8115
 *
8116
 * Letters are defined as chars not in tags and different from whitespace.
8117
 *
8118
 * @category string
8119
 * @param string $string The text to be searched for letters. May be HTML.
8120
 * @param int|null $format
8121
 * @return int The count of letters in the specified text.
8122
 */
8123
function count_letters($string, $format = null) {
8124
    if ($format !== null && $format != FORMAT_PLAIN) {
8125
        // Match the usual text cleaning before display.
8126
        // Ideally we should apply multilang filter only here, other filters might add extra text.
8127
        $string = format_text($string, $format, ['filter' => false, 'noclean' => false, 'para' => false]);
8128
    }
8129
    $string = strip_tags($string); // Tags are out now.
8130
    $string = html_entity_decode($string, ENT_COMPAT);
8131
    $string = preg_replace('/[[:space:]]*/', '', $string); // Whitespace are out now.
8132
 
8133
    return core_text::strlen($string);
8134
}
8135
 
8136
/**
8137
 * Generate and return a random string of the specified length.
8138
 *
8139
 * @param int $length The length of the string to be created.
8140
 * @return string
8141
 */
8142
function random_string($length=15) {
8143
    $randombytes = random_bytes($length);
8144
    $pool  = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
8145
    $pool .= 'abcdefghijklmnopqrstuvwxyz';
8146
    $pool .= '0123456789';
8147
    $poollen = strlen($pool);
8148
    $string = '';
8149
    for ($i = 0; $i < $length; $i++) {
8150
        $rand = ord($randombytes[$i]);
8151
        $string .= substr($pool, ($rand%($poollen)), 1);
8152
    }
8153
    return $string;
8154
}
8155
 
8156
/**
8157
 * Generate a complex random string (useful for md5 salts)
8158
 *
8159
 * This function is based on the above {@link random_string()} however it uses a
8160
 * larger pool of characters and generates a string between 24 and 32 characters
8161
 *
8162
 * @param int $length Optional if set generates a string to exactly this length
8163
 * @return string
8164
 */
8165
function complex_random_string($length=null) {
8166
    $pool  = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
8167
    $pool .= '`~!@#%^&*()_+-=[];,./<>?:{} ';
8168
    $poollen = strlen($pool);
8169
    if ($length===null) {
8170
        $length = floor(rand(24, 32));
8171
    }
8172
    $randombytes = random_bytes($length);
8173
    $string = '';
8174
    for ($i = 0; $i < $length; $i++) {
8175
        $rand = ord($randombytes[$i]);
8176
        $string .= $pool[($rand%$poollen)];
8177
    }
8178
    return $string;
8179
}
8180
 
8181
/**
8182
 * Given some text (which may contain HTML) and an ideal length,
8183
 * this function truncates the text neatly on a word boundary if possible
8184
 *
8185
 * @category string
8186
 * @param string $text text to be shortened
8187
 * @param int $ideal ideal string length
8188
 * @param boolean $exact if false, $text will not be cut mid-word
8189
 * @param string $ending The string to append if the passed string is truncated
8190
 * @return string $truncate shortened string
8191
 */
8192
function shorten_text($text, $ideal=30, $exact = false, $ending='...') {
8193
    // If the plain text is shorter than the maximum length, return the whole text.
8194
    if (core_text::strlen(preg_replace('/<.*?>/', '', $text)) <= $ideal) {
8195
        return $text;
8196
    }
8197
 
8198
    // Splits on HTML tags. Each open/close/empty tag will be the first thing
8199
    // and only tag in its 'line'.
8200
    preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER);
8201
 
8202
    $totallength = core_text::strlen($ending);
8203
    $truncate = '';
8204
 
8205
    // This array stores information about open and close tags and their position
8206
    // in the truncated string. Each item in the array is an object with fields
8207
    // ->open (true if open), ->tag (tag name in lower case), and ->pos
8208
    // (byte position in truncated text).
8209
    $tagdetails = array();
8210
 
8211
    foreach ($lines as $linematchings) {
8212
        // If there is any html-tag in this line, handle it and add it (uncounted) to the output.
8213
        if (!empty($linematchings[1])) {
8214
            // If it's an "empty element" with or without xhtml-conform closing slash (f.e. <br/>).
8215
            if (!preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $linematchings[1])) {
8216
                if (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $linematchings[1], $tagmatchings)) {
8217
                    // Record closing tag.
8218
                    $tagdetails[] = (object) array(
8219
                            'open' => false,
8220
                            'tag'  => core_text::strtolower($tagmatchings[1]),
8221
                            'pos'  => core_text::strlen($truncate),
8222
                        );
8223
 
8224
                } else if (preg_match('/^<\s*([^\s>!]+).*?>$/s', $linematchings[1], $tagmatchings)) {
8225
                    // Record opening tag.
8226
                    $tagdetails[] = (object) array(
8227
                            'open' => true,
8228
                            'tag'  => core_text::strtolower($tagmatchings[1]),
8229
                            'pos'  => core_text::strlen($truncate),
8230
                        );
8231
                } else if (preg_match('/^<!--\[if\s.*?\]>$/s', $linematchings[1], $tagmatchings)) {
8232
                    $tagdetails[] = (object) array(
8233
                            'open' => true,
8234
                            'tag'  => core_text::strtolower('if'),
8235
                            'pos'  => core_text::strlen($truncate),
8236
                    );
8237
                } else if (preg_match('/^<!--<!\[endif\]-->$/s', $linematchings[1], $tagmatchings)) {
8238
                    $tagdetails[] = (object) array(
8239
                            'open' => false,
8240
                            'tag'  => core_text::strtolower('if'),
8241
                            'pos'  => core_text::strlen($truncate),
8242
                    );
8243
                }
8244
            }
8245
            // Add html-tag to $truncate'd text.
8246
            $truncate .= $linematchings[1];
8247
        }
8248
 
8249
        // Calculate the length of the plain text part of the line; handle entities as one character.
8250
        $contentlength = core_text::strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $linematchings[2]));
8251
        if ($totallength + $contentlength > $ideal) {
8252
            // The number of characters which are left.
8253
            $left = $ideal - $totallength;
8254
            $entitieslength = 0;
8255
            // Search for html entities.
8256
            if (preg_match_all('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', $linematchings[2], $entities, PREG_OFFSET_CAPTURE)) {
8257
                // Calculate the real length of all entities in the legal range.
8258
                foreach ($entities[0] as $entity) {
8259
                    if ($entity[1]+1-$entitieslength <= $left) {
8260
                        $left--;
8261
                        $entitieslength += core_text::strlen($entity[0]);
8262
                    } else {
8263
                        // No more characters left.
8264
                        break;
8265
                    }
8266
                }
8267
            }
8268
            $breakpos = $left + $entitieslength;
8269
 
8270
            // If the words shouldn't be cut in the middle...
8271
            if (!$exact) {
8272
                // Search the last occurence of a space.
8273
                for (; $breakpos > 0; $breakpos--) {
8274
                    if ($char = core_text::substr($linematchings[2], $breakpos, 1)) {
8275
                        if ($char === '.' or $char === ' ') {
8276
                            $breakpos += 1;
8277
                            break;
8278
                        } else if (strlen($char) > 2) {
8279
                            // Chinese/Japanese/Korean text can be truncated at any UTF-8 character boundary.
8280
                            $breakpos += 1;
8281
                            break;
8282
                        }
8283
                    }
8284
                }
8285
            }
8286
            if ($breakpos == 0) {
8287
                // This deals with the test_shorten_text_no_spaces case.
8288
                $breakpos = $left + $entitieslength;
8289
            } else if ($breakpos > $left + $entitieslength) {
8290
                // This deals with the previous for loop breaking on the first char.
8291
                $breakpos = $left + $entitieslength;
8292
            }
8293
 
8294
            $truncate .= core_text::substr($linematchings[2], 0, $breakpos);
8295
            // Maximum length is reached, so get off the loop.
8296
            break;
8297
        } else {
8298
            $truncate .= $linematchings[2];
8299
            $totallength += $contentlength;
8300
        }
8301
 
8302
        // If the maximum length is reached, get off the loop.
8303
        if ($totallength >= $ideal) {
8304
            break;
8305
        }
8306
    }
8307
 
8308
    // Add the defined ending to the text.
8309
    $truncate .= $ending;
8310
 
8311
    // Now calculate the list of open html tags based on the truncate position.
8312
    $opentags = array();
8313
    foreach ($tagdetails as $taginfo) {
8314
        if ($taginfo->open) {
8315
            // Add tag to the beginning of $opentags list.
8316
            array_unshift($opentags, $taginfo->tag);
8317
        } else {
8318
            // Can have multiple exact same open tags, close the last one.
8319
            $pos = array_search($taginfo->tag, array_reverse($opentags, true));
8320
            if ($pos !== false) {
8321
                unset($opentags[$pos]);
8322
            }
8323
        }
8324
    }
8325
 
8326
    // Close all unclosed html-tags.
8327
    foreach ($opentags as $tag) {
8328
        if ($tag === 'if') {
8329
            $truncate .= '<!--<![endif]-->';
8330
        } else {
8331
            $truncate .= '</' . $tag . '>';
8332
        }
8333
    }
8334
 
8335
    return $truncate;
8336
}
8337
 
8338
/**
8339
 * Shortens a given filename by removing characters positioned after the ideal string length.
8340
 * When the filename is too long, the file cannot be created on the filesystem due to exceeding max byte size.
8341
 * Limiting the filename to a certain size (considering multibyte characters) will prevent this.
8342
 *
8343
 * @param string $filename file name
8344
 * @param int $length ideal string length
8345
 * @param bool $includehash Whether to include a file hash in the shortened version. This ensures uniqueness.
8346
 * @return string $shortened shortened file name
8347
 */
8348
function shorten_filename($filename, $length = MAX_FILENAME_SIZE, $includehash = false) {
8349
    $shortened = $filename;
8350
    // Extract a part of the filename if it's char size exceeds the ideal string length.
8351
    if (core_text::strlen($filename) > $length) {
8352
        // Exclude extension if present in filename.
8353
        $mimetypes = get_mimetypes_array();
8354
        $extension = pathinfo($filename, PATHINFO_EXTENSION);
8355
        if ($extension && !empty($mimetypes[$extension])) {
8356
            $basename = pathinfo($filename, PATHINFO_FILENAME);
8357
            $hash = empty($includehash) ? '' : ' - ' . substr(sha1($basename), 0, 10);
8358
            $shortened = core_text::substr($basename, 0, $length - strlen($hash)) . $hash;
8359
            $shortened .= '.' . $extension;
8360
        } else {
8361
            $hash = empty($includehash) ? '' : ' - ' . substr(sha1($filename), 0, 10);
8362
            $shortened = core_text::substr($filename, 0, $length - strlen($hash)) . $hash;
8363
        }
8364
    }
8365
    return $shortened;
8366
}
8367
 
8368
/**
8369
 * Shortens a given array of filenames by removing characters positioned after the ideal string length.
8370
 *
8371
 * @param array $path The paths to reduce the length.
8372
 * @param int $length Ideal string length
8373
 * @param bool $includehash Whether to include a file hash in the shortened version. This ensures uniqueness.
8374
 * @return array $result Shortened paths in array.
8375
 */
8376
function shorten_filenames(array $path, $length = MAX_FILENAME_SIZE, $includehash = false) {
8377
    $result = null;
8378
 
8379
    $result = array_reduce($path, function($carry, $singlepath) use ($length, $includehash) {
8380
        $carry[] = shorten_filename($singlepath, $length, $includehash);
8381
        return $carry;
8382
    }, []);
8383
 
8384
    return $result;
8385
}
8386
 
8387
/**
8388
 * Given dates in seconds, how many weeks is the date from startdate
8389
 * The first week is 1, the second 2 etc ...
8390
 *
8391
 * @param int $startdate Timestamp for the start date
8392
 * @param int $thedate Timestamp for the end date
8393
 * @return string
8394
 */
8395
function getweek ($startdate, $thedate) {
8396
    if ($thedate < $startdate) {
8397
        return 0;
8398
    }
8399
 
8400
    return floor(($thedate - $startdate) / WEEKSECS) + 1;
8401
}
8402
 
8403
/**
8404
 * Returns a randomly generated password of length $maxlen.  inspired by
8405
 *
8406
 * {@link http://www.phpbuilder.com/columns/jesus19990502.php3} and
8407
 * {@link http://es2.php.net/manual/en/function.str-shuffle.php#73254}
8408
 *
8409
 * @param int $maxlen  The maximum size of the password being generated.
8410
 * @return string
8411
 */
8412
function generate_password($maxlen=10) {
8413
    global $CFG;
8414
 
8415
    if (empty($CFG->passwordpolicy)) {
8416
        $fillers = PASSWORD_DIGITS;
8417
        $wordlist = file($CFG->wordlist);
8418
        $word1 = trim($wordlist[rand(0, count($wordlist) - 1)]);
8419
        $word2 = trim($wordlist[rand(0, count($wordlist) - 1)]);
8420
        $filler1 = $fillers[rand(0, strlen($fillers) - 1)];
8421
        $password = $word1 . $filler1 . $word2;
8422
    } else {
8423
        $minlen = !empty($CFG->minpasswordlength) ? $CFG->minpasswordlength : 0;
8424
        $digits = $CFG->minpassworddigits;
8425
        $lower = $CFG->minpasswordlower;
8426
        $upper = $CFG->minpasswordupper;
8427
        $nonalphanum = $CFG->minpasswordnonalphanum;
8428
        $total = $lower + $upper + $digits + $nonalphanum;
8429
        // Var minlength should be the greater one of the two ( $minlen and $total ).
8430
        $minlen = $minlen < $total ? $total : $minlen;
8431
        // Var maxlen can never be smaller than minlen.
8432
        $maxlen = $minlen > $maxlen ? $minlen : $maxlen;
8433
        $additional = $maxlen - $total;
8434
 
8435
        // Make sure we have enough characters to fulfill
8436
        // complexity requirements.
8437
        $passworddigits = PASSWORD_DIGITS;
8438
        while ($digits > strlen($passworddigits)) {
8439
            $passworddigits .= PASSWORD_DIGITS;
8440
        }
8441
        $passwordlower = PASSWORD_LOWER;
8442
        while ($lower > strlen($passwordlower)) {
8443
            $passwordlower .= PASSWORD_LOWER;
8444
        }
8445
        $passwordupper = PASSWORD_UPPER;
8446
        while ($upper > strlen($passwordupper)) {
8447
            $passwordupper .= PASSWORD_UPPER;
8448
        }
8449
        $passwordnonalphanum = PASSWORD_NONALPHANUM;
8450
        while ($nonalphanum > strlen($passwordnonalphanum)) {
8451
            $passwordnonalphanum .= PASSWORD_NONALPHANUM;
8452
        }
8453
 
8454
        // Now mix and shuffle it all.
8455
        $password = str_shuffle (substr(str_shuffle ($passwordlower), 0, $lower) .
8456
                                 substr(str_shuffle ($passwordupper), 0, $upper) .
8457
                                 substr(str_shuffle ($passworddigits), 0, $digits) .
8458
                                 substr(str_shuffle ($passwordnonalphanum), 0 , $nonalphanum) .
8459
                                 substr(str_shuffle ($passwordlower .
8460
                                                     $passwordupper .
8461
                                                     $passworddigits .
8462
                                                     $passwordnonalphanum), 0 , $additional));
8463
    }
8464
 
8465
    return substr ($password, 0, $maxlen);
8466
}
8467
 
8468
/**
8469
 * Given a float, prints it nicely.
8470
 * Localized floats must not be used in calculations!
8471
 *
8472
 * The stripzeros feature is intended for making numbers look nicer in small
8473
 * areas where it is not necessary to indicate the degree of accuracy by showing
8474
 * ending zeros. If you turn it on with $decimalpoints set to 3, for example,
8475
 * then it will display '5.4' instead of '5.400' or '5' instead of '5.000'.
8476
 *
8477
 * @param float $float The float to print
8478
 * @param int $decimalpoints The number of decimal places to print. -1 is a special value for auto detect (full precision).
8479
 * @param bool $localized use localized decimal separator
8480
 * @param bool $stripzeros If true, removes final zeros after decimal point. It will be ignored and the trailing zeros after
8481
 *                         the decimal point are always striped if $decimalpoints is -1.
8482
 * @return string locale float
8483
 */
8484
function format_float($float, $decimalpoints=1, $localized=true, $stripzeros=false) {
8485
    if (is_null($float)) {
8486
        return '';
8487
    }
8488
    if ($localized) {
8489
        $separator = get_string('decsep', 'langconfig');
8490
    } else {
8491
        $separator = '.';
8492
    }
8493
    if ($decimalpoints == -1) {
8494
        // The following counts the number of decimals.
8495
        // It is safe as both floatval() and round() functions have same behaviour when non-numeric values are provided.
8496
        $floatval = floatval($float);
8497
        for ($decimalpoints = 0; $floatval != round($float, $decimalpoints); $decimalpoints++);
8498
    }
8499
 
8500
    $result = number_format($float, $decimalpoints, $separator, '');
8501
    if ($stripzeros && $decimalpoints > 0) {
8502
        // Remove zeros and final dot if not needed.
8503
        // However, only do this if there is a decimal point!
8504
        $result = preg_replace('~(' . preg_quote($separator, '~') . ')?0+$~', '', $result);
8505
    }
8506
    return $result;
8507
}
8508
 
8509
/**
8510
 * Converts locale specific floating point/comma number back to standard PHP float value
8511
 * Do NOT try to do any math operations before this conversion on any user submitted floats!
8512
 *
8513
 * @param string $localefloat locale aware float representation
8514
 * @param bool $strict If true, then check the input and return false if it is not a valid number.
8515
 * @return mixed float|bool - false or the parsed float.
8516
 */
8517
function unformat_float($localefloat, $strict = false) {
8518
    $localefloat = trim((string)$localefloat);
8519
 
8520
    if ($localefloat == '') {
8521
        return null;
8522
    }
8523
 
8524
    $localefloat = str_replace(' ', '', $localefloat); // No spaces - those might be used as thousand separators.
8525
    $localefloat = str_replace(get_string('decsep', 'langconfig'), '.', $localefloat);
8526
 
8527
    if ($strict && !is_numeric($localefloat)) {
8528
        return false;
8529
    }
8530
 
8531
    return (float)$localefloat;
8532
}
8533
 
8534
/**
8535
 * Given a simple array, this shuffles it up just like shuffle()
8536
 * Unlike PHP's shuffle() this function works on any machine.
8537
 *
8538
 * @param array $array The array to be rearranged
8539
 * @return array
8540
 */
8541
function swapshuffle($array) {
8542
 
8543
    $last = count($array) - 1;
8544
    for ($i = 0; $i <= $last; $i++) {
8545
        $from = rand(0, $last);
8546
        $curr = $array[$i];
8547
        $array[$i] = $array[$from];
8548
        $array[$from] = $curr;
8549
    }
8550
    return $array;
8551
}
8552
 
8553
/**
8554
 * Like {@link swapshuffle()}, but works on associative arrays
8555
 *
8556
 * @param array $array The associative array to be rearranged
8557
 * @return array
8558
 */
8559
function swapshuffle_assoc($array) {
8560
 
8561
    $newarray = array();
8562
    $newkeys = swapshuffle(array_keys($array));
8563
 
8564
    foreach ($newkeys as $newkey) {
8565
        $newarray[$newkey] = $array[$newkey];
8566
    }
8567
    return $newarray;
8568
}
8569
 
8570
/**
8571
 * Given an arbitrary array, and a number of draws,
8572
 * this function returns an array with that amount
8573
 * of items.  The indexes are retained.
8574
 *
8575
 * @todo Finish documenting this function
8576
 *
8577
 * @param array $array
8578
 * @param int $draws
8579
 * @return array
8580
 */
8581
function draw_rand_array($array, $draws) {
8582
 
8583
    $return = array();
8584
 
8585
    $last = count($array);
8586
 
8587
    if ($draws > $last) {
8588
        $draws = $last;
8589
    }
8590
 
8591
    while ($draws > 0) {
8592
        $last--;
8593
 
8594
        $keys = array_keys($array);
8595
        $rand = rand(0, $last);
8596
 
8597
        $return[$keys[$rand]] = $array[$keys[$rand]];
8598
        unset($array[$keys[$rand]]);
8599
 
8600
        $draws--;
8601
    }
8602
 
8603
    return $return;
8604
}
8605
 
8606
/**
8607
 * Calculate the difference between two microtimes
8608
 *
8609
 * @param string $a The first Microtime
8610
 * @param string $b The second Microtime
8611
 * @return string
8612
 */
8613
function microtime_diff($a, $b) {
8614
    list($adec, $asec) = explode(' ', $a);
8615
    list($bdec, $bsec) = explode(' ', $b);
8616
    return $bsec - $asec + $bdec - $adec;
8617
}
8618
 
8619
/**
8620
 * Given a list (eg a,b,c,d,e) this function returns
8621
 * an array of 1->a, 2->b, 3->c etc
8622
 *
8623
 * @param string $list The string to explode into array bits
8624
 * @param string $separator The separator used within the list string
8625
 * @return array The now assembled array
8626
 */
8627
function make_menu_from_list($list, $separator=',') {
8628
 
8629
    $array = array_reverse(explode($separator, $list), true);
8630
    foreach ($array as $key => $item) {
8631
        $outarray[$key+1] = trim($item);
8632
    }
8633
    return $outarray;
8634
}
8635
 
8636
/**
8637
 * Creates an array that represents all the current grades that
8638
 * can be chosen using the given grading type.
8639
 *
8640
 * Negative numbers
8641
 * are scales, zero is no grade, and positive numbers are maximum
8642
 * grades.
8643
 *
8644
 * @todo Finish documenting this function or better deprecated this completely!
8645
 *
8646
 * @param int $gradingtype
8647
 * @return array
8648
 */
8649
function make_grades_menu($gradingtype) {
8650
    global $DB;
8651
 
8652
    $grades = array();
8653
    if ($gradingtype < 0) {
8654
        if ($scale = $DB->get_record('scale', array('id'=> (-$gradingtype)))) {
8655
            return make_menu_from_list($scale->scale);
8656
        }
8657
    } else if ($gradingtype > 0) {
8658
        for ($i=$gradingtype; $i>=0; $i--) {
8659
            $grades[$i] = $i .' / '. $gradingtype;
8660
        }
8661
        return $grades;
8662
    }
8663
    return $grades;
8664
}
8665
 
8666
/**
8667
 * make_unique_id_code
8668
 *
8669
 * @todo Finish documenting this function
8670
 *
8671
 * @uses $_SERVER
8672
 * @param string $extra Extra string to append to the end of the code
8673
 * @return string
8674
 */
8675
function make_unique_id_code($extra = '') {
8676
 
8677
    $hostname = 'unknownhost';
8678
    if (!empty($_SERVER['HTTP_HOST'])) {
8679
        $hostname = $_SERVER['HTTP_HOST'];
8680
    } else if (!empty($_ENV['HTTP_HOST'])) {
8681
        $hostname = $_ENV['HTTP_HOST'];
8682
    } else if (!empty($_SERVER['SERVER_NAME'])) {
8683
        $hostname = $_SERVER['SERVER_NAME'];
8684
    } else if (!empty($_ENV['SERVER_NAME'])) {
8685
        $hostname = $_ENV['SERVER_NAME'];
8686
    }
8687
 
8688
    $date = gmdate("ymdHis");
8689
 
8690
    $random =  random_string(6);
8691
 
8692
    if ($extra) {
8693
        return $hostname .'+'. $date .'+'. $random .'+'. $extra;
8694
    } else {
8695
        return $hostname .'+'. $date .'+'. $random;
8696
    }
8697
}
8698
 
8699
 
8700
/**
8701
 * Function to check the passed address is within the passed subnet
8702
 *
8703
 * The parameter is a comma separated string of subnet definitions.
8704
 * Subnet strings can be in one of three formats:
8705
 *   1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn          (number of bits in net mask)
8706
 *   2: xxx.xxx.xxx.xxx-yyy or  xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx::xxxx-yyyy (a range of IP addresses in the last group)
8707
 *   3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx.                  (incomplete address, a bit non-technical ;-)
8708
 * Code for type 1 modified from user posted comments by mediator at
8709
 * {@link http://au.php.net/manual/en/function.ip2long.php}
8710
 *
8711
 * @param string $addr    The address you are checking
8712
 * @param string $subnetstr    The string of subnet addresses
8713
 * @param bool $checkallzeros    The state to whether check for 0.0.0.0
8714
 * @return bool
8715
 */
8716
function address_in_subnet($addr, $subnetstr, $checkallzeros = false) {
8717
 
8718
    if ($addr == '0.0.0.0' && !$checkallzeros) {
8719
        return false;
8720
    }
8721
    $subnets = explode(',', $subnetstr);
8722
    $found = false;
8723
    $addr = trim($addr);
8724
    $addr = cleanremoteaddr($addr, false); // Normalise.
8725
    if ($addr === null) {
8726
        return false;
8727
    }
8728
    $addrparts = explode(':', $addr);
8729
 
8730
    $ipv6 = strpos($addr, ':');
8731
 
8732
    foreach ($subnets as $subnet) {
8733
        $subnet = trim($subnet);
8734
        if ($subnet === '') {
8735
            continue;
8736
        }
8737
 
8738
        if (strpos($subnet, '/') !== false) {
8739
            // 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn.
8740
            list($ip, $mask) = explode('/', $subnet);
8741
            $mask = trim($mask);
8742
            if (!is_number($mask)) {
8743
                continue; // Incorect mask number, eh?
8744
            }
8745
            $ip = cleanremoteaddr($ip, false); // Normalise.
8746
            if ($ip === null) {
8747
                continue;
8748
            }
8749
            if (strpos($ip, ':') !== false) {
8750
                // IPv6.
8751
                if (!$ipv6) {
8752
                    continue;
8753
                }
8754
                if ($mask > 128 or $mask < 0) {
8755
                    continue; // Nonsense.
8756
                }
8757
                if ($mask == 0) {
8758
                    return true; // Any address.
8759
                }
8760
                if ($mask == 128) {
8761
                    if ($ip === $addr) {
8762
                        return true;
8763
                    }
8764
                    continue;
8765
                }
8766
                $ipparts = explode(':', $ip);
8767
                $modulo  = $mask % 16;
8768
                $ipnet   = array_slice($ipparts, 0, ($mask-$modulo)/16);
8769
                $addrnet = array_slice($addrparts, 0, ($mask-$modulo)/16);
8770
                if (implode(':', $ipnet) === implode(':', $addrnet)) {
8771
                    if ($modulo == 0) {
8772
                        return true;
8773
                    }
8774
                    $pos     = ($mask-$modulo)/16;
8775
                    $ipnet   = hexdec($ipparts[$pos]);
8776
                    $addrnet = hexdec($addrparts[$pos]);
8777
                    $mask    = 0xffff << (16 - $modulo);
8778
                    if (($addrnet & $mask) == ($ipnet & $mask)) {
8779
                        return true;
8780
                    }
8781
                }
8782
 
8783
            } else {
8784
                // IPv4.
8785
                if ($ipv6) {
8786
                    continue;
8787
                }
8788
                if ($mask > 32 or $mask < 0) {
8789
                    continue; // Nonsense.
8790
                }
8791
                if ($mask == 0) {
8792
                    return true;
8793
                }
8794
                if ($mask == 32) {
8795
                    if ($ip === $addr) {
8796
                        return true;
8797
                    }
8798
                    continue;
8799
                }
8800
                $mask = 0xffffffff << (32 - $mask);
8801
                if (((ip2long($addr) & $mask) == (ip2long($ip) & $mask))) {
8802
                    return true;
8803
                }
8804
            }
8805
 
8806
        } else if (strpos($subnet, '-') !== false) {
8807
            // 2: xxx.xxx.xxx.xxx-yyy or  xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx::xxxx-yyyy. A range of IP addresses in the last group.
8808
            $parts = explode('-', $subnet);
8809
            if (count($parts) != 2) {
8810
                continue;
8811
            }
8812
 
8813
            if (strpos($subnet, ':') !== false) {
8814
                // IPv6.
8815
                if (!$ipv6) {
8816
                    continue;
8817
                }
8818
                $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
8819
                if ($ipstart === null) {
8820
                    continue;
8821
                }
8822
                $ipparts = explode(':', $ipstart);
8823
                $start = hexdec(array_pop($ipparts));
8824
                $ipparts[] = trim($parts[1]);
8825
                $ipend = cleanremoteaddr(implode(':', $ipparts), false); // Normalise.
8826
                if ($ipend === null) {
8827
                    continue;
8828
                }
8829
                $ipparts[7] = '';
8830
                $ipnet = implode(':', $ipparts);
8831
                if (strpos($addr, $ipnet) !== 0) {
8832
                    continue;
8833
                }
8834
                $ipparts = explode(':', $ipend);
8835
                $end = hexdec($ipparts[7]);
8836
 
8837
                $addrend = hexdec($addrparts[7]);
8838
 
8839
                if (($addrend >= $start) and ($addrend <= $end)) {
8840
                    return true;
8841
                }
8842
 
8843
            } else {
8844
                // IPv4.
8845
                if ($ipv6) {
8846
                    continue;
8847
                }
8848
                $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
8849
                if ($ipstart === null) {
8850
                    continue;
8851
                }
8852
                $ipparts = explode('.', $ipstart);
8853
                $ipparts[3] = trim($parts[1]);
8854
                $ipend = cleanremoteaddr(implode('.', $ipparts), false); // Normalise.
8855
                if ($ipend === null) {
8856
                    continue;
8857
                }
8858
 
8859
                if ((ip2long($addr) >= ip2long($ipstart)) and (ip2long($addr) <= ip2long($ipend))) {
8860
                    return true;
8861
                }
8862
            }
8863
 
8864
        } else {
8865
            // 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx.
8866
            if (strpos($subnet, ':') !== false) {
8867
                // IPv6.
8868
                if (!$ipv6) {
8869
                    continue;
8870
                }
8871
                $parts = explode(':', $subnet);
8872
                $count = count($parts);
8873
                if ($parts[$count-1] === '') {
8874
                    unset($parts[$count-1]); // Trim trailing :'s.
8875
                    $count--;
8876
                    $subnet = implode('.', $parts);
8877
                }
8878
                $isip = cleanremoteaddr($subnet, false); // Normalise.
8879
                if ($isip !== null) {
8880
                    if ($isip === $addr) {
8881
                        return true;
8882
                    }
8883
                    continue;
8884
                } else if ($count > 8) {
8885
                    continue;
8886
                }
8887
                $zeros = array_fill(0, 8-$count, '0');
8888
                $subnet = $subnet.':'.implode(':', $zeros).'/'.($count*16);
8889
                if (address_in_subnet($addr, $subnet)) {
8890
                    return true;
8891
                }
8892
 
8893
            } else {
8894
                // IPv4.
8895
                if ($ipv6) {
8896
                    continue;
8897
                }
8898
                $parts = explode('.', $subnet);
8899
                $count = count($parts);
8900
                if ($parts[$count-1] === '') {
8901
                    unset($parts[$count-1]); // Trim trailing .
8902
                    $count--;
8903
                    $subnet = implode('.', $parts);
8904
                }
8905
                if ($count == 4) {
8906
                    $subnet = cleanremoteaddr($subnet, false); // Normalise.
8907
                    if ($subnet === $addr) {
8908
                        return true;
8909
                    }
8910
                    continue;
8911
                } else if ($count > 4) {
8912
                    continue;
8913
                }
8914
                $zeros = array_fill(0, 4-$count, '0');
8915
                $subnet = $subnet.'.'.implode('.', $zeros).'/'.($count*8);
8916
                if (address_in_subnet($addr, $subnet)) {
8917
                    return true;
8918
                }
8919
            }
8920
        }
8921
    }
8922
 
8923
    return false;
8924
}
8925
 
8926
/**
8927
 * For outputting debugging info
8928
 *
8929
 * @param string $string The string to write
8930
 * @param string $eol The end of line char(s) to use
8931
 * @param string $sleep Period to make the application sleep
8932
 *                      This ensures any messages have time to display before redirect
8933
 */
8934
function mtrace($string, $eol="\n", $sleep=0) {
8935
    global $CFG;
8936
 
8937
    if (isset($CFG->mtrace_wrapper) && function_exists($CFG->mtrace_wrapper)) {
8938
        $fn = $CFG->mtrace_wrapper;
8939
        $fn($string, $eol);
8940
        return;
8941
    } else if (defined('STDOUT') && !PHPUNIT_TEST && !defined('BEHAT_TEST')) {
8942
        // We must explicitly call the add_line function here.
8943
        // Uses of fwrite to STDOUT are not picked up by ob_start.
8944
        if ($output = \core\task\logmanager::add_line("{$string}{$eol}")) {
8945
            fwrite(STDOUT, $output);
8946
        }
8947
    } else {
8948
        echo $string . $eol;
8949
    }
8950
 
8951
    // Flush again.
8952
    flush();
8953
 
8954
    // Delay to keep message on user's screen in case of subsequent redirect.
8955
    if ($sleep) {
8956
        sleep($sleep);
8957
    }
8958
}
8959
 
8960
/**
8961
 * Helper to {@see mtrace()} an exception or throwable, including all relevant information.
8962
 *
8963
 * @param Throwable $e the error to ouptput.
8964
 */
8965
function mtrace_exception(Throwable $e): void {
8966
    $info = get_exception_info($e);
8967
 
8968
    $message = $info->message;
8969
    if ($info->debuginfo) {
8970
        $message .= "\n\n" . $info->debuginfo;
8971
    }
8972
    if ($info->backtrace) {
8973
        $message .= "\n\n" . format_backtrace($info->backtrace, true);
8974
    }
8975
 
8976
    mtrace($message);
8977
}
8978
 
8979
/**
8980
 * Replace 1 or more slashes or backslashes to 1 slash
8981
 *
8982
 * @param string $path The path to strip
8983
 * @return string the path with double slashes removed
8984
 */
8985
function cleardoubleslashes ($path) {
8986
    return preg_replace('/(\/|\\\){1,}/', '/', $path);
8987
}
8988
 
8989
/**
8990
 * Is the current ip in a given list?
8991
 *
8992
 * @param string $list
8993
 * @return bool
8994
 */
8995
function remoteip_in_list($list) {
8996
    $clientip = getremoteaddr(null);
8997
 
8998
    if (!$clientip) {
8999
        // Ensure access on cli.
9000
        return true;
9001
    }
9002
    return \core\ip_utils::is_ip_in_subnet_list($clientip, $list);
9003
}
9004
 
9005
/**
9006
 * Returns most reliable client address
9007
 *
9008
 * @param string $default If an address can't be determined, then return this
9009
 * @return string The remote IP address
9010
 */
9011
function getremoteaddr($default='0.0.0.0') {
9012
    global $CFG;
9013
 
9014
    if (!isset($CFG->getremoteaddrconf)) {
9015
        // This will happen, for example, before just after the upgrade, as the
9016
        // user is redirected to the admin screen.
9017
        $variablestoskip = GETREMOTEADDR_SKIP_DEFAULT;
9018
    } else {
9019
        $variablestoskip = $CFG->getremoteaddrconf;
9020
    }
9021
    if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_CLIENT_IP)) {
9022
        if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
9023
            $address = cleanremoteaddr($_SERVER['HTTP_CLIENT_IP']);
9024
            return $address ? $address : $default;
9025
        }
9026
    }
9027
    if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR)) {
9028
        if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
9029
            $forwardedaddresses = explode(",", $_SERVER['HTTP_X_FORWARDED_FOR']);
9030
 
9031
            $forwardedaddresses = array_filter($forwardedaddresses, function($ip) {
9032
                global $CFG;
9033
                return !\core\ip_utils::is_ip_in_subnet_list($ip, $CFG->reverseproxyignore ?? '', ',');
9034
            });
9035
 
9036
            // Multiple proxies can append values to this header including an
9037
            // untrusted original request header so we must only trust the last ip.
9038
            $address = end($forwardedaddresses);
9039
 
9040
            if (substr_count($address, ":") > 1) {
9041
                // Remove port and brackets from IPv6.
9042
                if (preg_match("/\[(.*)\]:/", $address, $matches)) {
9043
                    $address = $matches[1];
9044
                }
9045
            } else {
9046
                // Remove port from IPv4.
9047
                if (substr_count($address, ":") == 1) {
9048
                    $parts = explode(":", $address);
9049
                    $address = $parts[0];
9050
                }
9051
            }
9052
 
9053
            $address = cleanremoteaddr($address);
9054
            return $address ? $address : $default;
9055
        }
9056
    }
9057
    if (!empty($_SERVER['REMOTE_ADDR'])) {
9058
        $address = cleanremoteaddr($_SERVER['REMOTE_ADDR']);
9059
        return $address ? $address : $default;
9060
    } else {
9061
        return $default;
9062
    }
9063
}
9064
 
9065
/**
9066
 * Cleans an ip address. Internal addresses are now allowed.
9067
 * (Originally local addresses were not allowed.)
9068
 *
9069
 * @param string $addr IPv4 or IPv6 address
9070
 * @param bool $compress use IPv6 address compression
9071
 * @return string normalised ip address string, null if error
9072
 */
9073
function cleanremoteaddr($addr, $compress=false) {
9074
    $addr = trim($addr);
9075
 
9076
    if (strpos($addr, ':') !== false) {
9077
        // Can be only IPv6.
9078
        $parts = explode(':', $addr);
9079
        $count = count($parts);
9080
 
9081
        if (strpos($parts[$count-1], '.') !== false) {
9082
            // Legacy ipv4 notation.
9083
            $last = array_pop($parts);
9084
            $ipv4 = cleanremoteaddr($last, true);
9085
            if ($ipv4 === null) {
9086
                return null;
9087
            }
9088
            $bits = explode('.', $ipv4);
9089
            $parts[] = dechex($bits[0]).dechex($bits[1]);
9090
            $parts[] = dechex($bits[2]).dechex($bits[3]);
9091
            $count = count($parts);
9092
            $addr = implode(':', $parts);
9093
        }
9094
 
9095
        if ($count < 3 or $count > 8) {
9096
            return null; // Severly malformed.
9097
        }
9098
 
9099
        if ($count != 8) {
9100
            if (strpos($addr, '::') === false) {
9101
                return null; // Malformed.
9102
            }
9103
            // Uncompress.
9104
            $insertat = array_search('', $parts, true);
9105
            $missing = array_fill(0, 1 + 8 - $count, '0');
9106
            array_splice($parts, $insertat, 1, $missing);
9107
            foreach ($parts as $key => $part) {
9108
                if ($part === '') {
9109
                    $parts[$key] = '0';
9110
                }
9111
            }
9112
        }
9113
 
9114
        $adr = implode(':', $parts);
9115
        if (!preg_match('/^([0-9a-f]{1,4})(:[0-9a-f]{1,4})*$/i', $adr)) {
9116
            return null; // Incorrect format - sorry.
9117
        }
9118
 
9119
        // Normalise 0s and case.
9120
        $parts = array_map('hexdec', $parts);
9121
        $parts = array_map('dechex', $parts);
9122
 
9123
        $result = implode(':', $parts);
9124
 
9125
        if (!$compress) {
9126
            return $result;
9127
        }
9128
 
9129
        if ($result === '0:0:0:0:0:0:0:0') {
9130
            return '::'; // All addresses.
9131
        }
9132
 
9133
        $compressed = preg_replace('/(:0)+:0$/', '::', $result, 1);
9134
        if ($compressed !== $result) {
9135
            return $compressed;
9136
        }
9137
 
9138
        $compressed = preg_replace('/^(0:){2,7}/', '::', $result, 1);
9139
        if ($compressed !== $result) {
9140
            return $compressed;
9141
        }
9142
 
9143
        $compressed = preg_replace('/(:0){2,6}:/', '::', $result, 1);
9144
        if ($compressed !== $result) {
9145
            return $compressed;
9146
        }
9147
 
9148
        return $result;
9149
    }
9150
 
9151
    // First get all things that look like IPv4 addresses.
9152
    $parts = array();
9153
    if (!preg_match('/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $addr, $parts)) {
9154
        return null;
9155
    }
9156
    unset($parts[0]);
9157
 
9158
    foreach ($parts as $key => $match) {
9159
        if ($match > 255) {
9160
            return null;
9161
        }
9162
        $parts[$key] = (int)$match; // Normalise 0s.
9163
    }
9164
 
9165
    return implode('.', $parts);
9166
}
9167
 
9168
 
9169
/**
9170
 * Is IP address a public address?
9171
 *
9172
 * @param string $ip The ip to check
9173
 * @return bool true if the ip is public
9174
 */
9175
function ip_is_public($ip) {
9176
    return (bool) filter_var($ip, FILTER_VALIDATE_IP, (FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE));
9177
}
9178
 
9179
/**
9180
 * This function will make a complete copy of anything it's given,
9181
 * regardless of whether it's an object or not.
9182
 *
9183
 * @param mixed $thing Something you want cloned
9184
 * @return mixed What ever it is you passed it
9185
 */
9186
function fullclone($thing) {
9187
    return unserialize(serialize($thing));
9188
}
9189
 
9190
/**
9191
 * Used to make sure that $min <= $value <= $max
9192
 *
9193
 * Make sure that value is between min, and max
9194
 *
9195
 * @param int $min The minimum value
9196
 * @param int $value The value to check
9197
 * @param int $max The maximum value
9198
 * @return int
9199
 */
9200
function bounded_number($min, $value, $max) {
9201
    if ($value < $min) {
9202
        return $min;
9203
    }
9204
    if ($value > $max) {
9205
        return $max;
9206
    }
9207
    return $value;
9208
}
9209
 
9210
/**
9211
 * Check if there is a nested array within the passed array
9212
 *
9213
 * @param array $array
9214
 * @return bool true if there is a nested array false otherwise
9215
 */
9216
function array_is_nested($array) {
9217
    foreach ($array as $value) {
9218
        if (is_array($value)) {
9219
            return true;
9220
        }
9221
    }
9222
    return false;
9223
}
9224
 
9225
/**
9226
 * get_performance_info() pairs up with init_performance_info()
9227
 * loaded in setup.php. Returns an array with 'html' and 'txt'
9228
 * values ready for use, and each of the individual stats provided
9229
 * separately as well.
9230
 *
9231
 * @return array
9232
 */
9233
function get_performance_info() {
9234
    global $CFG, $PERF, $DB, $PAGE;
9235
 
9236
    $info = array();
9237
    $info['txt']  = me() . ' '; // Holds log-friendly representation.
9238
 
9239
    $info['html'] = '';
9240
    if (!empty($CFG->themedesignermode)) {
9241
        // Attempt to avoid devs debugging peformance issues, when its caused by css building and so on.
9242
        $info['html'] .= '<p><strong>Warning: Theme designer mode is enabled.</strong></p>';
9243
    }
9244
    $info['html'] .= '<ul class="list-unstyled row mx-md-0">';         // Holds userfriendly HTML representation.
9245
 
9246
    $info['realtime'] = microtime_diff($PERF->starttime, microtime());
9247
 
9248
    $info['html'] .= '<li class="timeused col-sm-4">'.$info['realtime'].' secs</li> ';
9249
    $info['txt'] .= 'time: '.$info['realtime'].'s ';
9250
 
9251
    // GET/POST (or NULL if $_SERVER['REQUEST_METHOD'] is undefined) is useful for txt logged information.
9252
    $info['txt'] .= 'method: ' . ($_SERVER['REQUEST_METHOD'] ?? "NULL") . ' ';
9253
 
9254
    if (function_exists('memory_get_usage')) {
9255
        $info['memory_total'] = memory_get_usage();
9256
        $info['memory_growth'] = memory_get_usage() - $PERF->startmemory;
9257
        $info['html'] .= '<li class="memoryused col-sm-4">RAM: '.display_size($info['memory_total']).'</li> ';
9258
        $info['txt']  .= 'memory_total: '.$info['memory_total'].'B (' . display_size($info['memory_total']).') memory_growth: '.
9259
            $info['memory_growth'].'B ('.display_size($info['memory_growth']).') ';
9260
    }
9261
 
9262
    if (function_exists('memory_get_peak_usage')) {
9263
        $info['memory_peak'] = memory_get_peak_usage();
9264
        $info['html'] .= '<li class="memoryused col-sm-4">RAM peak: '.display_size($info['memory_peak']).'</li> ';
9265
        $info['txt']  .= 'memory_peak: '.$info['memory_peak'].'B (' . display_size($info['memory_peak']).') ';
9266
    }
9267
 
9268
    $info['html'] .= '</ul><ul class="list-unstyled row mx-md-0">';
9269
    $inc = get_included_files();
9270
    $info['includecount'] = count($inc);
9271
    $info['html'] .= '<li class="included col-sm-4">Included '.$info['includecount'].' files</li> ';
9272
    $info['txt']  .= 'includecount: '.$info['includecount'].' ';
9273
 
9274
    if (!empty($CFG->early_install_lang) or empty($PAGE)) {
9275
        // We can not track more performance before installation or before PAGE init, sorry.
9276
        return $info;
9277
    }
9278
 
9279
    $filtermanager = filter_manager::instance();
9280
    if (method_exists($filtermanager, 'get_performance_summary')) {
9281
        list($filterinfo, $nicenames) = $filtermanager->get_performance_summary();
9282
        $info = array_merge($filterinfo, $info);
9283
        foreach ($filterinfo as $key => $value) {
9284
            $info['html'] .= "<li class='$key col-sm-4'>$nicenames[$key]: $value </li> ";
9285
            $info['txt'] .= "$key: $value ";
9286
        }
9287
    }
9288
 
9289
    $stringmanager = get_string_manager();
9290
    if (method_exists($stringmanager, 'get_performance_summary')) {
9291
        list($filterinfo, $nicenames) = $stringmanager->get_performance_summary();
9292
        $info = array_merge($filterinfo, $info);
9293
        foreach ($filterinfo as $key => $value) {
9294
            $info['html'] .= "<li class='$key col-sm-4'>$nicenames[$key]: $value </li> ";
9295
            $info['txt'] .= "$key: $value ";
9296
        }
9297
    }
9298
 
9299
    $info['dbqueries'] = $DB->perf_get_reads().'/'.$DB->perf_get_writes();
9300
    $info['html'] .= '<li class="dbqueries col-sm-4">DB reads/writes: '.$info['dbqueries'].'</li> ';
9301
    $info['txt'] .= 'db reads/writes: '.$info['dbqueries'].' ';
9302
 
9303
    if ($DB->want_read_slave()) {
9304
        $info['dbreads_slave'] = $DB->perf_get_reads_slave();
9305
        $info['html'] .= '<li class="dbqueries col-sm-4">DB reads from slave: '.$info['dbreads_slave'].'</li> ';
9306
        $info['txt'] .= 'db reads from slave: '.$info['dbreads_slave'].' ';
9307
    }
9308
 
9309
    $info['dbtime'] = round($DB->perf_get_queries_time(), 5);
9310
    $info['html'] .= '<li class="dbtime col-sm-4">DB queries time: '.$info['dbtime'].' secs</li> ';
9311
    $info['txt'] .= 'db queries time: ' . $info['dbtime'] . 's ';
9312
 
9313
    if (function_exists('posix_times')) {
9314
        $ptimes = posix_times();
9315
        if (is_array($ptimes)) {
9316
            foreach ($ptimes as $key => $val) {
9317
                $info[$key] = $ptimes[$key] -  $PERF->startposixtimes[$key];
9318
            }
9319
            $info['html'] .= "<li class=\"posixtimes col-sm-4\">ticks: $info[ticks] user: $info[utime]";
9320
            $info['html'] .= "sys: $info[stime] cuser: $info[cutime] csys: $info[cstime]</li> ";
9321
            $info['txt'] .= "ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime] ";
9322
        }
9323
    }
9324
 
9325
    // Grab the load average for the last minute.
9326
    // /proc will only work under some linux configurations
9327
    // while uptime is there under MacOSX/Darwin and other unices.
9328
    if (is_readable('/proc/loadavg') && $loadavg = @file('/proc/loadavg')) {
9329
        list($serverload) = explode(' ', $loadavg[0]);
9330
        unset($loadavg);
9331
    } else if ( function_exists('is_executable') && is_executable('/usr/bin/uptime') && $loadavg = `/usr/bin/uptime` ) {
9332
        if (preg_match('/load averages?: (\d+[\.,:]\d+)/', $loadavg, $matches)) {
9333
            $serverload = $matches[1];
9334
        } else {
9335
            trigger_error('Could not parse uptime output!');
9336
        }
9337
    }
9338
    if (!empty($serverload)) {
9339
        $info['serverload'] = $serverload;
9340
        $info['html'] .= '<li class="serverload col-sm-4">Load average: '.$info['serverload'].'</li> ';
9341
        $info['txt'] .= "serverload: {$info['serverload']} ";
9342
    }
9343
 
9344
    // Display size of session if session started.
9345
    if ($si = \core\session\manager::get_performance_info()) {
9346
        $info['sessionsize'] = $si['size'];
9347
        $info['html'] .= "<li class=\"serverload col-sm-4\">" . $si['html'] . "</li>";
9348
        $info['txt'] .= $si['txt'];
9349
    }
9350
 
9351
    // Display time waiting for session if applicable.
9352
    if (!empty($PERF->sessionlock['wait'])) {
9353
        $sessionwait = number_format($PERF->sessionlock['wait'], 3) . ' secs';
9354
        $info['html'] .= html_writer::tag('li', 'Session wait: ' . $sessionwait, [
9355
            'class' => 'sessionwait col-sm-4'
9356
        ]);
9357
        $info['txt'] .= 'sessionwait: ' . $sessionwait . ' ';
9358
    }
9359
 
9360
    $info['html'] .= '</ul>';
9361
    $html = '';
9362
    if ($stats = cache_helper::get_stats()) {
9363
 
9364
        $table = new html_table();
9365
        $table->attributes['class'] = 'cachesused table table-dark table-sm w-auto table-bordered';
9366
        $table->head = ['Mode', 'Cache item', 'Static', 'H', 'M', get_string('mappingprimary', 'cache'), 'H', 'M', 'S', 'I/O'];
9367
        $table->data = [];
9368
        $table->align = ['left', 'left', 'left', 'right', 'right', 'left', 'right', 'right', 'right', 'right'];
9369
 
9370
        $text = 'Caches used (hits/misses/sets): ';
9371
        $hits = 0;
9372
        $misses = 0;
9373
        $sets = 0;
9374
        $maxstores = 0;
9375
 
9376
        // We want to align static caches into their own column.
9377
        $hasstatic = false;
9378
        foreach ($stats as $definition => $details) {
9379
            $numstores = count($details['stores']);
9380
            $first = key($details['stores']);
9381
            if ($first !== cache_store::STATIC_ACCEL) {
9382
                $numstores++; // Add a blank space for the missing static store.
9383
            }
9384
            $maxstores = max($maxstores, $numstores);
9385
        }
9386
 
9387
        $storec = 0;
9388
 
9389
        while ($storec++ < ($maxstores - 2)) {
9390
            if ($storec == ($maxstores - 2)) {
9391
                $table->head[] = get_string('mappingfinal', 'cache');
9392
            } else {
9393
                $table->head[] = "Store $storec";
9394
            }
9395
            $table->align[] = 'left';
9396
            $table->align[] = 'right';
9397
            $table->align[] = 'right';
9398
            $table->align[] = 'right';
9399
            $table->align[] = 'right';
9400
            $table->head[] = 'H';
9401
            $table->head[] = 'M';
9402
            $table->head[] = 'S';
9403
            $table->head[] = 'I/O';
9404
        }
9405
 
9406
        ksort($stats);
9407
 
9408
        foreach ($stats as $definition => $details) {
9409
            switch ($details['mode']) {
9410
                case cache_store::MODE_APPLICATION:
9411
                    $modeclass = 'application';
9412
                    $mode = ' <span title="application cache">App</span>';
9413
                    break;
9414
                case cache_store::MODE_SESSION:
9415
                    $modeclass = 'session';
9416
                    $mode = ' <span title="session cache">Ses</span>';
9417
                    break;
9418
                case cache_store::MODE_REQUEST:
9419
                    $modeclass = 'request';
9420
                    $mode = ' <span title="request cache">Req</span>';
9421
                    break;
9422
            }
9423
            $row = [$mode, $definition];
9424
 
9425
            $text .= "$definition {";
9426
 
9427
            $storec = 0;
9428
            foreach ($details['stores'] as $store => $data) {
9429
 
9430
                if ($storec == 0 && $store !== cache_store::STATIC_ACCEL) {
9431
                    $row[] = '';
9432
                    $row[] = '';
9433
                    $row[] = '';
9434
                    $storec++;
9435
                }
9436
 
9437
                $hits   += $data['hits'];
9438
                $misses += $data['misses'];
9439
                $sets   += $data['sets'];
9440
                if ($data['hits'] == 0 and $data['misses'] > 0) {
9441
                    $cachestoreclass = 'nohits bg-danger';
9442
                } else if ($data['hits'] < $data['misses']) {
9443
                    $cachestoreclass = 'lowhits bg-warning text-dark';
9444
                } else {
9445
                    $cachestoreclass = 'hihits';
9446
                }
9447
                $text .= "$store($data[hits]/$data[misses]/$data[sets]) ";
9448
                $cell = new html_table_cell($store);
9449
                $cell->attributes = ['class' => $cachestoreclass];
9450
                $row[] = $cell;
9451
                $cell = new html_table_cell($data['hits']);
9452
                $cell->attributes = ['class' => $cachestoreclass];
9453
                $row[] = $cell;
9454
                $cell = new html_table_cell($data['misses']);
9455
                $cell->attributes = ['class' => $cachestoreclass];
9456
                $row[] = $cell;
9457
 
9458
                if ($store !== cache_store::STATIC_ACCEL) {
9459
                    // The static cache is never set.
9460
                    $cell = new html_table_cell($data['sets']);
9461
                    $cell->attributes = ['class' => $cachestoreclass];
9462
                    $row[] = $cell;
9463
 
9464
                    if ($data['hits'] || $data['sets']) {
9465
                        if ($data['iobytes'] === cache_store::IO_BYTES_NOT_SUPPORTED) {
9466
                            $size = '-';
9467
                        } else {
9468
                            $size = display_size($data['iobytes'], 1, 'KB');
9469
                            if ($data['iobytes'] >= 10 * 1024) {
9470
                                $cachestoreclass = ' bg-warning text-dark';
9471
                            }
9472
                        }
9473
                    } else {
9474
                        $size = '';
9475
                    }
9476
                    $cell = new html_table_cell($size);
9477
                    $cell->attributes = ['class' => $cachestoreclass];
9478
                    $row[] = $cell;
9479
                }
9480
                $storec++;
9481
            }
9482
            while ($storec++ < $maxstores) {
9483
                $row[] = '';
9484
                $row[] = '';
9485
                $row[] = '';
9486
                $row[] = '';
9487
                $row[] = '';
9488
            }
9489
            $text .= '} ';
9490
 
9491
            $table->data[] = $row;
9492
        }
9493
 
9494
        $html .= html_writer::table($table);
9495
 
9496
        // Now lets also show sub totals for each cache store.
9497
        $storetotals = [];
9498
        $storetotal = ['hits' => 0, 'misses' => 0, 'sets' => 0, 'iobytes' => 0];
9499
        foreach ($stats as $definition => $details) {
9500
            foreach ($details['stores'] as $store => $data) {
9501
                if (!array_key_exists($store, $storetotals)) {
9502
                    $storetotals[$store] = ['hits' => 0, 'misses' => 0, 'sets' => 0, 'iobytes' => 0];
9503
                }
9504
                $storetotals[$store]['class']   = $data['class'];
9505
                $storetotals[$store]['hits']   += $data['hits'];
9506
                $storetotals[$store]['misses'] += $data['misses'];
9507
                $storetotals[$store]['sets']   += $data['sets'];
9508
                $storetotal['hits']   += $data['hits'];
9509
                $storetotal['misses'] += $data['misses'];
9510
                $storetotal['sets']   += $data['sets'];
9511
                if ($data['iobytes'] !== cache_store::IO_BYTES_NOT_SUPPORTED) {
9512
                    $storetotals[$store]['iobytes'] += $data['iobytes'];
9513
                    $storetotal['iobytes'] += $data['iobytes'];
9514
                }
9515
            }
9516
        }
9517
 
9518
        $table = new html_table();
9519
        $table->attributes['class'] = 'cachesused table table-dark table-sm w-auto table-bordered';
9520
        $table->head = [get_string('storename', 'cache'), get_string('type_cachestore', 'plugin'), 'H', 'M', 'S', 'I/O'];
9521
        $table->data = [];
9522
        $table->align = ['left', 'left', 'right', 'right', 'right', 'right'];
9523
 
9524
        ksort($storetotals);
9525
 
9526
        foreach ($storetotals as $store => $data) {
9527
            $row = [];
9528
            if ($data['hits'] == 0 and $data['misses'] > 0) {
9529
                $cachestoreclass = 'nohits bg-danger';
9530
            } else if ($data['hits'] < $data['misses']) {
9531
                $cachestoreclass = 'lowhits bg-warning text-dark';
9532
            } else {
9533
                $cachestoreclass = 'hihits';
9534
            }
9535
            $cell = new html_table_cell($store);
9536
            $cell->attributes = ['class' => $cachestoreclass];
9537
            $row[] = $cell;
9538
            $cell = new html_table_cell($data['class']);
9539
            $cell->attributes = ['class' => $cachestoreclass];
9540
            $row[] = $cell;
9541
            $cell = new html_table_cell($data['hits']);
9542
            $cell->attributes = ['class' => $cachestoreclass];
9543
            $row[] = $cell;
9544
            $cell = new html_table_cell($data['misses']);
9545
            $cell->attributes = ['class' => $cachestoreclass];
9546
            $row[] = $cell;
9547
            $cell = new html_table_cell($data['sets']);
9548
            $cell->attributes = ['class' => $cachestoreclass];
9549
            $row[] = $cell;
9550
            if ($data['hits'] || $data['sets']) {
9551
                if ($data['iobytes']) {
9552
                    $size = display_size($data['iobytes'], 1, 'KB');
9553
                } else {
9554
                    $size = '-';
9555
                }
9556
            } else {
9557
                $size = '';
9558
            }
9559
            $cell = new html_table_cell($size);
9560
            $cell->attributes = ['class' => $cachestoreclass];
9561
            $row[] = $cell;
9562
            $table->data[] = $row;
9563
        }
9564
        if (!empty($storetotal['iobytes'])) {
9565
            $size = display_size($storetotal['iobytes'], 1, 'KB');
9566
        } else if (!empty($storetotal['hits']) || !empty($storetotal['sets'])) {
9567
            $size = '-';
9568
        } else {
9569
            $size = '';
9570
        }
9571
        $row = [
9572
            get_string('total'),
9573
            '',
9574
            $storetotal['hits'],
9575
            $storetotal['misses'],
9576
            $storetotal['sets'],
9577
            $size,
9578
        ];
9579
        $table->data[] = $row;
9580
 
9581
        $html .= html_writer::table($table);
9582
 
9583
        $info['cachesused'] = "$hits / $misses / $sets";
9584
        $info['html'] .= $html;
9585
        $info['txt'] .= $text.'. ';
9586
    } else {
9587
        $info['cachesused'] = '0 / 0 / 0';
9588
        $info['html'] .= '<div class="cachesused">Caches used (hits/misses/sets): 0/0/0</div>';
9589
        $info['txt'] .= 'Caches used (hits/misses/sets): 0/0/0 ';
9590
    }
9591
 
9592
    // Display lock information if any.
9593
    if (!empty($PERF->locks)) {
9594
        $table = new html_table();
9595
        $table->attributes['class'] = 'locktimings table table-dark table-sm w-auto table-bordered';
9596
        $table->head = ['Lock', 'Waited (s)', 'Obtained', 'Held for (s)'];
9597
        $table->align = ['left', 'right', 'center', 'right'];
9598
        $table->data = [];
9599
        $text = 'Locks (waited/obtained/held):';
9600
        foreach ($PERF->locks as $locktiming) {
9601
            $row = [];
9602
            $row[] = s($locktiming->type . '/' . $locktiming->resource);
9603
            $text .= ' ' . $locktiming->type . '/' . $locktiming->resource . ' (';
9604
 
9605
            // The time we had to wait to get the lock.
9606
            $roundedtime = number_format($locktiming->wait, 1);
9607
            $cell = new html_table_cell($roundedtime);
9608
            if ($locktiming->wait > 0.5) {
9609
                $cell->attributes = ['class' => 'bg-warning text-dark'];
9610
            }
9611
            $row[] = $cell;
9612
            $text .= $roundedtime . '/';
9613
 
9614
            // Show a tick or cross for success.
9615
            $row[] = $locktiming->success ? '&#x2713;' : '&#x274c;';
9616
            $text .= ($locktiming->success ? 'y' : 'n') . '/';
9617
 
9618
            // If applicable, show how long we held the lock before releasing it.
9619
            if (property_exists($locktiming, 'held')) {
9620
                $roundedtime = number_format($locktiming->held, 1);
9621
                $cell = new html_table_cell($roundedtime);
9622
                if ($locktiming->held > 0.5) {
9623
                    $cell->attributes = ['class' => 'bg-warning text-dark'];
9624
                }
9625
                $row[] = $cell;
9626
                $text .= $roundedtime;
9627
            } else {
9628
                $row[] = '-';
9629
                $text .= '-';
9630
            }
9631
            $text .= ')';
9632
 
9633
            $table->data[] = $row;
9634
        }
9635
        $info['html'] .= html_writer::table($table);
9636
        $info['txt'] .= $text . '. ';
9637
    }
9638
 
9639
    $info['html'] = '<div class="performanceinfo siteinfo container-fluid px-md-0 overflow-auto pt-3">'.$info['html'].'</div>';
9640
    return $info;
9641
}
9642
 
9643
/**
9644
 * Renames a file or directory to a unique name within the same directory.
9645
 *
9646
 * This function is designed to avoid any potential race conditions, and select an unused name.
9647
 *
9648
 * @param string $filepath Original filepath
9649
 * @param string $prefix Prefix to use for the temporary name
9650
 * @return string|bool New file path or false if failed
9651
 * @since Moodle 3.10
9652
 */
9653
function rename_to_unused_name(string $filepath, string $prefix = '_temp_') {
9654
    $dir = dirname($filepath);
9655
    $basename = $dir . '/' . $prefix;
9656
    $limit = 0;
9657
    while ($limit < 100) {
9658
        // Select a new name based on a random number.
9659
        $newfilepath = $basename . md5(mt_rand());
9660
 
9661
        // Attempt a rename to that new name.
9662
        if (@rename($filepath, $newfilepath)) {
9663
            return $newfilepath;
9664
        }
9665
 
9666
        // The first time, do some sanity checks, maybe it is failing for a good reason and there
9667
        // is no point trying 100 times if so.
9668
        if ($limit === 0 && (!file_exists($filepath) || !is_writable($dir))) {
9669
            return false;
9670
        }
9671
        $limit++;
9672
    }
9673
    return false;
9674
}
9675
 
9676
/**
9677
 * Delete directory or only its content
9678
 *
9679
 * @param string $dir directory path
9680
 * @param bool $contentonly
9681
 * @return bool success, true also if dir does not exist
9682
 */
9683
function remove_dir($dir, $contentonly=false) {
9684
    if (!is_dir($dir)) {
9685
        // Nothing to do.
9686
        return true;
9687
    }
9688
 
9689
    if (!$contentonly) {
9690
        // Start by renaming the directory; this will guarantee that other processes don't write to it
9691
        // while it is in the process of being deleted.
9692
        $tempdir = rename_to_unused_name($dir);
9693
        if ($tempdir) {
9694
            // If the rename was successful then delete the $tempdir instead.
9695
            $dir = $tempdir;
9696
        }
9697
        // If the rename fails, we will continue through and attempt to delete the directory
9698
        // without renaming it since that is likely to at least delete most of the files.
9699
    }
9700
 
9701
    if (!$handle = opendir($dir)) {
9702
        return false;
9703
    }
9704
    $result = true;
9705
    while (false!==($item = readdir($handle))) {
9706
        if ($item != '.' && $item != '..') {
9707
            if (is_dir($dir.'/'.$item)) {
9708
                $result = remove_dir($dir.'/'.$item) && $result;
9709
            } else {
9710
                $result = unlink($dir.'/'.$item) && $result;
9711
            }
9712
        }
9713
    }
9714
    closedir($handle);
9715
    if ($contentonly) {
9716
        clearstatcache(); // Make sure file stat cache is properly invalidated.
9717
        return $result;
9718
    }
9719
    $result = rmdir($dir); // If anything left the result will be false, no need for && $result.
9720
    clearstatcache(); // Make sure file stat cache is properly invalidated.
9721
    return $result;
9722
}
9723
 
9724
/**
9725
 * Detect if an object or a class contains a given property
9726
 * will take an actual object or the name of a class
9727
 *
9728
 * @param mixed $obj Name of class or real object to test
9729
 * @param string $property name of property to find
9730
 * @return bool true if property exists
9731
 */
9732
function object_property_exists( $obj, $property ) {
9733
    if (is_string( $obj )) {
9734
        $properties = get_class_vars( $obj );
9735
    } else {
9736
        $properties = get_object_vars( $obj );
9737
    }
9738
    return array_key_exists( $property, $properties );
9739
}
9740
 
9741
/**
9742
 * Converts an object into an associative array
9743
 *
9744
 * This function converts an object into an associative array by iterating
9745
 * over its public properties. Because this function uses the foreach
9746
 * construct, Iterators are respected. It works recursively on arrays of objects.
9747
 * Arrays and simple values are returned as is.
9748
 *
9749
 * If class has magic properties, it can implement IteratorAggregate
9750
 * and return all available properties in getIterator()
9751
 *
9752
 * @param mixed $var
9753
 * @return array
9754
 */
9755
function convert_to_array($var) {
9756
    $result = array();
9757
 
9758
    // Loop over elements/properties.
9759
    foreach ($var as $key => $value) {
9760
        // Recursively convert objects.
9761
        if (is_object($value) || is_array($value)) {
9762
            $result[$key] = convert_to_array($value);
9763
        } else {
9764
            // Simple values are untouched.
9765
            $result[$key] = $value;
9766
        }
9767
    }
9768
    return $result;
9769
}
9770
 
9771
/**
9772
 * Detect a custom script replacement in the data directory that will
9773
 * replace an existing moodle script
9774
 *
9775
 * @return string|bool full path name if a custom script exists, false if no custom script exists
9776
 */
9777
function custom_script_path() {
9778
    global $CFG, $SCRIPT;
9779
 
9780
    if ($SCRIPT === null) {
9781
        // Probably some weird external script.
9782
        return false;
9783
    }
9784
 
9785
    $scriptpath = $CFG->customscripts . $SCRIPT;
9786
 
9787
    // Check the custom script exists.
9788
    if (file_exists($scriptpath) and is_file($scriptpath)) {
9789
        return $scriptpath;
9790
    } else {
9791
        return false;
9792
    }
9793
}
9794
 
9795
/**
9796
 * Returns whether or not the user object is a remote MNET user. This function
9797
 * is in moodlelib because it does not rely on loading any of the MNET code.
9798
 *
9799
 * @param object $user A valid user object
9800
 * @return bool        True if the user is from a remote Moodle.
9801
 */
9802
function is_mnet_remote_user($user) {
9803
    global $CFG;
9804
 
9805
    if (!isset($CFG->mnet_localhost_id)) {
9806
        include_once($CFG->dirroot . '/mnet/lib.php');
9807
        $env = new mnet_environment();
9808
        $env->init();
9809
        unset($env);
9810
    }
9811
 
9812
    return (!empty($user->mnethostid) && $user->mnethostid != $CFG->mnet_localhost_id);
9813
}
9814
 
9815
/**
9816
 * This function will search for browser prefereed languages, setting Moodle
9817
 * to use the best one available if $SESSION->lang is undefined
9818
 */
9819
function setup_lang_from_browser() {
9820
    global $CFG, $SESSION, $USER;
9821
 
9822
    if (!empty($SESSION->lang) or !empty($USER->lang) or empty($CFG->autolang)) {
9823
        // Lang is defined in session or user profile, nothing to do.
9824
        return;
9825
    }
9826
 
9827
    if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { // There isn't list of browser langs, nothing to do.
9828
        return;
9829
    }
9830
 
9831
    // Extract and clean langs from headers.
9832
    $rawlangs = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
9833
    $rawlangs = str_replace('-', '_', $rawlangs);         // We are using underscores.
9834
    $rawlangs = explode(',', $rawlangs);                  // Convert to array.
9835
    $langs = array();
9836
 
9837
    $order = 1.0;
9838
    foreach ($rawlangs as $lang) {
9839
        if (strpos($lang, ';') === false) {
9840
            $langs[(string)$order] = $lang;
9841
            $order = $order-0.01;
9842
        } else {
9843
            $parts = explode(';', $lang);
9844
            $pos = strpos($parts[1], '=');
9845
            $langs[substr($parts[1], $pos+1)] = $parts[0];
9846
        }
9847
    }
9848
    krsort($langs, SORT_NUMERIC);
9849
 
9850
    // Look for such langs under standard locations.
9851
    foreach ($langs as $lang) {
9852
        // Clean it properly for include.
9853
        $lang = strtolower(clean_param($lang, PARAM_SAFEDIR));
9854
        if (get_string_manager()->translation_exists($lang, false)) {
9855
            // If the translation for this language exists then try to set it
9856
            // for the rest of the session, if this is a read only session then
9857
            // we can only set it temporarily in $CFG.
9858
            if (defined('READ_ONLY_SESSION') && !empty($CFG->enable_read_only_sessions)) {
9859
                $CFG->lang = $lang;
9860
            } else {
9861
                $SESSION->lang = $lang;
9862
            }
9863
            // We have finished. Go out.
9864
            break;
9865
        }
9866
    }
9867
    return;
9868
}
9869
 
9870
/**
9871
 * Check if $url matches anything in proxybypass list
9872
 *
9873
 * Any errors just result in the proxy being used (least bad)
9874
 *
9875
 * @param string $url url to check
9876
 * @return boolean true if we should bypass the proxy
9877
 */
9878
function is_proxybypass( $url ) {
9879
    global $CFG;
9880
 
9881
    // Sanity check.
9882
    if (empty($CFG->proxyhost) or empty($CFG->proxybypass)) {
9883
        return false;
9884
    }
9885
 
9886
    // Get the host part out of the url.
9887
    if (!$host = parse_url( $url, PHP_URL_HOST )) {
9888
        return false;
9889
    }
9890
 
9891
    // Get the possible bypass hosts into an array.
9892
    $matches = explode( ',', $CFG->proxybypass );
9893
 
9894
    // Check for a exact match on the IP or in the domains.
9895
    $isdomaininallowedlist = \core\ip_utils::is_domain_in_allowed_list($host, $matches);
9896
    $isipinsubnetlist = \core\ip_utils::is_ip_in_subnet_list($host, $CFG->proxybypass, ',');
9897
 
9898
    if ($isdomaininallowedlist || $isipinsubnetlist) {
9899
        return true;
9900
    }
9901
 
9902
    // Nothing matched.
9903
    return false;
9904
}
9905
 
9906
/**
9907
 * Check if the passed navigation is of the new style
9908
 *
9909
 * @param mixed $navigation
9910
 * @return bool true for yes false for no
9911
 */
9912
function is_newnav($navigation) {
9913
    if (is_array($navigation) && !empty($navigation['newnav'])) {
9914
        return true;
9915
    } else {
9916
        return false;
9917
    }
9918
}
9919
 
9920
/**
9921
 * Checks whether the given variable name is defined as a variable within the given object.
9922
 *
9923
 * This will NOT work with stdClass objects, which have no class variables.
9924
 *
9925
 * @param string $var The variable name
9926
 * @param object $object The object to check
9927
 * @return boolean
9928
 */
9929
function in_object_vars($var, $object) {
9930
    $classvars = get_class_vars(get_class($object));
9931
    $classvars = array_keys($classvars);
9932
    return in_array($var, $classvars);
9933
}
9934
 
9935
/**
9936
 * Returns an array without repeated objects.
9937
 * This function is similar to array_unique, but for arrays that have objects as values
9938
 *
9939
 * @param array $array
9940
 * @param bool $keepkeyassoc
9941
 * @return array
9942
 */
9943
function object_array_unique($array, $keepkeyassoc = true) {
9944
    $duplicatekeys = array();
9945
    $tmp         = array();
9946
 
9947
    foreach ($array as $key => $val) {
9948
        // Convert objects to arrays, in_array() does not support objects.
9949
        if (is_object($val)) {
9950
            $val = (array)$val;
9951
        }
9952
 
9953
        if (!in_array($val, $tmp)) {
9954
            $tmp[] = $val;
9955
        } else {
9956
            $duplicatekeys[] = $key;
9957
        }
9958
    }
9959
 
9960
    foreach ($duplicatekeys as $key) {
9961
        unset($array[$key]);
9962
    }
9963
 
9964
    return $keepkeyassoc ? $array : array_values($array);
9965
}
9966
 
9967
/**
9968
 * Is a userid the primary administrator?
9969
 *
9970
 * @param int $userid int id of user to check
9971
 * @return boolean
9972
 */
9973
function is_primary_admin($userid) {
9974
    $primaryadmin =  get_admin();
9975
 
9976
    if ($userid == $primaryadmin->id) {
9977
        return true;
9978
    } else {
9979
        return false;
9980
    }
9981
}
9982
 
9983
/**
9984
 * Returns the site identifier
9985
 *
9986
 * @return string $CFG->siteidentifier, first making sure it is properly initialised.
9987
 */
9988
function get_site_identifier() {
9989
    global $CFG;
9990
    // Check to see if it is missing. If so, initialise it.
9991
    if (empty($CFG->siteidentifier)) {
9992
        set_config('siteidentifier', random_string(32) . $_SERVER['HTTP_HOST']);
9993
    }
9994
    // Return it.
9995
    return $CFG->siteidentifier;
9996
}
9997
 
9998
/**
9999
 * Check whether the given password has no more than the specified
10000
 * number of consecutive identical characters.
10001
 *
10002
 * @param string $password   password to be checked against the password policy
10003
 * @param integer $maxchars  maximum number of consecutive identical characters
10004
 * @return bool
10005
 */
10006
function check_consecutive_identical_characters($password, $maxchars) {
10007
 
10008
    if ($maxchars < 1) {
10009
        return true; // Zero 0 is to disable this check.
10010
    }
10011
    if (strlen($password) <= $maxchars) {
10012
        return true; // Too short to fail this test.
10013
    }
10014
 
10015
    $previouschar = '';
10016
    $consecutivecount = 1;
10017
    foreach (str_split($password) as $char) {
10018
        if ($char != $previouschar) {
10019
            $consecutivecount = 1;
10020
        } else {
10021
            $consecutivecount++;
10022
            if ($consecutivecount > $maxchars) {
10023
                return false; // Check failed already.
10024
            }
10025
        }
10026
 
10027
        $previouschar = $char;
10028
    }
10029
 
10030
    return true;
10031
}
10032
 
10033
/**
10034
 * Helper function to do partial function binding.
10035
 * so we can use it for preg_replace_callback, for example
10036
 * this works with php functions, user functions, static methods and class methods
10037
 * it returns you a callback that you can pass on like so:
10038
 *
10039
 * $callback = partial('somefunction', $arg1, $arg2);
10040
 *     or
10041
 * $callback = partial(array('someclass', 'somestaticmethod'), $arg1, $arg2);
10042
 *     or even
10043
 * $obj = new someclass();
10044
 * $callback = partial(array($obj, 'somemethod'), $arg1, $arg2);
10045
 *
10046
 * and then the arguments that are passed through at calltime are appended to the argument list.
10047
 *
10048
 * @param mixed $function a php callback
10049
 * @param mixed $arg1,... $argv arguments to partially bind with
10050
 * @return array Array callback
10051
 */
10052
function partial() {
10053
    if (!class_exists('partial')) {
10054
        /**
10055
         * Used to manage function binding.
10056
         * @copyright  2009 Penny Leach
10057
         * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10058
         */
10059
        class partial{
10060
            /** @var array */
10061
            public $values = array();
10062
            /** @var string The function to call as a callback. */
10063
            public $func;
10064
            /**
10065
             * Constructor
10066
             * @param string $func
10067
             * @param array $args
10068
             */
10069
            public function __construct($func, $args) {
10070
                $this->values = $args;
10071
                $this->func = $func;
10072
            }
10073
            /**
10074
             * Calls the callback function.
10075
             * @return mixed
10076
             */
10077
            public function method() {
10078
                $args = func_get_args();
10079
                return call_user_func_array($this->func, array_merge($this->values, $args));
10080
            }
10081
        }
10082
    }
10083
    $args = func_get_args();
10084
    $func = array_shift($args);
10085
    $p = new partial($func, $args);
10086
    return array($p, 'method');
10087
}
10088
 
10089
/**
10090
 * helper function to load up and initialise the mnet environment
10091
 * this must be called before you use mnet functions.
10092
 *
10093
 * @return mnet_environment the equivalent of old $MNET global
10094
 */
10095
function get_mnet_environment() {
10096
    global $CFG;
10097
    require_once($CFG->dirroot . '/mnet/lib.php');
10098
    static $instance = null;
10099
    if (empty($instance)) {
10100
        $instance = new mnet_environment();
10101
        $instance->init();
10102
    }
10103
    return $instance;
10104
}
10105
 
10106
/**
10107
 * during xmlrpc server code execution, any code wishing to access
10108
 * information about the remote peer must use this to get it.
10109
 *
10110
 * @return mnet_remote_client|false the equivalent of old $MNETREMOTE_CLIENT global
10111
 */
10112
function get_mnet_remote_client() {
10113
    if (!defined('MNET_SERVER')) {
10114
        debugging(get_string('notinxmlrpcserver', 'mnet'));
10115
        return false;
10116
    }
10117
    global $MNET_REMOTE_CLIENT;
10118
    if (isset($MNET_REMOTE_CLIENT)) {
10119
        return $MNET_REMOTE_CLIENT;
10120
    }
10121
    return false;
10122
}
10123
 
10124
/**
10125
 * during the xmlrpc server code execution, this will be called
10126
 * to setup the object returned by {@link get_mnet_remote_client}
10127
 *
10128
 * @param mnet_remote_client $client the client to set up
10129
 * @throws moodle_exception
10130
 */
10131
function set_mnet_remote_client($client) {
10132
    if (!defined('MNET_SERVER')) {
10133
        throw new moodle_exception('notinxmlrpcserver', 'mnet');
10134
    }
10135
    global $MNET_REMOTE_CLIENT;
10136
    $MNET_REMOTE_CLIENT = $client;
10137
}
10138
 
10139
/**
10140
 * return the jump url for a given remote user
10141
 * this is used for rewriting forum post links in emails, etc
10142
 *
10143
 * @param stdclass $user the user to get the idp url for
10144
 */
10145
function mnet_get_idp_jump_url($user) {
10146
    global $CFG;
10147
 
10148
    static $mnetjumps = array();
10149
    if (!array_key_exists($user->mnethostid, $mnetjumps)) {
10150
        $idp = mnet_get_peer_host($user->mnethostid);
10151
        $idpjumppath = mnet_get_app_jumppath($idp->applicationid);
10152
        $mnetjumps[$user->mnethostid] = $idp->wwwroot . $idpjumppath . '?hostwwwroot=' . $CFG->wwwroot . '&wantsurl=';
10153
    }
10154
    return $mnetjumps[$user->mnethostid];
10155
}
10156
 
10157
/**
10158
 * Gets the homepage to use for the current user
10159
 *
10160
 * @return int One of HOMEPAGE_*
10161
 */
10162
function get_home_page() {
10163
    global $CFG;
10164
 
10165
    if (isloggedin() && !isguestuser() && !empty($CFG->defaulthomepage)) {
10166
        // If dashboard is disabled, home will be set to default page.
10167
        $defaultpage = get_default_home_page();
10168
        if ($CFG->defaulthomepage == HOMEPAGE_MY) {
10169
            if (!empty($CFG->enabledashboard)) {
10170
                return HOMEPAGE_MY;
10171
            } else {
10172
                return $defaultpage;
10173
            }
10174
        } else if ($CFG->defaulthomepage == HOMEPAGE_MYCOURSES) {
10175
            return HOMEPAGE_MYCOURSES;
10176
        } else {
10177
            $userhomepage = (int) get_user_preferences('user_home_page_preference', $defaultpage);
10178
            if (empty($CFG->enabledashboard) && $userhomepage == HOMEPAGE_MY) {
10179
                // If the user was using the dashboard but it's disabled, return the default home page.
10180
                $userhomepage = $defaultpage;
10181
            }
10182
            return $userhomepage;
10183
        }
10184
    }
10185
    return HOMEPAGE_SITE;
10186
}
10187
 
10188
/**
10189
 * Returns the default home page to display if current one is not defined or can't be applied.
10190
 * The default behaviour is to return Dashboard if it's enabled or My courses page if it isn't.
10191
 *
10192
 * @return int The default home page.
10193
 */
10194
function get_default_home_page(): int {
10195
    global $CFG;
10196
 
10197
    return (!isset($CFG->enabledashboard) || $CFG->enabledashboard) ? HOMEPAGE_MY : HOMEPAGE_MYCOURSES;
10198
}
10199
 
10200
/**
10201
 * Gets the name of a course to be displayed when showing a list of courses.
10202
 * By default this is just $course->fullname but user can configure it. The
10203
 * result of this function should be passed through print_string.
10204
 * @param stdClass|core_course_list_element $course Moodle course object
10205
 * @return string Display name of course (either fullname or short + fullname)
10206
 */
10207
function get_course_display_name_for_list($course) {
10208
    global $CFG;
10209
    if (!empty($CFG->courselistshortnames)) {
10210
        if (!($course instanceof stdClass)) {
10211
            $course = (object)convert_to_array($course);
10212
        }
10213
        return get_string('courseextendednamedisplay', '', $course);
10214
    } else {
10215
        return $course->fullname;
10216
    }
10217
}
10218
 
10219
/**
10220
 * Safe analogue of unserialize() that can only parse arrays
10221
 *
10222
 * Arrays may contain only integers or strings as both keys and values. Nested arrays are allowed.
10223
 *
10224
 * @param string $expression
10225
 * @return array|bool either parsed array or false if parsing was impossible.
10226
 */
10227
function unserialize_array($expression) {
10228
 
10229
    // Check the expression is an array.
10230
    if (!preg_match('/^a:(\d+):/', $expression)) {
10231
        return false;
10232
    }
10233
 
10234
    $values = (array) unserialize_object($expression);
10235
 
10236
    // Callback that returns true if the given value is an unserialized object, executes recursively.
10237
    $invalidvaluecallback = static function($value) use (&$invalidvaluecallback): bool {
10238
        if (is_array($value)) {
10239
            return (bool) array_filter($value, $invalidvaluecallback);
10240
        }
10241
        return ($value instanceof stdClass) || ($value instanceof __PHP_Incomplete_Class);
10242
    };
10243
 
10244
    // Iterate over the result to ensure there are no stray objects.
10245
    if (array_filter($values, $invalidvaluecallback)) {
10246
        return false;
10247
    }
10248
 
10249
    return $values;
10250
}
10251
 
10252
/**
10253
 * Safe method for unserializing given input that is expected to contain only a serialized instance of an stdClass object
10254
 *
10255
 * If any class type other than stdClass is included in the input string, it will not be instantiated and will be cast to an
10256
 * stdClass object. The initial cast to array, then back to object is to ensure we are always returning the correct type,
10257
 * otherwise we would return an instances of {@see __PHP_Incomplete_class} for malformed strings
10258
 *
10259
 * @param string $input
10260
 * @return stdClass
10261
 */
10262
function unserialize_object(string $input): stdClass {
10263
    $instance = (array) unserialize($input, ['allowed_classes' => [stdClass::class]]);
10264
    return (object) $instance;
10265
}
10266
 
10267
/**
10268
 * The lang_string class
10269
 *
10270
 * This special class is used to create an object representation of a string request.
10271
 * It is special because processing doesn't occur until the object is first used.
10272
 * The class was created especially to aid performance in areas where strings were
10273
 * required to be generated but were not necessarily used.
10274
 * As an example the admin tree when generated uses over 1500 strings, of which
10275
 * normally only 1/3 are ever actually printed at any time.
10276
 * The performance advantage is achieved by not actually processing strings that
10277
 * arn't being used, as such reducing the processing required for the page.
10278
 *
10279
 * How to use the lang_string class?
10280
 *     There are two methods of using the lang_string class, first through the
10281
 *     forth argument of the get_string function, and secondly directly.
10282
 *     The following are examples of both.
10283
 * 1. Through get_string calls e.g.
10284
 *     $string = get_string($identifier, $component, $a, true);
10285
 *     $string = get_string('yes', 'moodle', null, true);
10286
 * 2. Direct instantiation
10287
 *     $string = new lang_string($identifier, $component, $a, $lang);
10288
 *     $string = new lang_string('yes');
10289
 *
10290
 * How do I use a lang_string object?
10291
 *     The lang_string object makes use of a magic __toString method so that you
10292
 *     are able to use the object exactly as you would use a string in most cases.
10293
 *     This means you are able to collect it into a variable and then directly
10294
 *     echo it, or concatenate it into another string, or similar.
10295
 *     The other thing you can do is manually get the string by calling the
10296
 *     lang_strings out method e.g.
10297
 *         $string = new lang_string('yes');
10298
 *         $string->out();
10299
 *     Also worth noting is that the out method can take one argument, $lang which
10300
 *     allows the developer to change the language on the fly.
10301
 *
10302
 * When should I use a lang_string object?
10303
 *     The lang_string object is designed to be used in any situation where a
10304
 *     string may not be needed, but needs to be generated.
10305
 *     The admin tree is a good example of where lang_string objects should be
10306
 *     used.
10307
 *     A more practical example would be any class that requries strings that may
10308
 *     not be printed (after all classes get renderer by renderers and who knows
10309
 *     what they will do ;))
10310
 *
10311
 * When should I not use a lang_string object?
10312
 *     Don't use lang_strings when you are going to use a string immediately.
10313
 *     There is no need as it will be processed immediately and there will be no
10314
 *     advantage, and in fact perhaps a negative hit as a class has to be
10315
 *     instantiated for a lang_string object, however get_string won't require
10316
 *     that.
10317
 *
10318
 * Limitations:
10319
 * 1. You cannot use a lang_string object as an array offset. Doing so will
10320
 *     result in PHP throwing an error. (You can use it as an object property!)
10321
 *
10322
 * @package    core
10323
 * @category   string
10324
 * @copyright  2011 Sam Hemelryk
10325
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10326
 */
10327
class lang_string {
10328
 
10329
    /** @var string The strings identifier */
10330
    protected $identifier;
10331
    /** @var string The strings component. Default '' */
10332
    protected $component = '';
10333
    /** @var array|stdClass Any arguments required for the string. Default null */
10334
    protected $a = null;
10335
    /** @var string The language to use when processing the string. Default null */
10336
    protected $lang = null;
10337
 
10338
    /** @var string The processed string (once processed) */
10339
    protected $string = null;
10340
 
10341
    /**
10342
     * A special boolean. If set to true then the object has been woken up and
10343
     * cannot be regenerated. If this is set then $this->string MUST be used.
10344
     * @var bool
10345
     */
10346
    protected $forcedstring = false;
10347
 
10348
    /**
10349
     * Constructs a lang_string object
10350
     *
10351
     * This function should do as little processing as possible to ensure the best
10352
     * performance for strings that won't be used.
10353
     *
10354
     * @param string $identifier The strings identifier
10355
     * @param string $component The strings component
10356
     * @param stdClass|array|mixed $a Any arguments the string requires
10357
     * @param string $lang The language to use when processing the string.
10358
     * @throws coding_exception
10359
     */
10360
    public function __construct($identifier, $component = '', $a = null, $lang = null) {
10361
        if (empty($component)) {
10362
            $component = 'moodle';
10363
        }
10364
 
10365
        $this->identifier = $identifier;
10366
        $this->component = $component;
10367
        $this->lang = $lang;
10368
 
10369
        // We MUST duplicate $a to ensure that it if it changes by reference those
10370
        // changes are not carried across.
10371
        // To do this we always ensure $a or its properties/values are strings
10372
        // and that any properties/values that arn't convertable are forgotten.
10373
        if ($a !== null) {
10374
            if (is_scalar($a)) {
10375
                $this->a = $a;
10376
            } else if ($a instanceof lang_string) {
10377
                $this->a = $a->out();
10378
            } else if (is_object($a) or is_array($a)) {
10379
                $a = (array)$a;
10380
                $this->a = array();
10381
                foreach ($a as $key => $value) {
10382
                    // Make sure conversion errors don't get displayed (results in '').
10383
                    if (is_array($value)) {
10384
                        $this->a[$key] = '';
10385
                    } else if (is_object($value)) {
10386
                        if (method_exists($value, '__toString')) {
10387
                            $this->a[$key] = $value->__toString();
10388
                        } else {
10389
                            $this->a[$key] = '';
10390
                        }
10391
                    } else {
10392
                        $this->a[$key] = (string)$value;
10393
                    }
10394
                }
10395
            }
10396
        }
10397
 
10398
        if (debugging(false, DEBUG_DEVELOPER)) {
10399
            if (clean_param($this->identifier, PARAM_STRINGID) == '') {
10400
                throw new coding_exception('Invalid string identifier. Most probably some illegal character is part of the string identifier. Please check your string definition');
10401
            }
10402
            if (!empty($this->component) && clean_param($this->component, PARAM_COMPONENT) == '') {
10403
                throw new coding_exception('Invalid string compontent. Please check your string definition');
10404
            }
10405
            if (!get_string_manager()->string_exists($this->identifier, $this->component)) {
10406
                debugging('String does not exist. Please check your string definition for '.$this->identifier.'/'.$this->component, DEBUG_DEVELOPER);
10407
            }
10408
        }
10409
    }
10410
 
10411
    /**
10412
     * Processes the string.
10413
     *
10414
     * This function actually processes the string, stores it in the string property
10415
     * and then returns it.
10416
     * You will notice that this function is VERY similar to the get_string method.
10417
     * That is because it is pretty much doing the same thing.
10418
     * However as this function is an upgrade it isn't as tolerant to backwards
10419
     * compatibility.
10420
     *
10421
     * @return string
10422
     * @throws coding_exception
10423
     */
10424
    protected function get_string() {
10425
        global $CFG;
10426
 
10427
        // Check if we need to process the string.
10428
        if ($this->string === null) {
10429
            // Check the quality of the identifier.
10430
            if ($CFG->debugdeveloper && clean_param($this->identifier, PARAM_STRINGID) === '') {
10431
                throw new coding_exception('Invalid string identifier. Most probably some illegal character is part of the string identifier. Please check your string definition', DEBUG_DEVELOPER);
10432
            }
10433
 
10434
            // Process the string.
10435
            $this->string = get_string_manager()->get_string($this->identifier, $this->component, $this->a, $this->lang);
10436
            // Debugging feature lets you display string identifier and component.
10437
            if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
10438
                $this->string .= ' {' . $this->identifier . '/' . $this->component . '}';
10439
            }
10440
        }
10441
        // Return the string.
10442
        return $this->string;
10443
    }
10444
 
10445
    /**
10446
     * Returns the string
10447
     *
10448
     * @param string $lang The langauge to use when processing the string
10449
     * @return string
10450
     */
10451
    public function out($lang = null) {
10452
        if ($lang !== null && $lang != $this->lang && ($this->lang == null && $lang != current_language())) {
10453
            if ($this->forcedstring) {
10454
                debugging('lang_string objects that have been used cannot be printed in another language. ('.$this->lang.' used)', DEBUG_DEVELOPER);
10455
                return $this->get_string();
10456
            }
10457
            $translatedstring = new lang_string($this->identifier, $this->component, $this->a, $lang);
10458
            return $translatedstring->out();
10459
        }
10460
        return $this->get_string();
10461
    }
10462
 
10463
    /**
10464
     * Magic __toString method for printing a string
10465
     *
10466
     * @return string
10467
     */
10468
    public function __toString() {
10469
        return $this->get_string();
10470
    }
10471
 
10472
    /**
10473
     * Magic __set_state method used for var_export
10474
     *
10475
     * @param array $array
10476
     * @return self
10477
     */
10478
    public static function __set_state(array $array): self {
10479
        $tmp = new lang_string($array['identifier'], $array['component'], $array['a'], $array['lang']);
10480
        $tmp->string = $array['string'];
10481
        $tmp->forcedstring = $array['forcedstring'];
10482
        return $tmp;
10483
    }
10484
 
10485
    /**
10486
     * Prepares the lang_string for sleep and stores only the forcedstring and
10487
     * string properties... the string cannot be regenerated so we need to ensure
10488
     * it is generated for this.
10489
     *
10490
     * @return array
10491
     */
10492
    public function __sleep() {
10493
        $this->get_string();
10494
        $this->forcedstring = true;
10495
        return array('forcedstring', 'string', 'lang');
10496
    }
10497
 
10498
    /**
10499
     * Returns the identifier.
10500
     *
10501
     * @return string
10502
     */
10503
    public function get_identifier() {
10504
        return $this->identifier;
10505
    }
10506
 
10507
    /**
10508
     * Returns the component.
10509
     *
10510
     * @return string
10511
     */
10512
    public function get_component() {
10513
        return $this->component;
10514
    }
10515
}
10516
 
10517
/**
10518
 * Get human readable name describing the given callable.
10519
 *
10520
 * This performs syntax check only to see if the given param looks like a valid function, method or closure.
10521
 * It does not check if the callable actually exists.
10522
 *
10523
 * @param callable|string|array $callable
10524
 * @return string|bool Human readable name of callable, or false if not a valid callable.
10525
 */
10526
function get_callable_name($callable) {
10527
 
10528
    if (!is_callable($callable, true, $name)) {
10529
        return false;
10530
 
10531
    } else {
10532
        return $name;
10533
    }
10534
}
10535
 
10536
/**
10537
 * Tries to guess if $CFG->wwwroot is publicly accessible or not.
10538
 * Never put your faith on this function and rely on its accuracy as there might be false positives.
10539
 * It just performs some simple checks, and mainly is used for places where we want to hide some options
10540
 * such as site registration when $CFG->wwwroot is not publicly accessible.
10541
 * Good thing is there is no false negative.
10542
 * Note that it's possible to force the result of this check by specifying $CFG->site_is_public in config.php
10543
 *
10544
 * @return bool
10545
 */
10546
function site_is_public() {
10547
    global $CFG;
10548
 
10549
    // Return early if site admin has forced this setting.
10550
    if (isset($CFG->site_is_public)) {
10551
        return (bool)$CFG->site_is_public;
10552
    }
10553
 
10554
    $host = parse_url($CFG->wwwroot, PHP_URL_HOST);
10555
 
10556
    if ($host === 'localhost' || preg_match('|^127\.\d+\.\d+\.\d+$|', $host)) {
10557
        $ispublic = false;
10558
    } else if (\core\ip_utils::is_ip_address($host) && !ip_is_public($host)) {
10559
        $ispublic = false;
10560
    } else if (($address = \core\ip_utils::get_ip_address($host)) && !ip_is_public($address)) {
10561
        $ispublic = false;
10562
    } else {
10563
        $ispublic = true;
10564
    }
10565
 
10566
    return $ispublic;
10567
}
10568
 
10569
/**
10570
 * Validates user's password length.
10571
 *
10572
 * @param string $password
10573
 * @param int $pepperlength The length of the used peppers
10574
 * @return bool
10575
 */
10576
function exceeds_password_length(string $password, int $pepperlength = 0): bool {
10577
    return (strlen($password) > (MAX_PASSWORD_CHARACTERS + $pepperlength));
10578
}
10579
 
10580
/**
10581
 * A helper to replace PHP 8.3 usage of array_keys with two args.
10582
 *
10583
 * There is an indication that this will become a new method in PHP 8.4, but that has not happened yet.
10584
 * Therefore this non-polyfill has been created with a different naming convention.
10585
 * In the future it can be deprecated if a core PHP method is created.
10586
 *
10587
 * https://wiki.php.net/rfc/deprecate_functions_with_overloaded_signatures#array_keys
10588
 *
10589
 * @param array $array
10590
 * @param mixed $filter The value to filter on
10591
 * @param bool $strict Whether to apply a strit test with the filter
10592
 * @return array
10593
 */
10594
function moodle_array_keys_filter(array $array, mixed $filter, bool $strict = false): array {
10595
    return array_keys(array_filter(
10596
        $array,
10597
        function($value, $key) use ($filter, $strict): bool {
10598
            if ($strict) {
10599
                return $value === $filter;
10600
            }
10601
            return $value == $filter;
10602
        },
10603
        ARRAY_FILTER_USE_BOTH,
10604
    ));
10605
}