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
/**
18
 * Weblib tests.
19
 *
20
 * @package    core
21
 * @category   phpunit
22
 * @copyright  &copy; 2006 The Open University
23
 * @author     T.J.Hunt@open.ac.uk
24
 * @license    http://www.gnu.org/copyleft/gpl.html GNU Public License
25
 */
26
class weblib_test extends advanced_testcase {
27
    /**
28
     * @covers ::s
29
     */
30
    public function test_s() {
31
        // Special cases.
32
        $this->assertSame('0', s(0));
33
        $this->assertSame('0', s('0'));
34
        $this->assertSame('0', s(false));
35
        $this->assertSame('', s(null));
36
 
37
        // Normal cases.
38
        $this->assertSame('This Breaks &quot; Strict', s('This Breaks " Strict'));
39
        $this->assertSame('This Breaks &lt;a&gt;&quot; Strict&lt;/a&gt;', s('This Breaks <a>" Strict</a>'));
40
 
41
        // Unicode characters.
42
        $this->assertSame('Café', s('Café'));
43
        $this->assertSame('一, 二, 三', s('一, 二, 三'));
44
 
45
        // Don't escape already-escaped numeric entities. (Note, this behaviour
46
        // may not be desirable. Perhaps we should remove these tests and that
47
        // functionality, but we can only do that if we understand why it was added.)
48
        $this->assertSame('An entity: &#x09ff;.', s('An entity: &#x09ff;.'));
49
        $this->assertSame('An entity: &#1073;.', s('An entity: &#1073;.'));
50
        $this->assertSame('An entity: &amp;amp;.', s('An entity: &amp;.'));
51
        $this->assertSame('Not an entity: &amp;amp;#x09ff;.', s('Not an entity: &amp;#x09ff;.'));
52
 
53
        // Test all ASCII characters (0-127).
54
        for ($i = 0; $i <= 127; $i++) {
55
            $character = chr($i);
56
            $result = s($character);
57
            switch ($character) {
58
                case '"' :
59
                    $this->assertSame('&quot;', $result);
60
                    break;
61
                case '&' :
62
                    $this->assertSame('&amp;', $result);
63
                    break;
64
                case "'" :
65
                    $this->assertSame('&#039;', $result);
66
                    break;
67
                case '<' :
68
                    $this->assertSame('&lt;', $result);
69
                    break;
70
                case '>' :
71
                    $this->assertSame('&gt;', $result);
72
                    break;
73
                default:
74
                    $this->assertSame($character, $result);
75
                    break;
76
            }
77
        }
78
    }
79
 
80
    /**
81
     * Test the format_string illegal options handling.
82
     *
83
     * @covers ::format_string
84
     * @dataProvider format_string_illegal_options_provider
85
     */
86
    public function test_format_string_illegal_options(
87
        string $input,
88
        string $result,
89
        mixed $options,
90
        string $pattern,
91
    ): void {
92
        $this->assertEquals(
93
            $result,
94
            format_string($input, false, $options),
95
        );
96
 
97
        $messages = $this->getDebuggingMessages();
98
        $this->assertdebuggingcalledcount(1);
99
        $this->assertMatchesRegularExpression(
100
            "/{$pattern}/",
101
            $messages[0]->message,
102
        );
103
    }
104
 
105
    /**
106
     * Data provider for test_format_string_illegal_options.
107
     * @return array
108
     */
109
    public static function format_string_illegal_options_provider(): array {
110
        return [
111
            [
112
                'Example',
113
                'Example',
114
                \core\context\system::instance(),
115
                preg_quote('The options argument should not be a context object directly.'),
116
            ],
117
            [
118
                'Example',
119
                'Example',
120
                true,
121
                preg_quote('The options argument should be an Array, or stdclass. boolean passed.'),
122
            ],
123
            [
124
                'Example',
125
                'Example',
126
                false,
127
                preg_quote('The options argument should be an Array, or stdclass. boolean passed.'),
128
            ],
129
        ];
130
    }
131
 
132
    /**
133
     * Ensure that if format_string is called with a context as the third param, that a debugging notice is emitted.
134
     *
135
     * @covers ::format_string
136
     */
137
    public function test_format_string_context(): void {
138
        global $CFG;
139
 
140
        $this->resetAfterTest(true);
141
 
142
        // Disable the formatstringstriptags option to ensure that the HTML tags are not stripped.
143
        $CFG->stringfilters = 'multilang';
144
 
145
        // Enable filters.
146
        $CFG->filterall = true;
147
 
148
        $course = $this->getDataGenerator()->create_course();
149
        $coursecontext = \core\context\course::instance($course->id);
150
 
151
        // Set up the multilang filter at the system context, but disable it at the course.
152
        filter_set_global_state('multilang', TEXTFILTER_ON);
153
        filter_set_local_state('multilang', $coursecontext->id, TEXTFILTER_OFF);
154
 
155
        // Previously, if a context was passed, it was converted into an Array, and ignored.
156
        // The PAGE context was used instead -- often this is the system context.
157
        $input = 'I really <span lang="en" class="multilang">do not </span><span lang="de" class="multilang">do not </span>like this!';
158
 
159
        $result = format_string(
160
            $input,
161
            true,
162
            $coursecontext,
163
        );
164
 
165
        // We emit a debugging notice to alert that the context has been moved to the options.
166
        $this->assertdebuggingcalledcount(1);
167
 
168
        // Check the result was _not_ filtered.
169
        $this->assertEquals(
170
            // Tags are stripped out due to striptags.
171
            "I really do not do not like this!",
172
            $result,
173
        );
174
 
175
        // But it should be filtered if called with the system context.
176
        $result = format_string(
177
            $input,
178
            true,
179
            ['context' => \core\context\system::instance()],
180
        );
181
        $this->assertEquals(
182
            'I really do not like this!',
183
            $result,
184
        );
185
    }
186
 
187
    /**
188
     * @covers ::format_text_email
189
     */
190
    public function test_format_text_email() {
191
        $this->assertSame("This is a TEST\n",
192
            format_text_email('<p>This is a <strong>test</strong></p>', FORMAT_HTML));
193
        $this->assertSame("This is a TEST\n",
194
            format_text_email('<p class="frogs">This is a <strong class=\'fishes\'>test</strong></p>', FORMAT_HTML));
195
        $this->assertSame('& so is this',
196
            format_text_email('&amp; so is this', FORMAT_HTML));
197
        $this->assertSame('Two bullets: ' . core_text::code2utf8(8226) . ' ' . core_text::code2utf8(8226),
198
            format_text_email('Two bullets: &#x2022; &#8226;', FORMAT_HTML));
199
        $this->assertSame(core_text::code2utf8(0x7fd2).core_text::code2utf8(0x7fd2),
200
            format_text_email('&#x7fd2;&#x7FD2;', FORMAT_HTML));
201
    }
202
 
203
    /**
204
     * @covers ::obfuscate_email
205
     */
206
    public function test_obfuscate_email() {
207
        $email = 'some.user@example.com';
208
        $obfuscated = obfuscate_email($email);
209
        $this->assertNotSame($email, $obfuscated);
210
        $back = core_text::entities_to_utf8(urldecode($email), true);
211
        $this->assertSame($email, $back);
212
    }
213
 
214
    /**
215
     * @covers ::obfuscate_text
216
     */
217
    public function test_obfuscate_text() {
218
        $text = 'Žluťoučký koníček 32131';
219
        $obfuscated = obfuscate_text($text);
220
        $this->assertNotSame($text, $obfuscated);
221
        $back = core_text::entities_to_utf8($obfuscated, true);
222
        $this->assertSame($text, $back);
223
    }
224
 
225
    /**
226
     * @covers ::highlight
227
     */
228
    public function test_highlight() {
229
        $this->assertSame('This is <span class="highlight">good</span>',
230
                highlight('good', 'This is good'));
231
 
232
        $this->assertSame('<span class="highlight">span</span>',
233
                highlight('SpaN', 'span'));
234
 
235
        $this->assertSame('<span class="highlight">SpaN</span>',
236
                highlight('span', 'SpaN'));
237
 
238
        $this->assertSame('<span><span class="highlight">span</span></span>',
239
                highlight('span', '<span>span</span>'));
240
 
241
        $this->assertSame('He <span class="highlight">is</span> <span class="highlight">good</span>',
242
                highlight('good is', 'He is good'));
243
 
244
        $this->assertSame('This is <span class="highlight">good</span>',
245
                highlight('+good', 'This is good'));
246
 
247
        $this->assertSame('This is good',
248
                highlight('-good', 'This is good'));
249
 
250
        $this->assertSame('This is goodness',
251
                highlight('+good', 'This is goodness'));
252
 
253
        $this->assertSame('This is <span class="highlight">good</span>ness',
254
                highlight('good', 'This is goodness'));
255
 
256
        $this->assertSame('<p><b>test</b> <b>1</b></p><p><b>1</b></p>',
257
                highlight('test 1', '<p>test 1</p><p>1</p>', false, '<b>', '</b>'));
258
 
259
        $this->assertSame('<p><b>test</b> <b>1</b></p><p><b>1</b></p>',
260
                    highlight('test +1', '<p>test 1</p><p>1</p>', false, '<b>', '</b>'));
261
 
262
        $this->assertSame('<p><b>test</b> 1</p><p>1</p>',
263
                    highlight('test -1', '<p>test 1</p><p>1</p>', false, '<b>', '</b>'));
264
    }
265
 
266
    /**
267
     * @covers ::replace_ampersands_not_followed_by_entity
268
     */
269
    public function test_replace_ampersands() {
270
        $this->assertSame("This &amp; that &nbsp;", replace_ampersands_not_followed_by_entity("This & that &nbsp;"));
271
        $this->assertSame("This &amp;nbsp that &nbsp;", replace_ampersands_not_followed_by_entity("This &nbsp that &nbsp;"));
272
    }
273
 
274
    /**
275
     * @covers ::strip_links
276
     */
277
    public function test_strip_links() {
278
        $this->assertSame('this is a link', strip_links('this is a <a href="http://someaddress.com/query">link</a>'));
279
    }
280
 
281
    /**
282
     * @covers ::wikify_links
283
     */
284
    public function test_wikify_links() {
285
        $this->assertSame('this is a link [ http://someaddress.com/query ]', wikify_links('this is a <a href="http://someaddress.com/query">link</a>'));
286
    }
287
 
288
    /**
289
     * @covers ::clean_text
290
     */
291
    public function test_clean_text() {
292
        $text = "lala <applet>xx</applet>";
293
        $this->assertSame($text, clean_text($text, FORMAT_PLAIN));
294
        $this->assertSame('lala xx', clean_text($text, FORMAT_MARKDOWN));
295
        $this->assertSame('lala xx', clean_text($text, FORMAT_MOODLE));
296
        $this->assertSame('lala xx', clean_text($text, FORMAT_HTML));
297
    }
298
 
299
    /**
300
     * Test trusttext enabling.
301
     *
302
     * @covers ::trusttext_active
303
     */
304
    public function test_trusttext_active() {
305
        global $CFG;
306
        $this->resetAfterTest();
307
 
308
        $this->assertFalse(trusttext_active());
309
        $CFG->enabletrusttext = '1';
310
        $this->assertTrue(trusttext_active());
311
    }
312
 
313
    /**
314
     * Test trusttext detection.
315
     *
316
     * @covers ::trusttext_trusted
317
     */
318
    public function test_trusttext_trusted() {
319
        global $CFG;
320
        $this->resetAfterTest();
321
 
322
        $syscontext = context_system::instance();
323
        $course = $this->getDataGenerator()->create_course();
324
        $coursecontext = context_course::instance($course->id);
325
        $user1 = $this->getDataGenerator()->create_user();
326
        $user2 = $this->getDataGenerator()->create_user();
327
        $this->getDataGenerator()->enrol_user($user2->id, $course->id, 'editingteacher');
328
 
329
        $this->setAdminUser();
330
 
331
        $CFG->enabletrusttext = '0';
332
        $this->assertFalse(trusttext_trusted($syscontext));
333
        $this->assertFalse(trusttext_trusted($coursecontext));
334
 
335
        $CFG->enabletrusttext = '1';
336
        $this->assertTrue(trusttext_trusted($syscontext));
337
        $this->assertTrue(trusttext_trusted($coursecontext));
338
 
339
        $this->setUser($user1);
340
 
341
        $CFG->enabletrusttext = '0';
342
        $this->assertFalse(trusttext_trusted($syscontext));
343
        $this->assertFalse(trusttext_trusted($coursecontext));
344
 
345
        $CFG->enabletrusttext = '1';
346
        $this->assertFalse(trusttext_trusted($syscontext));
347
        $this->assertFalse(trusttext_trusted($coursecontext));
348
 
349
        $this->setUser($user2);
350
 
351
        $CFG->enabletrusttext = '0';
352
        $this->assertFalse(trusttext_trusted($syscontext));
353
        $this->assertFalse(trusttext_trusted($coursecontext));
354
 
355
        $CFG->enabletrusttext = '1';
356
        $this->assertFalse(trusttext_trusted($syscontext));
357
        $this->assertTrue(trusttext_trusted($coursecontext));
358
    }
359
 
360
    /**
361
     * Data provider for trusttext_pre_edit() tests.
362
     */
363
    public function trusttext_pre_edit_provider(): array {
364
        return [
365
            [true, 0, 'editingteacher', FORMAT_HTML, 1],
366
            [true, 0, 'editingteacher', FORMAT_MOODLE, 1],
367
            [false, 0, 'editingteacher', FORMAT_MARKDOWN, 1],
368
            [false, 0, 'editingteacher', FORMAT_PLAIN, 1],
369
 
370
            [false, 1, 'editingteacher', FORMAT_HTML, 1],
371
            [false, 1, 'editingteacher', FORMAT_MOODLE, 1],
372
            [false, 1, 'editingteacher', FORMAT_MARKDOWN, 1],
373
            [false, 1, 'editingteacher', FORMAT_PLAIN, 1],
374
 
375
            [true, 0, 'student', FORMAT_HTML, 1],
376
            [true, 0, 'student', FORMAT_MOODLE, 1],
377
            [false, 0, 'student', FORMAT_MARKDOWN, 1],
378
            [false, 0, 'student', FORMAT_PLAIN, 1],
379
 
380
            [true, 1, 'student', FORMAT_HTML, 1],
381
            [true, 1, 'student', FORMAT_MOODLE, 1],
382
            [false, 1, 'student', FORMAT_MARKDOWN, 1],
383
            [false, 1, 'student', FORMAT_PLAIN, 1],
384
        ];
385
    }
386
 
387
    /**
388
     * Test text cleaning before editing.
389
     *
390
     * @dataProvider trusttext_pre_edit_provider
391
     * @covers ::trusttext_pre_edit
392
     *
393
     * @param bool $expectedsanitised
394
     * @param int $enabled
395
     * @param string $rolename
396
     * @param string $format
397
     * @param int $trust
398
     */
399
    public function test_trusttext_pre_edit(bool $expectedsanitised, int $enabled, string $rolename,
400
                                            string $format, int $trust) {
401
        global $CFG, $DB;
402
        $this->resetAfterTest();
403
 
404
        $exploit = "abc<script>alert('xss')</script> < > &";
405
        $sanitised = purify_html($exploit);
406
 
407
        $course = $this->getDataGenerator()->create_course();
408
        $context = context_course::instance($course->id);
409
 
410
        $user = $this->getDataGenerator()->create_user();
411
        $this->getDataGenerator()->enrol_user($user->id, $course->id, $rolename);
412
 
413
        $this->setUser($user);
414
 
415
        $CFG->enabletrusttext = (string)$enabled;
416
 
417
        $object = new stdClass();
418
        $object->some = $exploit;
419
        $object->someformat = $format;
420
        $object->sometrust = (string)$trust;
421
        $result = trusttext_pre_edit(clone($object), 'some', $context);
422
 
423
        if ($expectedsanitised) {
424
            $message = "sanitisation is expected for: $enabled, $rolename, $format, $trust";
425
            $this->assertSame($sanitised, $result->some, $message);
426
        } else {
427
            $message = "sanitisation is not expected for: $enabled, $rolename, $format, $trust";
428
            $this->assertSame($exploit, $result->some, $message);
429
        }
430
    }
431
 
432
    /**
433
     * Test removal of legacy trusttext flag.
434
     * @covers ::trusttext_strip
435
     */
436
    public function test_trusttext_strip() {
437
        $this->assertSame('abc', trusttext_strip('abc'));
438
        $this->assertSame('abc', trusttext_strip('ab#####TRUSTTEXT#####c'));
439
    }
440
 
441
    /**
442
     * Test trust option of format_text().
443
     * @covers ::format_text
444
     */
445
    public function test_format_text_trusted() {
446
        global $CFG;
447
        $this->resetAfterTest();
448
 
449
        $text = "lala <object>xx</object>";
450
 
451
        $CFG->enabletrusttext = 0;
452
 
453
        $this->assertSame(s($text),
454
            format_text($text, FORMAT_PLAIN, ['trusted' => true]));
455
        $this->assertSame("<p>lala xx</p>\n",
456
            format_text($text, FORMAT_MARKDOWN, ['trusted' => true]));
457
        $this->assertSame('<div class="text_to_html">lala xx</div>',
458
            format_text($text, FORMAT_MOODLE, ['trusted' => true]));
459
        $this->assertSame('lala xx',
460
            format_text($text, FORMAT_HTML, ['trusted' => true]));
461
 
462
        $this->assertSame(s($text),
463
            format_text($text, FORMAT_PLAIN, ['trusted' => false]));
464
        $this->assertSame("<p>lala xx</p>\n",
465
            format_text($text, FORMAT_MARKDOWN, ['trusted' => false]));
466
        $this->assertSame('<div class="text_to_html">lala xx</div>',
467
            format_text($text, FORMAT_MOODLE, ['trusted' => false]));
468
        $this->assertSame('lala xx',
469
            format_text($text, FORMAT_HTML, ['trusted' => false]));
470
 
471
        $CFG->enabletrusttext = 1;
472
 
473
        $this->assertSame(s($text),
474
            format_text($text, FORMAT_PLAIN, ['trusted' => true]));
475
        $this->assertSame("<p>lala xx</p>\n",
476
            format_text($text, FORMAT_MARKDOWN, ['trusted' => true]));
477
        $this->assertSame('<div class="text_to_html">lala <object>xx</object></div>',
478
            format_text($text, FORMAT_MOODLE, ['trusted' => true]));
479
        $this->assertSame('lala <object>xx</object>',
480
            format_text($text, FORMAT_HTML, ['trusted' => true]));
481
 
482
        $this->assertSame(s($text),
483
            format_text($text, FORMAT_PLAIN, ['trusted' => false]));
484
        $this->assertSame("<p>lala xx</p>\n",
485
            format_text($text, FORMAT_MARKDOWN, ['trusted' => false]));
486
        $this->assertSame('<div class="text_to_html">lala xx</div>',
487
            format_text($text, FORMAT_MOODLE, ['trusted' => false]));
488
        $this->assertSame('lala xx',
489
            format_text($text, FORMAT_HTML, ['trusted' => false]));
490
 
491
        $this->assertSame("<p>lala <object>xx</object></p>\n",
492
            format_text($text, FORMAT_MARKDOWN, ['trusted' => true, 'noclean' => true]));
493
        $this->assertSame("<p>lala <object>xx</object></p>\n",
494
            format_text($text, FORMAT_MARKDOWN, ['trusted' => false, 'noclean' => true]));
495
    }
496
 
497
    /**
498
     * @covers ::qualified_me
499
     */
500
    public function test_qualified_me() {
501
        global $PAGE, $FULLME, $CFG;
502
        $this->resetAfterTest();
503
 
504
        $PAGE = new moodle_page();
505
 
506
        $FULLME = $CFG->wwwroot.'/course/view.php?id=1&xx=yy';
507
        $this->assertSame($FULLME, qualified_me());
508
 
509
        $PAGE->set_url('/course/view.php', array('id'=>1));
510
        $this->assertSame($CFG->wwwroot.'/course/view.php?id=1', qualified_me());
511
    }
512
 
513
    /**
514
     * @covers \null_progress_trace
515
     */
516
    public function test_null_progress_trace() {
517
        $this->resetAfterTest(false);
518
 
519
        $trace = new null_progress_trace();
520
        $trace->output('do');
521
        $trace->output('re', 1);
522
        $trace->output('mi', 2);
523
        $trace->finished();
524
        $output = ob_get_contents();
525
        $this->assertSame('', $output);
526
        $this->expectOutputString('');
527
    }
528
 
529
    /**
530
     * @covers \null_progress_trace
531
     */
532
    public function test_text_progress_trace() {
533
        $this->resetAfterTest(false);
534
 
535
        $trace = new text_progress_trace();
536
        $trace->output('do');
537
        $trace->output('re', 1);
538
        $trace->output('mi', 2);
539
        $trace->finished();
540
        $this->expectOutputString("do\n  re\n    mi\n");
541
    }
542
 
543
    /**
544
     * @covers \html_progress_trace
545
     */
546
    public function test_html_progress_trace() {
547
        $this->resetAfterTest(false);
548
 
549
        $trace = new html_progress_trace();
550
        $trace->output('do');
551
        $trace->output('re', 1);
552
        $trace->output('mi', 2);
553
        $trace->finished();
554
        $this->expectOutputString("<p>do</p>\n<p>&#160;&#160;re</p>\n<p>&#160;&#160;&#160;&#160;mi</p>\n");
555
    }
556
 
557
    /**
558
     * @covers \html_list_progress_trace
559
     */
560
    public function test_html_list_progress_trace() {
561
        $this->resetAfterTest(false);
562
 
563
        $trace = new html_list_progress_trace();
564
        $trace->output('do');
565
        $trace->output('re', 1);
566
        $trace->output('mi', 2);
567
        $trace->finished();
568
        $this->expectOutputString("<ul>\n<li>do<ul>\n<li>re<ul>\n<li>mi</li>\n</ul>\n</li>\n</ul>\n</li>\n</ul>\n");
569
    }
570
 
571
    /**
572
     * @covers \progress_trace_buffer
573
     */
574
    public function test_progress_trace_buffer() {
575
        $this->resetAfterTest(false);
576
 
577
        $trace = new progress_trace_buffer(new html_progress_trace());
578
        ob_start();
579
        $trace->output('do');
580
        $trace->output('re', 1);
581
        $trace->output('mi', 2);
582
        $trace->finished();
583
        $output = ob_get_contents();
584
        ob_end_clean();
585
        $this->assertSame("<p>do</p>\n<p>&#160;&#160;re</p>\n<p>&#160;&#160;&#160;&#160;mi</p>\n", $output);
586
        $this->assertSame($output, $trace->get_buffer());
587
 
588
        $trace = new progress_trace_buffer(new html_progress_trace(), false);
589
        $trace->output('do');
590
        $trace->output('re', 1);
591
        $trace->output('mi', 2);
592
        $trace->finished();
593
        $this->assertSame("<p>do</p>\n<p>&#160;&#160;re</p>\n<p>&#160;&#160;&#160;&#160;mi</p>\n", $trace->get_buffer());
594
        $this->assertSame("<p>do</p>\n<p>&#160;&#160;re</p>\n<p>&#160;&#160;&#160;&#160;mi</p>\n", $trace->get_buffer());
595
        $trace->reset_buffer();
596
        $this->assertSame('', $trace->get_buffer());
597
        $this->expectOutputString('');
598
    }
599
 
600
    /**
601
     * @covers \combined_progress_trace
602
     */
603
    public function test_combined_progress_trace() {
604
        $this->resetAfterTest(false);
605
 
606
        $trace1 = new progress_trace_buffer(new html_progress_trace(), false);
607
        $trace2 = new progress_trace_buffer(new text_progress_trace(), false);
608
 
609
        $trace = new combined_progress_trace(array($trace1, $trace2));
610
        $trace->output('do');
611
        $trace->output('re', 1);
612
        $trace->output('mi', 2);
613
        $trace->finished();
614
        $this->assertSame("<p>do</p>\n<p>&#160;&#160;re</p>\n<p>&#160;&#160;&#160;&#160;mi</p>\n", $trace1->get_buffer());
615
        $this->assertSame("do\n  re\n    mi\n", $trace2->get_buffer());
616
        $this->expectOutputString('');
617
    }
618
 
619
    /**
620
     * @covers ::set_debugging
621
     */
622
    public function test_set_debugging() {
623
        global $CFG;
624
 
625
        $this->resetAfterTest();
626
 
627
        $this->assertEquals(DEBUG_DEVELOPER, $CFG->debug);
628
        $this->assertTrue($CFG->debugdeveloper);
629
        $this->assertNotEmpty($CFG->debugdisplay);
630
 
631
        set_debugging(DEBUG_DEVELOPER, true);
632
        $this->assertEquals(DEBUG_DEVELOPER, $CFG->debug);
633
        $this->assertTrue($CFG->debugdeveloper);
634
        $this->assertNotEmpty($CFG->debugdisplay);
635
 
636
        set_debugging(DEBUG_DEVELOPER, false);
637
        $this->assertEquals(DEBUG_DEVELOPER, $CFG->debug);
638
        $this->assertTrue($CFG->debugdeveloper);
639
        $this->assertEmpty($CFG->debugdisplay);
640
 
641
        set_debugging(-1);
642
        $this->assertEquals(-1, $CFG->debug);
643
        $this->assertTrue($CFG->debugdeveloper);
644
 
645
        set_debugging(DEBUG_ALL);
646
        $this->assertEquals(DEBUG_ALL, $CFG->debug);
647
        $this->assertFalse($CFG->debugdeveloper);
648
 
649
        set_debugging(DEBUG_NORMAL);
650
        $this->assertEquals(DEBUG_NORMAL, $CFG->debug);
651
        $this->assertFalse($CFG->debugdeveloper);
652
 
653
        set_debugging(DEBUG_MINIMAL);
654
        $this->assertEquals(DEBUG_MINIMAL, $CFG->debug);
655
        $this->assertFalse($CFG->debugdeveloper);
656
 
657
        set_debugging(DEBUG_NONE);
658
        $this->assertEquals(DEBUG_NONE, $CFG->debug);
659
        $this->assertFalse($CFG->debugdeveloper);
660
    }
661
 
662
    /**
663
     * @covers ::strip_pluginfile_content
664
     */
665
    public function test_strip_pluginfile_content() {
666
        $source = <<<SOURCE
667
Hello!
668
 
669
I'm writing to you from the Moodle Majlis in Muscat, Oman, where we just had several days of Moodle community goodness.
670
 
671
URL outside a tag: https://moodle.org/logo/logo-240x60.gif
672
Plugin url outside a tag: @@PLUGINFILE@@/logo-240x60.gif
673
 
674
External link 1:<img src='https://moodle.org/logo/logo-240x60.gif' alt='Moodle'/>
675
External link 2:<img alt="Moodle" src="https://moodle.org/logo/logo-240x60.gif"/>
676
Internal link 1:<img src='@@PLUGINFILE@@/logo-240x60.gif' alt='Moodle'/>
677
Internal link 2:<img alt="Moodle" src="@@PLUGINFILE@@logo-240x60.gif"/>
678
Anchor link 1:<a href="@@PLUGINFILE@@logo-240x60.gif" alt="bananas">Link text</a>
679
Anchor link 2:<a title="bananas" href="../logo-240x60.gif">Link text</a>
680
Anchor + ext. img:<a title="bananas" href="../logo-240x60.gif"><img alt="Moodle" src="@@PLUGINFILE@@logo-240x60.gif"/></a>
681
Ext. anchor + img:<a href="@@PLUGINFILE@@logo-240x60.gif"><img alt="Moodle" src="https://moodle.org/logo/logo-240x60.gif"/></a>
682
SOURCE;
683
        $expected = <<<EXPECTED
684
Hello!
685
 
686
I'm writing to you from the Moodle Majlis in Muscat, Oman, where we just had several days of Moodle community goodness.
687
 
688
URL outside a tag: https://moodle.org/logo/logo-240x60.gif
689
Plugin url outside a tag: @@PLUGINFILE@@/logo-240x60.gif
690
 
691
External link 1:<img src="https://moodle.org/logo/logo-240x60.gif" alt="Moodle" />
692
External link 2:<img alt="Moodle" src="https://moodle.org/logo/logo-240x60.gif" />
693
Internal link 1:
694
Internal link 2:
695
Anchor link 1:Link text
696
Anchor link 2:<a title="bananas" href="../logo-240x60.gif">Link text</a>
697
Anchor + ext. img:<a title="bananas" href="../logo-240x60.gif"></a>
698
Ext. anchor + img:<img alt="Moodle" src="https://moodle.org/logo/logo-240x60.gif" />
699
EXPECTED;
700
        $this->assertSame($expected, strip_pluginfile_content($source));
701
    }
702
 
703
    /**
704
     * @covers \purify_html
705
     */
706
    public function test_purify_html_ruby() {
707
 
708
        $this->resetAfterTest();
709
 
710
        $ruby =
711
            "<p><ruby><rb>京都</rb><rp>(</rp><rt>きょうと</rt><rp>)</rp></ruby>は" .
712
            "<ruby><rb>日本</rb><rp>(</rp><rt>にほん</rt><rp>)</rp></ruby>の" .
713
            "<ruby><rb>都</rb><rp>(</rp><rt>みやこ</rt><rp>)</rp></ruby>です。</p>";
714
        $illegal = '<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>';
715
 
716
        $cleaned = purify_html($ruby . $illegal);
717
        $this->assertEquals($ruby, $cleaned);
718
 
719
    }
720
 
721
    /**
722
     * Tests for content_to_text.
723
     *
724
     * @param string    $content   The content
725
     * @param int|false $format    The content format
726
     * @param string    $expected  Expected value
727
     * @dataProvider provider_content_to_text
728
     * @covers ::content_to_text
729
     */
730
    public function test_content_to_text($content, $format, $expected) {
731
        $content = content_to_text($content, $format);
732
        $this->assertEquals($expected, $content);
733
    }
734
 
735
    /**
736
     * Data provider for test_content_to_text.
737
     */
738
    public static function provider_content_to_text() {
739
        return array(
740
            array('asd', false, 'asd'),
741
            // Trim '\r\n '.
742
            array("Note that:\n\n3 > 1 ", FORMAT_PLAIN, "Note that:\n\n3 > 1"),
743
            array("Note that:\n\n3 > 1\r\n", FORMAT_PLAIN, "Note that:\n\n3 > 1"),
744
            // Multiple spaces to one.
745
            array('<span class="eheh">京都</span>  ->  hehe', FORMAT_HTML, '京都 -> hehe'),
746
            array('<span class="eheh">京都</span>  ->  hehe', false, '京都 -> hehe'),
747
            array('asd    asd', false, 'asd asd'),
748
            // From markdown to html and html to text.
749
            array('asd __lera__ con la', FORMAT_MARKDOWN, 'asd LERA con la'),
750
            // HTML to text.
751
            array('<p class="frogs">This is a <strong class=\'fishes\'>test</strong></p>', FORMAT_HTML, 'This is a TEST'),
752
            array("<span lang='en' class='multilang'>english</span>
753
<span lang='ca' class='multilang'>català</span>
754
<span lang='es' class='multilang'>español</span>
755
<span lang='fr' class='multilang'>français</span>", FORMAT_HTML, "english català español français")
756
        );
757
    }
758
 
759
    /**
760
     * Data provider for validate_email() function.
761
     *
762
     * @return array Returns aray of test data for the test_validate_email function
763
     */
764
    public function data_validate_email() {
765
        return [
766
            // Test addresses that should pass.
767
            [
768
                'email' => 'moodle@example.com',
769
                'result' => true
770
            ],
771
            [
772
                'email' => 'moodle@localhost.local',
773
                'result' => true
774
            ],
775
            [
776
                'email' => 'verp_email+is=mighty@moodle.org',
777
                'result' => true
778
            ],
779
            [
780
                'email' => "but_potentially'dangerous'too@example.org",
781
                'result' => true
782
            ],
783
            [
784
                'email' => 'posts+AAAAAAAAAAIAAAAAAAAGQQAAAAABFSXz1eM/P/lR2bYyljM+@posts.moodle.org',
785
                'result' => true
786
            ],
787
 
788
            // Test addresses that should NOT pass.
789
            [
790
                'email' => 'moodle@localhost',
791
                'result' => false
792
            ],
793
            [
794
                'email' => '"attacker\\" -oQ/tmp/ -X/var/www/vhost/moodle/backdoor.php  some"@email.com',
795
                'result' => false
796
            ],
797
            [
798
                'email' => "moodle@example.com>\r\nRCPT TO:<victim@example.com",
799
                'result' => false
800
            ],
801
            [
802
                'email' => 'greater>than@example.com',
803
                'result' => false
804
            ],
805
            [
806
                'email' => 'less<than@example.com',
807
                'result' => false
808
            ],
809
            [
810
                'email' => '"this<is>validbutwerejectit"@example.com',
811
                'result' => false
812
            ],
813
 
814
            // Empty e-mail addresess are not valid.
815
            [
816
                'email' => '',
817
                'result' => false,
818
            ],
819
            [
820
                'email' => null,
821
                'result' => false,
822
            ],
823
            [
824
                'email' => false,
825
                'result' => false,
826
            ],
827
 
828
            // Extra email addresses from Wikipedia page on Email Addresses.
829
            // Valid.
830
            [
831
                'email' => 'simple@example.com',
832
                'result' => true
833
            ],
834
            [
835
                'email' => 'very.common@example.com',
836
                'result' => true
837
            ],
838
            [
839
                'email' => 'disposable.style.email.with+symbol@example.com',
840
                'result' => true
841
            ],
842
            [
843
                'email' => 'other.email-with-hyphen@example.com',
844
                'result' => true
845
            ],
846
            [
847
                'email' => 'fully-qualified-domain@example.com',
848
                'result' => true
849
            ],
850
            [
851
                'email' => 'user.name+tag+sorting@example.com',
852
                'result' => true
853
            ],
854
            // One-letter local-part.
855
            [
856
                'email' => 'x@example.com',
857
                'result' => true
858
            ],
859
            [
860
                'email' => 'example-indeed@strange-example.com',
861
                'result' => true
862
            ],
863
            // See the List of Internet top-level domains.
864
            [
865
                'email' => 'example@s.example',
866
                'result' => true
867
            ],
868
            // Quoted double dot.
869
            [
870
                'email' => '"john..doe"@example.org',
871
                'result' => true
872
            ],
873
 
874
            // Invalid.
875
            // No @ character.
876
            [
877
                'email' => 'Abc.example.com',
878
                'result' => false
879
            ],
880
            // Only one @ is allowed outside quotation marks.
881
            [
882
                'email' => 'A@b@c@example.com',
883
                'result' => false
884
            ],
885
            // None of the special characters in this local-part are allowed outside quotation marks.
886
            [
887
                'email' => 'a"b(c)d,e:f;g<h>i[j\k]l@example.com',
888
                'result' => false
889
            ],
890
            // Quoted strings must be dot separated or the only element making up the local-part.
891
            [
892
                'email' => 'just"not"right@example.com',
893
                'result' => false
894
            ],
895
            // Spaces, quotes, and backslashes may only exist when within quoted strings and preceded by a backslash.
896
            [
897
                'email' => 'this is"not\allowed@example.com',
898
                'result' => false
899
            ],
900
            // Even if escaped (preceded by a backslash), spaces, quotes, and backslashes must still be contained by quotes.
901
            [
902
                'email' => 'this\ still\"not\\allowed@example.com',
903
                'result' => false
904
            ],
905
            // Local part is longer than 64 characters.
906
            [
907
                'email' => '1234567890123456789012345678901234567890123456789012345678901234+x@example.com',
908
                'result' => false
909
            ],
910
        ];
911
    }
912
 
913
    /**
914
     * Tests valid and invalid email address using the validate_email() function.
915
     *
916
     * @param string $email the email address to test
917
     * @param boolean $result Expected result (true or false)
918
     * @dataProvider    data_validate_email
919
     * @covers ::validate_email
920
     */
921
    public function test_validate_email($email, $result) {
922
        if ($result) {
923
            $this->assertTrue(validate_email($email));
924
        } else {
925
            $this->assertFalse(validate_email($email));
926
        }
927
    }
928
 
929
    /**
930
     * Data provider for test_get_file_argument.
931
     */
932
    public static function provider_get_file_argument() {
933
        return array(
934
            // Serving SCORM content w/o HTTP GET params.
935
            array(array(
936
                    'SERVER_SOFTWARE' => 'Apache',
937
                    'SERVER_PORT' => '80',
938
                    'REQUEST_METHOD' => 'GET',
939
                    'REQUEST_URI' => '/pluginfile.php/3854/mod_scorm/content/1/swf.html',
940
                    'SCRIPT_NAME' => '/pluginfile.php',
941
                    'PATH_INFO' => '/3854/mod_scorm/content/1/swf.html',
942
                ), 0, '/3854/mod_scorm/content/1/swf.html'),
943
            array(array(
944
                    'SERVER_SOFTWARE' => 'Apache',
945
                    'SERVER_PORT' => '80',
946
                    'REQUEST_METHOD' => 'GET',
947
                    'REQUEST_URI' => '/pluginfile.php/3854/mod_scorm/content/1/swf.html',
948
                    'SCRIPT_NAME' => '/pluginfile.php',
949
                    'PATH_INFO' => '/3854/mod_scorm/content/1/swf.html',
950
                ), 1, '/3854/mod_scorm/content/1/swf.html'),
951
            // Serving SCORM content w/ HTTP GET 'file' as first param.
952
            array(array(
953
                    'SERVER_SOFTWARE' => 'Apache',
954
                    'SERVER_PORT' => '80',
955
                    'REQUEST_METHOD' => 'GET',
956
                    'REQUEST_URI' => '/pluginfile.php/3854/mod_scorm/content/1/swf.html?file=video_.swf',
957
                    'SCRIPT_NAME' => '/pluginfile.php',
958
                    'PATH_INFO' => '/3854/mod_scorm/content/1/swf.html',
959
                ), 0, '/3854/mod_scorm/content/1/swf.html'),
960
            array(array(
961
                    'SERVER_SOFTWARE' => 'Apache',
962
                    'SERVER_PORT' => '80',
963
                    'REQUEST_METHOD' => 'GET',
964
                    'REQUEST_URI' => '/pluginfile.php/3854/mod_scorm/content/1/swf.html?file=video_.swf',
965
                    'SCRIPT_NAME' => '/pluginfile.php',
966
                    'PATH_INFO' => '/3854/mod_scorm/content/1/swf.html',
967
                ), 1, '/3854/mod_scorm/content/1/swf.html'),
968
            // Serving SCORM content w/ HTTP GET 'file' not as first param.
969
            array(array(
970
                    'SERVER_SOFTWARE' => 'Apache',
971
                    'SERVER_PORT' => '80',
972
                    'REQUEST_METHOD' => 'GET',
973
                    'REQUEST_URI' => '/pluginfile.php/3854/mod_scorm/content/1/swf.html?foo=bar&file=video_.swf',
974
                    'SCRIPT_NAME' => '/pluginfile.php',
975
                    'PATH_INFO' => '/3854/mod_scorm/content/1/swf.html',
976
                ), 0, '/3854/mod_scorm/content/1/swf.html'),
977
            array(array(
978
                    'SERVER_SOFTWARE' => 'Apache',
979
                    'SERVER_PORT' => '80',
980
                    'REQUEST_METHOD' => 'GET',
981
                    'REQUEST_URI' => '/pluginfile.php/3854/mod_scorm/content/1/swf.html?foo=bar&file=video_.swf',
982
                    'SCRIPT_NAME' => '/pluginfile.php',
983
                    'PATH_INFO' => '/3854/mod_scorm/content/1/swf.html',
984
                ), 1, '/3854/mod_scorm/content/1/swf.html'),
985
            // Serving content from a generic activity w/ HTTP GET 'file', still forcing slash arguments.
986
            array(array(
987
                    'SERVER_SOFTWARE' => 'Apache',
988
                    'SERVER_PORT' => '80',
989
                    'REQUEST_METHOD' => 'GET',
990
                    'REQUEST_URI' => '/pluginfile.php/3854/whatever/content/1/swf.html?file=video_.swf',
991
                    'SCRIPT_NAME' => '/pluginfile.php',
992
                    'PATH_INFO' => '/3854/whatever/content/1/swf.html',
993
                ), 0, '/3854/whatever/content/1/swf.html'),
994
            array(array(
995
                    'SERVER_SOFTWARE' => 'Apache',
996
                    'SERVER_PORT' => '80',
997
                    'REQUEST_METHOD' => 'GET',
998
                    'REQUEST_URI' => '/pluginfile.php/3854/whatever/content/1/swf.html?file=video_.swf',
999
                    'SCRIPT_NAME' => '/pluginfile.php',
1000
                    'PATH_INFO' => '/3854/whatever/content/1/swf.html',
1001
                ), 1, '/3854/whatever/content/1/swf.html'),
1002
            // Serving content from a generic activity w/ HTTP GET 'file', still forcing slash arguments (edge case).
1003
            array(array(
1004
                    'SERVER_SOFTWARE' => 'Apache',
1005
                    'SERVER_PORT' => '80',
1006
                    'REQUEST_METHOD' => 'GET',
1007
                    'REQUEST_URI' => '/pluginfile.php/?file=video_.swf',
1008
                    'SCRIPT_NAME' => '/pluginfile.php',
1009
                    'PATH_INFO' => '/',
1010
                ), 0, 'video_.swf'),
1011
            array(array(
1012
                    'SERVER_SOFTWARE' => 'Apache',
1013
                    'SERVER_PORT' => '80',
1014
                    'REQUEST_METHOD' => 'GET',
1015
                    'REQUEST_URI' => '/pluginfile.php/?file=video_.swf',
1016
                    'SCRIPT_NAME' => '/pluginfile.php',
1017
                    'PATH_INFO' => '/',
1018
                ), 1, 'video_.swf'),
1019
            // Serving content from a generic activity w/ HTTP GET 'file', w/o forcing slash arguments.
1020
            array(array(
1021
                    'SERVER_SOFTWARE' => 'Apache',
1022
                    'SERVER_PORT' => '80',
1023
                    'REQUEST_METHOD' => 'GET',
1024
                    'REQUEST_URI' => '/pluginfile.php?file=%2F3854%2Fwhatever%2Fcontent%2F1%2Fswf.html%3Ffile%3Dvideo_.swf',
1025
                    'SCRIPT_NAME' => '/pluginfile.php',
1026
                ), 0, '/3854/whatever/content/1/swf.html?file=video_.swf'),
1027
            array(array(
1028
                    'SERVER_SOFTWARE' => 'Apache',
1029
                    'SERVER_PORT' => '80',
1030
                    'REQUEST_METHOD' => 'GET',
1031
                    'REQUEST_URI' => '/pluginfile.php?file=%2F3854%2Fwhatever%2Fcontent%2F1%2Fswf.html%3Ffile%3Dvideo_.swf',
1032
                    'SCRIPT_NAME' => '/pluginfile.php',
1033
                ), 1, '/3854/whatever/content/1/swf.html?file=video_.swf'),
1034
        );
1035
    }
1036
 
1037
    /**
1038
     * Tests for get_file_argument() function.
1039
     *
1040
     * @param array $server mockup for $_SERVER.
1041
     * @param string $cfgslasharguments slasharguments setting.
1042
     * @param string|false $expected Expected value.
1043
     * @dataProvider provider_get_file_argument
1044
     * @covers ::get_file_argument
1045
     */
1046
    public function test_get_file_argument($server, $cfgslasharguments, $expected) {
1047
        global $CFG;
1048
 
1049
        // Overwrite the related settings.
1050
        $currentsetting = $CFG->slasharguments;
1051
        $CFG->slasharguments = $cfgslasharguments;
1052
        // Mock global $_SERVER.
1053
        $currentserver = isset($_SERVER) ? $_SERVER : null;
1054
        $_SERVER = $server;
1055
        initialise_fullme();
1056
        if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
1057
            $this->fail('Only HTTP GET mocked request allowed.');
1058
        }
1059
        if (empty($_SERVER['REQUEST_URI'])) {
1060
            $this->fail('Invalid HTTP GET mocked request.');
1061
        }
1062
        // Mock global $_GET.
1063
        $currentget = isset($_GET) ? $_GET : null;
1064
        $_GET = array();
1065
        $querystring = parse_url($_SERVER['REQUEST_URI'], PHP_URL_QUERY);
1066
        if (!empty($querystring)) {
1067
            $_SERVER['QUERY_STRING'] = $querystring;
1068
            parse_str($querystring, $_GET);
1069
        }
1070
 
1071
        $this->assertEquals($expected, get_file_argument());
1072
 
1073
        // Restore the current settings and global values.
1074
        $CFG->slasharguments = $currentsetting;
1075
        if (is_null($currentserver)) {
1076
            unset($_SERVER);
1077
        } else {
1078
            $_SERVER = $currentserver;
1079
        }
1080
        if (is_null($currentget)) {
1081
            unset($_GET);
1082
        } else {
1083
            $_GET = $currentget;
1084
        }
1085
    }
1086
 
1087
    /**
1088
     * Tests for extract_draft_file_urls_from_text() function.
1089
     *
1090
     * @covers ::extract_draft_file_urls_from_text
1091
     */
1092
    public function test_extract_draft_file_urls_from_text() {
1093
        global $CFG;
1094
 
1095
        $url1 = "{$CFG->wwwroot}/draftfile.php/5/user/draft/99999999/test1.jpg";
1096
        $url2 = "{$CFG->wwwroot}/draftfile.php/5/user/draft/99999998/test2.jpg";
1097
 
1098
        $html = "<p>This is a test.</p><p><img src=\"{$url1}\" alt=\"\"></p>
1099
                <br>Test content.<p></p><p><img src=\"{$url2}\" alt=\"\" width=\"2048\" height=\"1536\"
1100
                class=\"img-fluid atto_image_button_text-bottom\"><br></p>";
1101
        $draftareas = array(
1102
            array(
1103
                'urlbase' => 'draftfile.php',
1104
                'contextid' => '5',
1105
                'component' => 'user',
1106
                'filearea' => 'draft',
1107
                'itemid' => '99999999',
1108
                'filename' => 'test1.jpg',
1109
 
1110
                1 => 'draftfile.php',
1111
                2 => '5',
1112
                3 => 'user',
1113
                4 => 'draft',
1114
                5 => '99999999',
1115
                6 => 'test1.jpg'
1116
            ),
1117
            array(
1118
                'urlbase' => 'draftfile.php',
1119
                'contextid' => '5',
1120
                'component' => 'user',
1121
                'filearea' => 'draft',
1122
                'itemid' => '99999998',
1123
                'filename' => 'test2.jpg',
1124
 
1125
                1 => 'draftfile.php',
1126
                2 => '5',
1127
                3 => 'user',
1128
                4 => 'draft',
1129
                5 => '99999998',
1130
                6 => 'test2.jpg'
1131
            )
1132
        );
1133
        $extracteddraftareas = extract_draft_file_urls_from_text($html, false, 5, 'user', 'draft');
1134
        $this->assertEquals($draftareas, $extracteddraftareas);
1135
    }
1136
 
1137
    /**
1138
     * @covers ::print_password_policy
1139
     */
1140
    public function test_print_password_policy() {
1141
        $this->resetAfterTest(true);
1142
        global $CFG;
1143
 
1144
        $policydisabled = '';
1145
 
1146
        // Set password policy to disabled.
1147
        $CFG->passwordpolicy = false;
1148
 
1149
        // Check for empty response.
1150
        $this->assertEquals($policydisabled, print_password_policy());
1151
 
1152
        // Now set the policy to enabled with every control disabled.
1153
        $CFG->passwordpolicy = true;
1154
        $CFG->minpasswordlength = 0;
1155
        $CFG->minpassworddigits = 0;
1156
        $CFG->minpasswordlower = 0;
1157
        $CFG->minpasswordupper = 0;
1158
        $CFG->minpasswordnonalphanum = 0;
1159
        $CFG->maxconsecutiveidentchars = 0;
1160
 
1161
        // Check for empty response.
1162
        $this->assertEquals($policydisabled, print_password_policy());
1163
 
1164
        // Now enable some controls, and check that the policy responds with policy text.
1165
        $CFG->minpasswordlength = 8;
1166
        $CFG->minpassworddigits = 1;
1167
        $CFG->minpasswordlower = 1;
1168
        $CFG->minpasswordupper = 1;
1169
        $CFG->minpasswordnonalphanum = 1;
1170
        $CFG->maxconsecutiveidentchars = 1;
1171
 
1172
        $this->assertNotEquals($policydisabled, print_password_policy());
1173
    }
1174
 
1175
    /**
1176
     * Data provider for the testing get_html_lang_attribute_value().
1177
     *
1178
     * @return string[][]
1179
     */
1180
    public function get_html_lang_attribute_value_provider() {
1181
        return [
1182
            'Empty lang code' => ['    ', 'en'],
1183
            'English' => ['en', 'en'],
1184
            'English, US' => ['en_us', 'en'],
1185
            'Unknown' => ['xx', 'en'],
1186
        ];
1187
    }
1188
 
1189
    /**
1190
     * Test for get_html_lang_attribute_value().
1191
     *
1192
     * @covers ::get_html_lang_attribute_value()
1193
     * @dataProvider get_html_lang_attribute_value_provider
1194
     * @param string $langcode The language code to convert.
1195
     * @param string $expected The expected converted value.
1196
     * @return void
1197
     */
1198
    public function test_get_html_lang_attribute_value(string $langcode, string $expected): void {
1199
        $this->assertEquals($expected, get_html_lang_attribute_value($langcode));
1200
    }
1201
 
1202
    /**
1203
     * Test the coding exceptions when returning URL as relative path from $CFG->wwwroot.
1204
     *
1205
     * @param moodle_url $url The URL pointing to a web resource.
1206
     * @param string $exmessage The expected output URL.
1207
     * @throws coding_exception If called on a non-local URL.
1208
     * @see \moodle_url::out_as_local_url()
1209
     * @covers \moodle_url::out_as_local_url
1210
     * @dataProvider out_as_local_url_coding_exception_provider
1211
     */
1212
    public function test_out_as_local_url_coding_exception(\moodle_url $url, string $exmessage) {
1213
        $this->expectException(\coding_exception::class);
1214
        $this->expectExceptionMessage($exmessage);
1215
        $localurl = $url->out_as_local_url();
1216
    }
1217
 
1218
    /**
1219
     * Data provider for throwing coding exceptions in <u>\moodle_url::out_as_local_url()</u>.
1220
     *
1221
     * @return array
1222
     * @throws moodle_exception On seriously malformed URLs (<u>parse_url</u>).
1223
     * @see \moodle_url::out_as_local_url()
1224
     * @see parse_url()
1225
     */
1226
    public function out_as_local_url_coding_exception_provider() {
1227
        return [
1228
            'Google Maps CDN (HTTPS)' => [
1229
                new \moodle_url('https://maps.googleapis.com/maps/api/js', ['key' => 'googlemapkey3', 'sensor' => 'false']),
1230
                'Coding error detected, it must be fixed by a programmer: out_as_local_url called on a non-local URL'
1231
            ],
1232
            'Google Maps CDN (HTTP)' => [
1233
                new \moodle_url('http://maps.googleapis.com/maps/api/js', ['key' => 'googlemapkey3', 'sensor' => 'false']),
1234
                'Coding error detected, it must be fixed by a programmer: out_as_local_url called on a non-local URL'
1235
            ],
1236
        ];
1237
    }
1238
 
1239
    /**
1240
     * Test URL as relative path from $CFG->wwwroot.
1241
     *
1242
     * @param moodle_url $url The URL pointing to a web resource.
1243
     * @param string $expected The expected local URL.
1244
     * @throws coding_exception If called on a non-local URL.
1245
     * @see \moodle_url::out_as_local_url()
1246
     * @covers \moodle_url::out_as_local_url
1247
     * @dataProvider out_as_local_url_provider
1248
     */
1249
    public function test_out_as_local_url(\moodle_url $url, string $expected) {
1250
        $this->assertEquals($expected, $url->out_as_local_url(false));
1251
    }
1252
 
1253
    /**
1254
     * Data provider for returning local paths via <u>\moodle_url::out_as_local_url()</u>.
1255
     *
1256
     * @return array
1257
     * @throws moodle_exception On seriously malformed URLs (<u>parse_url</u>).
1258
     * @see \moodle_url::out_as_local_url()
1259
     * @see parse_url()
1260
     */
1261
    public function out_as_local_url_provider() {
1262
        global $CFG;
1263
        $wwwroot = rtrim($CFG->wwwroot, '/');
1264
 
1265
        return [
1266
            'Environment XML file' => [
1267
                new \moodle_url('/admin/environment.xml'),
1268
                '/admin/environment.xml'
1269
            ],
1270
            'H5P JS internal resource' => [
1271
                new \moodle_url('/h5p/js/embed.js'),
1272
                '/h5p/js/embed.js'
1273
            ],
1274
            'A Moodle JS resource using the full path including the proper JS Handler' => [
1275
                new \moodle_url($wwwroot . '/lib/javascript.php/1/lib/editor/tiny/js/tinymce/tinymce.js'),
1276
                '/lib/javascript.php/1/lib/editor/tiny/js/tinymce/tinymce.js'
1277
            ],
1278
        ];
1279
    }
1280
 
1281
    /**
1282
     * Test URL as relative path from $CFG->wwwroot.
1283
     *
1284
     * @param moodle_url $url The URL pointing to a web resource.
1285
     * @param bool $expected The expected result.
1286
     * @see \moodle_url::is_local_url()
1287
     * @covers \moodle_url::is_local_url
1288
     * @dataProvider is_local_url_provider
1289
     */
1290
    public function test_is_local_url(\moodle_url $url, bool $expected) {
1291
        $this->assertEquals($expected, $url->is_local_url(), "'{$url}' is not a local URL!");
1292
    }
1293
 
1294
    /**
1295
     * Data provider for testing <u>\moodle_url::is_local_url()</u>.
1296
     *
1297
     * @return array
1298
     * @see \moodle_url::is_local_url()
1299
     */
1300
    public function is_local_url_provider() {
1301
        global $CFG;
1302
        $wwwroot = rtrim($CFG->wwwroot, '/');
1303
 
1304
        return [
1305
            'Google Maps CDN (HTTPS)' => [
1306
                new \moodle_url('https://maps.googleapis.com/maps/api/js', ['key' => 'googlemapkey3', 'sensor' => 'false']),
1307
                false
1308
            ],
1309
            'Google Maps CDN (HTTP)' => [
1310
                new \moodle_url('http://maps.googleapis.com/maps/api/js', ['key' => 'googlemapkey3', 'sensor' => 'false']),
1311
                false
1312
            ],
1313
            'wwwroot' => [
1314
                new \moodle_url($wwwroot),
1315
                true
1316
            ],
1317
            'wwwroot/' => [
1318
                new \moodle_url($wwwroot . '/'),
1319
                true
1320
            ],
1321
            'Environment XML file' => [
1322
                new \moodle_url('/admin/environment.xml'),
1323
                true
1324
            ],
1325
            'H5P JS internal resource' => [
1326
                new \moodle_url('/h5p/js/embed.js'),
1327
                true
1328
            ],
1329
        ];
1330
    }
1331
 
1332
    /**
1333
     * Data provider for strip_querystring tests.
1334
     *
1335
     * @return array
1336
     */
1337
    public function strip_querystring_provider(): array {
1338
        return [
1339
            'Null' => [null, ''],
1340
            'Empty string' => ['', ''],
1341
            'No querystring' => ['https://example.com', 'https://example.com'],
1342
            'Querystring' => ['https://example.com?foo=bar', 'https://example.com'],
1343
            'Querystring with fragment' => ['https://example.com?foo=bar#baz', 'https://example.com'],
1344
            'Querystring with fragment and path' => ['https://example.com/foo/bar?foo=bar#baz', 'https://example.com/foo/bar'],
1345
        ];
1346
    }
1347
 
1348
    /**
1349
     * Test the strip_querystring function with various exampels.
1350
     *
1351
     * @dataProvider strip_querystring_provider
1352
     * @param mixed $value
1353
     * @param mixed $expected
1354
     * @covers ::strip_querystring
1355
     */
1356
    public function test_strip_querystring($value, $expected): void {
1357
        $this->assertEquals($expected, strip_querystring($value));
1358
    }
1359
}