Search moodle.org's
Developer Documentation

See Release Notes
Long Term Support Release

  • Bug fixes for general core bugs in 4.1.x will end 13 November 2023 (12 months).
  • Bug fixes for security issues in 4.1.x will end 10 November 2025 (36 months).
  • PHP version: minimum PHP 7.4.0 Note: minimum PHP version has increased since Moodle 4.0. PHP 8.0.x is supported too.

Differences Between: [Versions 310 and 401] [Versions 311 and 401] [Versions 39 and 401] [Versions 400 and 401] [Versions 401 and 402] [Versions 401 and 403]

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