Proyectos de Subversion Moodle

Rev

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

Rev Autor Línea Nro. Línea
1 efrain 1
<?php
2
// This file is part of Moodle - http://moodle.org/
3
//
4
// Moodle is free software: you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License as published by
6
// the Free Software Foundation, either version 3 of the License, or
7
// (at your option) any later version.
8
//
9
// Moodle is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
// GNU General Public License for more details.
13
//
14
// You should have received a copy of the GNU General Public License
15
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
16
 
17
/**
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
 */
1441 ariadna 26
final class weblib_test extends advanced_testcase {
1 efrain 27
    /**
28
     * @covers ::s
29
     */
11 efrain 30
    public function test_s(): void {
1 efrain 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
     */
11 efrain 190
    public function test_format_text_email(): void {
1 efrain 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
     */
11 efrain 206
    public function test_obfuscate_email(): void {
1 efrain 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
     */
11 efrain 217
    public function test_obfuscate_text(): void {
1 efrain 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
     */
11 efrain 228
    public function test_highlight(): void {
1 efrain 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
     */
11 efrain 269
    public function test_replace_ampersands(): void {
1 efrain 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
     */
11 efrain 277
    public function test_strip_links(): void {
1 efrain 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
     */
11 efrain 284
    public function test_wikify_links(): void {
1 efrain 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
     */
11 efrain 291
    public function test_clean_text(): void {
1 efrain 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
     */
11 efrain 304
    public function test_trusttext_active(): void {
1 efrain 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
     */
11 efrain 318
    public function test_trusttext_trusted(): void {
1 efrain 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
     */
1441 ariadna 363
    public static function trusttext_pre_edit_provider(): array {
1 efrain 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,
11 efrain 400
                                            string $format, int $trust): void {
1 efrain 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
     */
11 efrain 436
    public function test_trusttext_strip(): void {
1 efrain 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
     */
11 efrain 445
    public function test_format_text_trusted(): void {
1 efrain 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
     */
11 efrain 500
    public function test_qualified_me(): void {
1 efrain 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 ::set_debugging
515
     */
11 efrain 516
    public function test_set_debugging(): void {
1 efrain 517
        global $CFG;
518
 
519
        $this->resetAfterTest();
520
 
521
        $this->assertEquals(DEBUG_DEVELOPER, $CFG->debug);
522
        $this->assertTrue($CFG->debugdeveloper);
523
        $this->assertNotEmpty($CFG->debugdisplay);
524
 
525
        set_debugging(DEBUG_DEVELOPER, true);
526
        $this->assertEquals(DEBUG_DEVELOPER, $CFG->debug);
527
        $this->assertTrue($CFG->debugdeveloper);
528
        $this->assertNotEmpty($CFG->debugdisplay);
529
 
530
        set_debugging(DEBUG_DEVELOPER, false);
531
        $this->assertEquals(DEBUG_DEVELOPER, $CFG->debug);
532
        $this->assertTrue($CFG->debugdeveloper);
533
        $this->assertEmpty($CFG->debugdisplay);
534
 
535
        set_debugging(-1);
536
        $this->assertEquals(-1, $CFG->debug);
537
        $this->assertTrue($CFG->debugdeveloper);
538
 
539
        set_debugging(DEBUG_ALL);
540
        $this->assertEquals(DEBUG_ALL, $CFG->debug);
1441 ariadna 541
        $this->assertTrue($CFG->debugdeveloper);
1 efrain 542
 
543
        set_debugging(DEBUG_NORMAL);
544
        $this->assertEquals(DEBUG_NORMAL, $CFG->debug);
545
        $this->assertFalse($CFG->debugdeveloper);
546
 
547
        set_debugging(DEBUG_MINIMAL);
548
        $this->assertEquals(DEBUG_MINIMAL, $CFG->debug);
549
        $this->assertFalse($CFG->debugdeveloper);
550
 
551
        set_debugging(DEBUG_NONE);
552
        $this->assertEquals(DEBUG_NONE, $CFG->debug);
553
        $this->assertFalse($CFG->debugdeveloper);
554
    }
555
 
556
    /**
557
     * @covers ::strip_pluginfile_content
558
     */
11 efrain 559
    public function test_strip_pluginfile_content(): void {
1 efrain 560
        $source = <<<SOURCE
561
Hello!
562
 
563
I'm writing to you from the Moodle Majlis in Muscat, Oman, where we just had several days of Moodle community goodness.
564
 
565
URL outside a tag: https://moodle.org/logo/logo-240x60.gif
566
Plugin url outside a tag: @@PLUGINFILE@@/logo-240x60.gif
567
 
568
External link 1:<img src='https://moodle.org/logo/logo-240x60.gif' alt='Moodle'/>
569
External link 2:<img alt="Moodle" src="https://moodle.org/logo/logo-240x60.gif"/>
570
Internal link 1:<img src='@@PLUGINFILE@@/logo-240x60.gif' alt='Moodle'/>
571
Internal link 2:<img alt="Moodle" src="@@PLUGINFILE@@logo-240x60.gif"/>
572
Anchor link 1:<a href="@@PLUGINFILE@@logo-240x60.gif" alt="bananas">Link text</a>
573
Anchor link 2:<a title="bananas" href="../logo-240x60.gif">Link text</a>
574
Anchor + ext. img:<a title="bananas" href="../logo-240x60.gif"><img alt="Moodle" src="@@PLUGINFILE@@logo-240x60.gif"/></a>
575
Ext. anchor + img:<a href="@@PLUGINFILE@@logo-240x60.gif"><img alt="Moodle" src="https://moodle.org/logo/logo-240x60.gif"/></a>
576
SOURCE;
577
        $expected = <<<EXPECTED
578
Hello!
579
 
580
I'm writing to you from the Moodle Majlis in Muscat, Oman, where we just had several days of Moodle community goodness.
581
 
582
URL outside a tag: https://moodle.org/logo/logo-240x60.gif
583
Plugin url outside a tag: @@PLUGINFILE@@/logo-240x60.gif
584
 
585
External link 1:<img src="https://moodle.org/logo/logo-240x60.gif" alt="Moodle" />
586
External link 2:<img alt="Moodle" src="https://moodle.org/logo/logo-240x60.gif" />
587
Internal link 1:
588
Internal link 2:
589
Anchor link 1:Link text
590
Anchor link 2:<a title="bananas" href="../logo-240x60.gif">Link text</a>
591
Anchor + ext. img:<a title="bananas" href="../logo-240x60.gif"></a>
592
Ext. anchor + img:<img alt="Moodle" src="https://moodle.org/logo/logo-240x60.gif" />
593
EXPECTED;
594
        $this->assertSame($expected, strip_pluginfile_content($source));
595
    }
596
 
597
    /**
598
     * @covers \purify_html
599
     */
11 efrain 600
    public function test_purify_html_ruby(): void {
1 efrain 601
 
602
        $this->resetAfterTest();
603
 
604
        $ruby =
605
            "<p><ruby><rb>京都</rb><rp>(</rp><rt>きょうと</rt><rp>)</rp></ruby>は" .
606
            "<ruby><rb>日本</rb><rp>(</rp><rt>にほん</rt><rp>)</rp></ruby>の" .
607
            "<ruby><rb>都</rb><rp>(</rp><rt>みやこ</rt><rp>)</rp></ruby>です。</p>";
608
        $illegal = '<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>';
609
 
610
        $cleaned = purify_html($ruby . $illegal);
611
        $this->assertEquals($ruby, $cleaned);
612
 
613
    }
614
 
615
    /**
616
     * Tests for content_to_text.
617
     *
618
     * @param string    $content   The content
619
     * @param int|false $format    The content format
620
     * @param string    $expected  Expected value
621
     * @dataProvider provider_content_to_text
622
     * @covers ::content_to_text
623
     */
11 efrain 624
    public function test_content_to_text($content, $format, $expected): void {
1 efrain 625
        $content = content_to_text($content, $format);
626
        $this->assertEquals($expected, $content);
627
    }
628
 
629
    /**
630
     * Data provider for test_content_to_text.
631
     */
1441 ariadna 632
    public static function provider_content_to_text(): array {
1 efrain 633
        return array(
634
            array('asd', false, 'asd'),
635
            // Trim '\r\n '.
636
            array("Note that:\n\n3 > 1 ", FORMAT_PLAIN, "Note that:\n\n3 > 1"),
637
            array("Note that:\n\n3 > 1\r\n", FORMAT_PLAIN, "Note that:\n\n3 > 1"),
638
            // Multiple spaces to one.
639
            array('<span class="eheh">京都</span>  ->  hehe', FORMAT_HTML, '京都 -> hehe'),
640
            array('<span class="eheh">京都</span>  ->  hehe', false, '京都 -> hehe'),
641
            array('asd    asd', false, 'asd asd'),
642
            // From markdown to html and html to text.
643
            array('asd __lera__ con la', FORMAT_MARKDOWN, 'asd LERA con la'),
644
            // HTML to text.
645
            array('<p class="frogs">This is a <strong class=\'fishes\'>test</strong></p>', FORMAT_HTML, 'This is a TEST'),
646
            array("<span lang='en' class='multilang'>english</span>
647
<span lang='ca' class='multilang'>català</span>
648
<span lang='es' class='multilang'>español</span>
649
<span lang='fr' class='multilang'>français</span>", FORMAT_HTML, "english català español français")
650
        );
651
    }
652
 
653
    /**
654
     * Data provider for validate_email() function.
655
     *
656
     * @return array Returns aray of test data for the test_validate_email function
657
     */
1441 ariadna 658
    public static function data_validate_email(): array {
1 efrain 659
        return [
660
            // Test addresses that should pass.
661
            [
662
                'email' => 'moodle@example.com',
663
                'result' => true
664
            ],
665
            [
666
                'email' => 'moodle@localhost.local',
667
                'result' => true
668
            ],
669
            [
670
                'email' => 'verp_email+is=mighty@moodle.org',
671
                'result' => true
672
            ],
673
            [
674
                'email' => "but_potentially'dangerous'too@example.org",
675
                'result' => true
676
            ],
677
            [
678
                'email' => 'posts+AAAAAAAAAAIAAAAAAAAGQQAAAAABFSXz1eM/P/lR2bYyljM+@posts.moodle.org',
679
                'result' => true
680
            ],
681
 
682
            // Test addresses that should NOT pass.
683
            [
684
                'email' => 'moodle@localhost',
685
                'result' => false
686
            ],
687
            [
688
                'email' => '"attacker\\" -oQ/tmp/ -X/var/www/vhost/moodle/backdoor.php  some"@email.com',
689
                'result' => false
690
            ],
691
            [
692
                'email' => "moodle@example.com>\r\nRCPT TO:<victim@example.com",
693
                'result' => false
694
            ],
695
            [
696
                'email' => 'greater>than@example.com',
697
                'result' => false
698
            ],
699
            [
700
                'email' => 'less<than@example.com',
701
                'result' => false
702
            ],
703
            [
704
                'email' => '"this<is>validbutwerejectit"@example.com',
705
                'result' => false
706
            ],
707
 
708
            // Empty e-mail addresess are not valid.
709
            [
710
                'email' => '',
711
                'result' => false,
712
            ],
713
            [
714
                'email' => null,
715
                'result' => false,
716
            ],
717
            [
718
                'email' => false,
719
                'result' => false,
720
            ],
721
 
722
            // Extra email addresses from Wikipedia page on Email Addresses.
723
            // Valid.
724
            [
725
                'email' => 'simple@example.com',
726
                'result' => true
727
            ],
728
            [
729
                'email' => 'very.common@example.com',
730
                'result' => true
731
            ],
732
            [
733
                'email' => 'disposable.style.email.with+symbol@example.com',
734
                'result' => true
735
            ],
736
            [
737
                'email' => 'other.email-with-hyphen@example.com',
738
                'result' => true
739
            ],
740
            [
741
                'email' => 'fully-qualified-domain@example.com',
742
                'result' => true
743
            ],
744
            [
745
                'email' => 'user.name+tag+sorting@example.com',
746
                'result' => true
747
            ],
748
            // One-letter local-part.
749
            [
750
                'email' => 'x@example.com',
751
                'result' => true
752
            ],
753
            [
754
                'email' => 'example-indeed@strange-example.com',
755
                'result' => true
756
            ],
757
            // See the List of Internet top-level domains.
758
            [
759
                'email' => 'example@s.example',
760
                'result' => true
761
            ],
762
            // Quoted double dot.
763
            [
764
                'email' => '"john..doe"@example.org',
765
                'result' => true
766
            ],
767
 
768
            // Invalid.
769
            // No @ character.
770
            [
771
                'email' => 'Abc.example.com',
772
                'result' => false
773
            ],
774
            // Only one @ is allowed outside quotation marks.
775
            [
776
                'email' => 'A@b@c@example.com',
777
                'result' => false
778
            ],
779
            // None of the special characters in this local-part are allowed outside quotation marks.
780
            [
781
                'email' => 'a"b(c)d,e:f;g<h>i[j\k]l@example.com',
782
                'result' => false
783
            ],
784
            // Quoted strings must be dot separated or the only element making up the local-part.
785
            [
786
                'email' => 'just"not"right@example.com',
787
                'result' => false
788
            ],
789
            // Spaces, quotes, and backslashes may only exist when within quoted strings and preceded by a backslash.
790
            [
791
                'email' => 'this is"not\allowed@example.com',
792
                'result' => false
793
            ],
794
            // Even if escaped (preceded by a backslash), spaces, quotes, and backslashes must still be contained by quotes.
795
            [
796
                'email' => 'this\ still\"not\\allowed@example.com',
797
                'result' => false
798
            ],
799
            // Local part is longer than 64 characters.
800
            [
801
                'email' => '1234567890123456789012345678901234567890123456789012345678901234+x@example.com',
802
                'result' => false
803
            ],
804
        ];
805
    }
806
 
807
    /**
808
     * Tests valid and invalid email address using the validate_email() function.
809
     *
810
     * @param string $email the email address to test
811
     * @param boolean $result Expected result (true or false)
812
     * @dataProvider    data_validate_email
813
     * @covers ::validate_email
814
     */
11 efrain 815
    public function test_validate_email($email, $result): void {
1 efrain 816
        if ($result) {
817
            $this->assertTrue(validate_email($email));
818
        } else {
819
            $this->assertFalse(validate_email($email));
820
        }
821
    }
822
 
823
    /**
824
     * Data provider for test_get_file_argument.
825
     */
1441 ariadna 826
    public static function provider_get_file_argument(): array {
1 efrain 827
        return array(
828
            // Serving SCORM content w/o HTTP GET params.
829
            array(array(
830
                    'SERVER_SOFTWARE' => 'Apache',
831
                    'SERVER_PORT' => '80',
832
                    'REQUEST_METHOD' => 'GET',
833
                    'REQUEST_URI' => '/pluginfile.php/3854/mod_scorm/content/1/swf.html',
834
                    'SCRIPT_NAME' => '/pluginfile.php',
835
                    'PATH_INFO' => '/3854/mod_scorm/content/1/swf.html',
836
                ), 0, '/3854/mod_scorm/content/1/swf.html'),
837
            array(array(
838
                    'SERVER_SOFTWARE' => 'Apache',
839
                    'SERVER_PORT' => '80',
840
                    'REQUEST_METHOD' => 'GET',
841
                    'REQUEST_URI' => '/pluginfile.php/3854/mod_scorm/content/1/swf.html',
842
                    'SCRIPT_NAME' => '/pluginfile.php',
843
                    'PATH_INFO' => '/3854/mod_scorm/content/1/swf.html',
844
                ), 1, '/3854/mod_scorm/content/1/swf.html'),
845
            // Serving SCORM content w/ HTTP GET 'file' as first param.
846
            array(array(
847
                    'SERVER_SOFTWARE' => 'Apache',
848
                    'SERVER_PORT' => '80',
849
                    'REQUEST_METHOD' => 'GET',
850
                    'REQUEST_URI' => '/pluginfile.php/3854/mod_scorm/content/1/swf.html?file=video_.swf',
851
                    'SCRIPT_NAME' => '/pluginfile.php',
852
                    'PATH_INFO' => '/3854/mod_scorm/content/1/swf.html',
853
                ), 0, '/3854/mod_scorm/content/1/swf.html'),
854
            array(array(
855
                    'SERVER_SOFTWARE' => 'Apache',
856
                    'SERVER_PORT' => '80',
857
                    'REQUEST_METHOD' => 'GET',
858
                    'REQUEST_URI' => '/pluginfile.php/3854/mod_scorm/content/1/swf.html?file=video_.swf',
859
                    'SCRIPT_NAME' => '/pluginfile.php',
860
                    'PATH_INFO' => '/3854/mod_scorm/content/1/swf.html',
861
                ), 1, '/3854/mod_scorm/content/1/swf.html'),
862
            // Serving SCORM content w/ HTTP GET 'file' not as first param.
863
            array(array(
864
                    'SERVER_SOFTWARE' => 'Apache',
865
                    'SERVER_PORT' => '80',
866
                    'REQUEST_METHOD' => 'GET',
867
                    'REQUEST_URI' => '/pluginfile.php/3854/mod_scorm/content/1/swf.html?foo=bar&file=video_.swf',
868
                    'SCRIPT_NAME' => '/pluginfile.php',
869
                    'PATH_INFO' => '/3854/mod_scorm/content/1/swf.html',
870
                ), 0, '/3854/mod_scorm/content/1/swf.html'),
871
            array(array(
872
                    'SERVER_SOFTWARE' => 'Apache',
873
                    'SERVER_PORT' => '80',
874
                    'REQUEST_METHOD' => 'GET',
875
                    'REQUEST_URI' => '/pluginfile.php/3854/mod_scorm/content/1/swf.html?foo=bar&file=video_.swf',
876
                    'SCRIPT_NAME' => '/pluginfile.php',
877
                    'PATH_INFO' => '/3854/mod_scorm/content/1/swf.html',
878
                ), 1, '/3854/mod_scorm/content/1/swf.html'),
879
            // Serving content from a generic activity w/ HTTP GET 'file', still forcing slash arguments.
880
            array(array(
881
                    'SERVER_SOFTWARE' => 'Apache',
882
                    'SERVER_PORT' => '80',
883
                    'REQUEST_METHOD' => 'GET',
884
                    'REQUEST_URI' => '/pluginfile.php/3854/whatever/content/1/swf.html?file=video_.swf',
885
                    'SCRIPT_NAME' => '/pluginfile.php',
886
                    'PATH_INFO' => '/3854/whatever/content/1/swf.html',
887
                ), 0, '/3854/whatever/content/1/swf.html'),
888
            array(array(
889
                    'SERVER_SOFTWARE' => 'Apache',
890
                    'SERVER_PORT' => '80',
891
                    'REQUEST_METHOD' => 'GET',
892
                    'REQUEST_URI' => '/pluginfile.php/3854/whatever/content/1/swf.html?file=video_.swf',
893
                    'SCRIPT_NAME' => '/pluginfile.php',
894
                    'PATH_INFO' => '/3854/whatever/content/1/swf.html',
895
                ), 1, '/3854/whatever/content/1/swf.html'),
896
            // Serving content from a generic activity w/ HTTP GET 'file', still forcing slash arguments (edge case).
897
            array(array(
898
                    'SERVER_SOFTWARE' => 'Apache',
899
                    'SERVER_PORT' => '80',
900
                    'REQUEST_METHOD' => 'GET',
901
                    'REQUEST_URI' => '/pluginfile.php/?file=video_.swf',
902
                    'SCRIPT_NAME' => '/pluginfile.php',
903
                    'PATH_INFO' => '/',
904
                ), 0, 'video_.swf'),
905
            array(array(
906
                    'SERVER_SOFTWARE' => 'Apache',
907
                    'SERVER_PORT' => '80',
908
                    'REQUEST_METHOD' => 'GET',
909
                    'REQUEST_URI' => '/pluginfile.php/?file=video_.swf',
910
                    'SCRIPT_NAME' => '/pluginfile.php',
911
                    'PATH_INFO' => '/',
912
                ), 1, 'video_.swf'),
913
            // Serving content from a generic activity w/ HTTP GET 'file', w/o forcing slash arguments.
914
            array(array(
915
                    'SERVER_SOFTWARE' => 'Apache',
916
                    'SERVER_PORT' => '80',
917
                    'REQUEST_METHOD' => 'GET',
918
                    'REQUEST_URI' => '/pluginfile.php?file=%2F3854%2Fwhatever%2Fcontent%2F1%2Fswf.html%3Ffile%3Dvideo_.swf',
919
                    'SCRIPT_NAME' => '/pluginfile.php',
920
                ), 0, '/3854/whatever/content/1/swf.html?file=video_.swf'),
921
            array(array(
922
                    'SERVER_SOFTWARE' => 'Apache',
923
                    'SERVER_PORT' => '80',
924
                    'REQUEST_METHOD' => 'GET',
925
                    'REQUEST_URI' => '/pluginfile.php?file=%2F3854%2Fwhatever%2Fcontent%2F1%2Fswf.html%3Ffile%3Dvideo_.swf',
926
                    'SCRIPT_NAME' => '/pluginfile.php',
927
                ), 1, '/3854/whatever/content/1/swf.html?file=video_.swf'),
928
        );
929
    }
930
 
931
    /**
932
     * Tests for get_file_argument() function.
933
     *
934
     * @param array $server mockup for $_SERVER.
935
     * @param string $cfgslasharguments slasharguments setting.
936
     * @param string|false $expected Expected value.
937
     * @dataProvider provider_get_file_argument
938
     * @covers ::get_file_argument
939
     */
11 efrain 940
    public function test_get_file_argument($server, $cfgslasharguments, $expected): void {
1 efrain 941
        global $CFG;
942
 
943
        // Overwrite the related settings.
944
        $currentsetting = $CFG->slasharguments;
945
        $CFG->slasharguments = $cfgslasharguments;
946
        // Mock global $_SERVER.
947
        $currentserver = isset($_SERVER) ? $_SERVER : null;
948
        $_SERVER = $server;
949
        initialise_fullme();
950
        if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
951
            $this->fail('Only HTTP GET mocked request allowed.');
952
        }
953
        if (empty($_SERVER['REQUEST_URI'])) {
954
            $this->fail('Invalid HTTP GET mocked request.');
955
        }
956
        // Mock global $_GET.
957
        $currentget = isset($_GET) ? $_GET : null;
958
        $_GET = array();
959
        $querystring = parse_url($_SERVER['REQUEST_URI'], PHP_URL_QUERY);
960
        if (!empty($querystring)) {
961
            $_SERVER['QUERY_STRING'] = $querystring;
962
            parse_str($querystring, $_GET);
963
        }
964
 
965
        $this->assertEquals($expected, get_file_argument());
966
 
967
        // Restore the current settings and global values.
968
        $CFG->slasharguments = $currentsetting;
969
        if (is_null($currentserver)) {
970
            unset($_SERVER);
971
        } else {
972
            $_SERVER = $currentserver;
973
        }
974
        if (is_null($currentget)) {
975
            unset($_GET);
976
        } else {
977
            $_GET = $currentget;
978
        }
979
    }
980
 
981
    /**
982
     * Tests for extract_draft_file_urls_from_text() function.
983
     *
984
     * @covers ::extract_draft_file_urls_from_text
985
     */
11 efrain 986
    public function test_extract_draft_file_urls_from_text(): void {
1 efrain 987
        global $CFG;
988
 
989
        $url1 = "{$CFG->wwwroot}/draftfile.php/5/user/draft/99999999/test1.jpg";
990
        $url2 = "{$CFG->wwwroot}/draftfile.php/5/user/draft/99999998/test2.jpg";
991
 
992
        $html = "<p>This is a test.</p><p><img src=\"{$url1}\" alt=\"\"></p>
993
                <br>Test content.<p></p><p><img src=\"{$url2}\" alt=\"\" width=\"2048\" height=\"1536\"
1441 ariadna 994
                class=\"img-fluid \"><br></p>";
1 efrain 995
        $draftareas = array(
996
            array(
997
                'urlbase' => 'draftfile.php',
998
                'contextid' => '5',
999
                'component' => 'user',
1000
                'filearea' => 'draft',
1001
                'itemid' => '99999999',
1002
                'filename' => 'test1.jpg',
1003
 
1004
                1 => 'draftfile.php',
1005
                2 => '5',
1006
                3 => 'user',
1007
                4 => 'draft',
1008
                5 => '99999999',
1009
                6 => 'test1.jpg'
1010
            ),
1011
            array(
1012
                'urlbase' => 'draftfile.php',
1013
                'contextid' => '5',
1014
                'component' => 'user',
1015
                'filearea' => 'draft',
1016
                'itemid' => '99999998',
1017
                'filename' => 'test2.jpg',
1018
 
1019
                1 => 'draftfile.php',
1020
                2 => '5',
1021
                3 => 'user',
1022
                4 => 'draft',
1023
                5 => '99999998',
1024
                6 => 'test2.jpg'
1025
            )
1026
        );
1027
        $extracteddraftareas = extract_draft_file_urls_from_text($html, false, 5, 'user', 'draft');
1028
        $this->assertEquals($draftareas, $extracteddraftareas);
1029
    }
1030
 
1031
    /**
1032
     * @covers ::print_password_policy
1033
     */
11 efrain 1034
    public function test_print_password_policy(): void {
1 efrain 1035
        $this->resetAfterTest(true);
1036
        global $CFG;
1037
 
1038
        $policydisabled = '';
1039
 
1040
        // Set password policy to disabled.
1041
        $CFG->passwordpolicy = false;
1042
 
1043
        // Check for empty response.
1044
        $this->assertEquals($policydisabled, print_password_policy());
1045
 
1046
        // Now set the policy to enabled with every control disabled.
1047
        $CFG->passwordpolicy = true;
1048
        $CFG->minpasswordlength = 0;
1049
        $CFG->minpassworddigits = 0;
1050
        $CFG->minpasswordlower = 0;
1051
        $CFG->minpasswordupper = 0;
1052
        $CFG->minpasswordnonalphanum = 0;
1053
        $CFG->maxconsecutiveidentchars = 0;
1054
 
1055
        // Check for empty response.
1056
        $this->assertEquals($policydisabled, print_password_policy());
1057
 
1058
        // Now enable some controls, and check that the policy responds with policy text.
1059
        $CFG->minpasswordlength = 8;
1060
        $CFG->minpassworddigits = 1;
1061
        $CFG->minpasswordlower = 1;
1062
        $CFG->minpasswordupper = 1;
1063
        $CFG->minpasswordnonalphanum = 1;
1064
        $CFG->maxconsecutiveidentchars = 1;
1065
 
1066
        $this->assertNotEquals($policydisabled, print_password_policy());
1067
    }
1068
 
1069
    /**
1070
     * Data provider for the testing get_html_lang_attribute_value().
1071
     *
1072
     * @return string[][]
1073
     */
1441 ariadna 1074
    public static function get_html_lang_attribute_value_provider(): array {
1 efrain 1075
        return [
1076
            'Empty lang code' => ['    ', 'en'],
1077
            'English' => ['en', 'en'],
1078
            'English, US' => ['en_us', 'en'],
1079
            'Unknown' => ['xx', 'en'],
1080
        ];
1081
    }
1082
 
1083
    /**
1084
     * Test for get_html_lang_attribute_value().
1085
     *
1086
     * @covers ::get_html_lang_attribute_value()
1087
     * @dataProvider get_html_lang_attribute_value_provider
1088
     * @param string $langcode The language code to convert.
1089
     * @param string $expected The expected converted value.
1090
     * @return void
1091
     */
1092
    public function test_get_html_lang_attribute_value(string $langcode, string $expected): void {
1093
        $this->assertEquals($expected, get_html_lang_attribute_value($langcode));
1094
    }
1095
 
1096
    /**
1097
     * Data provider for strip_querystring tests.
1098
     *
1099
     * @return array
1100
     */
1441 ariadna 1101
    public static function strip_querystring_provider(): array {
1 efrain 1102
        return [
1103
            'Null' => [null, ''],
1104
            'Empty string' => ['', ''],
1105
            'No querystring' => ['https://example.com', 'https://example.com'],
1106
            'Querystring' => ['https://example.com?foo=bar', 'https://example.com'],
1107
            'Querystring with fragment' => ['https://example.com?foo=bar#baz', 'https://example.com'],
1108
            'Querystring with fragment and path' => ['https://example.com/foo/bar?foo=bar#baz', 'https://example.com/foo/bar'],
1109
        ];
1110
    }
1111
 
1112
    /**
1113
     * Test the strip_querystring function with various exampels.
1114
     *
1115
     * @dataProvider strip_querystring_provider
1116
     * @param mixed $value
1117
     * @param mixed $expected
1118
     * @covers ::strip_querystring
1119
     */
1120
    public function test_strip_querystring($value, $expected): void {
1121
        $this->assertEquals($expected, strip_querystring($value));
1122
    }
1123
}