Proyectos de Subversion Moodle

Rev

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
namespace core;
18
 
19
use lang_string;
20
 
21
/**
22
 * Unit tests for (some of) ../moodlelib.php.
23
 *
24
 * @package    core
25
 * @category   phpunit
26
 * @copyright  &copy; 2006 The Open University
27
 * @author     T.J.Hunt@open.ac.uk
28
 * @author     nicolas@moodle.com
29
 */
30
class moodlelib_test extends \advanced_testcase {
31
 
32
    /**
33
     * Define a local decimal separator.
34
     *
35
     * It is not possible to directly change the result of get_string in
36
     * a unit test. Instead, we create a language pack for language 'xx' in
37
     * dataroot and make langconfig.php with the string we need to change.
38
     * The default example separator used here is 'X'; on PHP 5.3 and before this
39
     * must be a single byte character due to PHP bug/limitation in
40
     * number_format, so you can't use UTF-8 characters.
41
     *
42
     * @param string $decsep Separator character. Defaults to `'X'`.
43
     */
44
    protected function define_local_decimal_separator(string $decsep = 'X') {
45
        global $SESSION, $CFG;
46
 
47
        $SESSION->lang = 'xx';
48
        $langconfig = "<?php\n\$string['decsep'] = '$decsep';";
49
        $langfolder = $CFG->dataroot . '/lang/xx';
50
        check_dir_exists($langfolder);
51
        file_put_contents($langfolder . '/langconfig.php', $langconfig);
52
 
53
        // Ensure the new value is picked up and not taken from the cache.
54
        $stringmanager = get_string_manager();
55
        $stringmanager->reset_caches(true);
56
    }
57
 
58
    public function test_cleanremoteaddr() {
59
        // IPv4.
60
        $this->assertNull(cleanremoteaddr('1023.121.234.1'));
61
        $this->assertSame('123.121.234.1', cleanremoteaddr('123.121.234.01 '));
62
 
63
        // IPv6.
64
        $this->assertNull(cleanremoteaddr('0:0:0:0:0:0:0:0:0'));
65
        $this->assertNull(cleanremoteaddr('0:0:0:0:0:0:0:abh'));
66
        $this->assertNull(cleanremoteaddr('0:0:0:::0:0:1'));
67
        $this->assertSame('::', cleanremoteaddr('0:0:0:0:0:0:0:0', true));
68
        $this->assertSame('::1:1', cleanremoteaddr('0:0:0:0:0:0:1:1', true));
69
        $this->assertSame('abcd:ef::', cleanremoteaddr('abcd:00ef:0:0:0:0:0:0', true));
70
        $this->assertSame('1::1', cleanremoteaddr('1:0:0:0:0:0:0:1', true));
71
        $this->assertSame('0:0:0:0:0:0:10:1', cleanremoteaddr('::10:1', false));
72
        $this->assertSame('1:1:0:0:0:0:0:0', cleanremoteaddr('01:1::', false));
73
        $this->assertSame('10:0:0:0:0:0:0:10', cleanremoteaddr('10::10', false));
74
        $this->assertSame('::ffff:c0a8:11', cleanremoteaddr('::ffff:192.168.1.1', true));
75
    }
76
 
77
    public function test_address_in_subnet() {
78
        // 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn (number of bits in net mask).
79
        $this->assertTrue(address_in_subnet('123.121.234.1', '123.121.234.1/32'));
80
        $this->assertFalse(address_in_subnet('123.121.23.1', '123.121.23.0/32'));
81
        $this->assertTrue(address_in_subnet('10.10.10.100',  '123.121.23.45/0'));
82
        $this->assertTrue(address_in_subnet('123.121.234.1', '123.121.234.0/24'));
83
        $this->assertFalse(address_in_subnet('123.121.34.1', '123.121.234.0/24'));
84
        $this->assertTrue(address_in_subnet('123.121.234.1', '123.121.234.0/30'));
85
        $this->assertFalse(address_in_subnet('123.121.23.8', '123.121.23.0/30'));
86
        $this->assertTrue(address_in_subnet('baba:baba::baba', 'baba:baba::baba/128'));
87
        $this->assertFalse(address_in_subnet('bab:baba::baba', 'bab:baba::cece/128'));
88
        $this->assertTrue(address_in_subnet('baba:baba::baba', 'cece:cece::cece/0'));
89
        $this->assertTrue(address_in_subnet('baba:baba::baba', 'baba:baba::baba/128'));
90
        $this->assertTrue(address_in_subnet('baba:baba::00ba', 'baba:baba::/120'));
91
        $this->assertFalse(address_in_subnet('baba:baba::aba', 'baba:baba::/120'));
92
        $this->assertTrue(address_in_subnet('baba::baba:00ba', 'baba::baba:0/112'));
93
        $this->assertFalse(address_in_subnet('baba::aba:00ba', 'baba::baba:0/112'));
94
        $this->assertFalse(address_in_subnet('aba::baba:0000', 'baba::baba:0/112'));
95
 
96
        // Fixed input.
97
        $this->assertTrue(address_in_subnet('123.121.23.1   ', ' 123.121.23.0 / 24'));
98
        $this->assertTrue(address_in_subnet('::ffff:10.1.1.1', ' 0:0:0:000:0:ffff:a1:10 / 126'));
99
 
100
        // Incorrect input.
101
        $this->assertFalse(address_in_subnet('123.121.234.1', '123.121.234.1/-2'));
102
        $this->assertFalse(address_in_subnet('123.121.234.1', '123.121.234.1/64'));
103
        $this->assertFalse(address_in_subnet('123.121.234.x', '123.121.234.1/24'));
104
        $this->assertFalse(address_in_subnet('123.121.234.0', '123.121.234.xx/24'));
105
        $this->assertFalse(address_in_subnet('123.121.234.1', '123.121.234.1/xx0'));
106
        $this->assertFalse(address_in_subnet('::1', '::aa:0/xx0'));
107
        $this->assertFalse(address_in_subnet('::1', '::aa:0/-5'));
108
        $this->assertFalse(address_in_subnet('::1', '::aa:0/130'));
109
        $this->assertFalse(address_in_subnet('x:1', '::aa:0/130'));
110
        $this->assertFalse(address_in_subnet('::1', '::ax:0/130'));
111
 
112
        // 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).
113
        $this->assertTrue(address_in_subnet('123.121.234.12', '123.121.234.12-14'));
114
        $this->assertTrue(address_in_subnet('123.121.234.13', '123.121.234.12-14'));
115
        $this->assertTrue(address_in_subnet('123.121.234.14', '123.121.234.12-14'));
116
        $this->assertFalse(address_in_subnet('123.121.234.1', '123.121.234.12-14'));
117
        $this->assertFalse(address_in_subnet('123.121.234.20', '123.121.234.12-14'));
118
        $this->assertFalse(address_in_subnet('123.121.23.12', '123.121.234.12-14'));
119
        $this->assertFalse(address_in_subnet('123.12.234.12', '123.121.234.12-14'));
120
        $this->assertTrue(address_in_subnet('baba:baba::baba', 'baba:baba::baba-babe'));
121
        $this->assertTrue(address_in_subnet('baba:baba::babc', 'baba:baba::baba-babe'));
122
        $this->assertTrue(address_in_subnet('baba:baba::babe', 'baba:baba::baba-babe'));
123
        $this->assertFalse(address_in_subnet('bab:baba::bab0', 'bab:baba::baba-babe'));
124
        $this->assertFalse(address_in_subnet('bab:baba::babf', 'bab:baba::baba-babe'));
125
        $this->assertFalse(address_in_subnet('bab:baba::bfbe', 'bab:baba::baba-babe'));
126
        $this->assertFalse(address_in_subnet('bfb:baba::babe', 'bab:baba::baba-babe'));
127
 
128
        // Fixed input.
129
        $this->assertTrue(address_in_subnet('123.121.234.12', '123.121.234.12 - 14 '));
130
        $this->assertTrue(address_in_subnet('bab:baba::babe', 'bab:baba::baba - babe  '));
131
 
132
        // Incorrect input.
133
        $this->assertFalse(address_in_subnet('123.121.234.12', '123.121.234.12-234.14'));
134
        $this->assertFalse(address_in_subnet('123.121.234.12', '123.121.234.12-256'));
135
        $this->assertFalse(address_in_subnet('123.121.234.12', '123.121.234.12--256'));
136
 
137
        // 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx. (incomplete address, a bit non-technical ;-).
138
        $this->assertTrue(address_in_subnet('123.121.234.12', '123.121.234.12'));
139
        $this->assertFalse(address_in_subnet('123.121.23.12', '123.121.23.13'));
140
        $this->assertTrue(address_in_subnet('123.121.234.12', '123.121.234.'));
141
        $this->assertTrue(address_in_subnet('123.121.234.12', '123.121.234'));
142
        $this->assertTrue(address_in_subnet('123.121.234.12', '123.121'));
143
        $this->assertTrue(address_in_subnet('123.121.234.12', '123'));
144
        $this->assertFalse(address_in_subnet('123.121.234.1', '12.121.234.'));
145
        $this->assertFalse(address_in_subnet('123.121.234.1', '12.121.234'));
146
        $this->assertTrue(address_in_subnet('baba:baba::bab', 'baba:baba::bab'));
147
        $this->assertFalse(address_in_subnet('baba:baba::ba', 'baba:baba::bc'));
148
        $this->assertTrue(address_in_subnet('baba:baba::bab', 'baba:baba'));
149
        $this->assertTrue(address_in_subnet('baba:baba::bab', 'baba:'));
150
        $this->assertFalse(address_in_subnet('bab:baba::bab', 'baba:'));
151
 
152
        // Multiple subnets.
153
        $this->assertTrue(address_in_subnet('123.121.234.12', '::1/64, 124., 123.121.234.10-30'));
154
        $this->assertTrue(address_in_subnet('124.121.234.12', '::1/64, 124., 123.121.234.10-30'));
155
        $this->assertTrue(address_in_subnet('::2',            '::1/64, 124., 123.121.234.10-30'));
156
        $this->assertFalse(address_in_subnet('12.121.234.12', '::1/64, 124., 123.121.234.10-30'));
157
 
158
        // Other incorrect input.
159
        $this->assertFalse(address_in_subnet('123.123.123.123', ''));
160
    }
161
 
162
    public function test_fix_utf8() {
163
        // Make sure valid data including other types is not changed.
164
        $this->assertSame(null, fix_utf8(null));
165
        $this->assertSame(1, fix_utf8(1));
166
        $this->assertSame(1.1, fix_utf8(1.1));
167
        $this->assertSame(true, fix_utf8(true));
168
        $this->assertSame('', fix_utf8(''));
169
        $this->assertSame('abc', fix_utf8('abc'));
170
        $array = array('do', 're', 'mi');
171
        $this->assertSame($array, fix_utf8($array));
172
        $object = new \stdClass();
173
        $object->a = 'aa';
174
        $object->b = 'bb';
175
        $this->assertEquals($object, fix_utf8($object));
176
 
177
        // valid utf8 string
178
        $this->assertSame("žlutý koníček přeskočil potůček \n\t\r", fix_utf8("žlutý koníček přeskočil potůček \n\t\r\0"));
179
 
180
        // Invalid utf8 string.
181
        $this->assertSame('aš', fix_utf8('a'.chr(130).'š'), 'This fails with buggy iconv() when mbstring extenstion is not available as fallback.');
182
        $this->assertSame('Hello ', fix_utf8('Hello ï¿¿'));
183
    }
184
 
185
    public function test_optional_param() {
186
        global $CFG;
187
 
188
        $_POST['username'] = 'post_user';
189
        $_GET['username'] = 'get_user';
190
        $this->assertSame($_POST['username'], optional_param('username', 'default_user', PARAM_RAW));
191
 
192
        unset($_POST['username']);
193
        $this->assertSame($_GET['username'], optional_param('username', 'default_user', PARAM_RAW));
194
 
195
        unset($_GET['username']);
196
        $this->assertSame('default_user', optional_param('username', 'default_user', PARAM_RAW));
197
 
198
        // Make sure warning is displayed if array submitted - TODO: throw exception in Moodle 2.3.
199
        $_POST['username'] = array('a'=>'a');
200
        try {
201
            optional_param('username', 'default_user', PARAM_RAW);
202
            $this->fail('coding_exception expected');
203
        } catch (\coding_exception $e) {
204
        }
205
    }
206
 
207
    public function test_optional_param_array() {
208
        global $CFG;
209
 
210
        $_POST['username'] = array('a'=>'post_user');
211
        $_GET['username'] = array('a'=>'get_user');
212
        $this->assertSame($_POST['username'], optional_param_array('username', array('a'=>'default_user'), PARAM_RAW));
213
 
214
        unset($_POST['username']);
215
        $this->assertSame($_GET['username'], optional_param_array('username', array('a'=>'default_user'), PARAM_RAW));
216
 
217
        unset($_GET['username']);
218
        $this->assertSame(array('a'=>'default_user'), optional_param_array('username', array('a'=>'default_user'), PARAM_RAW));
219
 
220
        // Do not allow nested arrays.
221
        try {
222
            $_POST['username'] = array('a'=>array('b'=>'post_user'));
223
            optional_param_array('username', array('a'=>'default_user'), PARAM_RAW);
224
            $this->fail('coding_exception expected');
225
        } catch (\coding_exception $ex) {
226
            $this->assertTrue(true);
227
        }
228
 
229
        // Do not allow non-arrays.
230
        $_POST['username'] = 'post_user';
231
        $this->assertSame(array('a'=>'default_user'), optional_param_array('username', array('a'=>'default_user'), PARAM_RAW));
232
        $this->assertDebuggingCalled();
233
 
234
        // Make sure array keys are sanitised.
235
        $_POST['username'] = array('abc123_;-/*-+ '=>'arrggh', 'a1_-'=>'post_user');
236
        $this->assertSame(array('a1_-'=>'post_user'), optional_param_array('username', array(), PARAM_RAW));
237
        $this->assertDebuggingCalled();
238
    }
239
 
240
    public function test_required_param() {
241
        $_POST['username'] = 'post_user';
242
        $_GET['username'] = 'get_user';
243
        $this->assertSame('post_user', required_param('username', PARAM_RAW));
244
 
245
        unset($_POST['username']);
246
        $this->assertSame('get_user', required_param('username', PARAM_RAW));
247
 
248
        unset($_GET['username']);
249
        try {
250
            $this->assertSame('default_user', required_param('username', PARAM_RAW));
251
            $this->fail('moodle_exception expected');
252
        } catch (\moodle_exception $ex) {
253
            $this->assertInstanceOf('moodle_exception', $ex);
254
        }
255
 
256
        try {
257
            required_param('', PARAM_RAW);
258
            $this->fail('coding_exception expected');
259
        } catch (\moodle_exception $ex) {
260
        }
261
 
262
        // Make sure warning is displayed if array submitted - TODO: throw exception in Moodle 2.3.
263
        $_POST['username'] = array('a'=>'a');
264
        try {
265
            required_param('username', PARAM_RAW);
266
            $this->fail('coding_exception expected');
267
        } catch (\coding_exception $e) {
268
        }
269
    }
270
 
271
    public function test_required_param_array() {
272
        global $CFG;
273
 
274
        $_POST['username'] = array('a'=>'post_user');
275
        $_GET['username'] = array('a'=>'get_user');
276
        $this->assertSame($_POST['username'], required_param_array('username', PARAM_RAW));
277
 
278
        unset($_POST['username']);
279
        $this->assertSame($_GET['username'], required_param_array('username', PARAM_RAW));
280
 
281
        // Do not allow nested arrays.
282
        try {
283
            $_POST['username'] = array('a'=>array('b'=>'post_user'));
284
            required_param_array('username', PARAM_RAW);
285
            $this->fail('coding_exception expected');
286
        } catch (\moodle_exception $ex) {
287
            $this->assertInstanceOf('coding_exception', $ex);
288
        }
289
 
290
        // Do not allow non-arrays.
291
        try {
292
            $_POST['username'] = 'post_user';
293
            required_param_array('username', PARAM_RAW);
294
            $this->fail('moodle_exception expected');
295
        } catch (\moodle_exception $ex) {
296
            $this->assertInstanceOf('moodle_exception', $ex);
297
        }
298
 
299
        // Make sure array keys are sanitised.
300
        $_POST['username'] = array('abc123_;-/*-+ '=>'arrggh', 'a1_-'=>'post_user');
301
        $this->assertSame(array('a1_-'=>'post_user'), required_param_array('username', PARAM_RAW));
302
        $this->assertDebuggingCalled();
303
    }
304
 
305
    /**
306
     * @covers \core\param
307
     * @covers \clean_param
308
     */
309
    public function test_clean_param() {
310
        // Forbid objects and arrays.
311
        try {
312
            clean_param(array('x', 'y'), PARAM_RAW);
313
            $this->fail('coding_exception expected');
314
        } catch (\moodle_exception $ex) {
315
            $this->assertInstanceOf('coding_exception', $ex);
316
        }
317
        try {
318
            $param = new \stdClass();
319
            $param->id = 1;
320
            clean_param($param, PARAM_RAW);
321
            $this->fail('coding_exception expected');
322
        } catch (\moodle_exception $ex) {
323
            $this->assertInstanceOf('coding_exception', $ex);
324
        }
325
 
326
        // Require correct type.
327
        try {
328
            clean_param('x', 'xxxxxx');
329
            $this->fail('moodle_exception expected');
330
        } catch (\moodle_exception $ex) {
331
            $this->assertInstanceOf('moodle_exception', $ex);
332
        }
333
    }
334
 
335
    /**
336
     * @covers \core\param
337
     * @covers \clean_param
338
     */
339
    public function test_clean_param_array() {
340
        $this->assertSame(array(), clean_param_array(null, PARAM_RAW));
341
        $this->assertSame(array('a', 'b'), clean_param_array(array('a', 'b'), PARAM_RAW));
342
        $this->assertSame(array('a', array('b')), clean_param_array(array('a', array('b')), PARAM_RAW, true));
343
 
344
        // Require correct type.
345
        try {
346
            clean_param_array(array('x'), 'xxxxxx');
347
            $this->fail('moodle_exception expected');
348
        } catch (\moodle_exception $ex) {
349
            $this->assertInstanceOf('moodle_exception', $ex);
350
        }
351
 
352
        try {
353
            clean_param_array(array('x', array('y')), PARAM_RAW);
354
            $this->fail('coding_exception expected');
355
        } catch (\moodle_exception $ex) {
356
            $this->assertInstanceOf('coding_exception', $ex);
357
        }
358
 
359
        // Test recursive.
360
    }
361
 
362
    /**
363
     * @covers \core\param
364
     * @covers \clean_param
365
     */
366
    public function test_clean_param_raw() {
367
        $this->assertSame(
368
            '#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)',
369
            clean_param('#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)', PARAM_RAW));
370
        $this->assertSame(null, clean_param(null, PARAM_RAW));
371
    }
372
 
373
    /**
374
     * @covers \core\param
375
     * @covers \clean_param
376
     */
377
    public function test_clean_param_trim() {
378
        $this->assertSame('Frog toad', clean_param("   Frog toad   \r\n  ", PARAM_RAW_TRIMMED));
379
        $this->assertSame('', clean_param(null, PARAM_RAW_TRIMMED));
380
    }
381
 
382
    /**
383
     * @covers \core\param
384
     * @covers \clean_param
385
     */
386
    public function test_clean_param_clean() {
387
        // PARAM_CLEAN is an ugly hack, do not use in new code (skodak),
388
        // instead use more specific type, or submit sothing that can be verified properly.
389
        $this->assertSame('xx', clean_param('xx<script>', PARAM_CLEAN));
390
        $this->assertSame('', clean_param(null, PARAM_CLEAN));
391
        $this->assertSame('', clean_param(null, PARAM_CLEANHTML));
392
    }
393
 
394
    /**
395
     * @covers \core\param
396
     * @covers \clean_param
397
     */
398
    public function test_clean_param_alpha() {
399
        $this->assertSame('DSFMOSDJ', clean_param('#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)', PARAM_ALPHA));
400
        $this->assertSame('', clean_param(null, PARAM_ALPHA));
401
    }
402
 
403
    /**
404
     * @covers \core\param
405
     * @covers \clean_param
406
     */
407
    public function test_clean_param_alphanum() {
408
        $this->assertSame('978942897DSFMOSDJ', clean_param('#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)', PARAM_ALPHANUM));
409
        $this->assertSame('', clean_param(null, PARAM_ALPHANUM));
410
    }
411
 
412
    /**
413
     * @covers \core\param
414
     * @covers \clean_param
415
     */
416
    public function test_clean_param_alphaext() {
417
        $this->assertSame('DSFMOSDJ', clean_param('#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)', PARAM_ALPHAEXT));
418
        $this->assertSame('', clean_param(null, PARAM_ALPHAEXT));
419
    }
420
 
421
    /**
422
     * @covers \core\param
423
     * @covers \clean_param
424
     */
425
    public function test_clean_param_sequence() {
426
        $this->assertSame(',9789,42897', clean_param('#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)', PARAM_SEQUENCE));
427
        $this->assertSame('', clean_param(null, PARAM_SEQUENCE));
428
    }
429
 
430
    /**
431
     * @covers \core\param
432
     * @covers \clean_param
433
     */
434
    public function test_clean_param_component() {
435
        // Please note the cleaning of component names is very strict, no guessing here.
436
        $this->assertSame('mod_forum', clean_param('mod_forum', PARAM_COMPONENT));
437
        $this->assertSame('block_online_users', clean_param('block_online_users', PARAM_COMPONENT));
438
        $this->assertSame('block_blond_online_users', clean_param('block_blond_online_users', PARAM_COMPONENT));
439
        $this->assertSame('mod_something2', clean_param('mod_something2', PARAM_COMPONENT));
440
        $this->assertSame('forum', clean_param('forum', PARAM_COMPONENT));
441
        $this->assertSame('user', clean_param('user', PARAM_COMPONENT));
442
        $this->assertSame('rating', clean_param('rating', PARAM_COMPONENT));
443
        $this->assertSame('feedback360', clean_param('feedback360', PARAM_COMPONENT));
444
        $this->assertSame('mod_feedback360', clean_param('mod_feedback360', PARAM_COMPONENT));
445
        $this->assertSame('', clean_param('mod_2something', PARAM_COMPONENT));
446
        $this->assertSame('', clean_param('2mod_something', PARAM_COMPONENT));
447
        $this->assertSame('', clean_param('mod_something_xx', PARAM_COMPONENT));
448
        $this->assertSame('', clean_param('auth_something__xx', PARAM_COMPONENT));
449
        $this->assertSame('', clean_param('mod_Something', PARAM_COMPONENT));
450
        $this->assertSame('', clean_param('mod_somethíng', PARAM_COMPONENT));
451
        $this->assertSame('', clean_param('mod__something', PARAM_COMPONENT));
452
        $this->assertSame('', clean_param('auth_xx-yy', PARAM_COMPONENT));
453
        $this->assertSame('', clean_param('_auth_xx', PARAM_COMPONENT));
454
        $this->assertSame('a2uth_xx', clean_param('a2uth_xx', PARAM_COMPONENT));
455
        $this->assertSame('', clean_param('auth_xx_', PARAM_COMPONENT));
456
        $this->assertSame('', clean_param('auth_xx.old', PARAM_COMPONENT));
457
        $this->assertSame('', clean_param('_user', PARAM_COMPONENT));
458
        $this->assertSame('', clean_param('2rating', PARAM_COMPONENT));
459
        $this->assertSame('', clean_param('user_', PARAM_COMPONENT));
460
        $this->assertSame('', clean_param(null, PARAM_COMPONENT));
461
    }
462
 
463
    /**
464
     * @covers \core\param
465
     * @covers \clean_param
466
     */
467
    public function test_clean_param_localisedfloat() {
468
 
469
        $this->assertSame(0.5, clean_param('0.5', PARAM_LOCALISEDFLOAT));
470
        $this->assertSame(false, clean_param('0X5', PARAM_LOCALISEDFLOAT));
471
        $this->assertSame(0.5, clean_param('.5', PARAM_LOCALISEDFLOAT));
472
        $this->assertSame(false, clean_param('X5', PARAM_LOCALISEDFLOAT));
473
        $this->assertSame(10.5, clean_param('10.5', PARAM_LOCALISEDFLOAT));
474
        $this->assertSame(false, clean_param('10X5', PARAM_LOCALISEDFLOAT));
475
        $this->assertSame(1000.5, clean_param('1 000.5', PARAM_LOCALISEDFLOAT));
476
        $this->assertSame(false, clean_param('1 000X5', PARAM_LOCALISEDFLOAT));
477
        $this->assertSame(false, clean_param('1.000.5', PARAM_LOCALISEDFLOAT));
478
        $this->assertSame(false, clean_param('1X000X5', PARAM_LOCALISEDFLOAT));
479
        $this->assertSame(false, clean_param('nan', PARAM_LOCALISEDFLOAT));
480
        $this->assertSame(false, clean_param('10.6blah', PARAM_LOCALISEDFLOAT));
481
        $this->assertSame(null, clean_param(null, PARAM_LOCALISEDFLOAT));
482
 
483
        // Tests with a localised decimal separator.
484
        $this->define_local_decimal_separator();
485
 
486
        $this->assertSame(0.5, clean_param('0.5', PARAM_LOCALISEDFLOAT));
487
        $this->assertSame(0.5, clean_param('0X5', PARAM_LOCALISEDFLOAT));
488
        $this->assertSame(0.5, clean_param('.5', PARAM_LOCALISEDFLOAT));
489
        $this->assertSame(0.5, clean_param('X5', PARAM_LOCALISEDFLOAT));
490
        $this->assertSame(10.5, clean_param('10.5', PARAM_LOCALISEDFLOAT));
491
        $this->assertSame(10.5, clean_param('10X5', PARAM_LOCALISEDFLOAT));
492
        $this->assertSame(1000.5, clean_param('1 000.5', PARAM_LOCALISEDFLOAT));
493
        $this->assertSame(1000.5, clean_param('1 000X5', PARAM_LOCALISEDFLOAT));
494
        $this->assertSame(false, clean_param('1.000.5', PARAM_LOCALISEDFLOAT));
495
        $this->assertSame(false, clean_param('1X000X5', PARAM_LOCALISEDFLOAT));
496
        $this->assertSame(false, clean_param('nan', PARAM_LOCALISEDFLOAT));
497
        $this->assertSame(false, clean_param('10X6blah', PARAM_LOCALISEDFLOAT));
498
    }
499
 
500
    public function test_is_valid_plugin_name() {
501
        $this->assertTrue(is_valid_plugin_name('forum'));
502
        $this->assertTrue(is_valid_plugin_name('forum2'));
503
        $this->assertTrue(is_valid_plugin_name('feedback360'));
504
        $this->assertTrue(is_valid_plugin_name('online_users'));
505
        $this->assertTrue(is_valid_plugin_name('blond_online_users'));
506
        $this->assertFalse(is_valid_plugin_name('online__users'));
507
        $this->assertFalse(is_valid_plugin_name('forum '));
508
        $this->assertFalse(is_valid_plugin_name('forum.old'));
509
        $this->assertFalse(is_valid_plugin_name('xx-yy'));
510
        $this->assertFalse(is_valid_plugin_name('2xx'));
511
        $this->assertFalse(is_valid_plugin_name('Xx'));
512
        $this->assertFalse(is_valid_plugin_name('_xx'));
513
        $this->assertFalse(is_valid_plugin_name('xx_'));
514
    }
515
 
516
    /**
517
     * @covers \core\param
518
     * @covers \clean_param
519
     */
520
    public function test_clean_param_plugin() {
521
        // Please note the cleaning of plugin names is very strict, no guessing here.
522
        $this->assertSame('forum', clean_param('forum', PARAM_PLUGIN));
523
        $this->assertSame('forum2', clean_param('forum2', PARAM_PLUGIN));
524
        $this->assertSame('feedback360', clean_param('feedback360', PARAM_PLUGIN));
525
        $this->assertSame('online_users', clean_param('online_users', PARAM_PLUGIN));
526
        $this->assertSame('blond_online_users', clean_param('blond_online_users', PARAM_PLUGIN));
527
        $this->assertSame('', clean_param('online__users', PARAM_PLUGIN));
528
        $this->assertSame('', clean_param('forum ', PARAM_PLUGIN));
529
        $this->assertSame('', clean_param('forum.old', PARAM_PLUGIN));
530
        $this->assertSame('', clean_param('xx-yy', PARAM_PLUGIN));
531
        $this->assertSame('', clean_param('2xx', PARAM_PLUGIN));
532
        $this->assertSame('', clean_param('Xx', PARAM_PLUGIN));
533
        $this->assertSame('', clean_param('_xx', PARAM_PLUGIN));
534
        $this->assertSame('', clean_param('xx_', PARAM_PLUGIN));
535
        $this->assertSame('', clean_param(null, PARAM_PLUGIN));
536
    }
537
 
538
    /**
539
     * @covers \core\param
540
     * @covers \clean_param
541
     */
542
    public function test_clean_param_area() {
543
        // Please note the cleaning of area names is very strict, no guessing here.
544
        $this->assertSame('something', clean_param('something', PARAM_AREA));
545
        $this->assertSame('something2', clean_param('something2', PARAM_AREA));
546
        $this->assertSame('some_thing', clean_param('some_thing', PARAM_AREA));
547
        $this->assertSame('some_thing_xx', clean_param('some_thing_xx', PARAM_AREA));
548
        $this->assertSame('feedback360', clean_param('feedback360', PARAM_AREA));
549
        $this->assertSame('', clean_param('_something', PARAM_AREA));
550
        $this->assertSame('', clean_param('something_', PARAM_AREA));
551
        $this->assertSame('', clean_param('2something', PARAM_AREA));
552
        $this->assertSame('', clean_param('Something', PARAM_AREA));
553
        $this->assertSame('', clean_param('some-thing', PARAM_AREA));
554
        $this->assertSame('', clean_param('somethííng', PARAM_AREA));
555
        $this->assertSame('', clean_param('something.x', PARAM_AREA));
556
        $this->assertSame('', clean_param(null, PARAM_AREA));
557
    }
558
 
559
    /**
560
     * @covers \core\param
561
     * @covers \clean_param
562
     */
563
    public function test_clean_param_text() {
564
        // Standard.
565
        $this->assertSame('xx<lang lang="en">aa</lang><lang lang="yy">pp</lang>', clean_param('xx<lang lang="en">aa</lang><lang lang="yy">pp</lang>', PARAM_TEXT));
566
        $this->assertSame('<span lang="en" class="multilang">aa</span><span lang="xy" class="multilang">bb</span>', clean_param('<span lang="en" class="multilang">aa</span><span lang="xy" class="multilang">bb</span>', PARAM_TEXT));
567
        $this->assertSame('xx<lang lang="en">aa'."\n".'</lang><lang lang="yy">pp</lang>', clean_param('xx<lang lang="en">aa'."\n".'</lang><lang lang="yy">pp</lang>', PARAM_TEXT));
568
        // Malformed.
569
        $this->assertSame('<span lang="en" class="multilang">aa</span>', clean_param('<span lang="en" class="multilang">aa</span>', PARAM_TEXT));
570
        $this->assertSame('aa', clean_param('<span lang="en" class="nothing" class="multilang">aa</span>', PARAM_TEXT));
571
        $this->assertSame('aa', clean_param('<lang lang="en" class="multilang">aa</lang>', PARAM_TEXT));
572
        $this->assertSame('aa', clean_param('<lang lang="en!!">aa</lang>', PARAM_TEXT));
573
        $this->assertSame('aa', clean_param('<span lang="en==" class="multilang">aa</span>', PARAM_TEXT));
574
        $this->assertSame('abc', clean_param('a<em>b</em>c', PARAM_TEXT));
575
        $this->assertSame('a>c>', clean_param('a><xx >c>', PARAM_TEXT)); // Standard strip_tags() behaviour.
576
        $this->assertSame('a', clean_param('a<b', PARAM_TEXT));
577
        $this->assertSame('a>b', clean_param('a>b', PARAM_TEXT));
578
        $this->assertSame('<lang lang="en">a>a</lang>', clean_param('<lang lang="en">a>a</lang>', PARAM_TEXT)); // Standard strip_tags() behaviour.
579
        $this->assertSame('a', clean_param('<lang lang="en">a<a</lang>', PARAM_TEXT));
580
        $this->assertSame('<lang lang="en">aa</lang>', clean_param('<lang lang="en">a<br>a</lang>', PARAM_TEXT));
581
        $this->assertSame('', clean_param(null, PARAM_TEXT));
582
    }
583
 
584
    /**
585
     * Data provider for {@see test_clean_param_host}
586
     *
587
     * @return array
588
     */
589
    public static function clean_param_host_provider(): array {
590
        return [
591
            'Valid (low octets)' => ['0.0.0.0', '0.0.0.0'],
592
            'Valid (high octets)' => ['255.255.255.255', '255.255.255.255'],
593
            'Invalid first octet' => ['256.1.1.1', ''],
594
            'Invalid second octet' => ['1.256.1.1', ''],
595
            'Invalid third octet' => ['1.1.256.1', ''],
596
            'Invalid fourth octet' => ['1.1.1.256', ''],
597
            'Valid host' => ['moodle.org', 'moodle.org'],
598
            'Invalid host' => ['.example.com', ''],
599
        ];
600
    }
601
 
602
    /**
603
     * Testing cleaning parameters with PARAM_HOST
604
     *
605
     * @param string $param
606
     * @param string $expected
607
     *
608
     * @dataProvider clean_param_host_provider
609
     *
610
     * @covers \core\param
611
     * @covers \clean_param
612
     */
613
    public function test_clean_param_host(string $param, string $expected): void {
614
        $this->assertEquals($expected, clean_param($param, PARAM_HOST));
615
    }
616
 
617
    /**
618
     * @covers \core\param
619
     * @covers \clean_param
620
     */
621
    public function test_clean_param_url() {
622
        // Test PARAM_URL and PARAM_LOCALURL a bit.
623
        // Valid URLs.
624
        $this->assertSame('http://google.com/', clean_param('http://google.com/', PARAM_URL));
625
        $this->assertSame('http://some.very.long.and.silly.domain/with/a/path/', clean_param('http://some.very.long.and.silly.domain/with/a/path/', PARAM_URL));
626
        $this->assertSame('http://localhost/', clean_param('http://localhost/', PARAM_URL));
627
        $this->assertSame('http://0.255.1.1/numericip.php', clean_param('http://0.255.1.1/numericip.php', PARAM_URL));
628
        $this->assertSame('https://google.com/', clean_param('https://google.com/', PARAM_URL));
629
        $this->assertSame('https://some.very.long.and.silly.domain/with/a/path/', clean_param('https://some.very.long.and.silly.domain/with/a/path/', PARAM_URL));
630
        $this->assertSame('https://localhost/', clean_param('https://localhost/', PARAM_URL));
631
        $this->assertSame('https://0.255.1.1/numericip.php', clean_param('https://0.255.1.1/numericip.php', PARAM_URL));
632
        $this->assertSame('ftp://ftp.debian.org/debian/', clean_param('ftp://ftp.debian.org/debian/', PARAM_URL));
633
        $this->assertSame('/just/a/path', clean_param('/just/a/path', PARAM_URL));
634
        // Invalid URLs.
635
        $this->assertSame('', clean_param('funny:thing', PARAM_URL));
636
        $this->assertSame('', clean_param('http://example.ee/sdsf"f', PARAM_URL));
637
        $this->assertSame('', clean_param('javascript://comment%0Aalert(1)', PARAM_URL));
638
        $this->assertSame('', clean_param('rtmp://example.com/livestream', PARAM_URL));
639
        $this->assertSame('', clean_param('rtmp://example.com/live&foo', PARAM_URL));
640
        $this->assertSame('', clean_param('rtmp://example.com/fms&mp4:path/to/file.mp4', PARAM_URL));
641
        $this->assertSame('', clean_param('mailto:support@moodle.org', PARAM_URL));
642
        $this->assertSame('', clean_param('mailto:support@moodle.org?subject=Hello%20Moodle', PARAM_URL));
643
        $this->assertSame('', clean_param('mailto:support@moodle.org?subject=Hello%20Moodle&cc=feedback@moodle.org', PARAM_URL));
644
        $this->assertSame('', clean_param(null, PARAM_URL));
645
    }
646
 
647
    /**
648
     * @covers \core\param
649
     * @covers \clean_param
650
     */
651
    public function test_clean_param_localurl() {
652
        global $CFG;
653
 
654
        $this->resetAfterTest();
655
 
656
        // External, invalid.
657
        $this->assertSame('', clean_param('funny:thing', PARAM_LOCALURL));
658
        $this->assertSame('', clean_param('http://google.com/', PARAM_LOCALURL));
659
        $this->assertSame('', clean_param('https://google.com/?test=true', PARAM_LOCALURL));
660
        $this->assertSame('', clean_param('http://some.very.long.and.silly.domain/with/a/path/', PARAM_LOCALURL));
661
 
662
        // Local absolute.
663
        $this->assertSame(clean_param($CFG->wwwroot, PARAM_LOCALURL), $CFG->wwwroot);
664
        $this->assertSame($CFG->wwwroot . '/with/something?else=true',
665
            clean_param($CFG->wwwroot . '/with/something?else=true', PARAM_LOCALURL));
666
 
667
        // Local relative.
668
        $this->assertSame('/just/a/path', clean_param('/just/a/path', PARAM_LOCALURL));
669
        $this->assertSame('course/view.php?id=3', clean_param('course/view.php?id=3', PARAM_LOCALURL));
670
 
671
        // Local absolute HTTPS in a non HTTPS site.
672
        $CFG->wwwroot = str_replace('https:', 'http:', $CFG->wwwroot); // Need to simulate non-https site.
673
        $httpsroot = str_replace('http:', 'https:', $CFG->wwwroot);
674
        $this->assertSame('', clean_param($httpsroot, PARAM_LOCALURL));
675
        $this->assertSame('', clean_param($httpsroot . '/with/something?else=true', PARAM_LOCALURL));
676
 
677
        // Local absolute HTTPS in a HTTPS site.
678
        $CFG->wwwroot = str_replace('http:', 'https:', $CFG->wwwroot);
679
        $httpsroot = $CFG->wwwroot;
680
        $this->assertSame($httpsroot, clean_param($httpsroot, PARAM_LOCALURL));
681
        $this->assertSame($httpsroot . '/with/something?else=true',
682
            clean_param($httpsroot . '/with/something?else=true', PARAM_LOCALURL));
683
 
684
        // Test open redirects are not possible.
685
        $CFG->wwwroot = 'http://www.example.com';
686
        $this->assertSame('', clean_param('http://www.example.com.evil.net/hack.php', PARAM_LOCALURL));
687
        $CFG->wwwroot = 'https://www.example.com';
688
        $this->assertSame('', clean_param('https://www.example.com.evil.net/hack.php', PARAM_LOCALURL));
689
 
690
        $this->assertSame('', clean_param('', PARAM_LOCALURL));
691
        $this->assertSame('', clean_param(null, PARAM_LOCALURL));
692
    }
693
 
694
    /**
695
     * @covers \core\param
696
     * @covers \clean_param
697
     */
698
    public function test_clean_param_file() {
699
        $this->assertSame('correctfile.txt', clean_param('correctfile.txt', PARAM_FILE));
700
        $this->assertSame('badfile.txt', clean_param('b\'a<d`\\/fi:l>e.t"x|t', PARAM_FILE));
701
        $this->assertSame('..parentdirfile.txt', clean_param('../parentdirfile.txt', PARAM_FILE));
702
        $this->assertSame('....grandparentdirfile.txt', clean_param('../../grandparentdirfile.txt', PARAM_FILE));
703
        $this->assertSame('..winparentdirfile.txt', clean_param('..\winparentdirfile.txt', PARAM_FILE));
704
        $this->assertSame('....wingrandparentdir.txt', clean_param('..\..\wingrandparentdir.txt', PARAM_FILE));
705
        $this->assertSame('myfile.a.b.txt', clean_param('myfile.a.b.txt', PARAM_FILE));
706
        $this->assertSame('myfile..a..b.txt', clean_param('myfile..a..b.txt', PARAM_FILE));
707
        $this->assertSame('myfile.a..b...txt', clean_param('myfile.a..b...txt', PARAM_FILE));
708
        $this->assertSame('myfile.a.txt', clean_param('myfile.a.txt', PARAM_FILE));
709
        $this->assertSame('myfile...txt', clean_param('myfile...txt', PARAM_FILE));
710
        $this->assertSame('...jpg', clean_param('...jpg', PARAM_FILE));
711
        $this->assertSame('.a.b.', clean_param('.a.b.', PARAM_FILE));
712
        $this->assertSame('', clean_param('.', PARAM_FILE));
713
        $this->assertSame('', clean_param('..', PARAM_FILE));
714
        $this->assertSame('...', clean_param('...', PARAM_FILE));
715
        $this->assertSame('. . . .', clean_param('. . . .', PARAM_FILE));
716
        $this->assertSame('dontrtrim.me. .. .. . ', clean_param('dontrtrim.me. .. .. . ', PARAM_FILE));
717
        $this->assertSame(' . .dontltrim.me', clean_param(' . .dontltrim.me', PARAM_FILE));
718
        $this->assertSame('here is a tab.txt', clean_param("here is a tab\t.txt", PARAM_FILE));
719
        $this->assertSame('here is a linebreak.txt', clean_param("here is a line\r\nbreak.txt", PARAM_FILE));
720
        $this->assertSame('', clean_param(null, PARAM_FILE));
721
 
722
        // The following behaviours have been maintained although they seem a little odd.
723
        $this->assertSame('funnything', clean_param('funny:thing', PARAM_FILE));
724
        $this->assertSame('.currentdirfile.txt', clean_param('./currentdirfile.txt', PARAM_FILE));
725
        $this->assertSame('ctempwindowsfile.txt', clean_param('c:\temp\windowsfile.txt', PARAM_FILE));
726
        $this->assertSame('homeuserlinuxfile.txt', clean_param('/home/user/linuxfile.txt', PARAM_FILE));
727
        $this->assertSame('~myfile.txt', clean_param('~/myfile.txt', PARAM_FILE));
728
    }
729
 
730
    /**
731
     * @covers \core\param
732
     * @covers \clean_param
733
     */
734
    public function test_clean_param_path() {
735
        $this->assertSame('correctfile.txt', clean_param('correctfile.txt', PARAM_PATH));
736
        $this->assertSame('bad/file.txt', clean_param('b\'a<d`\\/fi:l>e.t"x|t', PARAM_PATH));
737
        $this->assertSame('/parentdirfile.txt', clean_param('../parentdirfile.txt', PARAM_PATH));
738
        $this->assertSame('/grandparentdirfile.txt', clean_param('../../grandparentdirfile.txt', PARAM_PATH));
739
        $this->assertSame('/winparentdirfile.txt', clean_param('..\winparentdirfile.txt', PARAM_PATH));
740
        $this->assertSame('/wingrandparentdir.txt', clean_param('..\..\wingrandparentdir.txt', PARAM_PATH));
741
        $this->assertSame('funnything', clean_param('funny:thing', PARAM_PATH));
742
        $this->assertSame('./here', clean_param('./././here', PARAM_PATH));
743
        $this->assertSame('./currentdirfile.txt', clean_param('./currentdirfile.txt', PARAM_PATH));
744
        $this->assertSame('c/temp/windowsfile.txt', clean_param('c:\temp\windowsfile.txt', PARAM_PATH));
745
        $this->assertSame('/home/user/linuxfile.txt', clean_param('/home/user/linuxfile.txt', PARAM_PATH));
746
        $this->assertSame('/home../user ./.linuxfile.txt', clean_param('/home../user ./.linuxfile.txt', PARAM_PATH));
747
        $this->assertSame('~/myfile.txt', clean_param('~/myfile.txt', PARAM_PATH));
748
        $this->assertSame('~/myfile.txt', clean_param('~/../myfile.txt', PARAM_PATH));
749
        $this->assertSame('/..b../.../myfile.txt', clean_param('/..b../.../myfile.txt', PARAM_PATH));
750
        $this->assertSame('..b../.../myfile.txt', clean_param('..b../.../myfile.txt', PARAM_PATH));
751
        $this->assertSame('/super/slashes/', clean_param('/super//slashes///', PARAM_PATH));
752
        $this->assertSame('', clean_param(null, PARAM_PATH));
753
    }
754
 
755
    /**
756
     * @covers \core\param
757
     * @covers \clean_param
758
     */
759
    public function test_clean_param_safepath() {
760
        $this->assertSame('folder/file', clean_param('folder/file', PARAM_SAFEPATH));
761
        $this->assertSame('folder//file', clean_param('folder/../file', PARAM_SAFEPATH));
762
        $this->assertSame('', clean_param(null, PARAM_SAFEPATH));
763
    }
764
 
765
    /**
766
     * @covers \core\param
767
     * @covers \clean_param
768
     */
769
    public function test_clean_param_username() {
770
        global $CFG;
771
        $currentstatus =  $CFG->extendedusernamechars;
772
 
773
        // Run tests with extended character == false;.
774
        $CFG->extendedusernamechars = false;
775
        $this->assertSame('johndoe123', clean_param('johndoe123', PARAM_USERNAME) );
776
        $this->assertSame('john.doe', clean_param('john.doe', PARAM_USERNAME));
777
        $this->assertSame('john-doe', clean_param('john-doe', PARAM_USERNAME));
778
        $this->assertSame('john-doe', clean_param('john- doe', PARAM_USERNAME));
779
        $this->assertSame('john_doe', clean_param('john_doe', PARAM_USERNAME));
780
        $this->assertSame('john@doe', clean_param('john@doe', PARAM_USERNAME));
781
        $this->assertSame('johndoe', clean_param('john~doe', PARAM_USERNAME));
782
        $this->assertSame('johndoe', clean_param('john´doe', PARAM_USERNAME));
783
        $this->assertSame(clean_param('john# $%&()+_^', PARAM_USERNAME), 'john_');
784
        $this->assertSame(clean_param(' john# $%&()+_^ ', PARAM_USERNAME), 'john_');
785
        $this->assertSame(clean_param('john#$%&() ', PARAM_USERNAME), 'john');
786
        $this->assertSame('johnd', clean_param('JOHNdóé ', PARAM_USERNAME));
787
        $this->assertSame(clean_param('john.,:;-_/|\ñÑ[]A_X-,D {} ~!@#$%^&*()_+ ?><[] ščřžžý ?ýáž?žý??šdoe ', PARAM_USERNAME), 'john.-_a_x-d@_doe');
788
        $this->assertSame('', clean_param(null, PARAM_USERNAME));
789
 
790
        // Test success condition, if extendedusernamechars == ENABLE;.
791
        $CFG->extendedusernamechars = true;
792
        $this->assertSame('john_doe', clean_param('john_doe', PARAM_USERNAME));
793
        $this->assertSame('john@doe', clean_param('john@doe', PARAM_USERNAME));
794
        $this->assertSame(clean_param('john# $%&()+_^', PARAM_USERNAME), 'john# $%&()+_^');
795
        $this->assertSame(clean_param(' john# $%&()+_^ ', PARAM_USERNAME), 'john# $%&()+_^');
796
        $this->assertSame('john~doe', clean_param('john~doe', PARAM_USERNAME));
797
        $this->assertSame('john´doe', clean_param('joHN´doe', PARAM_USERNAME));
798
        $this->assertSame('johndoe', clean_param('johnDOE', PARAM_USERNAME));
799
        $this->assertSame('johndóé', clean_param('johndóé ', PARAM_USERNAME));
800
 
801
        $CFG->extendedusernamechars = $currentstatus;
802
    }
803
 
804
    /**
805
     * @covers \core\param
806
     * @covers \clean_param
807
     */
808
    public function test_clean_param_stringid() {
809
        // Test string identifiers validation.
810
        // Valid strings.
811
        $this->assertSame('validstring', clean_param('validstring', PARAM_STRINGID));
812
        $this->assertSame('mod/foobar:valid_capability', clean_param('mod/foobar:valid_capability', PARAM_STRINGID));
813
        $this->assertSame('CZ', clean_param('CZ', PARAM_STRINGID));
814
        $this->assertSame('application/vnd.ms-powerpoint', clean_param('application/vnd.ms-powerpoint', PARAM_STRINGID));
815
        $this->assertSame('grade2', clean_param('grade2', PARAM_STRINGID));
816
        // Invalid strings.
817
        $this->assertSame('', clean_param('trailing ', PARAM_STRINGID));
818
        $this->assertSame('', clean_param('space bar', PARAM_STRINGID));
819
        $this->assertSame('', clean_param('0numeric', PARAM_STRINGID));
820
        $this->assertSame('', clean_param('*', PARAM_STRINGID));
821
        $this->assertSame('', clean_param(' ', PARAM_STRINGID));
822
        $this->assertSame('', clean_param(null, PARAM_STRINGID));
823
    }
824
 
825
    /**
826
     * @covers \core\param
827
     * @covers \clean_param
828
     */
829
    public function test_clean_param_timezone() {
830
        // Test timezone validation.
831
        $testvalues = array (
832
            'America/Jamaica'                => 'America/Jamaica',
833
            'America/Argentina/Cordoba'      => 'America/Argentina/Cordoba',
834
            'America/Port-au-Prince'         => 'America/Port-au-Prince',
835
            'America/Argentina/Buenos_Aires' => 'America/Argentina/Buenos_Aires',
836
            'PST8PDT'                        => 'PST8PDT',
837
            'Wrong.Value'                    => '',
838
            'Wrong/.Value'                   => '',
839
            'Wrong(Value)'                   => '',
840
            '0'                              => '0',
841
            '0.0'                            => '0.0',
842
            '0.5'                            => '0.5',
843
            '9.0'                            => '9.0',
844
            '-9.0'                           => '-9.0',
845
            '+9.0'                           => '+9.0',
846
            '9.5'                            => '9.5',
847
            '-9.5'                           => '-9.5',
848
            '+9.5'                           => '+9.5',
849
            '12.0'                           => '12.0',
850
            '-12.0'                          => '-12.0',
851
            '+12.0'                          => '+12.0',
852
            '12.5'                           => '12.5',
853
            '-12.5'                          => '-12.5',
854
            '+12.5'                          => '+12.5',
855
            '13.0'                           => '13.0',
856
            '-13.0'                          => '-13.0',
857
            '+13.0'                          => '+13.0',
858
            '13.5'                           => '',
859
            '+13.5'                          => '',
860
            '-13.5'                          => '',
861
            '0.2'                            => '',
862
            ''                               => '',
863
            null                             => '',
864
        );
865
 
866
        foreach ($testvalues as $testvalue => $expectedvalue) {
867
            $actualvalue = clean_param($testvalue, PARAM_TIMEZONE);
868
            $this->assertEquals($expectedvalue, $actualvalue);
869
        }
870
    }
871
 
872
    /**
873
     * @covers \core\param
874
     * @covers \clean_param
875
     */
876
    public function test_clean_param_null_argument() {
877
        $this->assertEquals(0, clean_param(null, PARAM_INT));
878
        $this->assertEquals(0, clean_param(null, PARAM_FLOAT));
879
        $this->assertEquals(0, clean_param(null, PARAM_LOCALISEDFLOAT));
880
        $this->assertEquals(false, clean_param(null, PARAM_BOOL));
881
        $this->assertEquals('', clean_param(null, PARAM_NOTAGS));
882
        $this->assertEquals('', clean_param(null, PARAM_SAFEDIR));
883
        $this->assertEquals('', clean_param(null, PARAM_HOST));
884
        $this->assertEquals('', clean_param(null, PARAM_PEM));
885
        $this->assertEquals('', clean_param(null, PARAM_BASE64));
886
        $this->assertEquals('', clean_param(null, PARAM_TAG));
887
        $this->assertEquals('', clean_param(null, PARAM_TAGLIST));
888
        $this->assertEquals('', clean_param(null, PARAM_CAPABILITY));
889
        $this->assertEquals(0, clean_param(null, PARAM_PERMISSION));
890
        $this->assertEquals('', clean_param(null, PARAM_AUTH));
891
        $this->assertEquals('', clean_param(null, PARAM_LANG));
892
        $this->assertEquals('', clean_param(null, PARAM_THEME));
893
        $this->assertEquals('', clean_param(null, PARAM_EMAIL));
894
    }
895
 
896
    public function test_validate_param() {
897
        try {
898
            $param = validate_param('11a', PARAM_INT);
899
            $this->fail('invalid_parameter_exception expected');
900
        } catch (\moodle_exception $ex) {
901
            $this->assertInstanceOf('invalid_parameter_exception', $ex);
902
        }
903
 
904
        $param = validate_param('11', PARAM_INT);
905
        $this->assertSame(11, $param);
906
 
907
        try {
908
            $param = validate_param(null, PARAM_INT, false);
909
            $this->fail('invalid_parameter_exception expected');
910
        } catch (\moodle_exception $ex) {
911
            $this->assertInstanceOf('invalid_parameter_exception', $ex);
912
        }
913
 
914
        $param = validate_param(null, PARAM_INT, true);
915
        $this->assertSame(null, $param);
916
 
917
        try {
918
            $param = validate_param(array(), PARAM_INT);
919
            $this->fail('invalid_parameter_exception expected');
920
        } catch (\moodle_exception $ex) {
921
            $this->assertInstanceOf('invalid_parameter_exception', $ex);
922
        }
923
        try {
924
            $param = validate_param(new \stdClass, PARAM_INT);
925
            $this->fail('invalid_parameter_exception expected');
926
        } catch (\moodle_exception $ex) {
927
            $this->assertInstanceOf('invalid_parameter_exception', $ex);
928
        }
929
 
930
        $param = validate_param('1.0', PARAM_FLOAT);
931
        $this->assertSame(1.0, $param);
932
 
933
        // Make sure valid floats do not cause exception.
934
        validate_param(1.0, PARAM_FLOAT);
935
        validate_param(10, PARAM_FLOAT);
936
        validate_param('0', PARAM_FLOAT);
937
        validate_param('119813454.545464564564546564545646556564465465456465465465645645465645645645', PARAM_FLOAT);
938
        validate_param('011.1', PARAM_FLOAT);
939
        validate_param('11', PARAM_FLOAT);
940
        validate_param('+.1', PARAM_FLOAT);
941
        validate_param('-.1', PARAM_FLOAT);
942
        validate_param('1e10', PARAM_FLOAT);
943
        validate_param('.1e+10', PARAM_FLOAT);
944
        validate_param('1E-1', PARAM_FLOAT);
945
 
946
        try {
947
            $param = validate_param('1,2', PARAM_FLOAT);
948
            $this->fail('invalid_parameter_exception expected');
949
        } catch (\moodle_exception $ex) {
950
            $this->assertInstanceOf('invalid_parameter_exception', $ex);
951
        }
952
        try {
953
            $param = validate_param('', PARAM_FLOAT);
954
            $this->fail('invalid_parameter_exception expected');
955
        } catch (\moodle_exception $ex) {
956
            $this->assertInstanceOf('invalid_parameter_exception', $ex);
957
        }
958
        try {
959
            $param = validate_param('.', PARAM_FLOAT);
960
            $this->fail('invalid_parameter_exception expected');
961
        } catch (\moodle_exception $ex) {
962
            $this->assertInstanceOf('invalid_parameter_exception', $ex);
963
        }
964
        try {
965
            $param = validate_param('e10', PARAM_FLOAT);
966
            $this->fail('invalid_parameter_exception expected');
967
        } catch (\moodle_exception $ex) {
968
            $this->assertInstanceOf('invalid_parameter_exception', $ex);
969
        }
970
        try {
971
            $param = validate_param('abc', PARAM_FLOAT);
972
            $this->fail('invalid_parameter_exception expected');
973
        } catch (\moodle_exception $ex) {
974
            $this->assertInstanceOf('invalid_parameter_exception', $ex);
975
        }
976
    }
977
 
978
    public function test_shorten_text_no_tags_already_short_enough() {
979
        // ......12345678901234567890123456.
980
        $text = "short text already no tags";
981
        $this->assertSame($text, shorten_text($text));
982
    }
983
 
984
    public function test_shorten_text_with_tags_already_short_enough() {
985
        // .........123456...7890....12345678.......901234567.
986
        $text = "<p>short <b>text</b> already</p><p>with tags</p>";
987
        $this->assertSame($text, shorten_text($text));
988
    }
989
 
990
    public function test_shorten_text_no_tags_needs_shortening() {
991
        // Default truncation is after 30 chars, but allowing 3 for the final '...'.
992
        // ......12345678901234567890123456789023456789012345678901234.
993
        $text = "long text without any tags blah de blah blah blah what";
994
        $this->assertSame('long text without any tags ...', shorten_text($text));
995
    }
996
 
997
    public function test_shorten_text_with_tags_needs_shortening() {
998
        // .......................................123456789012345678901234567890...
999
        $text = "<div class='frog'><p><blockquote>Long text with tags that will ".
1000
            "be chopped off but <b>should be added back again</b></blockquote></p></div>";
1001
        $this->assertEquals("<div class='frog'><p><blockquote>Long text with " .
1002
            "tags that ...</blockquote></p></div>", shorten_text($text));
1003
    }
1004
 
1005
    public function test_shorten_text_with_tags_and_html_comment() {
1006
        $text = "<div class='frog'><p><blockquote><!--[if !IE]><!-->Long text with ".
1007
            "tags that will<!--<![endif]--> ".
1008
            "be chopped off but <b>should be added back again</b></blockquote></p></div>";
1009
        $this->assertEquals("<div class='frog'><p><blockquote><!--[if !IE]><!-->Long text with " .
1010
            "tags that ...<!--<![endif]--></blockquote></p></div>", shorten_text($text));
1011
    }
1012
 
1013
    public function test_shorten_text_with_entities() {
1014
        // Remember to allow 3 chars for the final '...'.
1015
        // ......123456789012345678901234567_____890...
1016
        $text = "some text which shouldn't &nbsp; break there";
1017
        $this->assertSame("some text which shouldn't &nbsp; ...", shorten_text($text, 31));
1018
        $this->assertSame("some text which shouldn't &nbsp;...", shorten_text($text, 30));
1019
        $this->assertSame("some text which shouldn't ...", shorten_text($text, 29));
1020
    }
1021
 
1022
    public function test_shorten_text_known_tricky_case() {
1023
        // This case caused a bug up to 1.9.5
1024
        // ..........123456789012345678901234567890123456789.....0_____1___2___...
1025
        $text = "<h3>standard 'break-out' sub groups in TGs?</h3>&nbsp;&lt;&lt;There are several";
1026
        $this->assertSame("<h3>standard 'break-out' sub groups in ...</h3>",
1027
            shorten_text($text, 41));
1028
        $this->assertSame("<h3>standard 'break-out' sub groups in TGs?...</h3>",
1029
            shorten_text($text, 42));
1030
        $this->assertSame("<h3>standard 'break-out' sub groups in TGs?</h3>&nbsp;...",
1031
            shorten_text($text, 43));
1032
    }
1033
 
1034
    public function test_shorten_text_no_spaces() {
1035
        // ..........123456789.
1036
        $text = "<h1>123456789</h1>"; // A string with no convenient breaks.
1037
        $this->assertSame("<h1>12345...</h1>", shorten_text($text, 8));
1038
    }
1039
 
1040
    public function test_shorten_text_utf8_european() {
1041
        // Text without tags.
1042
        // ......123456789012345678901234567.
1043
        $text = "Žluťoučký koníček přeskočil";
1044
        $this->assertSame($text, shorten_text($text)); // 30 chars by default.
1045
        $this->assertSame("Žluťoučký koníče...", shorten_text($text, 19, true));
1046
        $this->assertSame("Žluťoučký ...", shorten_text($text, 19, false));
1047
        // And try it with 2-less (that are, in bytes, the middle of a sequence).
1048
        $this->assertSame("Žluťoučký koní...", shorten_text($text, 17, true));
1049
        $this->assertSame("Žluťoučký ...", shorten_text($text, 17, false));
1050
 
1051
        // .........123456789012345678...901234567....89012345.
1052
        $text = "<p>Žluťoučký koníček <b>přeskočil</b> potůček</p>";
1053
        $this->assertSame($text, shorten_text($text, 60));
1054
        $this->assertSame("<p>Žluťoučký koníček ...</p>", shorten_text($text, 21));
1055
        $this->assertSame("<p>Žluťoučký koníče...</p>", shorten_text($text, 19, true));
1056
        $this->assertSame("<p>Žluťoučký ...</p>", shorten_text($text, 19, false));
1057
        // And try it with 2 fewer (that are, in bytes, the middle of a sequence).
1058
        $this->assertSame("<p>Žluťoučký koní...</p>", shorten_text($text, 17, true));
1059
        $this->assertSame("<p>Žluťoučký ...</p>", shorten_text($text, 17, false));
1060
        // And try over one tag (start/end), it does proper text len.
1061
        $this->assertSame("<p>Žluťoučký koníček <b>př...</b></p>", shorten_text($text, 23, true));
1062
        $this->assertSame("<p>Žluťoučký koníček <b>přeskočil</b> pot...</p>", shorten_text($text, 34, true));
1063
        // And in the middle of one tag.
1064
        $this->assertSame("<p>Žluťoučký koníček <b>přeskočil...</b></p>", shorten_text($text, 30, true));
1065
    }
1066
 
1067
    public function test_shorten_text_utf8_oriental() {
1068
        // Japanese
1069
        // text without tags
1070
        // ......123456789012345678901234.
1071
        $text = '言語設定言語設定abcdefghijkl';
1072
        $this->assertSame($text, shorten_text($text)); // 30 chars by default.
1073
        $this->assertSame("言語設定言語...", shorten_text($text, 9, true));
1074
        $this->assertSame("言語設定言語...", shorten_text($text, 9, false));
1075
        $this->assertSame("言語設定言語設定ab...", shorten_text($text, 13, true));
1076
        $this->assertSame("言語設定言語設定...", shorten_text($text, 13, false));
1077
 
1078
        // Chinese
1079
        // text without tags
1080
        // ......123456789012345678901234.
1081
        $text = '简体中文简体中文abcdefghijkl';
1082
        $this->assertSame($text, shorten_text($text)); // 30 chars by default.
1083
        $this->assertSame("简体中文简体...", shorten_text($text, 9, true));
1084
        $this->assertSame("简体中文简体...", shorten_text($text, 9, false));
1085
        $this->assertSame("简体中文简体中文ab...", shorten_text($text, 13, true));
1086
        $this->assertSame("简体中文简体中文...", shorten_text($text, 13, false));
1087
    }
1088
 
1089
    public function test_shorten_text_multilang() {
1090
        // This is not necessaryily specific to multilang. The issue is really
1091
        // tags with attributes, where before we were generating invalid HTML
1092
        // output like shorten_text('<span id="x" class="y">A</span> B', 1)
1093
        // returning '<span id="x" ...</span>'. It is just that multilang
1094
        // requires the sort of HTML that is quite likely to trigger this.
1095
        // ........................................1...
1096
        $text = '<span lang="en" class="multilang">A</span>' .
1097
                '<span lang="fr" class="multilang">B</span>';
1098
        $this->assertSame('<span lang="en" class="multilang">...</span>',
1099
                shorten_text($text, 1));
1100
    }
1101
 
1102
    /**
1103
     * Provider for long filenames and its expected result, with and without hash.
1104
     *
1105
     * @return array of ($filename, $length, $expected, $includehash)
1106
     */
1107
    public function shorten_filename_provider() {
1108
        $filename = 'sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium totam rem';
1109
        $shortfilename = 'sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque';
1110
 
1111
        return [
1112
            'More than 100 characters' => [
1113
                $filename,
1114
                null,
1115
                'sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium tot',
1116
                false,
1117
            ],
1118
            'More than 100 characters with hash' => [
1119
                $filename,
1120
                null,
1121
                'sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque l - 3bec1da8b8',
1122
                true,
1123
            ],
1124
            'More than 100 characters with extension' => [
1125
                "{$filename}.zip",
1126
                null,
1127
                'sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium tot.zip',
1128
                false,
1129
            ],
1130
            'More than 100 characters with extension and hash' => [
1131
                "{$filename}.zip",
1132
                null,
1133
                'sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque l - 3bec1da8b8.zip',
1134
                true,
1135
            ],
1136
            'Limit filename to 50 chars' => [
1137
                $filename,
1138
                50,
1139
                'sed ut perspiciatis unde omnis iste natus error si',
1140
                false,
1141
            ],
1142
            'Limit filename to 50 chars with hash' => [
1143
                $filename,
1144
                50,
1145
                'sed ut perspiciatis unde omnis iste n - 3bec1da8b8',
1146
                true,
1147
            ],
1148
            'Limit filename to 50 chars with extension' => [
1149
                "{$filename}.zip",
1150
                50,
1151
                'sed ut perspiciatis unde omnis iste natus error si.zip',
1152
                false,
1153
            ],
1154
            'Limit filename to 50 chars with extension and hash' => [
1155
                "{$filename}.zip",
1156
                50,
1157
                'sed ut perspiciatis unde omnis iste n - 3bec1da8b8.zip',
1158
                true,
1159
            ],
1160
            'Test filename that contains less than 100 characters' => [
1161
                $shortfilename,
1162
                null,
1163
                $shortfilename,
1164
                false,
1165
            ],
1166
            'Test filename that contains less than 100 characters and hash' => [
1167
                $shortfilename,
1168
                null,
1169
                $shortfilename,
1170
                true,
1171
            ],
1172
            'Test filename that contains less than 100 characters with extension' => [
1173
                "{$shortfilename}.zip",
1174
                null,
1175
                "{$shortfilename}.zip",
1176
                false,
1177
            ],
1178
            'Test filename that contains less than 100 characters with extension and hash' => [
1179
                "{$shortfilename}.zip",
1180
                null,
1181
                "{$shortfilename}.zip",
1182
                true,
1183
            ],
1184
        ];
1185
    }
1186
 
1187
    /**
1188
     * Test the {@link shorten_filename()} method.
1189
     *
1190
     * @dataProvider shorten_filename_provider
1191
     *
1192
     * @param string $filename
1193
     * @param int $length
1194
     * @param string $expected
1195
     * @param boolean $includehash
1196
     */
1197
    public function test_shorten_filename($filename, $length, $expected, $includehash) {
1198
        if (null === $length) {
1199
            $length = MAX_FILENAME_SIZE;
1200
        }
1201
 
1202
        $this->assertSame($expected, shorten_filename($filename, $length, $includehash));
1203
    }
1204
 
1205
    /**
1206
     * Provider for long filenames and its expected result, with and without hash.
1207
     *
1208
     * @return array of ($filename, $length, $expected, $includehash)
1209
     */
1210
    public function shorten_filenames_provider() {
1211
        $shortfilename = 'sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque';
1212
        $longfilename = 'sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium totam rem';
1213
        $extfilename = $longfilename.'.zip';
1214
        $expected = 'sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium tot';
1215
        $expectedwithhash = 'sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque l - 3bec1da8b8';
1216
        $expectedext = 'sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium tot.zip';
1217
        $expectedextwithhash = 'sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque l - 3bec1da8b8.zip';
1218
        $expected50 = 'sed ut perspiciatis unde omnis iste natus error si';
1219
        $expected50withhash = 'sed ut perspiciatis unde omnis iste n - 3bec1da8b8';
1220
        $expected50ext = 'sed ut perspiciatis unde omnis iste natus error si.zip';
1221
        $expected50extwithhash = 'sed ut perspiciatis unde omnis iste n - 3bec1da8b8.zip';
1222
        $expected50short = 'sed ut perspiciatis unde omnis iste n - 5fb6543490';
1223
 
1224
        return [
1225
            'Empty array without hash' => [
1226
                [],
1227
                null,
1228
                [],
1229
                false,
1230
            ],
1231
            'Empty array with hash' => [
1232
                [],
1233
                null,
1234
                [],
1235
                true,
1236
            ],
1237
            'Array with less than 100 characters' => [
1238
                [$shortfilename, $shortfilename, $shortfilename],
1239
                null,
1240
                [$shortfilename, $shortfilename, $shortfilename],
1241
                false,
1242
            ],
1243
            'Array with more than 100 characters without hash' => [
1244
                [$longfilename, $longfilename, $longfilename],
1245
                null,
1246
                [$expected, $expected, $expected],
1247
                false,
1248
            ],
1249
            'Array with more than 100 characters with hash' => [
1250
                [$longfilename, $longfilename, $longfilename],
1251
                null,
1252
                [$expectedwithhash, $expectedwithhash, $expectedwithhash],
1253
                true,
1254
            ],
1255
            'Array with more than 100 characters with extension' => [
1256
                [$extfilename, $extfilename, $extfilename],
1257
                null,
1258
                [$expectedext, $expectedext, $expectedext],
1259
                false,
1260
            ],
1261
            'Array with more than 100 characters with extension and hash' => [
1262
                [$extfilename, $extfilename, $extfilename],
1263
                null,
1264
                [$expectedextwithhash, $expectedextwithhash, $expectedextwithhash],
1265
                true,
1266
            ],
1267
            'Array with more than 100 characters mix (short, long, with extension) without hash' => [
1268
                [$shortfilename, $longfilename, $extfilename],
1269
                null,
1270
                [$shortfilename, $expected, $expectedext],
1271
                false,
1272
            ],
1273
            'Array with more than 100 characters mix (short, long, with extension) with hash' => [
1274
                [$shortfilename, $longfilename, $extfilename],
1275
                null,
1276
                [$shortfilename, $expectedwithhash, $expectedextwithhash],
1277
                true,
1278
            ],
1279
            'Array with less than 50 characters without hash' => [
1280
                [$longfilename, $longfilename, $longfilename],
1281
                50,
1282
                [$expected50, $expected50, $expected50],
1283
                false,
1284
            ],
1285
            'Array with less than 50 characters with hash' => [
1286
                [$longfilename, $longfilename, $longfilename],
1287
                50,
1288
                [$expected50withhash, $expected50withhash, $expected50withhash],
1289
                true,
1290
            ],
1291
            'Array with less than 50 characters with extension' => [
1292
                [$extfilename, $extfilename, $extfilename],
1293
                50,
1294
                [$expected50ext, $expected50ext, $expected50ext],
1295
                false,
1296
            ],
1297
            'Array with less than 50 characters with extension and hash' => [
1298
                [$extfilename, $extfilename, $extfilename],
1299
                50,
1300
                [$expected50extwithhash, $expected50extwithhash, $expected50extwithhash],
1301
                true,
1302
            ],
1303
            'Array with less than 50 characters mix (short, long, with extension) without hash' => [
1304
                [$shortfilename, $longfilename, $extfilename],
1305
                50,
1306
                [$expected50, $expected50, $expected50ext],
1307
                false,
1308
            ],
1309
            'Array with less than 50 characters mix (short, long, with extension) with hash' => [
1310
                [$shortfilename, $longfilename, $extfilename],
1311
                50,
1312
                [$expected50short, $expected50withhash, $expected50extwithhash],
1313
                true,
1314
            ],
1315
        ];
1316
    }
1317
 
1318
    /**
1319
     * Test the {@link shorten_filenames()} method.
1320
     *
1321
     * @dataProvider shorten_filenames_provider
1322
     *
1323
     * @param array $filenames
1324
     * @param int $length
1325
     * @param string $expected
1326
     * @param boolean $includehash
1327
     */
1328
    public function test_shorten_filenames($filenames, $length, $expected, $includehash) {
1329
        if (null === $length) {
1330
            $length = MAX_FILENAME_SIZE;
1331
        }
1332
 
1333
        $this->assertSame($expected, shorten_filenames($filenames, $length, $includehash));
1334
    }
1335
 
1336
    public function test_usergetdate() {
1337
        global $USER, $CFG, $DB;
1338
        $this->resetAfterTest();
1339
 
1340
        $this->setAdminUser();
1341
 
1342
        $USER->timezone = 2;// Set the timezone to a known state.
1343
 
1344
        $ts = 1261540267; // The time this function was created.
1345
 
1346
        $arr = usergetdate($ts, 1); // Specify the timezone as an argument.
1347
        $arr = array_values($arr);
1348
 
1349
        list($seconds, $minutes, $hours, $mday, $wday, $mon, $year, $yday, $weekday, $month) = $arr;
1350
        $this->assertSame(7, $seconds);
1351
        $this->assertSame(51, $minutes);
1352
        $this->assertSame(4, $hours);
1353
        $this->assertSame(23, $mday);
1354
        $this->assertSame(3, $wday);
1355
        $this->assertSame(12, $mon);
1356
        $this->assertSame(2009, $year);
1357
        $this->assertSame(356, $yday);
1358
        $this->assertSame('Wednesday', $weekday);
1359
        $this->assertSame('December', $month);
1360
        $arr = usergetdate($ts); // Gets the timezone from the $USER object.
1361
        $arr = array_values($arr);
1362
 
1363
        list($seconds, $minutes, $hours, $mday, $wday, $mon, $year, $yday, $weekday, $month) = $arr;
1364
        $this->assertSame(7, $seconds);
1365
        $this->assertSame(51, $minutes);
1366
        $this->assertSame(5, $hours);
1367
        $this->assertSame(23, $mday);
1368
        $this->assertSame(3, $wday);
1369
        $this->assertSame(12, $mon);
1370
        $this->assertSame(2009, $year);
1371
        $this->assertSame(356, $yday);
1372
        $this->assertSame('Wednesday', $weekday);
1373
        $this->assertSame('December', $month);
1374
 
1375
        // Edge cases - 0 and null - they all mean 1st Jan 1970. Null shows debugging message.
1376
        $this->assertSame(1970, usergetdate(0)['year']);
1377
        $this->assertDebuggingNotCalled();
1378
        $this->assertSame(1970, usergetdate(null)['year']);
1379
        $this->assertDebuggingCalled(null, DEBUG_DEVELOPER);
1380
    }
1381
 
1382
    public function test_mark_user_preferences_changed() {
1383
        $this->resetAfterTest();
1384
        $otheruser = $this->getDataGenerator()->create_user();
1385
        $otheruserid = $otheruser->id;
1386
 
1387
        set_cache_flag('userpreferenceschanged', $otheruserid, null);
1388
        mark_user_preferences_changed($otheruserid);
1389
 
1390
        $this->assertEquals(get_cache_flag('userpreferenceschanged', $otheruserid, time()-10), 1);
1391
        set_cache_flag('userpreferenceschanged', $otheruserid, null);
1392
    }
1393
 
1394
    public function test_check_user_preferences_loaded() {
1395
        global $DB;
1396
        $this->resetAfterTest();
1397
 
1398
        $otheruser = $this->getDataGenerator()->create_user();
1399
        $otheruserid = $otheruser->id;
1400
 
1401
        $DB->delete_records('user_preferences', array('userid'=>$otheruserid));
1402
        set_cache_flag('userpreferenceschanged', $otheruserid, null);
1403
 
1404
        $user = new \stdClass();
1405
        $user->id = $otheruserid;
1406
 
1407
        // Load.
1408
        check_user_preferences_loaded($user);
1409
        $this->assertTrue(isset($user->preference));
1410
        $this->assertTrue(is_array($user->preference));
1411
        $this->assertArrayHasKey('_lastloaded', $user->preference);
1412
        $this->assertCount(1, $user->preference);
1413
 
1414
        // Add preference via direct call.
1415
        $DB->insert_record('user_preferences', array('name'=>'xxx', 'value'=>'yyy', 'userid'=>$user->id));
1416
 
1417
        // No cache reload yet.
1418
        check_user_preferences_loaded($user);
1419
        $this->assertCount(1, $user->preference);
1420
 
1421
        // Forced reloading of cache.
1422
        unset($user->preference);
1423
        check_user_preferences_loaded($user);
1424
        $this->assertCount(2, $user->preference);
1425
        $this->assertSame('yyy', $user->preference['xxx']);
1426
 
1427
        // Add preference via direct call.
1428
        $DB->insert_record('user_preferences', array('name'=>'aaa', 'value'=>'bbb', 'userid'=>$user->id));
1429
 
1430
        // Test timeouts and modifications from different session.
1431
        set_cache_flag('userpreferenceschanged', $user->id, 1, time() + 1000);
1432
        $user->preference['_lastloaded'] = $user->preference['_lastloaded'] - 20;
1433
        check_user_preferences_loaded($user);
1434
        $this->assertCount(2, $user->preference);
1435
        check_user_preferences_loaded($user, 10);
1436
        $this->assertCount(3, $user->preference);
1437
        $this->assertSame('bbb', $user->preference['aaa']);
1438
        set_cache_flag('userpreferenceschanged', $user->id, null);
1439
    }
1440
 
1441
    public function test_set_user_preference() {
1442
        global $DB, $USER;
1443
        $this->resetAfterTest();
1444
 
1445
        $this->setAdminUser();
1446
 
1447
        $otheruser = $this->getDataGenerator()->create_user();
1448
        $otheruserid = $otheruser->id;
1449
 
1450
        $DB->delete_records('user_preferences', array('userid'=>$otheruserid));
1451
        set_cache_flag('userpreferenceschanged', $otheruserid, null);
1452
 
1453
        $user = new \stdClass();
1454
        $user->id = $otheruserid;
1455
 
1456
        set_user_preference('aaa', 'bbb', $otheruserid);
1457
        $this->assertSame('bbb', $DB->get_field('user_preferences', 'value', array('userid'=>$otheruserid, 'name'=>'aaa')));
1458
        $this->assertSame('bbb', get_user_preferences('aaa', null, $otheruserid));
1459
 
1460
        set_user_preference('xxx', 'yyy', $user);
1461
        $this->assertSame('yyy', $DB->get_field('user_preferences', 'value', array('userid'=>$otheruserid, 'name'=>'xxx')));
1462
        $this->assertSame('yyy', get_user_preferences('xxx', null, $otheruserid));
1463
        $this->assertTrue(is_array($user->preference));
1464
        $this->assertSame('bbb', $user->preference['aaa']);
1465
        $this->assertSame('yyy', $user->preference['xxx']);
1466
 
1467
        set_user_preference('xxx', null, $user);
1468
        $this->assertFalse($DB->get_field('user_preferences', 'value', array('userid'=>$otheruserid, 'name'=>'xxx')));
1469
        $this->assertNull(get_user_preferences('xxx', null, $otheruserid));
1470
 
1471
        set_user_preference('ooo', true, $user);
1472
        $prefs = get_user_preferences(null, null, $otheruserid);
1473
        $this->assertSame($user->preference['aaa'], $prefs['aaa']);
1474
        $this->assertSame($user->preference['ooo'], $prefs['ooo']);
1475
        $this->assertSame('1', $prefs['ooo']);
1476
 
1477
        set_user_preference('null', 0, $user);
1478
        $this->assertSame('0', get_user_preferences('null', null, $otheruserid));
1479
 
1480
        $this->assertSame('lala', get_user_preferences('undefined', 'lala', $otheruserid));
1481
 
1482
        $DB->delete_records('user_preferences', array('userid'=>$otheruserid));
1483
        set_cache_flag('userpreferenceschanged', $otheruserid, null);
1484
 
1485
        // Test $USER default.
1486
        set_user_preference('_test_user_preferences_pref', 'ok');
1487
        $this->assertSame('ok', $USER->preference['_test_user_preferences_pref']);
1488
        unset_user_preference('_test_user_preferences_pref');
1489
        $this->assertTrue(!isset($USER->preference['_test_user_preferences_pref']));
1490
 
1491
        // Test 1333 char values (no need for unicode, there are already tests for that in DB tests).
1492
        $longvalue = str_repeat('a', 1333);
1493
        set_user_preference('_test_long_user_preference', $longvalue);
1494
        $this->assertEquals($longvalue, get_user_preferences('_test_long_user_preference'));
1495
        $this->assertEquals($longvalue,
1496
            $DB->get_field('user_preferences', 'value', array('userid' => $USER->id, 'name' => '_test_long_user_preference')));
1497
 
1498
        // Test > 1333 char values, coding_exception expected.
1499
        $longvalue = str_repeat('a', 1334);
1500
        try {
1501
            set_user_preference('_test_long_user_preference', $longvalue);
1502
            $this->fail('Exception expected - longer than 1333 chars not allowed as preference value');
1503
        } catch (\moodle_exception $ex) {
1504
            $this->assertInstanceOf('coding_exception', $ex);
1505
        }
1506
 
1507
        // Test invalid params.
1508
        try {
1509
            set_user_preference('_test_user_preferences_pref', array());
1510
            $this->fail('Exception expected - array not valid preference value');
1511
        } catch (\moodle_exception $ex) {
1512
            $this->assertInstanceOf('coding_exception', $ex);
1513
        }
1514
        try {
1515
            set_user_preference('_test_user_preferences_pref', new \stdClass);
1516
            $this->fail('Exception expected - class not valid preference value');
1517
        } catch (\moodle_exception $ex) {
1518
            $this->assertInstanceOf('coding_exception', $ex);
1519
        }
1520
        try {
1521
            set_user_preference('_test_user_preferences_pref', 1, array('xx' => 1));
1522
            $this->fail('Exception expected - user instance expected');
1523
        } catch (\moodle_exception $ex) {
1524
            $this->assertInstanceOf('coding_exception', $ex);
1525
        }
1526
        try {
1527
            set_user_preference('_test_user_preferences_pref', 1, 'abc');
1528
            $this->fail('Exception expected - user instance expected');
1529
        } catch (\moodle_exception $ex) {
1530
            $this->assertInstanceOf('coding_exception', $ex);
1531
        }
1532
        try {
1533
            set_user_preference('', 1);
1534
            $this->fail('Exception expected - invalid name accepted');
1535
        } catch (\moodle_exception $ex) {
1536
            $this->assertInstanceOf('coding_exception', $ex);
1537
        }
1538
        try {
1539
            set_user_preference('1', 1);
1540
            $this->fail('Exception expected - invalid name accepted');
1541
        } catch (\moodle_exception $ex) {
1542
            $this->assertInstanceOf('coding_exception', $ex);
1543
        }
1544
    }
1545
 
1546
    public function test_set_user_preference_for_current_user() {
1547
        global $USER;
1548
        $this->resetAfterTest();
1549
        $this->setAdminUser();
1550
 
1551
        set_user_preference('test_pref', 2);
1552
        set_user_preference('test_pref', 1, $USER->id);
1553
        $this->assertEquals(1, get_user_preferences('test_pref'));
1554
    }
1555
 
1556
    public function test_unset_user_preference_for_current_user() {
1557
        global $USER;
1558
        $this->resetAfterTest();
1559
        $this->setAdminUser();
1560
 
1561
        set_user_preference('test_pref', 1);
1562
        unset_user_preference('test_pref', $USER->id);
1563
        $this->assertNull(get_user_preferences('test_pref'));
1564
    }
1565
 
1566
    /**
1567
     * Test some critical TZ/DST.
1568
     *
1569
     * This method tests some special TZ/DST combinations that were fixed
1570
     * by MDL-38999. The tests are done by comparing the results of the
1571
     * output using Moodle TZ/DST support and PHP native one.
1572
     *
1573
     * Note: If you don't trust PHP TZ/DST support, can verify the
1574
     * harcoded expectations below with:
1575
     * http://www.tools4noobs.com/online_tools/unix_timestamp_to_datetime/
1576
     */
1577
    public function test_some_moodle_special_dst() {
1578
        $stamp = 1365386400; // 2013/04/08 02:00:00 GMT/UTC.
1579
 
1580
        // In Europe/Tallinn it was 2013/04/08 05:00:00.
1581
        $expectation = '2013/04/08 05:00:00';
1582
        $phpdt = \DateTime::createFromFormat('U', $stamp, new \DateTimeZone('UTC'));
1583
        $phpdt->setTimezone(new \DateTimeZone('Europe/Tallinn'));
1584
        $phpres = $phpdt->format('Y/m/d H:i:s'); // PHP result.
1585
        $moodleres = userdate($stamp, '%Y/%m/%d %H:%M:%S', 'Europe/Tallinn', false); // Moodle result.
1586
        $this->assertSame($expectation, $phpres);
1587
        $this->assertSame($expectation, $moodleres);
1588
 
1589
        // In St. Johns it was 2013/04/07 23:30:00.
1590
        $expectation = '2013/04/07 23:30:00';
1591
        $phpdt = \DateTime::createFromFormat('U', $stamp, new \DateTimeZone('UTC'));
1592
        $phpdt->setTimezone(new \DateTimeZone('America/St_Johns'));
1593
        $phpres = $phpdt->format('Y/m/d H:i:s'); // PHP result.
1594
        $moodleres = userdate($stamp, '%Y/%m/%d %H:%M:%S', 'America/St_Johns', false); // Moodle result.
1595
        $this->assertSame($expectation, $phpres);
1596
        $this->assertSame($expectation, $moodleres);
1597
 
1598
        $stamp = 1383876000; // 2013/11/08 02:00:00 GMT/UTC.
1599
 
1600
        // In Europe/Tallinn it was 2013/11/08 04:00:00.
1601
        $expectation = '2013/11/08 04:00:00';
1602
        $phpdt = \DateTime::createFromFormat('U', $stamp, new \DateTimeZone('UTC'));
1603
        $phpdt->setTimezone(new \DateTimeZone('Europe/Tallinn'));
1604
        $phpres = $phpdt->format('Y/m/d H:i:s'); // PHP result.
1605
        $moodleres = userdate($stamp, '%Y/%m/%d %H:%M:%S', 'Europe/Tallinn', false); // Moodle result.
1606
        $this->assertSame($expectation, $phpres);
1607
        $this->assertSame($expectation, $moodleres);
1608
 
1609
        // In St. Johns it was 2013/11/07 22:30:00.
1610
        $expectation = '2013/11/07 22:30:00';
1611
        $phpdt = \DateTime::createFromFormat('U', $stamp, new \DateTimeZone('UTC'));
1612
        $phpdt->setTimezone(new \DateTimeZone('America/St_Johns'));
1613
        $phpres = $phpdt->format('Y/m/d H:i:s'); // PHP result.
1614
        $moodleres = userdate($stamp, '%Y/%m/%d %H:%M:%S', 'America/St_Johns', false); // Moodle result.
1615
        $this->assertSame($expectation, $phpres);
1616
        $this->assertSame($expectation, $moodleres);
1617
    }
1618
 
1619
    public function test_userdate() {
1620
        global $USER, $CFG, $DB;
1621
        $this->resetAfterTest();
1622
 
1623
        $this->setAdminUser();
1624
 
1625
        $testvalues = array(
1626
            array(
1627
                'time' => '1309514400',
1628
                'usertimezone' => 'America/Moncton',
1629
                'timezone' => '0.0', // No dst offset.
1630
                'expectedoutput' => 'Friday, 1 July 2011, 10:00 AM',
1631
                'expectedoutputhtml' => '<time datetime="2011-07-01T07:00:00-03:00">Friday, 1 July 2011, 10:00 AM</time>'
1632
            ),
1633
            array(
1634
                'time' => '1309514400',
1635
                'usertimezone' => 'America/Moncton',
1636
                'timezone' => '99', // Dst offset and timezone offset.
1637
                'expectedoutput' => 'Friday, 1 July 2011, 7:00 AM',
1638
                'expectedoutputhtml' => '<time datetime="2011-07-01T07:00:00-03:00">Friday, 1 July 2011, 7:00 AM</time>'
1639
            ),
1640
            array(
1641
                'time' => '1309514400',
1642
                'usertimezone' => 'America/Moncton',
1643
                'timezone' => 'America/Moncton', // Dst offset and timezone offset.
1644
                'expectedoutput' => 'Friday, 1 July 2011, 7:00 AM',
1645
                'expectedoutputhtml' => '<time datetime="2011-07-01t07:00:00-03:00">Friday, 1 July 2011, 7:00 AM</time>'
1646
            ),
1647
            array(
1648
                'time' => '1293876000 ',
1649
                'usertimezone' => 'America/Moncton',
1650
                'timezone' => '0.0', // No dst offset.
1651
                'expectedoutput' => 'Saturday, 1 January 2011, 10:00 AM',
1652
                'expectedoutputhtml' => '<time datetime="2011-01-01T06:00:00-04:00">Saturday, 1 January 2011, 10:00 AM</time>'
1653
            ),
1654
            array(
1655
                'time' => '1293876000 ',
1656
                'usertimezone' => 'America/Moncton',
1657
                'timezone' => '99', // No dst offset in jan, so just timezone offset.
1658
                'expectedoutput' => 'Saturday, 1 January 2011, 6:00 AM',
1659
                'expectedoutputhtml' => '<time datetime="2011-01-01T06:00:00-04:00">Saturday, 1 January 2011, 6:00 AM</time>'
1660
            ),
1661
            array(
1662
                'time' => '1293876000 ',
1663
                'usertimezone' => 'America/Moncton',
1664
                'timezone' => 'America/Moncton', // No dst offset in jan.
1665
                'expectedoutput' => 'Saturday, 1 January 2011, 6:00 AM',
1666
                'expectedoutputhtml' => '<time datetime="2011-01-01T06:00:00-04:00">Saturday, 1 January 2011, 6:00 AM</time>'
1667
            ),
1668
            array(
1669
                'time' => '1293876000 ',
1670
                'usertimezone' => '2',
1671
                'timezone' => '99', // Take user timezone.
1672
                'expectedoutput' => 'Saturday, 1 January 2011, 12:00 PM',
1673
                'expectedoutputhtml' => '<time datetime="2011-01-01T12:00:00+02:00">Saturday, 1 January 2011, 12:00 PM</time>'
1674
            ),
1675
            array(
1676
                'time' => '1293876000 ',
1677
                'usertimezone' => '-2',
1678
                'timezone' => '99', // Take user timezone.
1679
                'expectedoutput' => 'Saturday, 1 January 2011, 8:00 AM',
1680
                'expectedoutputhtml' => '<time datetime="2011-01-01T08:00:00-02:00">Saturday, 1 January 2011, 8:00 AM</time>'
1681
            ),
1682
            array(
1683
                'time' => '1293876000 ',
1684
                'usertimezone' => '-10',
1685
                'timezone' => '2', // Take this timezone.
1686
                'expectedoutput' => 'Saturday, 1 January 2011, 12:00 PM',
1687
                'expectedoutputhtml' => '<time datetime="2011-01-01T00:00:00-10:00">Saturday, 1 January 2011, 12:00 PM</time>'
1688
            ),
1689
            array(
1690
                'time' => '1293876000 ',
1691
                'usertimezone' => '-10',
1692
                'timezone' => '-2', // Take this timezone.
1693
                'expectedoutput' => 'Saturday, 1 January 2011, 8:00 AM',
1694
                'expectedoutputhtml' => '<time datetime="2011-01-01T00:00:00-10:00">Saturday, 1 January 2011, 8:00 AM</time>'
1695
            ),
1696
            array(
1697
                'time' => '1293876000 ',
1698
                'usertimezone' => '-10',
1699
                'timezone' => 'random/time', // This should show server time.
1700
                'expectedoutput' => 'Saturday, 1 January 2011, 6:00 PM',
1701
                'expectedoutputhtml' => '<time datetime="2011-01-01T00:00:00-10:00">Saturday, 1 January 2011, 6:00 PM</time>'
1702
            ),
1703
            array(
1704
                'time' => '1293876000 ',
1705
                'usertimezone' => '20', // Fallback to server time zone.
1706
                'timezone' => '99',     // This should show user time.
1707
                'expectedoutput' => 'Saturday, 1 January 2011, 6:00 PM',
1708
                'expectedoutputhtml' => '<time datetime="2011-01-01T18:00:00+08:00">Saturday, 1 January 2011, 6:00 PM</time>'
1709
            ),
1710
        );
1711
 
1712
        // Set default timezone to Australia/Perth, else time calculated
1713
        // will not match expected values.
1714
        $this->setTimezone(99, 'Australia/Perth');
1715
 
1716
        foreach ($testvalues as $vals) {
1717
            $USER->timezone = $vals['usertimezone'];
1718
            $actualoutput = userdate($vals['time'], '%A, %d %B %Y, %I:%M %p', $vals['timezone']);
1719
            $actualoutputhtml = userdate_htmltime($vals['time'], '%A, %d %B %Y, %I:%M %p', $vals['timezone']);
1720
 
1721
            // On different systems case of AM PM changes so compare case insensitive.
1722
            $vals['expectedoutput'] = \core_text::strtolower($vals['expectedoutput']);
1723
            $vals['expectedoutputhtml'] = \core_text::strtolower($vals['expectedoutputhtml']);
1724
            $actualoutput = \core_text::strtolower($actualoutput);
1725
            $actualoutputhtml = \core_text::strtolower($actualoutputhtml);
1726
 
1727
            $this->assertSame($vals['expectedoutput'], $actualoutput,
1728
                "Expected: {$vals['expectedoutput']} => Actual: {$actualoutput} \ndata: " . var_export($vals, true));
1729
            $this->assertSame($vals['expectedoutputhtml'], $actualoutputhtml,
1730
                "Expected: {$vals['expectedoutputhtml']} => Actual: {$actualoutputhtml} \ndata: " . var_export($vals, true));
1731
        }
1732
    }
1733
 
1734
    /**
1735
     * Make sure the DST changes happen at the right time in Moodle.
1736
     */
1737
    public function test_dst_changes() {
1738
        // DST switching in Prague.
1739
        // From 2AM to 3AM in 1989.
1740
        $date = new \DateTime('1989-03-26T01:59:00+01:00');
1741
        $this->assertSame('Sunday, 26 March 1989, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1742
        $date = new \DateTime('1989-03-26T02:01:00+01:00');
1743
        $this->assertSame('Sunday, 26 March 1989, 03:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1744
        // From 3AM to 2AM in 1989 - not the same as the west Europe.
1745
        $date = new \DateTime('1989-09-24T01:59:00+01:00');
1746
        $this->assertSame('Sunday, 24 September 1989, 02:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1747
        $date = new \DateTime('1989-09-24T02:01:00+01:00');
1748
        $this->assertSame('Sunday, 24 September 1989, 02:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1749
        // From 2AM to 3AM in 2014.
1750
        $date = new \DateTime('2014-03-30T01:59:00+01:00');
1751
        $this->assertSame('Sunday, 30 March 2014, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1752
        $date = new \DateTime('2014-03-30T02:01:00+01:00');
1753
        $this->assertSame('Sunday, 30 March 2014, 03:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1754
        // From 3AM to 2AM in 2014.
1755
        $date = new \DateTime('2014-10-26T01:59:00+01:00');
1756
        $this->assertSame('Sunday, 26 October 2014, 02:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1757
        $date = new \DateTime('2014-10-26T02:01:00+01:00');
1758
        $this->assertSame('Sunday, 26 October 2014, 02:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1759
        // From 2AM to 3AM in 2020.
1760
        $date = new \DateTime('2020-03-29T01:59:00+01:00');
1761
        $this->assertSame('Sunday, 29 March 2020, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1762
        $date = new \DateTime('2020-03-29T02:01:00+01:00');
1763
        $this->assertSame('Sunday, 29 March 2020, 03:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1764
        // From 3AM to 2AM in 2020.
1765
        $date = new \DateTime('2020-10-25T01:59:00+01:00');
1766
        $this->assertSame('Sunday, 25 October 2020, 02:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1767
        $date = new \DateTime('2020-10-25T02:01:00+01:00');
1768
        $this->assertSame('Sunday, 25 October 2020, 02:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
1769
 
1770
        // DST switching in NZ.
1771
        // From 3AM to 2AM in 2015.
1772
        $date = new \DateTime('2015-04-05T02:59:00+13:00');
1773
        $this->assertSame('Sunday, 5 April 2015, 02:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Pacific/Auckland'));
1774
        $date = new \DateTime('2015-04-05T03:01:00+13:00');
1775
        $this->assertSame('Sunday, 5 April 2015, 02:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Pacific/Auckland'));
1776
        // From 2AM to 3AM in 2009.
1777
        $date = new \DateTime('2015-09-27T01:59:00+12:00');
1778
        $this->assertSame('Sunday, 27 September 2015, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Pacific/Auckland'));
1779
        $date = new \DateTime('2015-09-27T02:01:00+12:00');
1780
        $this->assertSame('Sunday, 27 September 2015, 03:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Pacific/Auckland'));
1781
 
1782
        // DST switching in Perth.
1783
        // From 3AM to 2AM in 2009.
1784
        $date = new \DateTime('2008-03-30T01:59:00+08:00');
1785
        $this->assertSame('Sunday, 30 March 2008, 02:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Australia/Perth'));
1786
        $date = new \DateTime('2008-03-30T02:01:00+08:00');
1787
        $this->assertSame('Sunday, 30 March 2008, 02:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Australia/Perth'));
1788
        // From 2AM to 3AM in 2009.
1789
        $date = new \DateTime('2008-10-26T01:59:00+08:00');
1790
        $this->assertSame('Sunday, 26 October 2008, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Australia/Perth'));
1791
        $date = new \DateTime('2008-10-26T02:01:00+08:00');
1792
        $this->assertSame('Sunday, 26 October 2008, 03:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Australia/Perth'));
1793
 
1794
        // DST switching in US.
1795
        // From 2AM to 3AM in 2014.
1796
        $date = new \DateTime('2014-03-09T01:59:00-05:00');
1797
        $this->assertSame('Sunday, 9 March 2014, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'America/New_York'));
1798
        $date = new \DateTime('2014-03-09T02:01:00-05:00');
1799
        $this->assertSame('Sunday, 9 March 2014, 03:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'America/New_York'));
1800
        // From 3AM to 2AM in 2014.
1801
        $date = new \DateTime('2014-11-02T01:59:00-04:00');
1802
        $this->assertSame('Sunday, 2 November 2014, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'America/New_York'));
1803
        $date = new \DateTime('2014-11-02T02:01:00-04:00');
1804
        $this->assertSame('Sunday, 2 November 2014, 01:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'America/New_York'));
1805
    }
1806
 
1807
    public function test_make_timestamp() {
1808
        global $USER, $CFG, $DB;
1809
        $this->resetAfterTest();
1810
 
1811
        $this->setAdminUser();
1812
 
1813
        $testvalues = array(
1814
            array(
1815
                'usertimezone' => 'America/Moncton',
1816
                'year' => '2011',
1817
                'month' => '7',
1818
                'day' => '1',
1819
                'hour' => '10',
1820
                'minutes' => '00',
1821
                'seconds' => '00',
1822
                'timezone' => '0.0',
1823
                'applydst' => false, // No dst offset.
1824
                'expectedoutput' => '1309514400' // 6pm at UTC+0.
1825
            ),
1826
            array(
1827
                'usertimezone' => 'America/Moncton',
1828
                'year' => '2011',
1829
                'month' => '7',
1830
                'day' => '1',
1831
                'hour' => '10',
1832
                'minutes' => '00',
1833
                'seconds' => '00',
1834
                'timezone' => '99',  // User default timezone.
1835
                'applydst' => false, // Don't apply dst.
1836
                'expectedoutput' => '1309528800'
1837
            ),
1838
            array(
1839
                'usertimezone' => 'America/Moncton',
1840
                'year' => '2011',
1841
                'month' => '7',
1842
                'day' => '1',
1843
                'hour' => '10',
1844
                'minutes' => '00',
1845
                'seconds' => '00',
1846
                'timezone' => '99', // User default timezone.
1847
                'applydst' => true, // Apply dst.
1848
                'expectedoutput' => '1309525200'
1849
            ),
1850
            array(
1851
                'usertimezone' => 'America/Moncton',
1852
                'year' => '2011',
1853
                'month' => '7',
1854
                'day' => '1',
1855
                'hour' => '10',
1856
                'minutes' => '00',
1857
                'seconds' => '00',
1858
                'timezone' => 'America/Moncton', // String timezone.
1859
                'applydst' => true, // Apply dst.
1860
                'expectedoutput' => '1309525200'
1861
            ),
1862
            array(
1863
                'usertimezone' => '2', // No dst applyed.
1864
                'year' => '2011',
1865
                'month' => '7',
1866
                'day' => '1',
1867
                'hour' => '10',
1868
                'minutes' => '00',
1869
                'seconds' => '00',
1870
                'timezone' => '99', // Take user timezone.
1871
                'applydst' => true, // Apply dst.
1872
                'expectedoutput' => '1309507200'
1873
            ),
1874
            array(
1875
                'usertimezone' => '-2', // No dst applyed.
1876
                'year' => '2011',
1877
                'month' => '7',
1878
                'day' => '1',
1879
                'hour' => '10',
1880
                'minutes' => '00',
1881
                'seconds' => '00',
1882
                'timezone' => '99', // Take usertimezone.
1883
                'applydst' => true, // Apply dst.
1884
                'expectedoutput' => '1309521600'
1885
            ),
1886
            array(
1887
                'usertimezone' => '-10', // No dst applyed.
1888
                'year' => '2011',
1889
                'month' => '7',
1890
                'day' => '1',
1891
                'hour' => '10',
1892
                'minutes' => '00',
1893
                'seconds' => '00',
1894
                'timezone' => '2',  // Take this timezone.
1895
                'applydst' => true, // Apply dst.
1896
                'expectedoutput' => '1309507200'
1897
            ),
1898
            array(
1899
                'usertimezone' => '-10', // No dst applyed.
1900
                'year' => '2011',
1901
                'month' => '7',
1902
                'day' => '1',
1903
                'hour' => '10',
1904
                'minutes' => '00',
1905
                'seconds' => '00',
1906
                'timezone' => '-2', // Take this timezone.
1907
                'applydst' => true, // Apply dst.
1908
                'expectedoutput' => '1309521600'
1909
            ),
1910
            array(
1911
                'usertimezone' => '-10', // No dst applyed.
1912
                'year' => '2011',
1913
                'month' => '7',
1914
                'day' => '1',
1915
                'hour' => '10',
1916
                'minutes' => '00',
1917
                'seconds' => '00',
1918
                'timezone' => 'random/time', // This should show server time.
1919
                'applydst' => true,          // Apply dst.
1920
                'expectedoutput' => '1309485600'
1921
            ),
1922
            array(
1923
                'usertimezone' => '-14', // Server time.
1924
                'year' => '2011',
1925
                'month' => '7',
1926
                'day' => '1',
1927
                'hour' => '10',
1928
                'minutes' => '00',
1929
                'seconds' => '00',
1930
                'timezone' => '99', // Get user time.
1931
                'applydst' => true, // Apply dst.
1932
                'expectedoutput' => '1309485600'
1933
            )
1934
        );
1935
 
1936
        // Set default timezone to Australia/Perth, else time calculated
1937
        // will not match expected values.
1938
        $this->setTimezone(99, 'Australia/Perth');
1939
 
1940
        // Test make_timestamp with all testvals and assert if anything wrong.
1941
        foreach ($testvalues as $vals) {
1942
            $USER->timezone = $vals['usertimezone'];
1943
            $actualoutput = make_timestamp(
1944
                $vals['year'],
1945
                $vals['month'],
1946
                $vals['day'],
1947
                $vals['hour'],
1948
                $vals['minutes'],
1949
                $vals['seconds'],
1950
                $vals['timezone'],
1951
                $vals['applydst']
1952
            );
1953
 
1954
            // On different systems case of AM PM changes so compare case insensitive.
1955
            $vals['expectedoutput'] = \core_text::strtolower($vals['expectedoutput']);
1956
            $actualoutput = \core_text::strtolower($actualoutput);
1957
 
1958
            $this->assertSame($vals['expectedoutput'], $actualoutput,
1959
                "Expected: {$vals['expectedoutput']} => Actual: {$actualoutput},
1960
                Please check if timezones are updated (Site adminstration -> location -> update timezone)");
1961
        }
1962
    }
1963
 
1964
    /**
1965
     * Test get_string and most importantly the implementation of the lang_string
1966
     * object.
1967
     */
1968
    public function test_get_string() {
1969
        global $COURSE;
1970
 
1971
        // Make sure we are using English.
1972
        $originallang = $COURSE->lang;
1973
        $COURSE->lang = 'en';
1974
 
1975
        $yes = get_string('yes');
1976
        $yesexpected = 'Yes';
1977
        $this->assertIsString($yes);
1978
        $this->assertSame($yesexpected, $yes);
1979
 
1980
        $yes = get_string('yes', 'moodle');
1981
        $this->assertIsString($yes);
1982
        $this->assertSame($yesexpected, $yes);
1983
 
1984
        $yes = get_string('yes', 'core');
1985
        $this->assertIsString($yes);
1986
        $this->assertSame($yesexpected, $yes);
1987
 
1988
        $yes = get_string('yes', '');
1989
        $this->assertIsString($yes);
1990
        $this->assertSame($yesexpected, $yes);
1991
 
1992
        $yes = get_string('yes', null);
1993
        $this->assertIsString($yes);
1994
        $this->assertSame($yesexpected, $yes);
1995
 
1996
        $yes = get_string('yes', null, 1);
1997
        $this->assertIsString($yes);
1998
        $this->assertSame($yesexpected, $yes);
1999
 
2000
        $days = 1;
2001
        $numdays = get_string('numdays', 'core', '1');
2002
        $numdaysexpected = $days.' days';
2003
        $this->assertIsString($numdays);
2004
        $this->assertSame($numdaysexpected, $numdays);
2005
 
2006
        $yes = get_string('yes', null, null, true);
2007
        $this->assertInstanceOf('lang_string', $yes);
2008
        $this->assertSame($yesexpected, (string)$yes);
2009
 
2010
        // Test lazy loading (returning lang_string) correctly interpolates 0 being used as args.
2011
        $numdays = get_string('numdays', 'moodle', 0, true);
2012
        $this->assertInstanceOf(lang_string::class, $numdays);
2013
        $this->assertSame('0 days', (string) $numdays);
2014
 
2015
        // Test using a lang_string object as the $a argument for a normal
2016
        // get_string call (returning string).
2017
        $test = new lang_string('yes', null, null, true);
2018
        $testexpected = get_string('numdays', 'core', get_string('yes'));
2019
        $testresult = get_string('numdays', null, $test);
2020
        $this->assertIsString($testresult);
2021
        $this->assertSame($testexpected, $testresult);
2022
 
2023
        // Test using a lang_string object as the $a argument for an object
2024
        // get_string call (returning lang_string).
2025
        $test = new lang_string('yes', null, null, true);
2026
        $testexpected = get_string('numdays', 'core', get_string('yes'));
2027
        $testresult = get_string('numdays', null, $test, true);
2028
        $this->assertInstanceOf('lang_string', $testresult);
2029
        $this->assertSame($testexpected, "$testresult");
2030
 
2031
        // Make sure that object properties that can't be converted don't cause
2032
        // errors.
2033
        // Level one: This is as deep as current language processing goes.
2034
        $test = new \stdClass;
2035
        $test->one = 'here';
2036
        $string = get_string('yes', null, $test, true);
2037
        $this->assertEquals($yesexpected, $string);
2038
 
2039
        // Make sure that object properties that can't be converted don't cause
2040
        // errors.
2041
        // Level two: Language processing doesn't currently reach this deep.
2042
        // only immediate scalar properties are worked with.
2043
        $test = new \stdClass;
2044
        $test->one = new \stdClass;
2045
        $test->one->two = 'here';
2046
        $string = get_string('yes', null, $test, true);
2047
        $this->assertEquals($yesexpected, $string);
2048
 
2049
        // Make sure that object properties that can't be converted don't cause
2050
        // errors.
2051
        // Level three: It should never ever go this deep, but we're making sure
2052
        // it doesn't cause any probs anyway.
2053
        $test = new \stdClass;
2054
        $test->one = new \stdClass;
2055
        $test->one->two = new \stdClass;
2056
        $test->one->two->three = 'here';
2057
        $string = get_string('yes', null, $test, true);
2058
        $this->assertEquals($yesexpected, $string);
2059
 
2060
        // Make sure that object properties that can't be converted don't cause
2061
        // errors and check lang_string properties.
2062
        // Level one: This is as deep as current language processing goes.
2063
        $test = new \stdClass;
2064
        $test->one = new lang_string('yes');
2065
        $string = get_string('yes', null, $test, true);
2066
        $this->assertEquals($yesexpected, $string);
2067
 
2068
        // Make sure that object properties that can't be converted don't cause
2069
        // errors and check lang_string properties.
2070
        // Level two: Language processing doesn't currently reach this deep.
2071
        // only immediate scalar properties are worked with.
2072
        $test = new \stdClass;
2073
        $test->one = new \stdClass;
2074
        $test->one->two = new lang_string('yes');
2075
        $string = get_string('yes', null, $test, true);
2076
        $this->assertEquals($yesexpected, $string);
2077
 
2078
        // Make sure that object properties that can't be converted don't cause
2079
        // errors and check lang_string properties.
2080
        // Level three: It should never ever go this deep, but we're making sure
2081
        // it doesn't cause any probs anyway.
2082
        $test = new \stdClass;
2083
        $test->one = new \stdClass;
2084
        $test->one->two = new \stdClass;
2085
        $test->one->two->three = new lang_string('yes');
2086
        $string = get_string('yes', null, $test, true);
2087
        $this->assertEquals($yesexpected, $string);
2088
 
2089
        // Make sure that array properties that can't be converted don't cause
2090
        // errors.
2091
        $test = array();
2092
        $test['one'] = new \stdClass;
2093
        $test['one']->two = 'here';
2094
        $string = get_string('yes', null, $test, true);
2095
        $this->assertEquals($yesexpected, $string);
2096
 
2097
        // Same thing but as above except using an object... this is allowed :P.
2098
        $string = get_string('yes', null, null, true);
2099
        $object = new \stdClass;
2100
        $object->$string = 'Yes';
2101
        $this->assertEquals($yesexpected, $string);
2102
        $this->assertEquals($yesexpected, $object->$string);
2103
 
2104
        // Reset the language.
2105
        $COURSE->lang = $originallang;
2106
    }
2107
 
2108
    public function test_lang_string_var_export() {
2109
 
2110
        // Call var_export() on a newly generated lang_string.
2111
        $str = new lang_string('no');
2112
 
2113
        // In PHP 8.2 exported class names are now fully qualified;
2114
        // previously, the leading backslash was omitted.
2115
        $leadingbackslash = (version_compare(PHP_VERSION, '8.2.0', '>=')) ? '\\' : '';
2116
 
2117
        $expected1 = <<<EOF
2118
{$leadingbackslash}lang_string::__set_state(array(
2119
   'identifier' => 'no',
2120
   'component' => 'moodle',
2121
   'a' => NULL,
2122
   'lang' => NULL,
2123
   'string' => NULL,
2124
   'forcedstring' => false,
2125
))
2126
EOF;
2127
 
2128
        $v = var_export($str, true);
2129
        $this->assertEquals($expected1, $v);
2130
 
2131
        // Now execute the code that was returned - it should produce a correct string.
2132
        $str = lang_string::__set_state(array(
2133
            'identifier' => 'no',
2134
            'component' => 'moodle',
2135
            'a' => NULL,
2136
            'lang' => NULL,
2137
            'string' => NULL,
2138
            'forcedstring' => false,
2139
        ));
2140
 
2141
        $this->assertInstanceOf(lang_string::class, $str);
2142
        $this->assertEquals('No', $str);
2143
    }
2144
 
2145
    public function test_get_string_limitation() {
2146
        // This is one of the limitations to the lang_string class. It can't be
2147
        // used as a key.
2148
        $this->expectException(\TypeError::class);
2149
        $array = array(get_string('yes', null, null, true) => 'yes');
2150
    }
2151
 
2152
    /**
2153
     * Test localised float formatting.
2154
     */
2155
    public function test_format_float() {
2156
 
2157
        // Special case for null.
2158
        $this->assertEquals('', format_float(null));
2159
 
2160
        // Default 1 decimal place.
2161
        $this->assertEquals('5.4', format_float(5.43));
2162
        $this->assertEquals('5.0', format_float(5.001));
2163
 
2164
        // Custom number of decimal places.
2165
        $this->assertEquals('5.43000', format_float(5.43, 5));
2166
 
2167
        // Auto detect the number of decimal places.
2168
        $this->assertEquals('5.43', format_float(5.43, -1));
2169
        $this->assertEquals('5.43', format_float(5.43000, -1));
2170
        $this->assertEquals('5', format_float(5, -1));
2171
        $this->assertEquals('5', format_float(5.0, -1));
2172
        $this->assertEquals('0.543', format_float('5.43e-1', -1));
2173
        $this->assertEquals('0.543', format_float('5.43000e-1', -1));
2174
 
2175
        // Option to strip ending zeros after rounding.
2176
        $this->assertEquals('5.43', format_float(5.43, 5, true, true));
2177
        $this->assertEquals('5', format_float(5.0001, 3, true, true));
2178
        $this->assertEquals('100', format_float(100, 2, true, true));
2179
        $this->assertEquals('100', format_float(100, 0, true, true));
2180
 
2181
        // Tests with a localised decimal separator.
2182
        $this->define_local_decimal_separator();
2183
 
2184
        // Localisation on (default).
2185
        $this->assertEquals('5X43000', format_float(5.43, 5));
2186
        $this->assertEquals('5X43', format_float(5.43, 5, true, true));
2187
 
2188
        // Localisation off.
2189
        $this->assertEquals('5.43000', format_float(5.43, 5, false));
2190
        $this->assertEquals('5.43', format_float(5.43, 5, false, true));
2191
 
2192
        // Tests with tilde as localised decimal separator.
2193
        $this->define_local_decimal_separator('~');
2194
 
2195
        // Must also work for '~' as decimal separator.
2196
        $this->assertEquals('5', format_float(5.0001, 3, true, true));
2197
        $this->assertEquals('5~43000', format_float(5.43, 5));
2198
        $this->assertEquals('5~43', format_float(5.43, 5, true, true));
2199
    }
2200
 
2201
    /**
2202
     * Test localised float unformatting.
2203
     */
2204
    public function test_unformat_float() {
2205
 
2206
        // Tests without the localised decimal separator.
2207
 
2208
        // Special case for null, empty or white spaces only strings.
2209
        $this->assertEquals(null, unformat_float(null));
2210
        $this->assertEquals(null, unformat_float(''));
2211
        $this->assertEquals(null, unformat_float('    '));
2212
 
2213
        // Regular use.
2214
        $this->assertEquals(5.4, unformat_float('5.4'));
2215
        $this->assertEquals(5.4, unformat_float('5.4', true));
2216
 
2217
        // No decimal.
2218
        $this->assertEquals(5.0, unformat_float('5'));
2219
 
2220
        // Custom number of decimal.
2221
        $this->assertEquals(5.43267, unformat_float('5.43267'));
2222
 
2223
        // Empty decimal.
2224
        $this->assertEquals(100.0, unformat_float('100.00'));
2225
 
2226
        // With the thousand separator.
2227
        $this->assertEquals(1000.0, unformat_float('1 000'));
2228
        $this->assertEquals(1000.32, unformat_float('1 000.32'));
2229
 
2230
        // Negative number.
2231
        $this->assertEquals(-100.0, unformat_float('-100'));
2232
 
2233
        // Wrong value.
2234
        $this->assertEquals(0.0, unformat_float('Wrong value'));
2235
        // Wrong value in strict mode.
2236
        $this->assertFalse(unformat_float('Wrong value', true));
2237
 
2238
        // Combining options.
2239
        $this->assertEquals(-1023.862567, unformat_float('   -1 023.862567     '));
2240
 
2241
        // Bad decimal separator (should crop the decimal).
2242
        $this->assertEquals(50.0, unformat_float('50,57'));
2243
        // Bad decimal separator in strict mode (should return false).
2244
        $this->assertFalse(unformat_float('50,57', true));
2245
 
2246
        // Tests with a localised decimal separator.
2247
        $this->define_local_decimal_separator();
2248
 
2249
        // We repeat the tests above but with the current decimal separator.
2250
 
2251
        // Regular use without and with the localised separator.
2252
        $this->assertEquals (5.4, unformat_float('5.4'));
2253
        $this->assertEquals (5.4, unformat_float('5X4'));
2254
 
2255
        // Custom number of decimal.
2256
        $this->assertEquals (5.43267, unformat_float('5X43267'));
2257
 
2258
        // Empty decimal.
2259
        $this->assertEquals (100.0, unformat_float('100X00'));
2260
 
2261
        // With the thousand separator.
2262
        $this->assertEquals (1000.32, unformat_float('1 000X32'));
2263
 
2264
        // Bad different separator (should crop the decimal).
2265
        $this->assertEquals (50.0, unformat_float('50Y57'));
2266
        // Bad different separator in strict mode (should return false).
2267
        $this->assertFalse (unformat_float('50Y57', true));
2268
 
2269
        // Combining options.
2270
        $this->assertEquals (-1023.862567, unformat_float('   -1 023X862567     '));
2271
        // Combining options in strict mode.
2272
        $this->assertEquals (-1023.862567, unformat_float('   -1 023X862567     ', true));
2273
    }
2274
 
2275
    /**
2276
     * Test deleting of users.
2277
     */
2278
    public function test_delete_user() {
2279
        global $DB, $CFG;
2280
 
2281
        $this->resetAfterTest();
2282
 
2283
        $guest = $DB->get_record('user', array('id'=>$CFG->siteguest), '*', MUST_EXIST);
2284
        $admin = $DB->get_record('user', array('id'=>$CFG->siteadmins), '*', MUST_EXIST);
2285
        $this->assertEquals(0, $DB->count_records('user', array('deleted'=>1)));
2286
 
2287
        $user = $this->getDataGenerator()->create_user(array('idnumber'=>'abc'));
2288
        $user2 = $this->getDataGenerator()->create_user(array('idnumber'=>'xyz'));
2289
        $usersharedemail1 = $this->getDataGenerator()->create_user(array('email' => 'sharedemail@example.invalid'));
2290
        $usersharedemail2 = $this->getDataGenerator()->create_user(array('email' => 'sharedemail@example.invalid'));
2291
        $useremptyemail1 = $this->getDataGenerator()->create_user(array('email' => ''));
2292
        $useremptyemail2 = $this->getDataGenerator()->create_user(array('email' => ''));
2293
 
2294
        // Delete user and capture event.
2295
        $sink = $this->redirectEvents();
2296
        $result = delete_user($user);
2297
        $events = $sink->get_events();
2298
        $sink->close();
2299
        $event = array_pop($events);
2300
 
2301
        // Test user is deleted in DB.
2302
        $this->assertTrue($result);
2303
        $deluser = $DB->get_record('user', array('id'=>$user->id), '*', MUST_EXIST);
2304
        $this->assertEquals(1, $deluser->deleted);
2305
        $this->assertEquals(0, $deluser->picture);
2306
        $this->assertSame('', $deluser->idnumber);
2307
        $this->assertSame(md5($user->username), $deluser->email);
2308
        $this->assertMatchesRegularExpression('/^'.preg_quote($user->email, '/').'\.\d*$/', $deluser->username);
2309
 
2310
        $this->assertEquals(1, $DB->count_records('user', array('deleted'=>1)));
2311
 
2312
        // Test Event.
2313
        $this->assertInstanceOf('\core\event\user_deleted', $event);
2314
        $this->assertSame($user->id, $event->objectid);
2315
        $eventdata = $event->get_data();
2316
        $this->assertSame($eventdata['other']['username'], $user->username);
2317
        $this->assertSame($eventdata['other']['email'], $user->email);
2318
        $this->assertSame($eventdata['other']['idnumber'], $user->idnumber);
2319
        $this->assertSame($eventdata['other']['picture'], $user->picture);
2320
        $this->assertSame($eventdata['other']['mnethostid'], $user->mnethostid);
2321
        $this->assertEquals($user, $event->get_record_snapshot('user', $event->objectid));
2322
        $this->assertEventContextNotUsed($event);
2323
 
2324
        // Try invalid params.
2325
        $record = new \stdClass();
2326
        $record->grrr = 1;
2327
        try {
2328
            delete_user($record);
2329
            $this->fail('Expecting exception for invalid delete_user() $user parameter');
2330
        } catch (\moodle_exception $ex) {
2331
            $this->assertInstanceOf('coding_exception', $ex);
2332
        }
2333
        $record->id = 1;
2334
        try {
2335
            delete_user($record);
2336
            $this->fail('Expecting exception for invalid delete_user() $user parameter');
2337
        } catch (\moodle_exception $ex) {
2338
            $this->assertInstanceOf('coding_exception', $ex);
2339
        }
2340
 
2341
        $record = new \stdClass();
2342
        $record->id = 666;
2343
        $record->username = 'xx';
2344
        $this->assertFalse($DB->record_exists('user', array('id'=>666))); // Any non-existent id is ok.
2345
        $result = delete_user($record);
2346
        $this->assertFalse($result);
2347
 
2348
        $result = delete_user($guest);
2349
        $this->assertFalse($result);
2350
 
2351
        $result = delete_user($admin);
2352
        $this->assertFalse($result);
2353
 
2354
        // Simultaneously deleting users with identical email addresses.
2355
        $result1 = delete_user($usersharedemail1);
2356
        $result2 = delete_user($usersharedemail2);
2357
 
2358
        $usersharedemail1after = $DB->get_record('user', array('id' => $usersharedemail1->id));
2359
        $usersharedemail2after = $DB->get_record('user', array('id' => $usersharedemail2->id));
2360
        $this->assertTrue($result1);
2361
        $this->assertTrue($result2);
2362
        $this->assertStringStartsWith($usersharedemail1->email . '.', $usersharedemail1after->username);
2363
        $this->assertStringStartsWith($usersharedemail2->email . '.', $usersharedemail2after->username);
2364
 
2365
        // Simultaneously deleting users without email addresses.
2366
        $result1 = delete_user($useremptyemail1);
2367
        $result2 = delete_user($useremptyemail2);
2368
 
2369
        $useremptyemail1after = $DB->get_record('user', array('id' => $useremptyemail1->id));
2370
        $useremptyemail2after = $DB->get_record('user', array('id' => $useremptyemail2->id));
2371
        $this->assertTrue($result1);
2372
        $this->assertTrue($result2);
2373
        $this->assertStringStartsWith($useremptyemail1->username . '.' . $useremptyemail1->id . '@unknownemail.invalid.',
2374
            $useremptyemail1after->username);
2375
        $this->assertStringStartsWith($useremptyemail2->username . '.' . $useremptyemail2->id . '@unknownemail.invalid.',
2376
            $useremptyemail2after->username);
2377
 
2378
        $this->resetDebugging();
2379
    }
2380
 
2381
    /**
2382
     * Test deletion of user with long username
2383
     */
2384
    public function test_delete_user_long_username() {
2385
        global $DB;
2386
 
2387
        $this->resetAfterTest();
2388
 
2389
        // For users without an e-mail, one will be created during deletion using {$username}.{$id}@unknownemail.invalid format.
2390
        $user = $this->getDataGenerator()->create_user([
2391
            'username' => str_repeat('a', 75),
2392
            'email' => '',
2393
        ]);
2394
 
2395
        delete_user($user);
2396
 
2397
        // The username for the deleted user shouldn't exceed 100 characters.
2398
        $usernamedeleted = $DB->get_field('user', 'username', ['id' => $user->id]);
2399
        $this->assertEquals(100, \core_text::strlen($usernamedeleted));
2400
 
2401
        $timestrlength = \core_text::strlen((string) time());
2402
 
2403
        // It should start with the user name, and end with the current time.
2404
        $this->assertStringStartsWith("{$user->username}.{$user->id}@", $usernamedeleted);
2405
        $this->assertMatchesRegularExpression('/\.\d{' . $timestrlength . '}$/', $usernamedeleted);
2406
    }
2407
 
2408
    /**
2409
     * Test deletion of user with long email address
2410
     */
2411
    public function test_delete_user_long_email() {
2412
        global $DB;
2413
 
2414
        $this->resetAfterTest();
2415
 
2416
        // Create user with 90 character email address.
2417
        $user = $this->getDataGenerator()->create_user([
2418
            'email' => str_repeat('a', 78) . '@example.com',
2419
        ]);
2420
 
2421
        delete_user($user);
2422
 
2423
        // The username for the deleted user shouldn't exceed 100 characters.
2424
        $usernamedeleted = $DB->get_field('user', 'username', ['id' => $user->id]);
2425
        $this->assertEquals(100, \core_text::strlen($usernamedeleted));
2426
 
2427
        $timestrlength = \core_text::strlen((string) time());
2428
 
2429
        // Max username length is 100 chars. Select up to limit - (length of current time + 1 [period character]) from users email.
2430
        $expectedemail = \core_text::substr($user->email, 0, 100 - ($timestrlength + 1));
2431
        $this->assertMatchesRegularExpression('/^' . preg_quote($expectedemail) . '\.\d{' . $timestrlength . '}$/',
2432
            $usernamedeleted);
2433
    }
2434
 
2435
    /**
2436
     * Test function convert_to_array()
2437
     */
2438
    public function test_convert_to_array() {
2439
        // Check that normal classes are converted to arrays the same way as (array) would do.
2440
        $obj = new \stdClass();
2441
        $obj->prop1 = 'hello';
2442
        $obj->prop2 = array('first', 'second', 13);
2443
        $obj->prop3 = 15;
2444
        $this->assertEquals(convert_to_array($obj), (array)$obj);
2445
 
2446
        // Check that context object (with iterator) is converted to array properly.
2447
        $obj = \context_system::instance();
2448
        $ar = array(
2449
            'id'           => $obj->id,
2450
            'contextlevel' => $obj->contextlevel,
2451
            'instanceid'   => $obj->instanceid,
2452
            'path'         => $obj->path,
2453
            'depth'        => $obj->depth,
2454
            'locked'       => $obj->locked,
2455
        );
2456
        $this->assertEquals(convert_to_array($obj), $ar);
2457
    }
2458
 
2459
    /**
2460
     * Test the function date_format_string().
2461
     */
2462
    public function test_date_format_string() {
2463
        global $CFG;
2464
 
2465
        $this->resetAfterTest();
2466
        $this->setTimezone(99, 'Australia/Perth');
2467
 
2468
        $tests = array(
2469
            array(
2470
                'tz' => 99,
2471
                'str' => '%A, %d %B %Y, %I:%M %p',
2472
                'expected' => 'Saturday, 01 January 2011, 06:00 PM'
2473
            ),
2474
            array(
2475
                'tz' => 0,
2476
                'str' => '%A, %d %B %Y, %I:%M %p',
2477
                'expected' => 'Saturday, 01 January 2011, 10:00 AM'
2478
            ),
2479
            array(
2480
                // Note: this function expected the timestamp in weird format before,
2481
                // since 2.9 it uses UTC.
2482
                'tz' => 'Pacific/Auckland',
2483
                'str' => '%A, %d %B %Y, %I:%M %p',
2484
                'expected' => 'Saturday, 01 January 2011, 11:00 PM'
2485
            ),
2486
            // Following tests pass on Windows only because en lang pack does
2487
            // not contain localewincharset, in real life lang pack maintainers
2488
            // may use only characters that are present in localewincharset
2489
            // in format strings!
2490
            array(
2491
                'tz' => 99,
2492
                'str' => 'Žluťoučký koníček %A',
2493
                'expected' => 'Žluťoučký koníček Saturday'
2494
            ),
2495
            array(
2496
                'tz' => 99,
2497
                'str' => '言語設定言語 %A',
2498
                'expected' => '言語設定言語 Saturday'
2499
            ),
2500
            array(
2501
                'tz' => 99,
2502
                'str' => '简体中文简体 %A',
2503
                'expected' => '简体中文简体 Saturday'
2504
            ),
2505
        );
2506
 
2507
        // Note: date_format_string() uses the timezone only to differenciate
2508
        // the server time from the UTC time. It does not modify the timestamp.
2509
        // Hence similar results for timezones <= 13.
2510
        // On different systems case of AM PM changes so compare case insensitive.
2511
        foreach ($tests as $test) {
2512
            $str = date_format_string(1293876000, $test['str'], $test['tz']);
2513
            $this->assertSame(\core_text::strtolower($test['expected']), \core_text::strtolower($str));
2514
        }
2515
    }
2516
 
2517
    public function test_get_config() {
2518
        global $CFG;
2519
 
2520
        $this->resetAfterTest();
2521
 
2522
        // Preparation.
2523
        set_config('phpunit_test_get_config_1', 'test 1');
2524
        set_config('phpunit_test_get_config_2', 'test 2', 'mod_forum');
2525
        if (!is_array($CFG->config_php_settings)) {
2526
            $CFG->config_php_settings = array();
2527
        }
2528
        $CFG->config_php_settings['phpunit_test_get_config_3'] = 'test 3';
2529
 
2530
        if (!is_array($CFG->forced_plugin_settings)) {
2531
            $CFG->forced_plugin_settings = array();
2532
        }
2533
        if (!array_key_exists('mod_forum', $CFG->forced_plugin_settings)) {
2534
            $CFG->forced_plugin_settings['mod_forum'] = array();
2535
        }
2536
        $CFG->forced_plugin_settings['mod_forum']['phpunit_test_get_config_4'] = 'test 4';
2537
        $CFG->phpunit_test_get_config_5 = 'test 5';
2538
 
2539
        // Testing.
2540
        $this->assertSame('test 1', get_config('core', 'phpunit_test_get_config_1'));
2541
        $this->assertSame('test 2', get_config('mod_forum', 'phpunit_test_get_config_2'));
2542
        $this->assertSame('test 3', get_config('core', 'phpunit_test_get_config_3'));
2543
        $this->assertSame('test 4', get_config('mod_forum', 'phpunit_test_get_config_4'));
2544
        $this->assertFalse(get_config('core', 'phpunit_test_get_config_5'));
2545
        $this->assertFalse(get_config('core', 'phpunit_test_get_config_x'));
2546
        $this->assertFalse(get_config('mod_forum', 'phpunit_test_get_config_x'));
2547
 
2548
        // Test config we know to exist.
2549
        $this->assertSame($CFG->dataroot, get_config('core', 'dataroot'));
2550
        $this->assertSame($CFG->phpunit_dataroot, get_config('core', 'phpunit_dataroot'));
2551
        $this->assertSame($CFG->dataroot, get_config('core', 'phpunit_dataroot'));
2552
        $this->assertSame(get_config('core', 'dataroot'), get_config('core', 'phpunit_dataroot'));
2553
 
2554
        // Test setting a config var that already exists.
2555
        set_config('phpunit_test_get_config_1', 'test a');
2556
        $this->assertSame('test a', $CFG->phpunit_test_get_config_1);
2557
        $this->assertSame('test a', get_config('core', 'phpunit_test_get_config_1'));
2558
 
2559
        // Test cache invalidation.
2560
        $cache = \cache::make('core', 'config');
2561
        $this->assertIsArray($cache->get('core'));
2562
        $this->assertIsArray($cache->get('mod_forum'));
2563
        set_config('phpunit_test_get_config_1', 'test b');
2564
        $this->assertFalse($cache->get('core'));
2565
        set_config('phpunit_test_get_config_4', 'test c', 'mod_forum');
2566
        $this->assertFalse($cache->get('mod_forum'));
2567
    }
2568
 
2569
    public function test_get_max_upload_sizes() {
2570
        // Test with very low limits so we are not affected by php upload limits.
2571
        // Test activity limit smallest.
2572
        $sitebytes = 102400;
2573
        $coursebytes = 51200;
2574
        $modulebytes = 10240;
2575
        $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2576
 
2577
        $nbsp = "\xc2\xa0";
2578
        $this->assertSame("Activity upload limit (10{$nbsp}KB)", $result['0']);
2579
        $this->assertCount(2, $result);
2580
 
2581
        // Test course limit smallest.
2582
        $sitebytes = 102400;
2583
        $coursebytes = 10240;
2584
        $modulebytes = 51200;
2585
        $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2586
 
2587
        $this->assertSame("Course upload limit (10{$nbsp}KB)", $result['0']);
2588
        $this->assertCount(2, $result);
2589
 
2590
        // Test site limit smallest.
2591
        $sitebytes = 10240;
2592
        $coursebytes = 102400;
2593
        $modulebytes = 51200;
2594
        $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2595
 
2596
        $this->assertSame("Site upload limit (10{$nbsp}KB)", $result['0']);
2597
        $this->assertCount(2, $result);
2598
 
2599
        // Test site limit not set.
2600
        $sitebytes = 0;
2601
        $coursebytes = 102400;
2602
        $modulebytes = 51200;
2603
        $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2604
 
2605
        $this->assertSame("Activity upload limit (50{$nbsp}KB)", $result['0']);
2606
        $this->assertCount(3, $result);
2607
 
2608
        $sitebytes = 0;
2609
        $coursebytes = 51200;
2610
        $modulebytes = 102400;
2611
        $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
2612
 
2613
        $this->assertSame("Course upload limit (50{$nbsp}KB)", $result['0']);
2614
        $this->assertCount(3, $result);
2615
 
2616
        // Test custom bytes in range.
2617
        $sitebytes = 102400;
2618
        $coursebytes = 51200;
2619
        $modulebytes = 51200;
2620
        $custombytes = 10240;
2621
        $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes, $custombytes);
2622
 
2623
        $this->assertCount(3, $result);
2624
 
2625
        // Test custom bytes in range but non-standard.
2626
        $sitebytes = 102400;
2627
        $coursebytes = 51200;
2628
        $modulebytes = 51200;
2629
        $custombytes = 25600;
2630
        $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes, $custombytes);
2631
 
2632
        $this->assertCount(4, $result);
2633
 
2634
        // Test custom bytes out of range.
2635
        $sitebytes = 102400;
2636
        $coursebytes = 51200;
2637
        $modulebytes = 51200;
2638
        $custombytes = 102400;
2639
        $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes, $custombytes);
2640
 
2641
        $this->assertCount(3, $result);
2642
 
2643
        // Test custom bytes out of range and non-standard.
2644
        $sitebytes = 102400;
2645
        $coursebytes = 51200;
2646
        $modulebytes = 51200;
2647
        $custombytes = 256000;
2648
        $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes, $custombytes);
2649
 
2650
        $this->assertCount(3, $result);
2651
 
2652
        // Test site limit only.
2653
        $sitebytes = 51200;
2654
        $result = get_max_upload_sizes($sitebytes);
2655
 
2656
        $this->assertSame("Site upload limit (50{$nbsp}KB)", $result['0']);
2657
        $this->assertSame("50{$nbsp}KB", $result['51200']);
2658
        $this->assertSame("10{$nbsp}KB", $result['10240']);
2659
        $this->assertCount(3, $result);
2660
 
2661
        // Test no limit.
2662
        $result = get_max_upload_sizes();
2663
        $this->assertArrayHasKey('0', $result);
2664
        $this->assertArrayHasKey(get_max_upload_file_size(), $result);
2665
    }
2666
 
2667
    /**
2668
     * Test function password_is_legacy_hash.
2669
     * @covers ::password_is_legacy_hash
2670
     */
2671
    public function test_password_is_legacy_hash() {
2672
        // Well formed bcrypt hashes should be matched.
2673
        foreach (array('some', 'strings', 'to_check!') as $password) {
2674
            $bcrypt = password_hash($password, '2y');
2675
            $this->assertTrue(password_is_legacy_hash($bcrypt));
2676
        }
2677
        // Strings that are not bcrypt should not be matched.
2678
        $sha512 = '$6$rounds=5000$somesalt$9nEA35u5h4oDrUdcVFUwXDSwIBiZtuKDHiaI/kxnBSslH4wVXeAhVsDn1UFxBxrnRJva/8dZ8IouaijJdd4cF';
2679
        foreach (array('', AUTH_PASSWORD_NOT_CACHED, $sha512) as $notbcrypt) {
2680
            $this->assertFalse(password_is_legacy_hash($notbcrypt));
2681
        }
2682
    }
2683
 
2684
    /**
2685
     * Test function that calculates password pepper entropy.
2686
     * @covers ::calculate_entropy
2687
     */
2688
    public function test_calculate_entropy() {
2689
        // Test that the function returns 0 with an empty string.
2690
        $this->assertEquals(0, calculate_entropy(''));
2691
 
2692
        // Test that the function returns the correct entropy.
2693
        $this->assertEquals(132.8814, number_format(calculate_entropy('#GV]NLie|x$H9[$rW%94bXZvJHa%z'), 4));
2694
    }
2695
 
2696
    /**
2697
     * Test function to get password peppers.
2698
     * @covers ::get_password_peppers
2699
     */
2700
    public function test_get_password_peppers() {
2701
        global $CFG;
2702
        $this->resetAfterTest();
2703
 
2704
        // First assert that the function returns an empty array,
2705
        // when no peppers are set.
2706
        $this->assertEquals([], get_password_peppers());
2707
 
2708
        // Now set some peppers and check that they are returned.
2709
        $CFG->passwordpeppers = [
2710
                1 => '#GV]NLie|x$H9[$rW%94bXZvJHa%z',
2711
                2 => '#GV]NLie|x$H9[$rW%94bXZvJHa%$'
2712
        ];
2713
        $peppers = get_password_peppers();
2714
        $this->assertCount(2, $peppers);
2715
        $this->assertEquals($CFG->passwordpeppers, $peppers);
2716
 
2717
        // Check that the peppers are returned in the correct order.
2718
        // Highest numerical key first.
2719
        $this->assertEquals('#GV]NLie|x$H9[$rW%94bXZvJHa%$', $peppers[2]);
2720
        $this->assertEquals('#GV]NLie|x$H9[$rW%94bXZvJHa%z', $peppers[1]);
2721
 
2722
        // Update the latest pepper to be an empty string,
2723
        // to test phasing out peppers.
2724
        $CFG->passwordpeppers = [
2725
                1 => '#GV]NLie|x$H9[$rW%94bXZvJHa%z',
2726
                2 => '#GV]NLie|x$H9[$rW%94bXZvJHa%$',
2727
                3 => ''
2728
        ];
2729
        $peppers = get_password_peppers();
2730
        $this->assertCount(3, $peppers);
2731
        $this->assertEquals($CFG->passwordpeppers, $peppers);
2732
 
2733
        // Finally, check that low entropy peppers throw an exception.
2734
        $CFG->passwordpeppers = [
2735
                1 => 'foo',
2736
                2 => 'bar'
2737
        ];
2738
        $this->expectException(\coding_exception::class);
2739
        get_password_peppers();
2740
    }
2741
 
2742
    /**
2743
     * Test function to validate password length.
2744
     *
2745
     * @covers ::exceeds_password_length
2746
     * @return void
2747
     */
2748
    public function test_exceeds_password_length() {
2749
        $this->resetAfterTest(true);
2750
 
2751
        // With password less than equals to MAX_PASSWORD_CHARACTERS.
2752
        $this->assertFalse(exceeds_password_length('test'));
2753
 
2754
        // With password more than MAX_PASSWORD_CHARACTERS.
2755
        $password = 'thisisapasswordthatcontainscharactersthatcan';
2756
        $password .= 'exeedthepasswordlengthof128thisispasswordthatcont';
2757
        $password .= 'ainscharactersthatcanexeedthelength-----';
2758
        $this->assertTrue(exceeds_password_length($password));
2759
    }
2760
 
2761
    /**
2762
     * Test function validate_internal_user_password.
2763
     * @covers ::validate_internal_user_password
2764
     */
2765
    public function test_validate_internal_user_password() {
2766
        $this->resetAfterTest(true);
2767
        // Test bcrypt hashes (these will be updated but will still count as valid).
2768
        $bcrypthashes = [
2769
            'pw' => '$2y$10$LOSDi5eaQJhutSRun.OVJ.ZSxQZabCMay7TO1KmzMkDMPvU40zGXK',
2770
            'abc' => '$2y$10$VWTOhVdsBbWwtdWNDRHSpewjd3aXBQlBQf5rBY/hVhw8hciarFhXa',
2771
            'C0mP1eX_&}<?@*&%` |\"' => '$2y$10$3PJf.q.9ywNJlsInPbqc8.IFeSsvXrGvQLKRFBIhVu1h1I3vpIry6',
2772
            'ĩńťėŕňăţĩōŋāĹ' => '$2y$10$3A2Y8WpfRAnP3czJiSv6N.6Xp0T8hW3QZz2hUCYhzyWr1kGP1yUve',
2773
        ];
2774
 
2775
        // Test sha512 hashes.
2776
        $sha512hashes = [
2777
            'pw2' => '$6$rounds=10000$0rDIzh/4.MMf9Dm8$Zrj6Ulc1JFj0RFXwMJFsngRSNGlqkPlV1wwRVv7wBLrMeQeMZrwsBO62zy63D//6R5sNGVYQwPB0K8jPCScxB/',
2778
            'abc2' => '$6$rounds=10000$t0L6PklgpijV4tMB$1vpCRKCImsVqTPMiZTi6zLGbs.hpAU8I2BhD/IFliBnHJkFZCWEBfTCq6pEzo0Q8nXsryrgeZ.qngcW.eifuW.',
2779
            'C0mP1eX_&}<?@*&%` |\"2' => '$6$rounds=10000$3TAyVAXN0zmFZ4il$KF8YzduX6Gu0C2xHsY83zoqQ/rLVsb9mLe417wDObo9tO00qeUC68/y2tMq4FL2ixnMPH3OMwzGYo8VJrm8Eq1',
2780
            'ĩńťėŕňăţĩōŋāĹ2' => '$6$rounds=10000$SHR/6ctTkfXOy5NP$YPv42hjDjohVWD3B0boyEYTnLcBXBKO933ijHmkPXNL7BpqAcbYMLfTl9rjsPmCt.1GZvEJZ8ikkCPYBC5Sdp.',
2781
        ];
2782
 
2783
        $validhashes = array_merge($bcrypthashes, $sha512hashes);
2784
 
2785
        foreach ($validhashes as $password => $hash) {
2786
            $user = $this->getDataGenerator()->create_user(array('auth' => 'manual', 'password' => $password));
2787
            $user->password = $hash;
2788
            // The correct password should be validated.
2789
            $this->assertTrue(validate_internal_user_password($user, $password));
2790
            // An incorrect password should not be validated.
2791
            $this->assertFalse(validate_internal_user_password($user, 'badpw'));
2792
        }
2793
    }
2794
 
2795
    /**
2796
     * Test function validate_internal_user_password() with a peppered password,
2797
     * when the pepper no longer exists.
2798
     *
2799
     * @covers ::validate_internal_user_password
2800
     */
2801
    public function test_validate_internal_user_password_bad_pepper() {
2802
        global $CFG;
2803
        $this->resetAfterTest();
2804
 
2805
        // Set a pepper.
2806
        $CFG->passwordpeppers = [
2807
                1 => '#GV]NLie|x$H9[$rW%94bXZvJHa%z',
2808
                2 => '#GV]NLie|x$H9[$rW%94bXZvJHa%$'
2809
        ];
2810
        $password = 'test';
2811
 
2812
        $user = $this->getDataGenerator()->create_user(['auth' => 'manual', 'password' => $password]);
2813
        $this->assertTrue(validate_internal_user_password($user, $password));
2814
        $this->assertFalse(validate_internal_user_password($user, 'badpw'));
2815
 
2816
        // Now remove the peppers.
2817
        // Things should not work.
2818
        unset($CFG->passwordpeppers);
2819
        $this->assertFalse(validate_internal_user_password($user, $password));
2820
    }
2821
 
2822
    /**
2823
     * Helper method to test hashing passwords.
2824
     *
2825
     * @param array $passwords
2826
     * @return void
2827
     * @covers ::hash_internal_user_password
2828
     */
2829
    public function validate_hashed_passwords(array $passwords): void {
2830
        foreach ($passwords as $password) {
2831
            $hash = hash_internal_user_password($password);
2832
            $fasthash = hash_internal_user_password($password, true);
2833
            $user = $this->getDataGenerator()->create_user(['auth' => 'manual']);
2834
            $user->password = $hash;
2835
            $this->assertTrue(validate_internal_user_password($user, $password));
2836
 
2837
            // They should not be in bycrypt format.
2838
            $this->assertFalse(password_is_legacy_hash($hash));
2839
 
2840
            // Check that cost factor in hash is correctly set.
2841
            $this->assertMatchesRegularExpression('/\$6\$rounds=10000\$.{103}/', $hash);
2842
            $this->assertMatchesRegularExpression('/\$6\$rounds=5000\$.{103}/', $fasthash);
2843
        }
2844
    }
2845
 
2846
    /**
2847
     * Test function update_internal_user_password.
2848
     * @covers ::update_internal_user_password
2849
     */
2850
    public function test_hash_internal_user_password() {
2851
        global $CFG;
2852
        $this->resetAfterTest();
2853
        $passwords = ['pw', 'abc123', 'C0mP1eX_&}<?@*&%` |\"', 'ĩńťėŕňăţĩōŋāĹ'];
2854
 
2855
        // Check that some passwords that we convert to hashes can
2856
        // be validated.
2857
        $this->validate_hashed_passwords($passwords);
2858
 
2859
        // Test again with peppers.
2860
        $CFG->passwordpeppers = [
2861
                1 => '#GV]NLie|x$H9[$rW%94bXZvJHa%z',
2862
                2 => '#GV]NLie|x$H9[$rW%94bXZvJHa%$'
2863
        ];
2864
        $this->validate_hashed_passwords($passwords);
2865
 
2866
        // Add a new pepper and check that things still pass.
2867
        $CFG->passwordpeppers = [
2868
                1 => '#GV]NLie|x$H9[$rW%94bXZvJHa%z',
2869
                2 => '#GV]NLie|x$H9[$rW%94bXZvJHa%$',
2870
                3 => '#GV]NLie|x$H9[$rW%94bXZvJHQ%$'
2871
        ];
2872
        $this->validate_hashed_passwords($passwords);
2873
    }
2874
 
2875
    /**
2876
     * Test function update_internal_user_password().
2877
     */
2878
    public function test_update_internal_user_password() {
2879
        global $DB;
2880
        $this->resetAfterTest();
2881
        $passwords = array('password', '1234', 'changeme', '****');
2882
        foreach ($passwords as $password) {
2883
            $user = $this->getDataGenerator()->create_user(array('auth'=>'manual'));
2884
            update_internal_user_password($user, $password);
2885
            // The user object should have been updated.
2886
            $this->assertTrue(validate_internal_user_password($user, $password));
2887
            // The database field for the user should also have been updated to the
2888
            // same value.
2889
            $this->assertSame($user->password, $DB->get_field('user', 'password', array('id' => $user->id)));
2890
        }
2891
 
2892
        $user = $this->getDataGenerator()->create_user(array('auth'=>'manual'));
2893
        // Manually set the user's password to the bcrypt of the string 'password'.
2894
        $DB->set_field('user', 'password', '$2y$10$HhNAYmQcU1GqU/psOmZjfOWlhPEcxx9aEgSJqBfEtYVyq1jPKqMAi', ['id' => $user->id]);
2895
 
2896
        $sink = $this->redirectEvents();
2897
        // Update the password.
2898
        update_internal_user_password($user, 'password');
2899
        $events = $sink->get_events();
2900
        $sink->close();
2901
        $event = array_pop($events);
2902
 
2903
        // Password should have been updated to a SHA512 hash.
2904
        $this->assertFalse(password_is_legacy_hash($user->password));
2905
 
2906
        // Verify event information.
2907
        $this->assertInstanceOf('\core\event\user_password_updated', $event);
2908
        $this->assertSame($user->id, $event->relateduserid);
2909
        $this->assertEquals(\context_user::instance($user->id), $event->get_context());
2910
        $this->assertEventContextNotUsed($event);
2911
 
2912
        // Verify recovery of property 'auth'.
2913
        unset($user->auth);
2914
        update_internal_user_password($user, 'newpassword');
2915
        $this->assertDebuggingCalled('User record in update_internal_user_password() must include field auth',
2916
                DEBUG_DEVELOPER);
2917
        $this->assertEquals('manual', $user->auth);
2918
    }
2919
 
2920
    /**
2921
     * Testing that if the password is not cached, that it does not update
2922
     * the user table and fire event.
2923
     */
2924
    public function test_update_internal_user_password_no_cache() {
2925
        global $DB;
2926
        $this->resetAfterTest();
2927
 
2928
        $user = $this->getDataGenerator()->create_user(array('auth' => 'cas'));
2929
        $DB->update_record('user', ['id' => $user->id, 'password' => AUTH_PASSWORD_NOT_CACHED]);
2930
        $user->password = AUTH_PASSWORD_NOT_CACHED;
2931
 
2932
        $sink = $this->redirectEvents();
2933
        update_internal_user_password($user, 'wonkawonka');
2934
        $this->assertEquals(0, $sink->count(), 'User updated event should not fire');
2935
    }
2936
 
2937
    /**
2938
     * Test if the user has a password hash, but now their auth method
2939
     * says not to cache it.  Then it should update.
2940
     */
2941
    public function test_update_internal_user_password_update_no_cache() {
2942
        $this->resetAfterTest();
2943
 
2944
        $user = $this->getDataGenerator()->create_user(array('password' => 'test'));
2945
        $this->assertNotEquals(AUTH_PASSWORD_NOT_CACHED, $user->password);
2946
        $user->auth = 'cas'; // Change to a auth that does not store passwords.
2947
 
2948
        $sink = $this->redirectEvents();
2949
        update_internal_user_password($user, 'wonkawonka');
2950
        $this->assertGreaterThanOrEqual(1, $sink->count(), 'User updated event should fire');
2951
 
2952
        $this->assertEquals(AUTH_PASSWORD_NOT_CACHED, $user->password);
2953
    }
2954
 
2955
    public function test_fullname() {
2956
        global $CFG;
2957
 
2958
        $this->resetAfterTest();
2959
 
2960
        // Create a user to test the name display on.
2961
        $record = array();
2962
        $record['firstname'] = 'Scott';
2963
        $record['lastname'] = 'Fletcher';
2964
        $record['firstnamephonetic'] = 'スコット';
2965
        $record['lastnamephonetic'] = 'フレチャー';
2966
        $record['alternatename'] = 'No friends';
2967
        $user = $this->getDataGenerator()->create_user($record);
2968
 
2969
        // Back up config settings for restore later.
2970
        $originalcfg = new \stdClass();
2971
        $originalcfg->fullnamedisplay = $CFG->fullnamedisplay;
2972
        $originalcfg->alternativefullnameformat = $CFG->alternativefullnameformat;
2973
 
2974
        // Testing existing fullnamedisplay settings.
2975
        $CFG->fullnamedisplay = 'firstname';
2976
        $testname = fullname($user);
2977
        $this->assertSame($user->firstname, $testname);
2978
 
2979
        $CFG->fullnamedisplay = 'firstname lastname';
2980
        $expectedname = "$user->firstname $user->lastname";
2981
        $testname = fullname($user);
2982
        $this->assertSame($expectedname, $testname);
2983
 
2984
        $CFG->fullnamedisplay = 'lastname firstname';
2985
        $expectedname = "$user->lastname $user->firstname";
2986
        $testname = fullname($user);
2987
        $this->assertSame($expectedname, $testname);
2988
 
2989
        $expectedname = get_string('fullnamedisplay', null, $user);
2990
        $CFG->fullnamedisplay = 'language';
2991
        $testname = fullname($user);
2992
        $this->assertSame($expectedname, $testname);
2993
 
2994
        // Test override parameter.
2995
        $CFG->fullnamedisplay = 'firstname';
2996
        $expectedname = "$user->firstname $user->lastname";
2997
        $testname = fullname($user, true);
2998
        $this->assertSame($expectedname, $testname);
2999
 
3000
        // Test alternativefullnameformat setting.
3001
        // Test alternativefullnameformat that has been set to nothing.
3002
        $CFG->alternativefullnameformat = '';
3003
        $expectedname = "$user->firstname $user->lastname";
3004
        $testname = fullname($user, true);
3005
        $this->assertSame($expectedname, $testname);
3006
 
3007
        // Test alternativefullnameformat that has been set to 'language'.
3008
        $CFG->alternativefullnameformat = 'language';
3009
        $expectedname = "$user->firstname $user->lastname";
3010
        $testname = fullname($user, true);
3011
        $this->assertSame($expectedname, $testname);
3012
 
3013
        // Test customising the alternativefullnameformat setting with all additional name fields.
3014
        $CFG->alternativefullnameformat = 'firstname lastname firstnamephonetic lastnamephonetic middlename alternatename';
3015
        $expectedname = "$user->firstname $user->lastname $user->firstnamephonetic $user->lastnamephonetic $user->middlename $user->alternatename";
3016
        $testname = fullname($user, true);
3017
        $this->assertSame($expectedname, $testname);
3018
 
3019
        // Test additional name fields.
3020
        $CFG->fullnamedisplay = 'lastname lastnamephonetic firstname firstnamephonetic';
3021
        $expectedname = "$user->lastname $user->lastnamephonetic $user->firstname $user->firstnamephonetic";
3022
        $testname = fullname($user);
3023
        $this->assertSame($expectedname, $testname);
3024
 
3025
        // Test for handling missing data.
3026
        $user->middlename = null;
3027
        // Parenthesis with no data.
3028
        $CFG->fullnamedisplay = 'firstname (middlename) lastname';
3029
        $expectedname = "$user->firstname $user->lastname";
3030
        $testname = fullname($user);
3031
        $this->assertSame($expectedname, $testname);
3032
 
3033
        // Extra spaces due to no data.
3034
        $CFG->fullnamedisplay = 'firstname middlename lastname';
3035
        $expectedname = "$user->firstname $user->lastname";
3036
        $testname = fullname($user);
3037
        $this->assertSame($expectedname, $testname);
3038
 
3039
        // Regular expression testing.
3040
        // Remove some data from the user fields.
3041
        $user->firstnamephonetic = '';
3042
        $user->lastnamephonetic = '';
3043
 
3044
        // Removing empty brackets and excess whitespace.
3045
        // All of these configurations should resolve to just firstname lastname.
3046
        $configarray = array();
3047
        $configarray[] = 'firstname lastname [firstnamephonetic lastnamephonetic]';
3048
        $configarray[] = 'firstname lastname \'middlename\'';
3049
        $configarray[] = 'firstname "firstnamephonetic" lastname';
3050
        $configarray[] = 'firstname 「firstnamephonetic」 lastname 「lastnamephonetic」';
3051
 
3052
        foreach ($configarray as $config) {
3053
            $CFG->fullnamedisplay = $config;
3054
            $expectedname = "$user->firstname $user->lastname";
3055
            $testname = fullname($user);
3056
            $this->assertSame($expectedname, $testname);
3057
        }
3058
 
3059
        // Check to make sure that other characters are left in place.
3060
        $configarray = array();
3061
        $configarray['0'] = new \stdClass();
3062
        $configarray['0']->config = 'lastname firstname, middlename';
3063
        $configarray['0']->expectedname = "$user->lastname $user->firstname,";
3064
        $configarray['1'] = new \stdClass();
3065
        $configarray['1']->config = 'lastname firstname + alternatename';
3066
        $configarray['1']->expectedname = "$user->lastname $user->firstname + $user->alternatename";
3067
        $configarray['2'] = new \stdClass();
3068
        $configarray['2']->config = 'firstname aka: alternatename';
3069
        $configarray['2']->expectedname = "$user->firstname aka: $user->alternatename";
3070
        $configarray['3'] = new \stdClass();
3071
        $configarray['3']->config = 'firstname (alternatename)';
3072
        $configarray['3']->expectedname = "$user->firstname ($user->alternatename)";
3073
        $configarray['4'] = new \stdClass();
3074
        $configarray['4']->config = 'firstname [alternatename]';
3075
        $configarray['4']->expectedname = "$user->firstname [$user->alternatename]";
3076
        $configarray['5'] = new \stdClass();
3077
        $configarray['5']->config = 'firstname "lastname"';
3078
        $configarray['5']->expectedname = "$user->firstname \"$user->lastname\"";
3079
 
3080
        foreach ($configarray as $config) {
3081
            $CFG->fullnamedisplay = $config->config;
3082
            $expectedname = $config->expectedname;
3083
            $testname = fullname($user);
3084
            $this->assertSame($expectedname, $testname);
3085
        }
3086
 
3087
        // Test debugging message displays when
3088
        // fullnamedisplay setting is "normal".
3089
        $CFG->fullnamedisplay = 'firstname lastname';
3090
        unset($user);
3091
        $user = new \stdClass();
3092
        $user->firstname = 'Stan';
3093
        $user->lastname = 'Lee';
3094
        $namedisplay = fullname($user);
3095
        $this->assertDebuggingCalled();
3096
 
3097
        // Tidy up after we finish testing.
3098
        $CFG->fullnamedisplay = $originalcfg->fullnamedisplay;
3099
        $CFG->alternativefullnameformat = $originalcfg->alternativefullnameformat;
3100
    }
3101
 
3102
    public function test_order_in_string() {
3103
        $this->resetAfterTest();
3104
 
3105
        // Return an array in an order as they are encountered in a string.
3106
        $valuearray = array('second', 'firsthalf', 'first');
3107
        $formatstring = 'first firsthalf some other text (second)';
3108
        $expectedarray = array('0' => 'first', '6' => 'firsthalf', '33' => 'second');
3109
        $this->assertEquals($expectedarray, order_in_string($valuearray, $formatstring));
3110
 
3111
        // Try again with a different order for the format.
3112
        $valuearray = array('second', 'firsthalf', 'first');
3113
        $formatstring = 'firsthalf first second';
3114
        $expectedarray = array('0' => 'firsthalf', '10' => 'first', '16' => 'second');
3115
        $this->assertEquals($expectedarray, order_in_string($valuearray, $formatstring));
3116
 
3117
        // Try again with yet another different order for the format.
3118
        $valuearray = array('second', 'firsthalf', 'first');
3119
        $formatstring = 'start seconds away second firstquater first firsthalf';
3120
        $expectedarray = array('19' => 'second', '38' => 'first', '44' => 'firsthalf');
3121
        $this->assertEquals($expectedarray, order_in_string($valuearray, $formatstring));
3122
    }
3123
 
3124
    public function test_complete_user_login() {
3125
        global $USER, $DB;
3126
 
3127
        $this->resetAfterTest();
3128
        $user = $this->getDataGenerator()->create_user();
3129
        $this->setUser(0);
3130
 
3131
        $sink = $this->redirectEvents();
3132
        $loginuser = clone($user);
3133
        $this->setCurrentTimeStart();
3134
        @complete_user_login($loginuser); // Hide session header errors.
3135
        $this->assertSame($loginuser, $USER);
3136
        $this->assertEquals($user->id, $USER->id);
3137
        $events = $sink->get_events();
3138
        $sink->close();
3139
 
3140
        $this->assertCount(1, $events);
3141
        $event = reset($events);
3142
        $this->assertInstanceOf('\core\event\user_loggedin', $event);
3143
        $this->assertEquals('user', $event->objecttable);
3144
        $this->assertEquals($user->id, $event->objectid);
3145
        $this->assertEquals(\context_system::instance()->id, $event->contextid);
3146
        $this->assertEventContextNotUsed($event);
3147
 
3148
        $user = $DB->get_record('user', array('id'=>$user->id));
3149
 
3150
        $this->assertTimeCurrent($user->firstaccess);
3151
        $this->assertTimeCurrent($user->lastaccess);
3152
 
3153
        $this->assertTimeCurrent($USER->firstaccess);
3154
        $this->assertTimeCurrent($USER->lastaccess);
3155
        $this->assertTimeCurrent($USER->currentlogin);
3156
        $this->assertSame(sesskey(), $USER->sesskey);
3157
        $this->assertTimeCurrent($USER->preference['_lastloaded']);
3158
        $this->assertObjectNotHasProperty('password', $USER);
3159
        $this->assertObjectNotHasProperty('description', $USER);
3160
    }
3161
 
3162
    /**
3163
     * Test require_logout.
3164
     */
3165
    public function test_require_logout() {
3166
        $this->resetAfterTest();
3167
        $user = $this->getDataGenerator()->create_user();
3168
        $this->setUser($user);
3169
 
3170
        $this->assertTrue(isloggedin());
3171
 
3172
        // Logout user and capture event.
3173
        $sink = $this->redirectEvents();
3174
        require_logout();
3175
        $events = $sink->get_events();
3176
        $sink->close();
3177
        $event = array_pop($events);
3178
 
3179
        // Check if user is logged out.
3180
        $this->assertFalse(isloggedin());
3181
 
3182
        // Test Event.
3183
        $this->assertInstanceOf('\core\event\user_loggedout', $event);
3184
        $this->assertSame($user->id, $event->objectid);
3185
        $this->assertEventContextNotUsed($event);
3186
    }
3187
 
3188
    /**
3189
     * A data provider for testing email messageid
3190
     */
3191
    public function generate_email_messageid_provider() {
3192
        return array(
3193
            'nopath' => array(
3194
                'wwwroot' => 'http://www.example.com',
3195
                'ids' => array(
3196
                    'a-custom-id' => '<a-custom-id@www.example.com>',
3197
                    'an-id-with-/-a-slash' => '<an-id-with-%2F-a-slash@www.example.com>',
3198
                ),
3199
            ),
3200
            'path' => array(
3201
                'wwwroot' => 'http://www.example.com/path/subdir',
3202
                'ids' => array(
3203
                    'a-custom-id' => '<a-custom-id/path/subdir@www.example.com>',
3204
                    'an-id-with-/-a-slash' => '<an-id-with-%2F-a-slash/path/subdir@www.example.com>',
3205
                ),
3206
            ),
3207
        );
3208
    }
3209
 
3210
    /**
3211
     * Test email message id generation
3212
     *
3213
     * @dataProvider generate_email_messageid_provider
3214
     *
3215
     * @param string $wwwroot The wwwroot
3216
     * @param array $msgids An array of msgid local parts and the final result
3217
     */
3218
    public function test_generate_email_messageid($wwwroot, $msgids) {
3219
        global $CFG;
3220
 
3221
        $this->resetAfterTest();
3222
        $CFG->wwwroot = $wwwroot;
3223
 
3224
        foreach ($msgids as $local => $final) {
3225
            $this->assertEquals($final, generate_email_messageid($local));
3226
        }
3227
    }
3228
 
3229
    /**
3230
     * Test email with custom headers
3231
     */
3232
    public function test_send_email_with_custom_header() {
3233
        global $DB, $CFG;
3234
        $this->preventResetByRollback();
3235
        $this->resetAfterTest();
3236
 
3237
        $touser = $this->getDataGenerator()->create_user();
3238
        $fromuser = $this->getDataGenerator()->create_user();
3239
        $fromuser->customheaders = 'X-Custom-Header: foo';
3240
 
3241
        set_config('allowedemaildomains', 'example.com');
3242
        set_config('emailheaders', 'X-Fixed-Header: bar');
3243
 
3244
        $sink = $this->redirectEmails();
3245
        email_to_user($touser, $fromuser, 'subject', 'message');
3246
 
3247
        $emails = $sink->get_messages();
3248
        $this->assertCount(1, $emails);
3249
        $email = reset($emails);
3250
        $this->assertStringContainsString('X-Custom-Header: foo', $email->header);
3251
        $this->assertStringContainsString("X-Fixed-Header: bar", $email->header);
3252
        $sink->clear();
3253
    }
3254
 
3255
    /**
3256
     * A data provider for testing email diversion
3257
     */
3258
    public function diverted_emails_provider() {
3259
        return array(
3260
            'nodiverts' => array(
3261
                'divertallemailsto' => null,
3262
                'divertallemailsexcept' => null,
3263
                array(
3264
                    'foo@example.com',
3265
                    'test@real.com',
3266
                    'fred.jones@example.com',
3267
                    'dev1@dev.com',
3268
                    'fred@example.com',
3269
                    'fred+verp@example.com',
3270
                ),
3271
                false,
3272
            ),
3273
            'alldiverts' => array(
3274
                'divertallemailsto' => 'somewhere@elsewhere.com',
3275
                'divertallemailsexcept' => null,
3276
                array(
3277
                    'foo@example.com',
3278
                    'test@real.com',
3279
                    'fred.jones@example.com',
3280
                    'dev1@dev.com',
3281
                    'fred@example.com',
3282
                    'fred+verp@example.com',
3283
                ),
3284
                true,
3285
            ),
3286
            'alsodiverts' => array(
3287
                'divertallemailsto' => 'somewhere@elsewhere.com',
3288
                'divertallemailsexcept' => '@dev.com, fred(\+.*)?@example.com',
3289
                array(
3290
                    'foo@example.com',
3291
                    'test@real.com',
3292
                    'fred.jones@example.com',
3293
                    'Fred.Jones@Example.com',
3294
                ),
3295
                true,
3296
            ),
3297
            'divertsexceptions' => array(
3298
                'divertallemailsto' => 'somewhere@elsewhere.com',
3299
                'divertallemailsexcept' => '@dev.com, fred(\+.*)?@example.com',
3300
                array(
3301
                    'dev1@dev.com',
3302
                    'fred@example.com',
3303
                    'Fred@Example.com',
3304
                    'fred+verp@example.com',
3305
                ),
3306
                false,
3307
            ),
3308
            'divertsexceptionsnewline' => array(
3309
                'divertallemailsto' => 'somewhere@elsewhere.com',
3310
                'divertallemailsexcept' => "@dev.com\nfred(\+.*)?@example.com",
3311
                array(
3312
                    'dev1@dev.com',
3313
                    'fred@example.com',
3314
                    'fred+verp@example.com',
3315
                ),
3316
                false,
3317
            ),
3318
            'alsodivertsnewline' => array(
3319
                'divertallemailsto' => 'somewhere@elsewhere.com',
3320
                'divertallemailsexcept' => "@dev.com\nfred(\+.*)?@example.com",
3321
                array(
3322
                    'foo@example.com',
3323
                    'test@real.com',
3324
                    'fred.jones@example.com',
3325
                ),
3326
                true,
3327
            ),
3328
            'alsodivertsblankline' => array(
3329
                'divertallemailsto' => 'somewhere@elsewhere.com',
3330
                'divertallemailsexcept' => "@dev.com\n",
3331
                [
3332
                    'lionel@example.com',
3333
                ],
3334
                true,
3335
            ),
3336
            'divertsexceptionblankline' => array(
3337
                'divertallemailsto' => 'somewhere@elsewhere.com',
3338
                'divertallemailsexcept' => "@example.com\n",
3339
                [
3340
                    'lionel@example.com',
3341
                ],
3342
                false,
3343
            ),
3344
        );
3345
    }
3346
 
3347
    /**
3348
     * Test email diversion
3349
     *
3350
     * @dataProvider diverted_emails_provider
3351
     *
3352
     * @param string $divertallemailsto An optional email address
3353
     * @param string $divertallemailsexcept An optional exclusion list
3354
     * @param array $addresses An array of test addresses
3355
     * @param boolean $expected Expected result
3356
     */
3357
    public function test_email_should_be_diverted($divertallemailsto, $divertallemailsexcept, $addresses, $expected) {
3358
        global $CFG;
3359
 
3360
        $this->resetAfterTest();
3361
        $CFG->divertallemailsto = $divertallemailsto;
3362
        $CFG->divertallemailsexcept = $divertallemailsexcept;
3363
 
3364
        foreach ($addresses as $address) {
3365
            $this->assertEquals($expected, email_should_be_diverted($address));
3366
        }
3367
    }
3368
 
3369
    public function test_email_to_user() {
3370
        global $CFG;
3371
 
3372
        $this->resetAfterTest();
3373
 
3374
        $user1 = $this->getDataGenerator()->create_user(array('maildisplay' => 1, 'mailformat' => 0));
3375
        $user2 = $this->getDataGenerator()->create_user(array('maildisplay' => 1, 'mailformat' => 1));
3376
        $user3 = $this->getDataGenerator()->create_user(array('maildisplay' => 0));
3377
        set_config('allowedemaildomains', "example.com\r\nmoodle.org");
3378
 
3379
        $subject = 'subject';
3380
        $messagetext = 'message text';
3381
        $subject2 = 'subject 2';
3382
        $messagetext2 = '<b>message text 2</b>';
3383
 
3384
        // Close the default email sink.
3385
        $sink = $this->redirectEmails();
3386
        $sink->close();
3387
 
3388
        $CFG->noemailever = true;
3389
        $this->assertNotEmpty($CFG->noemailever);
3390
        email_to_user($user1, $user2, $subject, $messagetext);
3391
        $this->assertDebuggingCalled('Not sending email due to $CFG->noemailever config setting');
3392
 
3393
        unset_config('noemailever');
3394
 
3395
        email_to_user($user1, $user2, $subject, $messagetext);
3396
        $this->assertDebuggingCalled('Unit tests must not send real emails! Use $this->redirectEmails()');
3397
 
3398
        $sink = $this->redirectEmails();
3399
        email_to_user($user1, $user2, $subject, $messagetext);
3400
        email_to_user($user2, $user1, $subject2, $messagetext2);
3401
        $this->assertSame(2, $sink->count());
3402
        $result = $sink->get_messages();
3403
        $this->assertCount(2, $result);
3404
        $sink->close();
3405
 
3406
        $this->assertSame($subject, $result[0]->subject);
3407
        $this->assertSame($messagetext, trim($result[0]->body));
3408
        $this->assertSame($user1->email, $result[0]->to);
3409
        $this->assertSame($user2->email, $result[0]->from);
3410
        $this->assertStringContainsString('Content-Type: text/plain', $result[0]->header);
3411
 
3412
        $this->assertSame($subject2, $result[1]->subject);
3413
        $this->assertStringContainsString($messagetext2, quoted_printable_decode($result[1]->body));
3414
        $this->assertSame($user2->email, $result[1]->to);
3415
        $this->assertSame($user1->email, $result[1]->from);
3416
        $this->assertStringNotContainsString('Content-Type: text/plain', $result[1]->header);
3417
 
3418
        email_to_user($user1, $user2, $subject, $messagetext);
3419
        $this->assertDebuggingCalled('Unit tests must not send real emails! Use $this->redirectEmails()');
3420
 
3421
        // Test that an empty noreplyaddress will default to a no-reply address.
3422
        $sink = $this->redirectEmails();
3423
        email_to_user($user1, $user3, $subject, $messagetext);
3424
        $result = $sink->get_messages();
3425
        $this->assertEquals($CFG->noreplyaddress, $result[0]->from);
3426
        $sink->close();
3427
        set_config('noreplyaddress', '');
3428
        $sink = $this->redirectEmails();
3429
        email_to_user($user1, $user3, $subject, $messagetext);
3430
        $result = $sink->get_messages();
3431
        $this->assertEquals('noreply@www.example.com', $result[0]->from);
3432
        $sink->close();
3433
 
3434
        // Test $CFG->allowedemaildomains.
3435
        set_config('noreplyaddress', 'noreply@www.example.com');
3436
        $this->assertNotEmpty($CFG->allowedemaildomains);
3437
        $sink = $this->redirectEmails();
3438
        email_to_user($user1, $user2, $subject, $messagetext);
3439
        unset_config('allowedemaildomains');
3440
        email_to_user($user1, $user2, $subject, $messagetext);
3441
        $result = $sink->get_messages();
3442
        $this->assertNotEquals($CFG->noreplyaddress, $result[0]->from);
3443
        $this->assertEquals($CFG->noreplyaddress, $result[1]->from);
3444
        $sink->close();
3445
 
3446
        // Try to send an unsafe attachment, we should see an error message in the eventual mail body.
3447
        $attachment = '../test.txt';
3448
        $attachname = 'txt';
3449
 
3450
        $sink = $this->redirectEmails();
3451
        email_to_user($user1, $user2, $subject, $messagetext, '', $attachment, $attachname);
3452
        $this->assertSame(1, $sink->count());
3453
        $result = $sink->get_messages();
3454
        $this->assertCount(1, $result);
3455
        $this->assertStringContainsString('error.txt', $result[0]->body);
3456
        $this->assertStringContainsString('Error in attachment.  User attempted to attach a filename with a unsafe name.', $result[0]->body);
3457
        $sink->close();
3458
    }
3459
 
3460
    /**
3461
     * Data provider for {@see test_email_to_user_attachment}
3462
     *
3463
     * @return array
3464
     */
3465
    public function email_to_user_attachment_provider(): array {
3466
        global $CFG;
3467
 
3468
        // Return all paths that can be used to send attachments from.
3469
        return [
3470
            'cachedir' => [$CFG->cachedir],
3471
            'dataroot' => [$CFG->dataroot],
3472
            'dirroot' => [$CFG->dirroot],
3473
            'localcachedir' => [$CFG->localcachedir],
3474
            'tempdir' => [$CFG->tempdir],
3475
            // Paths within $CFG->localrequestdir.
3476
            'localrequestdir_request_directory' => [make_request_directory()],
3477
            'localrequestdir_request_storage_directory' => [get_request_storage_directory()],
3478
            // Pass null to indicate we want to test a path relative to $CFG->dataroot.
3479
            'relative' => [null]
3480
        ];
3481
    }
3482
 
3483
    /**
3484
     * Test sending attachments with email_to_user
3485
     *
3486
     * @param string|null $filedir
3487
     *
3488
     * @dataProvider email_to_user_attachment_provider
3489
     */
3490
    public function test_email_to_user_attachment(?string $filedir): void {
3491
        global $CFG;
3492
 
3493
        // If $filedir is null, then write our test file to $CFG->dataroot.
3494
        $filepath = ($filedir ?: $CFG->dataroot) . '/hello.txt';
3495
        file_put_contents($filepath, 'Hello');
3496
 
3497
        $user = \core_user::get_support_user();
3498
        $message = 'Test attachment path';
3499
 
3500
        // Create sink to catch all sent e-mails.
3501
        $sink = $this->redirectEmails();
3502
 
3503
        // Attachment path will be that of the test file if $filedir was passed, otherwise the relative path from $CFG->dataroot.
3504
        $filename = basename($filepath);
3505
        $attachmentpath = $filedir ? $filepath : $filename;
3506
        email_to_user($user, $user, $message, $message, $message, $attachmentpath, $filename);
3507
 
3508
        $messages = $sink->get_messages();
3509
        $sink->close();
3510
 
3511
        $this->assertCount(1, $messages);
3512
 
3513
        // Verify attachment in message body (attachment is in MIME format, but we can detect some Content fields).
3514
        $messagebody = reset($messages)->body;
3515
        $this->assertStringContainsString('Content-Type: text/plain; name=' . $filename, $messagebody);
3516
        $this->assertStringContainsString('Content-Disposition: attachment; filename=' . $filename, $messagebody);
3517
 
3518
        // Cleanup.
3519
        unlink($filepath);
3520
    }
3521
 
3522
    /**
3523
     * Test sending an attachment that doesn't exist to email_to_user
3524
     */
3525
    public function test_email_to_user_attachment_missing(): void {
3526
        $user = \core_user::get_support_user();
3527
        $message = 'Test attachment path';
3528
 
3529
        // Create sink to catch all sent e-mails.
3530
        $sink = $this->redirectEmails();
3531
 
3532
        $attachmentpath = '/hola/hello.txt';
3533
        $filename = basename($attachmentpath);
3534
        email_to_user($user, $user, $message, $message, $message, $attachmentpath, $filename);
3535
 
3536
        $messages = $sink->get_messages();
3537
        $sink->close();
3538
 
3539
        $this->assertCount(1, $messages);
3540
 
3541
        // Verify attachment not in message body (attachment is in MIME format, but we can detect some Content fields).
3542
        $messagebody = reset($messages)->body;
3543
        $this->assertStringNotContainsString('Content-Type: text/plain; name="' . $filename . '"', $messagebody);
3544
        $this->assertStringNotContainsString('Content-Disposition: attachment; filename=' . $filename, $messagebody);
3545
    }
3546
 
3547
    /**
3548
     * Test setnew_password_and_mail.
3549
     */
3550
    public function test_setnew_password_and_mail() {
3551
        global $DB, $CFG;
3552
 
3553
        $this->resetAfterTest();
3554
 
3555
        $user = $this->getDataGenerator()->create_user();
3556
 
3557
        // Update user password.
3558
        $sink = $this->redirectEvents();
3559
        $sink2 = $this->redirectEmails(); // Make sure we are redirecting emails.
3560
        setnew_password_and_mail($user);
3561
        $events = $sink->get_events();
3562
        $sink->close();
3563
        $sink2->close();
3564
        $event = array_pop($events);
3565
 
3566
        // Test updated value.
3567
        $dbuser = $DB->get_record('user', array('id' => $user->id));
3568
        $this->assertSame($user->firstname, $dbuser->firstname);
3569
        $this->assertNotEmpty($dbuser->password);
3570
 
3571
        // Test event.
3572
        $this->assertInstanceOf('\core\event\user_password_updated', $event);
3573
        $this->assertSame($user->id, $event->relateduserid);
3574
        $this->assertEquals(\context_user::instance($user->id), $event->get_context());
3575
        $this->assertEventContextNotUsed($event);
3576
    }
3577
 
3578
    /**
3579
     * Data provider for test_generate_confirmation_link
3580
     * @return Array of confirmation urls and expected resultant confirmation links
3581
     */
3582
    public function generate_confirmation_link_provider() {
3583
        global $CFG;
3584
        return [
3585
            "Simple name" => [
3586
                "username" => "simplename",
3587
                "confirmationurl" => null,
3588
                "expected" => $CFG->wwwroot . "/login/confirm.php?data=/simplename"
3589
            ],
3590
            "Period in between words in username" => [
3591
                "username" => "period.inbetween",
3592
                "confirmationurl" => null,
3593
                "expected" => $CFG->wwwroot . "/login/confirm.php?data=/period%2Einbetween"
3594
            ],
3595
            "Trailing periods in username" => [
3596
                "username" => "trailingperiods...",
3597
                "confirmationurl" => null,
3598
                "expected" => $CFG->wwwroot . "/login/confirm.php?data=/trailingperiods%2E%2E%2E"
3599
            ],
3600
            "At symbol in username" => [
3601
                "username" => "at@symbol",
3602
                "confirmationurl" => null,
3603
                "expected" => $CFG->wwwroot . "/login/confirm.php?data=/at%40symbol"
3604
            ],
3605
            "Dash symbol in username" => [
3606
                "username" => "has-dash",
3607
                "confirmationurl" => null,
3608
                "expected" => $CFG->wwwroot . "/login/confirm.php?data=/has-dash"
3609
            ],
3610
            "Underscore in username" => [
3611
                "username" => "under_score",
3612
                "confirmationurl" => null,
3613
                "expected" => $CFG->wwwroot . "/login/confirm.php?data=/under_score"
3614
            ],
3615
            "Many different characters in username" => [
3616
                "username" => "many_-.@characters@_@-..-..",
3617
                "confirmationurl" => null,
3618
                "expected" => $CFG->wwwroot . "/login/confirm.php?data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E"
3619
            ],
3620
            "Custom relative confirmation url" => [
3621
                "username" => "many_-.@characters@_@-..-..",
3622
                "confirmationurl" => "/custom/local/url.php",
3623
                "expected" => $CFG->wwwroot . "/custom/local/url.php?data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E"
3624
            ],
3625
            "Custom relative confirmation url with parameters" => [
3626
                "username" => "many_-.@characters@_@-..-..",
3627
                "confirmationurl" => "/custom/local/url.php?with=param",
3628
                "expected" => $CFG->wwwroot . "/custom/local/url.php?with=param&data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E"
3629
            ],
3630
            "Custom local confirmation url" => [
3631
                "username" => "many_-.@characters@_@-..-..",
3632
                "confirmationurl" => $CFG->wwwroot . "/custom/local/url.php",
3633
                "expected" => $CFG->wwwroot . "/custom/local/url.php?data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E"
3634
            ],
3635
            "Custom local confirmation url with parameters" => [
3636
                "username" => "many_-.@characters@_@-..-..",
3637
                "confirmationurl" => $CFG->wwwroot . "/custom/local/url.php?with=param",
3638
                "expected" => $CFG->wwwroot . "/custom/local/url.php?with=param&data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E"
3639
            ],
3640
            "Custom external confirmation url" => [
3641
                "username" => "many_-.@characters@_@-..-..",
3642
                "confirmationurl" => "http://moodle.org/custom/external/url.php",
3643
                "expected" => "http://moodle.org/custom/external/url.php?data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E"
3644
            ],
3645
            "Custom external confirmation url with parameters" => [
3646
                "username" => "many_-.@characters@_@-..-..",
3647
                "confirmationurl" => "http://moodle.org/ext.php?with=some&param=eters",
3648
                "expected" => "http://moodle.org/ext.php?with=some&param=eters&data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E"
3649
            ],
3650
            "Custom external confirmation url with parameters" => [
3651
                "username" => "many_-.@characters@_@-..-..",
3652
                "confirmationurl" => "http://moodle.org/ext.php?with=some&data=test",
3653
                "expected" => "http://moodle.org/ext.php?with=some&data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E"
3654
            ],
3655
        ];
3656
    }
3657
 
3658
    /**
3659
     * Test generate_confirmation_link
3660
     * @dataProvider generate_confirmation_link_provider
3661
     * @param string $username The name of the user
3662
     * @param string $confirmationurl The url the user should go to to confirm
3663
     * @param string $expected The expected url of the confirmation link
3664
     */
3665
    public function test_generate_confirmation_link($username, $confirmationurl, $expected) {
3666
        $this->resetAfterTest();
3667
        $sink = $this->redirectEmails();
3668
 
3669
        $user = $this->getDataGenerator()->create_user(
3670
            [
3671
                "username" => $username,
3672
                "confirmed" => 0,
3673
                "email" => 'test@example.com',
3674
            ]
3675
        );
3676
 
3677
        send_confirmation_email($user, $confirmationurl);
3678
        $sink->close();
3679
        $messages = $sink->get_messages();
3680
        $message = array_shift($messages);
3681
        $messagebody = quoted_printable_decode($message->body);
3682
 
3683
        $this->assertStringContainsString($expected, $messagebody);
3684
    }
3685
 
3686
    /**
3687
     * Test generate_confirmation_link with custom admin link
3688
     */
3689
    public function test_generate_confirmation_link_with_custom_admin() {
3690
        global $CFG;
3691
 
3692
        $this->resetAfterTest();
3693
        $sink = $this->redirectEmails();
3694
 
3695
        $admin = $CFG->admin;
3696
        $CFG->admin = 'custom/admin/path';
3697
 
3698
        $user = $this->getDataGenerator()->create_user(
3699
            [
3700
                "username" => "many_-.@characters@_@-..-..",
3701
                "confirmed" => 0,
3702
                "email" => 'test@example.com',
3703
            ]
3704
        );
3705
        $confirmationurl = "/admin/test.php?with=params";
3706
        $expected = $CFG->wwwroot . "/" . $CFG->admin . "/test.php?with=params&data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E";
3707
 
3708
        send_confirmation_email($user, $confirmationurl);
3709
        $sink->close();
3710
        $messages = $sink->get_messages();
3711
        $message = array_shift($messages);
3712
        $messagebody = quoted_printable_decode($message->body);
3713
 
3714
        $sink->close();
3715
        $this->assertStringContainsString($expected, $messagebody);
3716
 
3717
        $CFG->admin = $admin;
3718
    }
3719
 
3720
 
3721
    /**
3722
     * Test remove_course_content deletes course contents
3723
     * TODO Add asserts to verify other data related to course is deleted as well.
3724
     */
3725
    public function test_remove_course_contents() {
3726
 
3727
        $this->resetAfterTest();
3728
 
3729
        $course = $this->getDataGenerator()->create_course();
3730
        $user = $this->getDataGenerator()->create_user();
3731
        $gen = $this->getDataGenerator()->get_plugin_generator('core_notes');
3732
        $note = $gen->create_instance(array('courseid' => $course->id, 'userid' => $user->id));
3733
 
3734
        $this->assertNotEquals(false, note_load($note->id));
3735
        remove_course_contents($course->id, false);
3736
        $this->assertFalse(note_load($note->id));
3737
    }
3738
 
3739
    /**
3740
     * Test function username_load_fields_from_object().
3741
     */
3742
    public function test_username_load_fields_from_object() {
3743
        $this->resetAfterTest();
3744
 
3745
        // This object represents the information returned from an sql query.
3746
        $userinfo = new \stdClass();
3747
        $userinfo->userid = 1;
3748
        $userinfo->username = 'loosebruce';
3749
        $userinfo->firstname = 'Bruce';
3750
        $userinfo->lastname = 'Campbell';
3751
        $userinfo->firstnamephonetic = 'ブルース';
3752
        $userinfo->lastnamephonetic = 'カンベッル';
3753
        $userinfo->middlename = '';
3754
        $userinfo->alternatename = '';
3755
        $userinfo->email = '';
3756
        $userinfo->picture = 23;
3757
        $userinfo->imagealt = 'Michael Jordan draining another basket.';
3758
        $userinfo->idnumber = 3982;
3759
 
3760
        // Just user name fields.
3761
        $user = new \stdClass();
3762
        $user = username_load_fields_from_object($user, $userinfo);
3763
        $expectedarray = new \stdClass();
3764
        $expectedarray->firstname = 'Bruce';
3765
        $expectedarray->lastname = 'Campbell';
3766
        $expectedarray->firstnamephonetic = 'ブルース';
3767
        $expectedarray->lastnamephonetic = 'カンベッル';
3768
        $expectedarray->middlename = '';
3769
        $expectedarray->alternatename = '';
3770
        $this->assertEquals($user, $expectedarray);
3771
 
3772
        // User information for showing a picture.
3773
        $user = new \stdClass();
3774
        $additionalfields = explode(',', implode(',', \core_user\fields::get_picture_fields()));
3775
        $user = username_load_fields_from_object($user, $userinfo, null, $additionalfields);
3776
        $user->id = $userinfo->userid;
3777
        $expectedarray = new \stdClass();
3778
        $expectedarray->id = 1;
3779
        $expectedarray->firstname = 'Bruce';
3780
        $expectedarray->lastname = 'Campbell';
3781
        $expectedarray->firstnamephonetic = 'ブルース';
3782
        $expectedarray->lastnamephonetic = 'カンベッル';
3783
        $expectedarray->middlename = '';
3784
        $expectedarray->alternatename = '';
3785
        $expectedarray->email = '';
3786
        $expectedarray->picture = 23;
3787
        $expectedarray->imagealt = 'Michael Jordan draining another basket.';
3788
        $this->assertEquals($user, $expectedarray);
3789
 
3790
        // Alter the userinfo object to have a prefix.
3791
        $userinfo->authorfirstname = 'Bruce';
3792
        $userinfo->authorlastname = 'Campbell';
3793
        $userinfo->authorfirstnamephonetic = 'ブルース';
3794
        $userinfo->authorlastnamephonetic = 'カンベッル';
3795
        $userinfo->authormiddlename = '';
3796
        $userinfo->authorpicture = 23;
3797
        $userinfo->authorimagealt = 'Michael Jordan draining another basket.';
3798
        $userinfo->authoremail = 'test@example.com';
3799
 
3800
 
3801
        // Return an object with user picture information.
3802
        $user = new \stdClass();
3803
        $additionalfields = explode(',', implode(',', \core_user\fields::get_picture_fields()));
3804
        $user = username_load_fields_from_object($user, $userinfo, 'author', $additionalfields);
3805
        $user->id = $userinfo->userid;
3806
        $expectedarray = new \stdClass();
3807
        $expectedarray->id = 1;
3808
        $expectedarray->firstname = 'Bruce';
3809
        $expectedarray->lastname = 'Campbell';
3810
        $expectedarray->firstnamephonetic = 'ブルース';
3811
        $expectedarray->lastnamephonetic = 'カンベッル';
3812
        $expectedarray->middlename = '';
3813
        $expectedarray->alternatename = '';
3814
        $expectedarray->email = 'test@example.com';
3815
        $expectedarray->picture = 23;
3816
        $expectedarray->imagealt = 'Michael Jordan draining another basket.';
3817
        $this->assertEquals($user, $expectedarray);
3818
    }
3819
 
3820
    /**
3821
     * Test function {@see count_words()}.
3822
     *
3823
     * @dataProvider count_words_testcases
3824
     * @param int $expectedcount number of words in $string.
3825
     * @param string $string the test string to count the words of.
3826
     * @param int|null $format
3827
     */
3828
    public function test_count_words(int $expectedcount, string $string, $format = null): void {
3829
        $this->assertEquals($expectedcount, count_words($string, $format),
3830
            "'$string' with format '$format' does not match count $expectedcount");
3831
    }
3832
 
3833
    /**
3834
     * Data provider for {@see test_count_words}.
3835
     *
3836
     * @return array of test cases.
3837
     */
3838
    public function count_words_testcases(): array {
3839
        // Copy-pasting example from MDL-64240.
3840
        $copypasted = <<<EOT
3841
<p onclick="alert('boop');">Snoot is booped</p>
3842
 <script>alert('Boop the snoot');</script>
3843
 <img alt="Boop the Snoot." src="https://proxy.duckduckgo.com/iu/?u=http%3A%2F%2Fwww.geekfill.com%2Fwp-content%2Fuploads%2F2015%2F08%2FBoop-the-Snoot.jpg&f=1">
3844
EOT;
3845
 
3846
        // The counts here should match MS Word and Libre Office.
3847
        return [
3848
            [0, ''],
3849
            [4, 'one two three four'],
3850
            [1, "a'b"],
3851
            [1, '1+1=2'],
3852
            [1, ' one-sided '],
3853
            [2, 'one&nbsp;two'],
3854
            [1, 'email@example.com'],
3855
            [2, 'first\part second/part'],
3856
            [4, '<p>one two<br></br>three four</p>'],
3857
            [4, '<p>one two<br>three four</p>'],
3858
            [4, '<p>one two<br />three four</p>'], // XHTML style.
3859
            [3, ' one ... three '],
3860
            [1, 'just...one'],
3861
            [3, ' one & three '],
3862
            [1, 'just&one'],
3863
            [2, 'em—dash'],
3864
            [2, 'en–dash'],
3865
            [4, '1³ £2 €3.45 $6,789'],
3866
            [2, 'ブルース カンベッル'], // MS word counts this as 11, but we don't handle that yet.
3867
            [4, '<p>one two</p><p>three four</p>'],
3868
            [4, '<p>one two</p><p><br/></p><p>three four</p>'],
3869
            [4, '<p>one</p><ul><li>two</li><li>three</li></ul><p>four.</p>'],
3870
            [1, '<p>em<b>phas</b>is.</p>'],
3871
            [1, '<p>em<i>phas</i>is.</p>'],
3872
            [1, '<p>em<strong>phas</strong>is.</p>'],
3873
            [1, '<p>em<em>phas</em>is.</p>'],
3874
            [2, "one\ntwo"],
3875
            [2, "one\rtwo"],
3876
            [2, "one\ttwo"],
3877
            [2, "one\vtwo"],
3878
            [2, "one\ftwo"],
3879
            [1, "SO<sub>4</sub><sup>2-</sup>"],
3880
            [6, '4+4=8 i.e. O(1) a,b,c,d I’m black&blue_really'],
3881
            [1, '<span>a</span><span>b</span>'],
3882
            [1, '<span>a</span><span>b</span>', FORMAT_PLAIN],
3883
            [1, '<span>a</span><span>b</span>', FORMAT_HTML],
3884
            [1, '<span>a</span><span>b</span>', FORMAT_MOODLE],
3885
            [1, '<span>a</span><span>b</span>', FORMAT_MARKDOWN],
3886
            [1, 'aa <argh <bleh>pokus</bleh>'],
3887
            [2, 'aa <argh <bleh>pokus</bleh>', FORMAT_HTML],
3888
            [6, $copypasted],
3889
            [6, $copypasted, FORMAT_PLAIN],
3890
            [3, $copypasted, FORMAT_HTML],
3891
            [3, $copypasted, FORMAT_MOODLE],
3892
        ];
3893
    }
3894
 
3895
    /**
3896
     * Test function {@see count_letters()}.
3897
     *
3898
     * @dataProvider count_letters_testcases
3899
     * @param int $expectedcount number of characters in $string.
3900
     * @param string $string the test string to count the letters of.
3901
     * @param int|null $format
3902
     */
3903
    public function test_count_letters(int $expectedcount, string $string, $format = null): void {
3904
        $this->assertEquals($expectedcount, count_letters($string, $format),
3905
            "'$string' with format '$format' does not match count $expectedcount");
3906
    }
3907
 
3908
    /**
3909
     * Data provider for {@see count_letters_testcases}.
3910
     *
3911
     * @return array of test cases.
3912
     */
3913
    public function count_letters_testcases(): array {
3914
        return [
3915
            [0, ''],
3916
            [1, 'x'],
3917
            [1, '&amp;'],
3918
            [4, '<p>frog</p>'],
3919
            [4, '<p>frog</p>', FORMAT_PLAIN],
3920
            [4, '<p>frog</p>', FORMAT_MOODLE],
3921
            [4, '<p>frog</p>', FORMAT_HTML],
3922
            [4, '<p>frog</p>', FORMAT_MARKDOWN],
3923
            [2, 'aa <argh <bleh>pokus</bleh>'],
3924
            [7, 'aa <argh <bleh>pokus</bleh>', FORMAT_HTML],
3925
        ];
3926
    }
3927
 
3928
    /**
3929
     * Tests the getremoteaddr() function.
3930
     */
3931
    public function test_getremoteaddr() {
3932
        global $CFG;
3933
 
3934
        $this->resetAfterTest();
3935
 
3936
        $CFG->getremoteaddrconf = null; // Use default value, GETREMOTEADDR_SKIP_DEFAULT.
3937
        $noip = getremoteaddr('1.1.1.1');
3938
        $this->assertEquals('1.1.1.1', $noip);
3939
 
3940
        $remoteaddr = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : null;
3941
        $_SERVER['REMOTE_ADDR'] = '127.0.0.1';
3942
        $singleip = getremoteaddr();
3943
        $this->assertEquals('127.0.0.1', $singleip);
3944
 
3945
        $_SERVER['REMOTE_ADDR'] = $remoteaddr; // Restore server value.
3946
 
3947
        $CFG->getremoteaddrconf = 0; // Don't skip any source.
3948
        $noip = getremoteaddr('1.1.1.1');
3949
        $this->assertEquals('1.1.1.1', $noip);
3950
 
3951
        // Populate all $_SERVER values to review order.
3952
        $ipsources = [
3953
            'HTTP_CLIENT_IP' => '2.2.2.2',
3954
            'HTTP_X_FORWARDED_FOR' => '3.3.3.3',
3955
            'REMOTE_ADDR' => '4.4.4.4',
3956
        ];
3957
        $originalvalues = [];
3958
        foreach ($ipsources as $source => $ip) {
3959
            $originalvalues[$source] = isset($_SERVER[$source]) ? $_SERVER[$source] : null; // Saving data to restore later.
3960
            $_SERVER[$source] = $ip;
3961
        }
3962
 
3963
        foreach ($ipsources as $source => $expectedip) {
3964
            $ip = getremoteaddr();
3965
            $this->assertEquals($expectedip, $ip);
3966
            unset($_SERVER[$source]); // Removing the value so next time we get the following ip.
3967
        }
3968
 
3969
        // Restore server values.
3970
        foreach ($originalvalues as $source => $ip) {
3971
            $_SERVER[$source] = $ip;
3972
        }
3973
 
3974
        // All $_SERVER values have been removed, we should get the default again.
3975
        $noip = getremoteaddr('1.1.1.1');
3976
        $this->assertEquals('1.1.1.1', $noip);
3977
 
3978
        $CFG->getremoteaddrconf = GETREMOTEADDR_SKIP_HTTP_CLIENT_IP;
3979
        $xforwardedfor = isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : null;
3980
 
3981
        $_SERVER['HTTP_X_FORWARDED_FOR'] = '';
3982
        $noip = getremoteaddr('1.1.1.1');
3983
        $this->assertEquals('1.1.1.1', $noip);
3984
 
3985
        $_SERVER['HTTP_X_FORWARDED_FOR'] = '';
3986
        $noip = getremoteaddr();
3987
        $this->assertEquals('0.0.0.0', $noip);
3988
 
3989
        $_SERVER['HTTP_X_FORWARDED_FOR'] = '127.0.0.1';
3990
        $singleip = getremoteaddr();
3991
        $this->assertEquals('127.0.0.1', $singleip);
3992
 
3993
        $_SERVER['HTTP_X_FORWARDED_FOR'] = '127.0.0.1,127.0.0.2';
3994
        $twoip = getremoteaddr();
3995
        $this->assertEquals('127.0.0.2', $twoip);
3996
 
3997
        $_SERVER['HTTP_X_FORWARDED_FOR'] = '127.0.0.1,127.0.0.2,127.0.0.3';
3998
        $threeip = getremoteaddr();
3999
        $this->assertEquals('127.0.0.3', $threeip);
4000
 
4001
        $_SERVER['HTTP_X_FORWARDED_FOR'] = '127.0.0.1,127.0.0.2:65535';
4002
        $portip = getremoteaddr();
4003
        $this->assertEquals('127.0.0.2', $portip);
4004
 
4005
        $_SERVER['HTTP_X_FORWARDED_FOR'] = '127.0.0.1,0:0:0:0:0:0:0:2';
4006
        $portip = getremoteaddr();
4007
        $this->assertEquals('0:0:0:0:0:0:0:2', $portip);
4008
 
4009
        $_SERVER['HTTP_X_FORWARDED_FOR'] = '127.0.0.1,0::2';
4010
        $portip = getremoteaddr();
4011
        $this->assertEquals('0:0:0:0:0:0:0:2', $portip);
4012
 
4013
        $_SERVER['HTTP_X_FORWARDED_FOR'] = '127.0.0.1,[0:0:0:0:0:0:0:2]:65535';
4014
        $portip = getremoteaddr();
4015
        $this->assertEquals('0:0:0:0:0:0:0:2', $portip);
4016
 
4017
        $_SERVER['HTTP_X_FORWARDED_FOR'] = $xforwardedfor;
4018
 
4019
    }
4020
 
4021
    /**
4022
     * Test function for creation of random strings.
4023
     */
4024
    public function test_random_string() {
4025
        $pool = 'a-zA-Z0-9';
4026
 
4027
        $result = random_string(10);
4028
        $this->assertSame(10, strlen($result));
4029
        $this->assertMatchesRegularExpression('/^[' . $pool . ']+$/', $result);
4030
        $this->assertNotSame($result, random_string(10));
4031
 
4032
        $result = random_string(21);
4033
        $this->assertSame(21, strlen($result));
4034
        $this->assertMatchesRegularExpression('/^[' . $pool . ']+$/', $result);
4035
        $this->assertNotSame($result, random_string(21));
4036
 
4037
        $result = random_string(666);
4038
        $this->assertSame(666, strlen($result));
4039
        $this->assertMatchesRegularExpression('/^[' . $pool . ']+$/', $result);
4040
 
4041
        $result = random_string();
4042
        $this->assertSame(15, strlen($result));
4043
        $this->assertMatchesRegularExpression('/^[' . $pool . ']+$/', $result);
4044
 
4045
        $this->assertDebuggingNotCalled();
4046
    }
4047
 
4048
    /**
4049
     * Test function for creation of complex random strings.
4050
     */
4051
    public function test_complex_random_string() {
4052
        $pool = preg_quote('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789`~!@#%^&*()_+-=[];,./<>?:{} ', '/');
4053
 
4054
        $result = complex_random_string(10);
4055
        $this->assertSame(10, strlen($result));
4056
        $this->assertMatchesRegularExpression('/^[' . $pool . ']+$/', $result);
4057
        $this->assertNotSame($result, complex_random_string(10));
4058
 
4059
        $result = complex_random_string(21);
4060
        $this->assertSame(21, strlen($result));
4061
        $this->assertMatchesRegularExpression('/^[' . $pool . ']+$/', $result);
4062
        $this->assertNotSame($result, complex_random_string(21));
4063
 
4064
        $result = complex_random_string(666);
4065
        $this->assertSame(666, strlen($result));
4066
        $this->assertMatchesRegularExpression('/^[' . $pool . ']+$/', $result);
4067
 
4068
        $result = complex_random_string();
4069
        $this->assertEqualsWithDelta(28, strlen($result), 4); // Expected length is 24 - 32.
4070
        $this->assertMatchesRegularExpression('/^[' . $pool . ']+$/', $result);
4071
 
4072
        $this->assertDebuggingNotCalled();
4073
    }
4074
 
4075
    /**
4076
     * Data provider for private ips.
4077
     */
4078
    public function data_private_ips() {
4079
        return array(
4080
            array('10.0.0.0'),
4081
            array('172.16.0.0'),
4082
            array('192.168.1.0'),
4083
            array('fdfe:dcba:9876:ffff:fdc6:c46b:bb8f:7d4c'),
4084
            array('fdc6:c46b:bb8f:7d4c:fdc6:c46b:bb8f:7d4c'),
4085
            array('fdc6:c46b:bb8f:7d4c:0000:8a2e:0370:7334'),
4086
            array('127.0.0.1'), // This has been buggy in past: https://bugs.php.net/bug.php?id=53150.
4087
        );
4088
    }
4089
 
4090
    /**
4091
     * Checks ip_is_public returns false for private ips.
4092
     *
4093
     * @param string $ip the ipaddress to test
4094
     * @dataProvider data_private_ips
4095
     */
4096
    public function test_ip_is_public_private_ips($ip) {
4097
        $this->assertFalse(ip_is_public($ip));
4098
    }
4099
 
4100
    /**
4101
     * Data provider for public ips.
4102
     */
4103
    public function data_public_ips() {
4104
        return array(
4105
            array('2400:cb00:2048:1::8d65:71b3'),
4106
            array('2400:6180:0:d0::1b:2001'),
4107
            array('141.101.113.179'),
4108
            array('123.45.67.178'),
4109
        );
4110
    }
4111
 
4112
    /**
4113
     * Checks ip_is_public returns true for public ips.
4114
     *
4115
     * @param string $ip the ipaddress to test
4116
     * @dataProvider data_public_ips
4117
     */
4118
    public function test_ip_is_public_public_ips($ip) {
4119
        $this->assertTrue(ip_is_public($ip));
4120
    }
4121
 
4122
    /**
4123
     * Test the function can_send_from_real_email_address
4124
     *
4125
     * @param string $email Email address for the from user.
4126
     * @param int $display The user's email display preference.
4127
     * @param bool $samecourse Are the users in the same course?
4128
     * @param string $config The CFG->allowedemaildomains config values
4129
     * @param bool $result The expected result.
4130
     * @dataProvider data_can_send_from_real_email_address
4131
     */
4132
    public function test_can_send_from_real_email_address($email, $display, $samecourse, $config, $result) {
4133
        $this->resetAfterTest();
4134
 
4135
        $fromuser = $this->getDataGenerator()->create_user();
4136
        $touser = $this->getDataGenerator()->create_user();
4137
        $course = $this->getDataGenerator()->create_course();
4138
        set_config('allowedemaildomains', $config);
4139
 
4140
        $fromuser->email = $email;
4141
        $fromuser->maildisplay = $display;
4142
        if ($samecourse) {
4143
            $this->getDataGenerator()->enrol_user($fromuser->id, $course->id, 'student');
4144
            $this->getDataGenerator()->enrol_user($touser->id, $course->id, 'student');
4145
        } else {
4146
            $this->getDataGenerator()->enrol_user($fromuser->id, $course->id, 'student');
4147
        }
4148
        $this->assertEquals($result, can_send_from_real_email_address($fromuser, $touser));
4149
    }
4150
 
4151
    /**
4152
     * Data provider for test_can_send_from_real_email_address.
4153
     *
4154
     * @return array Returns an array of test data for the above function.
4155
     */
4156
    public function data_can_send_from_real_email_address() {
4157
        return [
4158
            // Test from email is in allowed domain.
4159
            // Test that from display is set to show no one.
4160
            [
4161
                'email' => 'fromuser@example.com',
4162
                'display' => \core_user::MAILDISPLAY_HIDE,
4163
                'samecourse' => false,
4164
                'config' => "example.com\r\ntest.com",
4165
                'result' => false
4166
            ],
4167
            // Test that from display is set to course members only (course member).
4168
            [
4169
                'email' => 'fromuser@example.com',
4170
                'display' => \core_user::MAILDISPLAY_COURSE_MEMBERS_ONLY,
4171
                'samecourse' => true,
4172
                'config' => "example.com\r\ntest.com",
4173
                'result' => true
4174
            ],
4175
            // Test that from display is set to course members only (Non course member).
4176
            [
4177
                'email' => 'fromuser@example.com',
4178
                'display' => \core_user::MAILDISPLAY_COURSE_MEMBERS_ONLY,
4179
                'samecourse' => false,
4180
                'config' => "example.com\r\ntest.com",
4181
                'result' => false
4182
            ],
4183
            // Test that from display is set to show everyone.
4184
            [
4185
                'email' => 'fromuser@example.com',
4186
                'display' => \core_user::MAILDISPLAY_EVERYONE,
4187
                'samecourse' => false,
4188
                'config' => "example.com\r\ntest.com",
4189
                'result' => true
4190
            ],
4191
            // Test a few different config value formats for parsing correctness.
4192
            [
4193
                'email' => 'fromuser@example.com',
4194
                'display' => \core_user::MAILDISPLAY_EVERYONE,
4195
                'samecourse' => false,
4196
                'config' => "\n test.com\nexample.com \n",
4197
                'result' => true
4198
            ],
4199
            [
4200
                'email' => 'fromuser@example.com',
4201
                'display' => \core_user::MAILDISPLAY_EVERYONE,
4202
                'samecourse' => false,
4203
                'config' => "\r\n example.com \r\n test.com \r\n",
4204
                'result' => true
4205
            ],
4206
            [
4207
                'email' => 'fromuser@EXAMPLE.com',
4208
                'display' => \core_user::MAILDISPLAY_EVERYONE,
4209
                'samecourse' => false,
4210
                'config' => "example.com\r\ntest.com",
4211
                'result' => true,
4212
            ],
4213
            // Test from email is not in allowed domain.
4214
            // Test that from display is set to show no one.
4215
            [   'email' => 'fromuser@moodle.com',
4216
                'display' => \core_user::MAILDISPLAY_HIDE,
4217
                'samecourse' => false,
4218
                'config' => "example.com\r\ntest.com",
4219
                'result' => false
4220
            ],
4221
            // Test that from display is set to course members only (course member).
4222
            [   'email' => 'fromuser@moodle.com',
4223
                'display' => \core_user::MAILDISPLAY_COURSE_MEMBERS_ONLY,
4224
                'samecourse' => true,
4225
                'config' => "example.com\r\ntest.com",
4226
                'result' => false
4227
            ],
4228
            // Test that from display is set to course members only (Non course member.
4229
            [   'email' => 'fromuser@moodle.com',
4230
                'display' => \core_user::MAILDISPLAY_COURSE_MEMBERS_ONLY,
4231
                'samecourse' => false,
4232
                'config' => "example.com\r\ntest.com",
4233
                'result' => false
4234
            ],
4235
            // Test that from display is set to show everyone.
4236
            [   'email' => 'fromuser@moodle.com',
4237
                'display' => \core_user::MAILDISPLAY_EVERYONE,
4238
                'samecourse' => false,
4239
                'config' => "example.com\r\ntest.com",
4240
                'result' => false
4241
            ],
4242
            // Test a few erroneous config value and confirm failure.
4243
            [   'email' => 'fromuser@moodle.com',
4244
                'display' => \core_user::MAILDISPLAY_EVERYONE,
4245
                'samecourse' => false,
4246
                'config' => "\r\n   \r\n",
4247
                'result' => false
4248
            ],
4249
            [   'email' => 'fromuser@moodle.com',
4250
                'display' => \core_user::MAILDISPLAY_EVERYONE,
4251
                'samecourse' => false,
4252
                'config' => " \n   \n \n ",
4253
                'result' => false
4254
            ],
4255
        ];
4256
    }
4257
 
4258
    /**
4259
     * Test that generate_email_processing_address() returns valid email address.
4260
     */
4261
    public function test_generate_email_processing_address() {
4262
        global $CFG;
4263
        $this->resetAfterTest();
4264
 
4265
        $data = (object)[
4266
            'id' => 42,
4267
            'email' => 'my.email+from_moodle@example.com',
4268
        ];
4269
 
4270
        $modargs = 'B'.base64_encode(pack('V', $data->id)).substr(md5($data->email), 0, 16);
4271
 
4272
        $CFG->maildomain = 'example.com';
4273
        $CFG->mailprefix = 'mdl+';
4274
        $this->assertTrue(validate_email(generate_email_processing_address(0, $modargs)));
4275
 
4276
        $CFG->maildomain = 'mail.example.com';
4277
        $CFG->mailprefix = 'mdl-';
4278
        $this->assertTrue(validate_email(generate_email_processing_address(23, $modargs)));
4279
    }
4280
 
4281
    /**
4282
     * Test allowemailaddresses setting.
4283
     *
4284
     * @param string $email Email address for the from user.
4285
     * @param string $config The CFG->allowemailaddresses config values
4286
     * @param false/string $result The expected result.
4287
     *
4288
     * @dataProvider data_email_is_not_allowed_for_allowemailaddresses
4289
     */
4290
    public function test_email_is_not_allowed_for_allowemailaddresses($email, $config, $result) {
4291
        $this->resetAfterTest();
4292
 
4293
        set_config('allowemailaddresses', $config);
4294
        $this->assertEquals($result, email_is_not_allowed($email));
4295
    }
4296
 
4297
    /**
4298
     * Data provider for data_email_is_not_allowed_for_allowemailaddresses.
4299
     *
4300
     * @return array Returns an array of test data for the above function.
4301
     */
4302
    public function data_email_is_not_allowed_for_allowemailaddresses() {
4303
        return [
4304
            // Test allowed domain empty list.
4305
            [
4306
                'email' => 'fromuser@example.com',
4307
                'config' => '',
4308
                'result' => false
4309
            ],
4310
            // Test from email is in allowed domain.
4311
            [
4312
                'email' => 'fromuser@example.com',
4313
                'config' => 'example.com test.com',
4314
                'result' => false
4315
            ],
4316
            // Test from email is in allowed domain but uppercase config.
4317
            [
4318
                'email' => 'fromuser@example.com',
4319
                'config' => 'EXAMPLE.com test.com',
4320
                'result' => false
4321
            ],
4322
            // Test from email is in allowed domain but uppercase email.
4323
            [
4324
                'email' => 'fromuser@EXAMPLE.com',
4325
                'config' => 'example.com test.com',
4326
                'result' => false
4327
            ],
4328
            // Test from email is in allowed subdomain.
4329
            [
4330
                'email' => 'fromuser@something.example.com',
4331
                'config' => '.example.com test.com',
4332
                'result' => false
4333
            ],
4334
            // Test from email is in allowed subdomain but uppercase config.
4335
            [
4336
                'email' => 'fromuser@something.example.com',
4337
                'config' => '.EXAMPLE.com test.com',
4338
                'result' => false
4339
            ],
4340
            // Test from email is in allowed subdomain but uppercase email.
4341
            [
4342
                'email' => 'fromuser@something.EXAMPLE.com',
4343
                'config' => '.example.com test.com',
4344
                'result' => false
4345
            ],
4346
            // Test from email is not in allowed domain.
4347
            [   'email' => 'fromuser@moodle.com',
4348
                'config' => 'example.com test.com',
4349
                'result' => get_string('emailonlyallowed', '', 'example.com test.com')
4350
            ],
4351
            // Test from email is not in allowed subdomain.
4352
            [   'email' => 'fromuser@something.example.com',
4353
                'config' => 'example.com test.com',
4354
                'result' => get_string('emailonlyallowed', '', 'example.com test.com')
4355
            ],
4356
        ];
4357
    }
4358
 
4359
    /**
4360
     * Test denyemailaddresses setting.
4361
     *
4362
     * @param string $email Email address for the from user.
4363
     * @param string $config The CFG->denyemailaddresses config values
4364
     * @param false/string $result The expected result.
4365
     *
4366
     * @dataProvider data_email_is_not_allowed_for_denyemailaddresses
4367
     */
4368
    public function test_email_is_not_allowed_for_denyemailaddresses($email, $config, $result) {
4369
        $this->resetAfterTest();
4370
 
4371
        set_config('denyemailaddresses', $config);
4372
        $this->assertEquals($result, email_is_not_allowed($email));
4373
    }
4374
 
4375
 
4376
    /**
4377
     * Data provider for test_email_is_not_allowed_for_denyemailaddresses.
4378
     *
4379
     * @return array Returns an array of test data for the above function.
4380
     */
4381
    public function data_email_is_not_allowed_for_denyemailaddresses() {
4382
        return [
4383
            // Test denied domain empty list.
4384
            [
4385
                'email' => 'fromuser@example.com',
4386
                'config' => '',
4387
                'result' => false
4388
            ],
4389
            // Test from email is in denied domain.
4390
            [
4391
                'email' => 'fromuser@example.com',
4392
                'config' => 'example.com test.com',
4393
                'result' => get_string('emailnotallowed', '', 'example.com test.com')
4394
            ],
4395
            // Test from email is in denied domain but uppercase config.
4396
            [
4397
                'email' => 'fromuser@example.com',
4398
                'config' => 'EXAMPLE.com test.com',
4399
                'result' => get_string('emailnotallowed', '', 'EXAMPLE.com test.com')
4400
            ],
4401
            // Test from email is in denied domain but uppercase email.
4402
            [
4403
                'email' => 'fromuser@EXAMPLE.com',
4404
                'config' => 'example.com test.com',
4405
                'result' => get_string('emailnotallowed', '', 'example.com test.com')
4406
            ],
4407
            // Test from email is in denied subdomain.
4408
            [
4409
                'email' => 'fromuser@something.example.com',
4410
                'config' => '.example.com test.com',
4411
                'result' => get_string('emailnotallowed', '', '.example.com test.com')
4412
            ],
4413
            // Test from email is in denied subdomain but uppercase config.
4414
            [
4415
                'email' => 'fromuser@something.example.com',
4416
                'config' => '.EXAMPLE.com test.com',
4417
                'result' => get_string('emailnotallowed', '', '.EXAMPLE.com test.com')
4418
            ],
4419
            // Test from email is in denied subdomain but uppercase email.
4420
            [
4421
                'email' => 'fromuser@something.EXAMPLE.com',
4422
                'config' => '.example.com test.com',
4423
                'result' => get_string('emailnotallowed', '', '.example.com test.com')
4424
            ],
4425
            // Test from email is not in denied domain.
4426
            [   'email' => 'fromuser@moodle.com',
4427
                'config' => 'example.com test.com',
4428
                'result' => false
4429
            ],
4430
            // Test from email is not in denied subdomain.
4431
            [   'email' => 'fromuser@something.example.com',
4432
                'config' => 'example.com test.com',
4433
                'result' => false
4434
            ],
4435
        ];
4436
    }
4437
 
4438
    /**
4439
     * Test safe method unserialize_array().
4440
     */
4441
    public function test_unserialize_array() {
4442
        $a = [1, 2, 3];
4443
        $this->assertEquals($a, unserialize_array(serialize($a)));
4444
        $a = ['a' => 1, 2 => 2, 'b' => 'cde'];
4445
        $this->assertEquals($a, unserialize_array(serialize($a)));
4446
        $a = ['a' => 1, 2 => 2, 'b' => 'c"d"e'];
4447
        $this->assertEquals($a, unserialize_array(serialize($a)));
4448
        $a = ['a' => 1, 2 => ['c' => 'd', 'e' => 'f'], 'b' => 'cde'];
4449
        $this->assertEquals($a, unserialize_array(serialize($a)));
4450
        $a = ['a' => 1, 2 => ['c' => 'd', 'e' => ['f' => 'g']], 'b' => 'cde'];
4451
        $this->assertEquals($a, unserialize_array(serialize($a)));
4452
        $a = ['a' => 1, 2 => 2, 'b' => 'c"d";e'];
4453
        $this->assertEquals($a, unserialize_array(serialize($a)));
4454
 
4455
        // Can not unserialize if there are any objects.
4456
        $a = (object)['a' => 1, 2 => 2, 'b' => 'cde'];
4457
        $this->assertFalse(unserialize_array(serialize($a)));
4458
        $a = ['a' => 1, 2 => 2, 'b' => (object)['a' => 'cde']];
4459
        $this->assertFalse(unserialize_array(serialize($a)));
4460
        $a = ['a' => 1, 2 => 2, 'b' => ['c' => (object)['a' => 'cde']]];
4461
        $this->assertFalse(unserialize_array(serialize($a)));
4462
        $a = ['a' => 1, 2 => 2, 'b' => ['c' => new lang_string('no')]];
4463
        $this->assertFalse(unserialize_array(serialize($a)));
4464
 
4465
        // Array used in the grader report.
4466
        $a = array('aggregatesonly' => [51, 34], 'gradesonly' => [21, 45, 78]);
4467
        $this->assertEquals($a, unserialize_array(serialize($a)));
4468
    }
4469
 
4470
    /**
4471
     * Test method for safely unserializing a serialized object of type stdClass
4472
     */
4473
    public function test_unserialize_object(): void {
4474
        $object = (object) [
4475
            'foo' => 42,
4476
            'bar' => 'Hamster',
4477
            'innerobject' => (object) [
4478
                'baz' => 'happy',
4479
            ],
4480
        ];
4481
 
4482
        // We should get back the same object we serialized.
4483
        $serializedobject = serialize($object);
4484
        $this->assertEquals($object, unserialize_object($serializedobject));
4485
 
4486
        // Try serializing a different class, not allowed.
4487
        $langstr = new lang_string('no');
4488
        $serializedlangstr = serialize($langstr);
4489
        $unserializedlangstr = unserialize_object($serializedlangstr);
4490
        $this->assertInstanceOf(\stdClass::class, $unserializedlangstr);
4491
    }
4492
 
4493
    /**
4494
     * Test that the component_class_callback returns the correct default value when the class was not found.
4495
     *
4496
     * @dataProvider component_class_callback_default_provider
4497
     * @param $default
4498
     */
4499
    public function test_component_class_callback_not_found($default) {
4500
        $this->assertSame($default, component_class_callback('thisIsNotTheClassYouWereLookingFor', 'anymethod', [], $default));
4501
    }
4502
 
4503
    /**
4504
     * Test that the component_class_callback returns the correct default value when the class was not found.
4505
     *
4506
     * @dataProvider component_class_callback_default_provider
4507
     * @param $default
4508
     */
4509
    public function test_component_class_callback_method_not_found($default) {
4510
        require_once(__DIR__ . '/fixtures/component_class_callback_example.php');
4511
 
4512
        $this->assertSame($default, component_class_callback(test_component_class_callback_example::class, 'this_is_not_the_method_you_were_looking_for', ['abc'], $default));
4513
    }
4514
 
4515
    /**
4516
     * Test that the component_class_callback returns the default when the method returned null.
4517
     *
4518
     * @dataProvider component_class_callback_default_provider
4519
     * @param $default
4520
     */
4521
    public function test_component_class_callback_found_returns_null($default) {
4522
        require_once(__DIR__ . '/fixtures/component_class_callback_example.php');
4523
 
4524
        $this->assertSame($default, component_class_callback(\test_component_class_callback_example::class, 'method_returns_value', [null], $default));
4525
        $this->assertSame($default, component_class_callback(\test_component_class_callback_child_example::class, 'method_returns_value', [null], $default));
4526
    }
4527
 
4528
    /**
4529
     * Test that the component_class_callback returns the expected value and not the default when there was a value.
4530
     *
4531
     * @dataProvider component_class_callback_data_provider
4532
     * @param $default
4533
     */
4534
    public function test_component_class_callback_found_returns_value($value) {
4535
        require_once(__DIR__ . '/fixtures/component_class_callback_example.php');
4536
 
4537
        $this->assertSame($value, component_class_callback(\test_component_class_callback_example::class, 'method_returns_value', [$value], 'This is not the value you were looking for'));
4538
        $this->assertSame($value, component_class_callback(\test_component_class_callback_child_example::class, 'method_returns_value', [$value], 'This is not the value you were looking for'));
4539
    }
4540
 
4541
    /**
4542
     * Test that the component_class_callback handles multiple params correctly.
4543
     *
4544
     * @dataProvider component_class_callback_multiple_params_provider
4545
     * @param $default
4546
     */
4547
    public function test_component_class_callback_found_accepts_multiple($params, $count) {
4548
        require_once(__DIR__ . '/fixtures/component_class_callback_example.php');
4549
 
4550
        $this->assertSame($count, component_class_callback(\test_component_class_callback_example::class, 'method_returns_all_params', $params, 'This is not the value you were looking for'));
4551
        $this->assertSame($count, component_class_callback(\test_component_class_callback_child_example::class, 'method_returns_all_params', $params, 'This is not the value you were looking for'));
4552
    }
4553
 
4554
    /**
4555
     * Data provider with list of default values for user in component_class_callback tests.
4556
     *
4557
     * @return array
4558
     */
4559
    public function component_class_callback_default_provider() {
4560
        return [
4561
            'null' => [null],
4562
            'empty string' => [''],
4563
            'string' => ['This is a string'],
4564
            'int' => [12345],
4565
            'stdClass' => [(object) ['this is my content']],
4566
            'array' => [['a' => 'b',]],
4567
        ];
4568
    }
4569
 
4570
    /**
4571
     * Data provider with list of default values for user in component_class_callback tests.
4572
     *
4573
     * @return array
4574
     */
4575
    public function component_class_callback_data_provider() {
4576
        return [
4577
            'empty string' => [''],
4578
            'string' => ['This is a string'],
4579
            'int' => [12345],
4580
            'stdClass' => [(object) ['this is my content']],
4581
            'array' => [['a' => 'b',]],
4582
        ];
4583
    }
4584
 
4585
    /**
4586
     * Data provider with list of default values for user in component_class_callback tests.
4587
     *
4588
     * @return array
4589
     */
4590
    public function component_class_callback_multiple_params_provider() {
4591
        return [
4592
            'empty array' => [
4593
                [],
4594
                0,
4595
            ],
4596
            'string value' => [
4597
                ['one'],
4598
                1,
4599
            ],
4600
            'string values' => [
4601
                ['one', 'two'],
4602
                2,
4603
            ],
4604
            'arrays' => [
4605
                [[], []],
4606
                2,
4607
            ],
4608
            'nulls' => [
4609
                [null, null, null, null],
4610
                4,
4611
            ],
4612
            'mixed' => [
4613
                ['a', 1, null, (object) [], []],
4614
                5,
4615
            ],
4616
        ];
4617
    }
4618
 
4619
    /**
4620
     * Test that {@link get_callable_name()} describes the callable as expected.
4621
     *
4622
     * @dataProvider callable_names_provider
4623
     * @param callable $callable
4624
     * @param string $expectedname
4625
     */
4626
    public function test_get_callable_name($callable, $expectedname) {
4627
        $this->assertSame($expectedname, get_callable_name($callable));
4628
    }
4629
 
4630
    /**
4631
     * Provides a set of callables and their human readable names.
4632
     *
4633
     * @return array of (string)case => [(mixed)callable, (string|bool)expected description]
4634
     */
4635
    public function callable_names_provider() {
4636
        return [
4637
            'integer' => [
4638
                386,
4639
                false,
4640
            ],
4641
            'boolean' => [
4642
                true,
4643
                false,
4644
            ],
4645
            'static_method_as_literal' => [
4646
                'my_foobar_class::my_foobar_method',
4647
                'my_foobar_class::my_foobar_method',
4648
            ],
4649
            'static_method_of_literal_class' => [
4650
                ['my_foobar_class', 'my_foobar_method'],
4651
                'my_foobar_class::my_foobar_method',
4652
            ],
4653
            'static_method_of_object' => [
4654
                [$this, 'my_foobar_method'],
4655
                'core\moodlelib_test::my_foobar_method',
4656
            ],
4657
            'method_of_object' => [
4658
                [new lang_string('parentlanguage', 'core_langconfig'), 'my_foobar_method'],
4659
                'lang_string::my_foobar_method',
4660
            ],
4661
            'function_as_literal' => [
4662
                'my_foobar_callback',
4663
                'my_foobar_callback',
4664
            ],
4665
            'function_as_closure' => [
4666
                function($a) { return $a; },
4667
                'Closure::__invoke',
4668
            ],
4669
        ];
4670
    }
4671
 
4672
    /**
4673
     * Data provider for \core_moodlelib_testcase::test_get_complete_user_data().
4674
     *
4675
     * @return array
4676
     */
4677
    public function user_data_provider() {
4678
        return [
4679
            'Fetch data using a valid username' => [
4680
                'username', 's1', true
4681
            ],
4682
            'Fetch data using a valid username, different case' => [
4683
                'username', 'S1', true
4684
            ],
4685
            'Fetch data using a valid username, different case for fieldname and value' => [
4686
                'USERNAME', 'S1', true
4687
            ],
4688
            'Fetch data using an invalid username' => [
4689
                'username', 's2', false
4690
            ],
4691
            'Fetch by email' => [
4692
                'email', 's1@example.com', true
4693
            ],
4694
            'Fetch data using a non-existent email' => [
4695
                'email', 's2@example.com', false
4696
            ],
4697
            'Fetch data using a non-existent email, throw exception' => [
4698
                'email', 's2@example.com', false, \dml_missing_record_exception::class
4699
            ],
4700
            'Multiple accounts with the same email' => [
4701
                'email', 's1@example.com', false, 1
4702
            ],
4703
            'Multiple accounts with the same email, throw exception' => [
4704
                'email', 's1@example.com', false, 1, \dml_multiple_records_exception::class
4705
            ],
4706
            'Fetch data using a valid user ID' => [
4707
                'id', true, true
4708
            ],
4709
            'Fetch data using a non-existent user ID' => [
4710
                'id', false, false
4711
            ],
4712
        ];
4713
    }
4714
 
4715
    /**
4716
     * Test for get_complete_user_data().
4717
     *
4718
     * @dataProvider user_data_provider
4719
     * @param string $field The field to use for the query.
4720
     * @param string|boolean $value The field value. When fetching by ID, set true to fetch valid user ID, false otherwise.
4721
     * @param boolean $success Whether we expect for the fetch to succeed or return false.
4722
     * @param int $allowaccountssameemail Value for $CFG->allowaccountssameemail.
4723
     * @param string $expectedexception The exception to be expected.
4724
     */
4725
    public function test_get_complete_user_data($field, $value, $success, $allowaccountssameemail = 0, $expectedexception = '') {
4726
        $this->resetAfterTest();
4727
 
4728
        // Set config settings we need for our environment.
4729
        set_config('allowaccountssameemail', $allowaccountssameemail);
4730
 
4731
        // Generate the user data.
4732
        $generator = $this->getDataGenerator();
4733
        $userdata = [
4734
            'username' => 's1',
4735
            'email' => 's1@example.com',
4736
        ];
4737
        $user = $generator->create_user($userdata);
4738
 
4739
        if ($allowaccountssameemail) {
4740
            // Create another user with the same email address.
4741
            $generator->create_user(['email' => 's1@example.com']);
4742
        }
4743
 
4744
        // Since the data provider can't know what user ID to use, do a special handling for ID field tests.
4745
        if ($field === 'id') {
4746
            if ($value) {
4747
                // Test for fetching data using a valid user ID. Use the generated user's ID.
4748
                $value = $user->id;
4749
            } else {
4750
                // Test for fetching data using a non-existent user ID.
4751
                $value = $user->id + 1;
4752
            }
4753
        }
4754
 
4755
        // When an exception is expected.
4756
        $throwexception = false;
4757
        if ($expectedexception) {
4758
            $this->expectException($expectedexception);
4759
            $throwexception = true;
4760
        }
4761
 
4762
        $fetcheduser = get_complete_user_data($field, $value, null, $throwexception);
4763
        if ($success) {
4764
            $this->assertEquals($user->id, $fetcheduser->id);
4765
            $this->assertEquals($user->username, $fetcheduser->username);
4766
            $this->assertEquals($user->email, $fetcheduser->email);
4767
        } else {
4768
            $this->assertFalse($fetcheduser);
4769
        }
4770
    }
4771
 
4772
    /**
4773
     * Test for send_password_change_().
4774
     */
4775
    public function test_send_password_change_info() {
4776
        $this->resetAfterTest();
4777
 
4778
        $user = $this->getDataGenerator()->create_user();
4779
 
4780
        $sink = $this->redirectEmails(); // Make sure we are redirecting emails.
4781
        send_password_change_info($user);
4782
        $result = $sink->get_messages();
4783
        $sink->close();
4784
 
4785
        $this->assertStringContainsString('passwords cannot be reset on this site', quoted_printable_decode($result[0]->body));
4786
    }
4787
 
4788
    /**
4789
     * Test the get_time_interval_string for a range of inputs.
4790
     *
4791
     * @dataProvider get_time_interval_string_provider
4792
     * @param int $time1 the time1 param.
4793
     * @param int $time2 the time2 param.
4794
     * @param string|null $format the format param.
4795
     * @param string $expected the expected string.
4796
     * @param bool $dropzeroes the value passed for the `$dropzeros` param.
4797
     * @param bool $fullformat the value passed for the `$fullformat` param.
4798
     * @covers \get_time_interval_string
4799
     */
4800
    public function test_get_time_interval_string(int $time1, int $time2, ?string $format, string $expected,
4801
            bool $dropzeroes = false, bool $fullformat = false) {
4802
        if (is_null($format)) {
4803
            $this->assertEquals($expected, get_time_interval_string($time1, $time2));
4804
        } else {
4805
            $this->assertEquals($expected, get_time_interval_string($time1, $time2, $format, $dropzeroes, $fullformat));
4806
        }
4807
    }
4808
 
4809
    /**
4810
     * Data provider for the test_get_time_interval_string() method.
4811
     */
4812
    public function get_time_interval_string_provider() {
4813
        return [
4814
            'Time is after the reference time by 1 minute, omitted format' => [
4815
                'time1' => 12345660,
4816
                'time2' => 12345600,
4817
                'format' => null,
4818
                'expected' => '0d 0h 1m'
4819
            ],
4820
            'Time is before the reference time by 1 minute, omitted format' => [
4821
                'time1' => 12345540,
4822
                'time2' => 12345600,
4823
                'format' => null,
4824
                'expected' => '0d 0h 1m'
4825
            ],
4826
            'Time is equal to the reference time, omitted format' => [
4827
                'time1' => 12345600,
4828
                'time2' => 12345600,
4829
                'format' => null,
4830
                'expected' => '0d 0h 0m'
4831
            ],
4832
            'Time is after the reference time by 1 minute, empty string format' => [
4833
                'time1' => 12345660,
4834
                'time2' => 12345600,
4835
                'format' => '',
4836
                'expected' => '0d 0h 1m'
4837
            ],
4838
            'Time is before the reference time by 1 minute, empty string format' => [
4839
                'time1' => 12345540,
4840
                'time2' => 12345600,
4841
                'format' => '',
4842
                'expected' => '0d 0h 1m'
4843
            ],
4844
            'Time is equal to the reference time, empty string format' => [
4845
                'time1' => 12345600,
4846
                'time2' => 12345600,
4847
                'format' => '',
4848
                'expected' => '0d 0h 0m'
4849
            ],
4850
            'Time is after the reference time by 1 minute, custom format' => [
4851
                'time1' => 12345660,
4852
                'time2' => 12345600,
4853
                'format' => '%R%adays %hhours %imins',
4854
                'expected' => '+0days 0hours 1mins'
4855
            ],
4856
            'Time is before the reference time by 1 minute, custom format' => [
4857
                'time1' => 12345540,
4858
                'time2' => 12345600,
4859
                'format' => '%R%adays %hhours %imins',
4860
                'expected' => '-0days 0hours 1mins'
4861
            ],
4862
            'Time is equal to the reference time, custom format' => [
4863
                'time1' => 12345600,
4864
                'time2' => 12345600,
4865
                'format' => '%R%adays %hhours %imins',
4866
                'expected' => '+0days 0hours 0mins'
4867
            ],
4868
            'Default format, time is after the reference time by 1 minute, drop zeroes, short form' => [
4869
                'time1' => 12345660,
4870
                'time2' => 12345600,
4871
                'format' => '',
4872
                'expected' => '1m',
4873
                'dropzeroes' => true,
4874
            ],
4875
            'Default format, time is after the reference time by 1 minute, drop zeroes, full form' => [
4876
                'time1' => 12345660,
4877
                'time2' => 12345600,
4878
                'format' => '',
4879
                'expected' => '1 minutes',
4880
                'dropzeroes' => true,
4881
                'fullformat' => true,
4882
            ],
4883
            'Default format, time is after the reference time by 1 minute, retain zeroes, full form' => [
4884
                'time1' => 12345660,
4885
                'time2' => 12345600,
4886
                'format' => '',
4887
                'expected' => '0 days 0 hours 1 minutes',
4888
                'dropzeroes' => false,
4889
                'fullformat' => true,
4890
            ],
4891
            'Empty string format, time is after the reference time by 1 minute, retain zeroes, full form' => [
4892
                'time1' => 12345660,
4893
                'time2' => 12345600,
4894
                'format' => '     ',
4895
                'expected' => '0 days 0 hours 1 minutes',
4896
                'dropzeroes' => false,
4897
                'fullformat' => true,
4898
            ],
4899
        ];
4900
    }
4901
 
4902
    /**
4903
     * Tests the rename_to_unused_name function with a file.
4904
     */
4905
    public function test_rename_to_unused_name_file() {
4906
        global $CFG;
4907
 
4908
        // Create a new file in dataroot.
4909
        $file = $CFG->dataroot . '/argh.txt';
4910
        file_put_contents($file, 'Frogs');
4911
 
4912
        // Rename it.
4913
        $newname = rename_to_unused_name($file);
4914
 
4915
        // Check new name has expected format.
4916
        $this->assertMatchesRegularExpression('~/_temp_[a-f0-9]+$~', $newname);
4917
 
4918
        // Check it's still in the same folder.
4919
        $this->assertEquals($CFG->dataroot, dirname($newname));
4920
 
4921
        // Check file can be loaded.
4922
        $this->assertEquals('Frogs', file_get_contents($newname));
4923
 
4924
        // OK, delete the file.
4925
        unlink($newname);
4926
    }
4927
 
4928
    /**
4929
     * Tests the rename_to_unused_name function with a directory.
4930
     */
4931
    public function test_rename_to_unused_name_dir() {
4932
        global $CFG;
4933
 
4934
        // Create a new directory in dataroot.
4935
        $file = $CFG->dataroot . '/arghdir';
4936
        mkdir($file);
4937
 
4938
        // Rename it.
4939
        $newname = rename_to_unused_name($file);
4940
 
4941
        // Check new name has expected format.
4942
        $this->assertMatchesRegularExpression('~/_temp_[a-f0-9]+$~', $newname);
4943
 
4944
        // Check it's still in the same folder.
4945
        $this->assertEquals($CFG->dataroot, dirname($newname));
4946
 
4947
        // Check it's still a directory
4948
        $this->assertTrue(is_dir($newname));
4949
 
4950
        // OK, delete the directory.
4951
        rmdir($newname);
4952
    }
4953
 
4954
    /**
4955
     * Tests the rename_to_unused_name function with error cases.
4956
     */
4957
    public function test_rename_to_unused_name_failure() {
4958
        global $CFG;
4959
 
4960
        // Rename a file that doesn't exist.
4961
        $file = $CFG->dataroot . '/argh.txt';
4962
        $this->assertFalse(rename_to_unused_name($file));
4963
    }
4964
 
4965
    /**
4966
     * Provider for display_size
4967
     *
4968
     * @return array of ($size, $expected)
4969
     */
4970
    public function display_size_provider() {
4971
 
4972
        return [
4973
            [0, '0 bytes'],
4974
            [1, '1 bytes'],
4975
            [1023, '1023 bytes'],
4976
            [1024, '1.0 KB'],
4977
            [2222, '2.2 KB'],
4978
            [33333, '32.6 KB'],
4979
            [444444, '434.0 KB'],
4980
            [5555555, '5.3 MB'],
4981
            [66666666, '63.6 MB'],
4982
            [777777777, '741.7 MB'],
4983
            [8888888888, '8.3 GB'],
4984
            [99999999999, '93.1 GB'],
4985
            [111111111111, '103.5 GB'],
4986
            [2222222222222, '2.0 TB'],
4987
            [33333333333333, '30.3 TB'],
4988
            [444444444444444, '404.2 TB'],
4989
            [5555555555555555, '4.9 PB'],
4990
            [66666666666666666, '59.2 PB'],
4991
            [777777777777777777, '690.8 PB'],
4992
        ];
4993
    }
4994
 
4995
    /**
4996
     * Test display_size
4997
     * @dataProvider display_size_provider
4998
     * @param int $size the size in bytes
4999
     * @param string $expected the expected string.
5000
     */
5001
    public function test_display_size($size, $expected) {
5002
        $result = display_size($size);
5003
        $expected = str_replace(' ', "\xc2\xa0", $expected); // Should be non-breaking space.
5004
        $this->assertEquals($expected, $result);
5005
    }
5006
 
5007
    /**
5008
     * Provider for display_size using fixed units.
5009
     *
5010
     * @return array of ($size, $units, $expected)
5011
     */
5012
    public function display_size_fixed_provider(): array {
5013
        return [
5014
            [0, 'KB', '0.0 KB'],
5015
            [1, 'MB', '0.0 MB'],
5016
            [777777777, 'GB', '0.7 GB'],
5017
            [8888888888, 'PB', '0.0 PB'],
5018
            [99999999999, 'TB', '0.1 TB'],
5019
            [99999999999, 'B', '99999999999 bytes'],
5020
        ];
5021
    }
5022
 
5023
    /**
5024
     * Test display_size using fixed units.
5025
     *
5026
     * @dataProvider display_size_fixed_provider
5027
     * @param int $size Size in bytes
5028
     * @param string $units Fixed units
5029
     * @param string $expected Expected string.
5030
     */
5031
    public function test_display_size_fixed(int $size, string $units, string $expected): void {
5032
        $result = display_size($size, 1, $units);
5033
        $expected = str_replace(' ', "\xc2\xa0", $expected); // Should be non-breaking space.
5034
        $this->assertEquals($expected, $result);
5035
    }
5036
 
5037
    /**
5038
     * Provider for display_size using specified decimal places.
5039
     *
5040
     * @return array of ($size, $decimalplaces, $units, $expected)
5041
     */
5042
    public function display_size_dp_provider(): array {
5043
        return [
5044
            [0, 1, 'KB', '0.0 KB'],
5045
            [1, 6, 'MB', '0.000001 MB'],
5046
            [777777777, 0, 'GB', '1 GB'],
5047
            [777777777, 0, '', '742 MB'],
5048
            [42, 6, '', '42 bytes'],
5049
        ];
5050
    }
5051
 
5052
    /**
5053
     * Test display_size using specified decimal places.
5054
     *
5055
     * @dataProvider display_size_dp_provider
5056
     * @param int $size Size in bytes
5057
     * @param int $places Number of decimal places
5058
     * @param string $units Fixed units
5059
     * @param string $expected Expected string.
5060
     */
5061
    public function test_display_size_dp(int $size, int $places, string $units, string $expected): void {
5062
        $result = display_size($size, $places, $units);
5063
        $expected = str_replace(' ', "\xc2\xa0", $expected); // Should be non-breaking space.
5064
        $this->assertEquals($expected, $result);
5065
    }
5066
 
5067
    /**
5068
     * Test that the get_list_of_plugins function includes/excludes directories as appropriate.
5069
     *
5070
     * @dataProvider get_list_of_plugins_provider
5071
     * @param   array $expectedlist The expected list of folders
5072
     * @param   array $content The list of file content to set up in the virtual file root
5073
     * @param   string $dir The base dir to look at in the virtual file root
5074
     * @param   string $exclude Any additional folder to exclude
5075
     */
5076
    public function test_get_list_of_plugins(array $expectedlist, array $content, string $dir, string $exclude): void {
5077
        $vfileroot = \org\bovigo\vfs\vfsStream::setup('root', null, $content);
5078
        $base = \org\bovigo\vfs\vfsStream::url('root');
5079
 
5080
        $this->assertEquals($expectedlist, get_list_of_plugins($dir, $exclude, $base));
5081
    }
5082
 
5083
    /**
5084
     * Data provider for get_list_of_plugins checks.
5085
     *
5086
     * @return  array
5087
     */
5088
    public function get_list_of_plugins_provider(): array {
5089
        return [
5090
            'Standard excludes' => [
5091
                ['amdd', 'class', 'local', 'test'],
5092
                [
5093
                    '.' => [],
5094
                    '..' => [],
5095
                    'amd' => [],
5096
                    'amdd' => [],
5097
                    'class' => [],
5098
                    'classes' => [],
5099
                    'local' => [],
5100
                    'test' => [],
5101
                    'tests' => [],
5102
                    'yui' => [],
5103
                ],
5104
                '',
5105
                '',
5106
            ],
5107
            'Standard excludes with addition' => [
5108
                ['amdd', 'local', 'test'],
5109
                [
5110
                    '.' => [],
5111
                    '..' => [],
5112
                    'amd' => [],
5113
                    'amdd' => [],
5114
                    'class' => [],
5115
                    'classes' => [],
5116
                    'local' => [],
5117
                    'test' => [],
5118
                    'tests' => [],
5119
                    'yui' => [],
5120
                ],
5121
                '',
5122
                'class',
5123
            ],
5124
            'Files excluded' => [
5125
                ['def'],
5126
                [
5127
                    '.' => [],
5128
                    '..' => [],
5129
                    'abc' => 'File with filename abc',
5130
                    'def' => [
5131
                        '.' => [],
5132
                        '..' => [],
5133
                        'example.txt' => 'In a directory called "def"',
5134
                    ],
5135
                ],
5136
                '',
5137
                '',
5138
            ],
5139
            'Subdirectories only' => [
5140
                ['abc'],
5141
                [
5142
                    '.' => [],
5143
                    '..' => [],
5144
                    'foo' => [
5145
                        '.' => [],
5146
                        '..' => [],
5147
                        'abc' => [],
5148
                    ],
5149
                    'bar' => [
5150
                        '.' => [],
5151
                        '..' => [],
5152
                        'def' => [],
5153
                    ],
5154
                ],
5155
                'foo',
5156
                '',
5157
            ],
5158
        ];
5159
    }
5160
 
5161
    /**
5162
     * Test get_home_page() method.
5163
     *
5164
     * @dataProvider get_home_page_provider
5165
     * @param string $user Whether the user is logged, guest or not logged.
5166
     * @param int $expected Expected value after calling the get_home_page method.
5167
     * @param int $defaulthomepage The $CFG->defaulthomepage setting value.
5168
     * @param int $enabledashboard Whether the dashboard should be enabled or not.
5169
     * @param int $userpreference User preference for the home page setting.
5170
     * @covers ::get_home_page
5171
     */
5172
    public function test_get_home_page(string $user, int $expected, ?int $defaulthomepage = null, ?int $enabledashboard = null,
5173
            ?int $userpreference = null) {
5174
        global $CFG, $USER;
5175
 
5176
        $this->resetAfterTest();
5177
 
5178
        if ($user == 'guest') {
5179
            $this->setGuestUser();
5180
        } else if ($user == 'logged') {
5181
            $this->setUser($this->getDataGenerator()->create_user());
5182
        }
5183
 
5184
        if (isset($defaulthomepage)) {
5185
            $CFG->defaulthomepage = $defaulthomepage;
5186
        }
5187
        if (isset($enabledashboard)) {
5188
            $CFG->enabledashboard = $enabledashboard;
5189
        }
5190
 
5191
        if ($USER) {
5192
            set_user_preferences(['user_home_page_preference' => $userpreference], $USER->id);
5193
        }
5194
 
5195
        $homepage = get_home_page();
5196
        $this->assertEquals($expected, $homepage);
5197
    }
5198
 
5199
    /**
5200
     * Data provider for get_home_page checks.
5201
     *
5202
     * @return array
5203
     */
5204
    public function get_home_page_provider(): array {
5205
        return [
5206
            'No logged user' => [
5207
                'user' => 'nologged',
5208
                'expected' => HOMEPAGE_SITE,
5209
            ],
5210
            'Guest user' => [
5211
                'user' => 'guest',
5212
                'expected' => HOMEPAGE_SITE,
5213
            ],
5214
            'Logged user. Dashboard set as default home page and enabled' => [
5215
                'user' => 'logged',
5216
                'expected' => HOMEPAGE_MY,
5217
                'defaulthomepage' => HOMEPAGE_MY,
5218
                'enabledashboard' => 1,
5219
            ],
5220
            'Logged user. Dashboard set as default home page but disabled' => [
5221
                'user' => 'logged',
5222
                'expected' => HOMEPAGE_MYCOURSES,
5223
                'defaulthomepage' => HOMEPAGE_MY,
5224
                'enabledashboard' => 0,
5225
            ],
5226
            'Logged user. My courses set as default home page with dashboard enabled' => [
5227
                'user' => 'logged',
5228
                'expected' => HOMEPAGE_MYCOURSES,
5229
                'defaulthomepage' => HOMEPAGE_MYCOURSES,
5230
                'enabledashboard' => 1,
5231
            ],
5232
            'Logged user. My courses set as default home page with dashboard disabled' => [
5233
                'user' => 'logged',
5234
                'expected' => HOMEPAGE_MYCOURSES,
5235
                'defaulthomepage' => HOMEPAGE_MYCOURSES,
5236
                'enabledashboard' => 0,
5237
            ],
5238
            'Logged user. Site set as default home page with dashboard enabled' => [
5239
                'user' => 'logged',
5240
                'expected' => HOMEPAGE_SITE,
5241
                'defaulthomepage' => HOMEPAGE_SITE,
5242
                'enabledashboard' => 1,
5243
            ],
5244
            'Logged user. Site set as default home page with dashboard disabled' => [
5245
                'user' => 'logged',
5246
                'expected' => HOMEPAGE_SITE,
5247
                'defaulthomepage' => HOMEPAGE_SITE,
5248
                'enabledashboard' => 0,
5249
            ],
5250
            'Logged user. User preference set as default page with dashboard enabled and user preference set to dashboard' => [
5251
                'user' => 'logged',
5252
                'expected' => HOMEPAGE_MY,
5253
                'defaulthomepage' => HOMEPAGE_USER,
5254
                'enabledashboard' => 1,
5255
                'userpreference' => HOMEPAGE_MY,
5256
            ],
5257
            'Logged user. User preference set as default page with dashboard disabled and user preference set to dashboard' => [
5258
                'user' => 'logged',
5259
                'expected' => HOMEPAGE_MYCOURSES,
5260
                'defaulthomepage' => HOMEPAGE_USER,
5261
                'enabledashboard' => 0,
5262
                'userpreference' => HOMEPAGE_MY,
5263
            ],
5264
            'Logged user. User preference set as default page with dashboard enabled and user preference set to my courses' => [
5265
                'user' => 'logged',
5266
                'expected' => HOMEPAGE_MYCOURSES,
5267
                'defaulthomepage' => HOMEPAGE_USER,
5268
                'enabledashboard' => 1,
5269
                'userpreference' => HOMEPAGE_MYCOURSES,
5270
            ],
5271
            'Logged user. User preference set as default page with dashboard disabled and user preference set to my courses' => [
5272
                'user' => 'logged',
5273
                'expected' => HOMEPAGE_MYCOURSES,
5274
                'defaulthomepage' => HOMEPAGE_USER,
5275
                'enabledashboard' => 0,
5276
                'userpreference' => HOMEPAGE_MYCOURSES,
5277
            ],
5278
        ];
5279
    }
5280
 
5281
    /**
5282
     * Test get_default_home_page() method.
5283
     *
5284
     * @covers ::get_default_home_page
5285
     */
5286
    public function test_get_default_home_page() {
5287
        global $CFG;
5288
 
5289
        $this->resetAfterTest();
5290
 
5291
        $CFG->enabledashboard = 1;
5292
        $default = get_default_home_page();
5293
        $this->assertEquals(HOMEPAGE_MY, $default);
5294
 
5295
        $CFG->enabledashboard = 0;
5296
        $default = get_default_home_page();
5297
        $this->assertEquals(HOMEPAGE_MYCOURSES, $default);
5298
    }
5299
 
5300
    /**
5301
     * Tests the get_performance_info function with regard to locks.
5302
     *
5303
     * @covers ::get_performance_info
5304
     */
5305
    public function test_get_performance_info_locks(): void {
5306
        global $PERF;
5307
 
5308
        // Unset lock data just in case previous tests have set it.
5309
        unset($PERF->locks);
5310
 
5311
        // With no lock data, there should be no information about locks in the results.
5312
        $result = get_performance_info();
5313
        $this->assertStringNotContainsString('Lock', $result['html']);
5314
        $this->assertStringNotContainsString('Lock', $result['txt']);
5315
 
5316
        // Rather than really do locks, just fill the array with fake data in the right format.
5317
        $PERF->locks = [
5318
            (object) [
5319
                'type' => 'phpunit',
5320
                'resource' => 'lock1',
5321
                'wait' => 0.59,
5322
                'success' => true,
5323
                'held' => '6.04'
5324
            ], (object) [
5325
                'type' => 'phpunit',
5326
                'resource' => 'lock2',
5327
                'wait' => 0.91,
5328
                'success' => false
5329
            ]
5330
        ];
5331
        $result = get_performance_info();
5332
 
5333
        // Extract HTML table rows.
5334
        $this->assertEquals(1, preg_match('~<table class="locktimings.*?</table>~s',
5335
                $result['html'], $matches));
5336
        $this->assertEquals(3, preg_match_all('~<tr[> ].*?</tr>~s', $matches[0], $matches2));
5337
        $rows = $matches2[0];
5338
 
5339
        // Check header.
5340
        $this->assertMatchesRegularExpression('~Lock.*Waited.*Obtained.*Held~s', $rows[0]);
5341
        // Check both locks.
5342
        $this->assertMatchesRegularExpression('~phpunit/lock1.*0\.6.*&#x2713;.*6\.0~s', $rows[1]);
5343
        $this->assertMatchesRegularExpression('~phpunit/lock2.*0\.9.*&#x274c;.*-~s', $rows[2]);
5344
 
5345
        $this->assertStringContainsString('Locks (waited/obtained/held): ' .
5346
                'phpunit/lock1 (0.6/y/6.0) phpunit/lock2 (0.9/n/-).', $result['txt']);
5347
    }
5348
 
5349
    /**
5350
     * Tests the get_performance_info function with regard to session wait time.
5351
     *
5352
     * @covers ::get_performance_info
5353
     */
5354
    public function test_get_performance_info_session_wait(): void {
5355
        global $PERF;
5356
 
5357
        // With no session lock data, there should be no session wait information in the results.
5358
        unset($PERF->sessionlock);
5359
        $result = get_performance_info();
5360
        $this->assertStringNotContainsString('Session wait', $result['html']);
5361
        $this->assertStringNotContainsString('sessionwait', $result['txt']);
5362
 
5363
        // With suitable data, it should be included in the result.
5364
        $PERF->sessionlock = ['wait' => 4.2];
5365
        $result = get_performance_info();
5366
        $this->assertStringContainsString('Session wait: 4.200 secs', $result['html']);
5367
        $this->assertStringContainsString('sessionwait: 4.200 secs', $result['txt']);
5368
    }
5369
 
5370
    /**
5371
     * Test the html_is_blank() function.
5372
     *
5373
     * @covers ::html_is_blank
5374
     */
5375
    public function test_html_is_blank() {
5376
        $this->assertEquals(true, html_is_blank(null));
5377
        $this->assertEquals(true, html_is_blank(''));
5378
        $this->assertEquals(true, html_is_blank('<p> </p>'));
5379
        $this->assertEquals(false, html_is_blank('<p>.</p>'));
5380
        $this->assertEquals(false, html_is_blank('<img src="#">'));
5381
    }
5382
 
5383
    /**
5384
     * Provider for is_proxybypass
5385
     *
5386
     * @return array of test cases.
5387
     */
5388
    public function is_proxybypass_provider(): array {
5389
 
5390
        return [
5391
            'Proxybypass contains the same IP as the beginning of the URL' => [
5392
                'http://192.168.5.5-fake-app-7f000101.nip.io',
5393
                '192.168.5.5, 127.0.0.1',
5394
                false
5395
            ],
5396
            'Proxybypass contains the last part of the URL' => [
5397
                'http://192.168.5.5-fake-app-7f000101.nip.io',
5398
                'app-7f000101.nip.io',
5399
                false
5400
            ],
5401
            'Proxybypass contains the last part of the URL 2' => [
5402
                'http://store.mydomain.com',
5403
                'mydomain.com',
5404
                false
5405
            ],
5406
            'Proxybypass contains part of the url' => [
5407
                'http://myweb.com',
5408
                'store.myweb.com',
5409
                false
5410
            ],
5411
            'Different IPs used in proxybypass' => [
5412
                'http://192.168.5.5',
5413
                '192.168.5.3',
5414
                false
5415
            ],
5416
            'Proxybypass and URL matchs' => [
5417
                'http://store.mydomain.com',
5418
                'store.mydomain.com',
5419
                true
5420
            ],
5421
            'IP used in proxybypass' => [
5422
                'http://192.168.5.5',
5423
                '192.168.5.5',
5424
                true
5425
            ],
5426
        ];
5427
    }
5428
 
5429
    /**
5430
     * Check if $url matches anything in proxybypass list
5431
     *
5432
     * Test function {@see is_proxybypass()}.
5433
     * @dataProvider is_proxybypass_provider
5434
     * @param string $url url to check
5435
     * @param string $proxybypass
5436
     * @param bool $expected Expected value.
5437
     */
5438
    public function test_is_proxybypass(string $url, string $proxybypass, bool $expected): void {
5439
        $this->resetAfterTest();
5440
 
5441
        global $CFG;
5442
        $CFG->proxyhost = '192.168.5.5'; // Test with a fake proxy.
5443
        $CFG->proxybypass = $proxybypass;
5444
 
5445
        $this->assertEquals($expected, is_proxybypass($url));
5446
    }
5447
 
5448
    /**
5449
     * Test that the moodle_array_keys_filter method behaves in the same way
5450
     * that array_keys behaved before Moodle 8.3.
5451
     *
5452
     * @dataProvider moodle_array_keys_filter_provider
5453
     * @param array $array
5454
     * @param mixed $filter
5455
     * @param bool $strict
5456
     * @param array $expected
5457
     * @covers ::moodle_array_keys_filter
5458
     */
5459
    public function test_moodle_array_keys_filter(
5460
        array $array,
5461
        mixed $filter,
5462
        bool $strict,
5463
        array $expected,
5464
    ): void {
5465
        $this->assertSame(
5466
            $expected,
5467
            moodle_array_keys_filter($array, $filter, $strict),
5468
        );
5469
    }
5470
 
5471
    /**
5472
     * Data provider for moodle_array_keys_filter tests.
5473
     *
5474
     * @return array
5475
     */
5476
    public static function moodle_array_keys_filter_provider(): array {
5477
        return [
5478
            [['a', 'b', 'c'], 'b', false, [1]],
5479
            [
5480
                [
5481
                    'alpha' => 'a',
5482
                    'bravo' => 'b',
5483
                    'charlie' => 'c',
5484
                ],
5485
                'b',
5486
                false,
5487
                ['bravo'],
5488
            ],
5489
            [
5490
                [
5491
                    'zero' => 0,
5492
                    'one' => 1,
5493
                    'true' => true,
5494
                ],
5495
                '1',
5496
                false,
5497
                ['one', 'true'],
5498
            ],
5499
            [
5500
                [
5501
                    'zero' => 0,
5502
                    'one' => 1,
5503
                    'true' => true,
5504
                ],
5505
                true,
5506
                false,
5507
                ['one', 'true'],
5508
            ],
5509
            [
5510
                [
5511
                    'zero' => 0,
5512
                    'one' => 1,
5513
                    'true' => true,
5514
                ],
5515
                true,
5516
                true,
5517
                ['true'],
5518
            ],
5519
            [
5520
                [
5521
                    'zero' => 0,
5522
                    'one' => 1,
5523
                    'true' => true,
5524
                ],
5525
                1,
5526
                true,
5527
                ['one'],
5528
            ],
5529
        ];
5530
    }
5531
}