Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 4.2.x will end 22 April 2024 (12 months).
  • Bug fixes for security issues in 4.2.x will end 7 October 2024 (18 months).
  • PHP version: minimum PHP 8.0.0 Note: minimum PHP version has increased since Moodle 4.1. PHP 8.1.x is supported too.

Differences Between: [Versions 310 and 402] [Versions 311 and 402] [Versions 39 and 402] [Versions 400 and 402] [Versions 401 and 402] [Versions 402 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 array $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          // In PHP 8.2 exported class names are now fully qualified;
2331          // previously, the leading backslash was omitted.
2332          $leadingbackslash = (version_compare(PHP_VERSION, '8.2.0', '>=')) ? '\\' : '';
2333  
2334          $expected1 = <<<EOF
2335  {$leadingbackslash}lang_string::__set_state(array(
2336     'identifier' => 'no',
2337     'component' => 'moodle',
2338     'a' => NULL,
2339     'lang' => NULL,
2340     'string' => NULL,
2341     'forcedstring' => false,
2342  ))
2343  EOF;
2344  
2345          $v = var_export($str, true);
2346          $this->assertEquals($expected1, $v);
2347  
2348          // Now execute the code that was returned - it should produce a correct string.
2349          $str = lang_string::__set_state(array(
2350              'identifier' => 'no',
2351              'component' => 'moodle',
2352              'a' => NULL,
2353              'lang' => NULL,
2354              'string' => NULL,
2355              'forcedstring' => false,
2356          ));
2357  
2358          $this->assertInstanceOf(lang_string::class, $str);
2359          $this->assertEquals('No', $str);
2360      }
2361  
2362      public function test_get_string_limitation() {
2363          // This is one of the limitations to the lang_string class. It can't be
2364          // used as a key.
2365          if (PHP_VERSION_ID >= 80000) {
2366              $this->expectException(\TypeError::class);
2367          } else {
2368              $this->expectWarning();
2369          }
2370          $array = array(get_string('yes', null, null, true) => 'yes');
2371      }
2372  
2373      /**
2374       * Test localised float formatting.
2375       */
2376      public function test_format_float() {
2377  
2378          // Special case for null.
2379          $this->assertEquals('', format_float(null));
2380  
2381          // Default 1 decimal place.
2382          $this->assertEquals('5.4', format_float(5.43));
2383          $this->assertEquals('5.0', format_float(5.001));
2384  
2385          // Custom number of decimal places.
2386          $this->assertEquals('5.43000', format_float(5.43, 5));
2387  
2388          // Auto detect the number of decimal places.
2389          $this->assertEquals('5.43', format_float(5.43, -1));
2390          $this->assertEquals('5.43', format_float(5.43000, -1));
2391          $this->assertEquals('5', format_float(5, -1));
2392          $this->assertEquals('5', format_float(5.0, -1));
2393          $this->assertEquals('0.543', format_float('5.43e-1', -1));
2394          $this->assertEquals('0.543', format_float('5.43000e-1', -1));
2395  
2396          // Option to strip ending zeros after rounding.
2397          $this->assertEquals('5.43', format_float(5.43, 5, true, true));
2398          $this->assertEquals('5', format_float(5.0001, 3, true, true));
2399          $this->assertEquals('100', format_float(100, 2, true, true));
2400          $this->assertEquals('100', format_float(100, 0, true, true));
2401  
2402          // Tests with a localised decimal separator.
2403          $this->define_local_decimal_separator();
2404  
2405          // Localisation on (default).
2406          $this->assertEquals('5X43000', format_float(5.43, 5));
2407          $this->assertEquals('5X43', format_float(5.43, 5, true, true));
2408  
2409          // Localisation off.
2410          $this->assertEquals('5.43000', format_float(5.43, 5, false));
2411          $this->assertEquals('5.43', format_float(5.43, 5, false, true));
2412  
2413          // Tests with tilde as localised decimal separator.
2414          $this->define_local_decimal_separator('~');
2415  
2416          // Must also work for '~' as decimal separator.
2417          $this->assertEquals('5', format_float(5.0001, 3, true, true));
2418          $this->assertEquals('5~43000', format_float(5.43, 5));
2419          $this->assertEquals('5~43', format_float(5.43, 5, true, true));
2420      }
2421  
2422      /**
2423       * Test localised float unformatting.
2424       */
2425      public function test_unformat_float() {
2426  
2427          // Tests without the localised decimal separator.
2428  
2429          // Special case for null, empty or white spaces only strings.
2430          $this->assertEquals(null, unformat_float(null));
2431          $this->assertEquals(null, unformat_float(''));
2432          $this->assertEquals(null, unformat_float('    '));
2433  
2434          // Regular use.
2435          $this->assertEquals(5.4, unformat_float('5.4'));
2436          $this->assertEquals(5.4, unformat_float('5.4', true));
2437  
2438          // No decimal.
2439          $this->assertEquals(5.0, unformat_float('5'));
2440  
2441          // Custom number of decimal.
2442          $this->assertEquals(5.43267, unformat_float('5.43267'));
2443  
2444          // Empty decimal.
2445          $this->assertEquals(100.0, unformat_float('100.00'));
2446  
2447          // With the thousand separator.
2448          $this->assertEquals(1000.0, unformat_float('1 000'));
2449          $this->assertEquals(1000.32, unformat_float('1 000.32'));
2450  
2451          // Negative number.
2452          $this->assertEquals(-100.0, unformat_float('-100'));
2453  
2454          // Wrong value.
2455          $this->assertEquals(0.0, unformat_float('Wrong value'));
2456          // Wrong value in strict mode.
2457          $this->assertFalse(unformat_float('Wrong value', true));
2458  
2459          // Combining options.
2460          $this->assertEquals(-1023.862567, unformat_float('   -1 023.862567     '));
2461  
2462          // Bad decimal separator (should crop the decimal).
2463          $this->assertEquals(50.0, unformat_float('50,57'));
2464          // Bad decimal separator in strict mode (should return false).
2465          $this->assertFalse(unformat_float('50,57', true));
2466  
2467          // Tests with a localised decimal separator.
2468          $this->define_local_decimal_separator();
2469  
2470          // We repeat the tests above but with the current decimal separator.
2471  
2472          // Regular use without and with the localised separator.
2473          $this->assertEquals (5.4, unformat_float('5.4'));
2474          $this->assertEquals (5.4, unformat_float('5X4'));
2475  
2476          // Custom number of decimal.
2477          $this->assertEquals (5.43267, unformat_float('5X43267'));
2478  
2479          // Empty decimal.
2480          $this->assertEquals (100.0, unformat_float('100X00'));
2481  
2482          // With the thousand separator.
2483          $this->assertEquals (1000.32, unformat_float('1 000X32'));
2484  
2485          // Bad different separator (should crop the decimal).
2486          $this->assertEquals (50.0, unformat_float('50Y57'));
2487          // Bad different separator in strict mode (should return false).
2488          $this->assertFalse (unformat_float('50Y57', true));
2489  
2490          // Combining options.
2491          $this->assertEquals (-1023.862567, unformat_float('   -1 023X862567     '));
2492          // Combining options in strict mode.
2493          $this->assertEquals (-1023.862567, unformat_float('   -1 023X862567     ', true));
2494      }
2495  
2496      /**
2497       * Test deleting of users.
2498       */
2499      public function test_delete_user() {
2500          global $DB, $CFG;
2501  
2502          $this->resetAfterTest();
2503  
2504          $guest = $DB->get_record('user', array('id'=>$CFG->siteguest), '*', MUST_EXIST);
2505          $admin = $DB->get_record('user', array('id'=>$CFG->siteadmins), '*', MUST_EXIST);
2506          $this->assertEquals(0, $DB->count_records('user', array('deleted'=>1)));
2507  
2508          $user = $this->getDataGenerator()->create_user(array('idnumber'=>'abc'));
2509          $user2 = $this->getDataGenerator()->create_user(array('idnumber'=>'xyz'));
2510          $usersharedemail1 = $this->getDataGenerator()->create_user(array('email' => 'sharedemail@example.invalid'));
2511          $usersharedemail2 = $this->getDataGenerator()->create_user(array('email' => 'sharedemail@example.invalid'));
2512          $useremptyemail1 = $this->getDataGenerator()->create_user(array('email' => ''));
2513          $useremptyemail2 = $this->getDataGenerator()->create_user(array('email' => ''));
2514  
2515          // Delete user and capture event.
2516          $sink = $this->redirectEvents();
2517          $result = delete_user($user);
2518          $events = $sink->get_events();
2519          $sink->close();
2520          $event = array_pop($events);
2521  
2522          // Test user is deleted in DB.
2523          $this->assertTrue($result);
2524          $deluser = $DB->get_record('user', array('id'=>$user->id), '*', MUST_EXIST);
2525          $this->assertEquals(1, $deluser->deleted);
2526          $this->assertEquals(0, $deluser->picture);
2527          $this->assertSame('', $deluser->idnumber);
2528          $this->assertSame(md5($user->username), $deluser->email);
2529          $this->assertMatchesRegularExpression('/^'.preg_quote($user->email, '/').'\.\d*$/', $deluser->username);
2530  
2531          $this->assertEquals(1, $DB->count_records('user', array('deleted'=>1)));
2532  
2533          // Test Event.
2534          $this->assertInstanceOf('\core\event\user_deleted', $event);
2535          $this->assertSame($user->id, $event->objectid);
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->assertEventContextNotUsed($event);
3318      }
3319  
3320      /**
3321       * A data provider for testing email messageid
3322       */
3323      public function generate_email_messageid_provider() {
3324          return array(
3325              'nopath' => array(
3326                  'wwwroot' => 'http://www.example.com',
3327                  'ids' => array(
3328                      'a-custom-id' => '<a-custom-id@www.example.com>',
3329                      'an-id-with-/-a-slash' => '<an-id-with-%2F-a-slash@www.example.com>',
3330                  ),
3331              ),
3332              'path' => array(
3333                  'wwwroot' => 'http://www.example.com/path/subdir',
3334                  'ids' => array(
3335                      'a-custom-id' => '<a-custom-id/path/subdir@www.example.com>',
3336                      'an-id-with-/-a-slash' => '<an-id-with-%2F-a-slash/path/subdir@www.example.com>',
3337                  ),
3338              ),
3339          );
3340      }
3341  
3342      /**
3343       * Test email message id generation
3344       *
3345       * @dataProvider generate_email_messageid_provider
3346       *
3347       * @param string $wwwroot The wwwroot
3348       * @param array $msgids An array of msgid local parts and the final result
3349       */
3350      public function test_generate_email_messageid($wwwroot, $msgids) {
3351          global $CFG;
3352  
3353          $this->resetAfterTest();
3354          $CFG->wwwroot = $wwwroot;
3355  
3356          foreach ($msgids as $local => $final) {
3357              $this->assertEquals($final, generate_email_messageid($local));
3358          }
3359      }
3360  
3361      /**
3362       * Test email with custom headers
3363       */
3364      public function test_send_email_with_custom_header() {
3365          global $DB, $CFG;
3366          $this->preventResetByRollback();
3367          $this->resetAfterTest();
3368  
3369          $touser = $this->getDataGenerator()->create_user();
3370          $fromuser = $this->getDataGenerator()->create_user();
3371          $fromuser->customheaders = 'X-Custom-Header: foo';
3372  
3373          set_config('allowedemaildomains', 'example.com');
3374          set_config('emailheaders', 'X-Fixed-Header: bar');
3375  
3376          $sink = $this->redirectEmails();
3377          email_to_user($touser, $fromuser, 'subject', 'message');
3378  
3379          $emails = $sink->get_messages();
3380          $this->assertCount(1, $emails);
3381          $email = reset($emails);
3382          $this->assertStringContainsString('X-Custom-Header: foo', $email->header);
3383          $this->assertStringContainsString("X-Fixed-Header: bar", $email->header);
3384          $sink->clear();
3385      }
3386  
3387      /**
3388       * A data provider for testing email diversion
3389       */
3390      public function diverted_emails_provider() {
3391          return array(
3392              'nodiverts' => array(
3393                  'divertallemailsto' => null,
3394                  'divertallemailsexcept' => null,
3395                  array(
3396                      'foo@example.com',
3397                      'test@real.com',
3398                      'fred.jones@example.com',
3399                      'dev1@dev.com',
3400                      'fred@example.com',
3401                      'fred+verp@example.com',
3402                  ),
3403                  false,
3404              ),
3405              'alldiverts' => array(
3406                  'divertallemailsto' => 'somewhere@elsewhere.com',
3407                  'divertallemailsexcept' => null,
3408                  array(
3409                      'foo@example.com',
3410                      'test@real.com',
3411                      'fred.jones@example.com',
3412                      'dev1@dev.com',
3413                      'fred@example.com',
3414                      'fred+verp@example.com',
3415                  ),
3416                  true,
3417              ),
3418              'alsodiverts' => array(
3419                  'divertallemailsto' => 'somewhere@elsewhere.com',
3420                  'divertallemailsexcept' => '@dev.com, fred(\+.*)?@example.com',
3421                  array(
3422                      'foo@example.com',
3423                      'test@real.com',
3424                      'fred.jones@example.com',
3425                      'Fred.Jones@Example.com',
3426                  ),
3427                  true,
3428              ),
3429              'divertsexceptions' => array(
3430                  'divertallemailsto' => 'somewhere@elsewhere.com',
3431                  'divertallemailsexcept' => '@dev.com, fred(\+.*)?@example.com',
3432                  array(
3433                      'dev1@dev.com',
3434                      'fred@example.com',
3435                      'Fred@Example.com',
3436                      'fred+verp@example.com',
3437                  ),
3438                  false,
3439              ),
3440              'divertsexceptionsnewline' => array(
3441                  'divertallemailsto' => 'somewhere@elsewhere.com',
3442                  'divertallemailsexcept' => "@dev.com\nfred(\+.*)?@example.com",
3443                  array(
3444                      'dev1@dev.com',
3445                      'fred@example.com',
3446                      'fred+verp@example.com',
3447                  ),
3448                  false,
3449              ),
3450              'alsodivertsnewline' => array(
3451                  'divertallemailsto' => 'somewhere@elsewhere.com',
3452                  'divertallemailsexcept' => "@dev.com\nfred(\+.*)?@example.com",
3453                  array(
3454                      'foo@example.com',
3455                      'test@real.com',
3456                      'fred.jones@example.com',
3457                  ),
3458                  true,
3459              ),
3460              'alsodivertsblankline' => array(
3461                  'divertallemailsto' => 'somewhere@elsewhere.com',
3462                  'divertallemailsexcept' => "@dev.com\n",
3463                  [
3464                      'lionel@example.com',
3465                  ],
3466                  true,
3467              ),
3468              'divertsexceptionblankline' => array(
3469                  'divertallemailsto' => 'somewhere@elsewhere.com',
3470                  'divertallemailsexcept' => "@example.com\n",
3471                  [
3472                      'lionel@example.com',
3473                  ],
3474                  false,
3475              ),
3476          );
3477      }
3478  
3479      /**
3480       * Test email diversion
3481       *
3482       * @dataProvider diverted_emails_provider
3483       *
3484       * @param string $divertallemailsto An optional email address
3485       * @param string $divertallemailsexcept An optional exclusion list
3486       * @param array $addresses An array of test addresses
3487       * @param boolean $expected Expected result
3488       */
3489      public function test_email_should_be_diverted($divertallemailsto, $divertallemailsexcept, $addresses, $expected) {
3490          global $CFG;
3491  
3492          $this->resetAfterTest();
3493          $CFG->divertallemailsto = $divertallemailsto;
3494          $CFG->divertallemailsexcept = $divertallemailsexcept;
3495  
3496          foreach ($addresses as $address) {
3497              $this->assertEquals($expected, email_should_be_diverted($address));
3498          }
3499      }
3500  
3501      public function test_email_to_user() {
3502          global $CFG;
3503  
3504          $this->resetAfterTest();
3505  
3506          $user1 = $this->getDataGenerator()->create_user(array('maildisplay' => 1, 'mailformat' => 0));
3507          $user2 = $this->getDataGenerator()->create_user(array('maildisplay' => 1, 'mailformat' => 1));
3508          $user3 = $this->getDataGenerator()->create_user(array('maildisplay' => 0));
3509          set_config('allowedemaildomains', "example.com\r\nmoodle.org");
3510  
3511          $subject = 'subject';
3512          $messagetext = 'message text';
3513          $subject2 = 'subject 2';
3514          $messagetext2 = '<b>message text 2</b>';
3515  
3516          // Close the default email sink.
3517          $sink = $this->redirectEmails();
3518          $sink->close();
3519  
3520          $CFG->noemailever = true;
3521          $this->assertNotEmpty($CFG->noemailever);
3522          email_to_user($user1, $user2, $subject, $messagetext);
3523          $this->assertDebuggingCalled('Not sending email due to $CFG->noemailever config setting');
3524  
3525          unset_config('noemailever');
3526  
3527          email_to_user($user1, $user2, $subject, $messagetext);
3528          $this->assertDebuggingCalled('Unit tests must not send real emails! Use $this->redirectEmails()');
3529  
3530          $sink = $this->redirectEmails();
3531          email_to_user($user1, $user2, $subject, $messagetext);
3532          email_to_user($user2, $user1, $subject2, $messagetext2);
3533          $this->assertSame(2, $sink->count());
3534          $result = $sink->get_messages();
3535          $this->assertCount(2, $result);
3536          $sink->close();
3537  
3538          $this->assertSame($subject, $result[0]->subject);
3539          $this->assertSame($messagetext, trim($result[0]->body));
3540          $this->assertSame($user1->email, $result[0]->to);
3541          $this->assertSame($user2->email, $result[0]->from);
3542          $this->assertStringContainsString('Content-Type: text/plain', $result[0]->header);
3543  
3544          $this->assertSame($subject2, $result[1]->subject);
3545          $this->assertStringContainsString($messagetext2, quoted_printable_decode($result[1]->body));
3546          $this->assertSame($user2->email, $result[1]->to);
3547          $this->assertSame($user1->email, $result[1]->from);
3548          $this->assertStringNotContainsString('Content-Type: text/plain', $result[1]->header);
3549  
3550          email_to_user($user1, $user2, $subject, $messagetext);
3551          $this->assertDebuggingCalled('Unit tests must not send real emails! Use $this->redirectEmails()');
3552  
3553          // Test that an empty noreplyaddress will default to a no-reply address.
3554          $sink = $this->redirectEmails();
3555          email_to_user($user1, $user3, $subject, $messagetext);
3556          $result = $sink->get_messages();
3557          $this->assertEquals($CFG->noreplyaddress, $result[0]->from);
3558          $sink->close();
3559          set_config('noreplyaddress', '');
3560          $sink = $this->redirectEmails();
3561          email_to_user($user1, $user3, $subject, $messagetext);
3562          $result = $sink->get_messages();
3563          $this->assertEquals('noreply@www.example.com', $result[0]->from);
3564          $sink->close();
3565  
3566          // Test $CFG->allowedemaildomains.
3567          set_config('noreplyaddress', 'noreply@www.example.com');
3568          $this->assertNotEmpty($CFG->allowedemaildomains);
3569          $sink = $this->redirectEmails();
3570          email_to_user($user1, $user2, $subject, $messagetext);
3571          unset_config('allowedemaildomains');
3572          email_to_user($user1, $user2, $subject, $messagetext);
3573          $result = $sink->get_messages();
3574          $this->assertNotEquals($CFG->noreplyaddress, $result[0]->from);
3575          $this->assertEquals($CFG->noreplyaddress, $result[1]->from);
3576          $sink->close();
3577  
3578          // Try to send an unsafe attachment, we should see an error message in the eventual mail body.
3579          $attachment = '../test.txt';
3580          $attachname = 'txt';
3581  
3582          $sink = $this->redirectEmails();
3583          email_to_user($user1, $user2, $subject, $messagetext, '', $attachment, $attachname);
3584          $this->assertSame(1, $sink->count());
3585          $result = $sink->get_messages();
3586          $this->assertCount(1, $result);
3587          $this->assertStringContainsString('error.txt', $result[0]->body);
3588          $this->assertStringContainsString('Error in attachment.  User attempted to attach a filename with a unsafe name.', $result[0]->body);
3589          $sink->close();
3590      }
3591  
3592      /**
3593       * Data provider for {@see test_email_to_user_attachment}
3594       *
3595       * @return array
3596       */
3597      public function email_to_user_attachment_provider(): array {
3598          global $CFG;
3599  
3600          // Return all paths that can be used to send attachments from.
3601          return [
3602              'cachedir' => [$CFG->cachedir],
3603              'dataroot' => [$CFG->dataroot],
3604              'dirroot' => [$CFG->dirroot],
3605              'localcachedir' => [$CFG->localcachedir],
3606              'tempdir' => [$CFG->tempdir],
3607              // Paths within $CFG->localrequestdir.
3608              'localrequestdir_request_directory' => [make_request_directory()],
3609              'localrequestdir_request_storage_directory' => [get_request_storage_directory()],
3610              // Pass null to indicate we want to test a path relative to $CFG->dataroot.
3611              'relative' => [null]
3612          ];
3613      }
3614  
3615      /**
3616       * Test sending attachments with email_to_user
3617       *
3618       * @param string|null $filedir
3619       *
3620       * @dataProvider email_to_user_attachment_provider
3621       */
3622      public function test_email_to_user_attachment(?string $filedir): void {
3623          global $CFG;
3624  
3625          // If $filedir is null, then write our test file to $CFG->dataroot.
3626          $filepath = ($filedir ?: $CFG->dataroot) . '/hello.txt';
3627          file_put_contents($filepath, 'Hello');
3628  
3629          $user = \core_user::get_support_user();
3630          $message = 'Test attachment path';
3631  
3632          // Create sink to catch all sent e-mails.
3633          $sink = $this->redirectEmails();
3634  
3635          // Attachment path will be that of the test file if $filedir was passed, otherwise the relative path from $CFG->dataroot.
3636          $filename = basename($filepath);
3637          $attachmentpath = $filedir ? $filepath : $filename;
3638          email_to_user($user, $user, $message, $message, $message, $attachmentpath, $filename);
3639  
3640          $messages = $sink->get_messages();
3641          $sink->close();
3642  
3643          $this->assertCount(1, $messages);
3644  
3645          // Verify attachment in message body (attachment is in MIME format, but we can detect some Content fields).
3646          $messagebody = reset($messages)->body;
3647          $this->assertStringContainsString('Content-Type: text/plain; name=' . $filename, $messagebody);
3648          $this->assertStringContainsString('Content-Disposition: attachment; filename=' . $filename, $messagebody);
3649  
3650          // Cleanup.
3651          unlink($filepath);
3652      }
3653  
3654      /**
3655       * Test sending an attachment that doesn't exist to email_to_user
3656       */
3657      public function test_email_to_user_attachment_missing(): void {
3658          $user = \core_user::get_support_user();
3659          $message = 'Test attachment path';
3660  
3661          // Create sink to catch all sent e-mails.
3662          $sink = $this->redirectEmails();
3663  
3664          $attachmentpath = '/hola/hello.txt';
3665          $filename = basename($attachmentpath);
3666          email_to_user($user, $user, $message, $message, $message, $attachmentpath, $filename);
3667  
3668          $messages = $sink->get_messages();
3669          $sink->close();
3670  
3671          $this->assertCount(1, $messages);
3672  
3673          // Verify attachment not in message body (attachment is in MIME format, but we can detect some Content fields).
3674          $messagebody = reset($messages)->body;
3675          $this->assertStringNotContainsString('Content-Type: text/plain; name="' . $filename . '"', $messagebody);
3676          $this->assertStringNotContainsString('Content-Disposition: attachment; filename=' . $filename, $messagebody);
3677      }
3678  
3679      /**
3680       * Test setnew_password_and_mail.
3681       */
3682      public function test_setnew_password_and_mail() {
3683          global $DB, $CFG;
3684  
3685          $this->resetAfterTest();
3686  
3687          $user = $this->getDataGenerator()->create_user();
3688  
3689          // Update user password.
3690          $sink = $this->redirectEvents();
3691          $sink2 = $this->redirectEmails(); // Make sure we are redirecting emails.
3692          setnew_password_and_mail($user);
3693          $events = $sink->get_events();
3694          $sink->close();
3695          $sink2->close();
3696          $event = array_pop($events);
3697  
3698          // Test updated value.
3699          $dbuser = $DB->get_record('user', array('id' => $user->id));
3700          $this->assertSame($user->firstname, $dbuser->firstname);
3701          $this->assertNotEmpty($dbuser->password);
3702  
3703          // Test event.
3704          $this->assertInstanceOf('\core\event\user_password_updated', $event);
3705          $this->assertSame($user->id, $event->relateduserid);
3706          $this->assertEquals(\context_user::instance($user->id), $event->get_context());
3707          $this->assertEventContextNotUsed($event);
3708      }
3709  
3710      /**
3711       * Data provider for test_generate_confirmation_link
3712       * @return Array of confirmation urls and expected resultant confirmation links
3713       */
3714      public function generate_confirmation_link_provider() {
3715          global $CFG;
3716          return [
3717              "Simple name" => [
3718                  "username" => "simplename",
3719                  "confirmationurl" => null,
3720                  "expected" => $CFG->wwwroot . "/login/confirm.php?data=/simplename"
3721              ],
3722              "Period in between words in username" => [
3723                  "username" => "period.inbetween",
3724                  "confirmationurl" => null,
3725                  "expected" => $CFG->wwwroot . "/login/confirm.php?data=/period%2Einbetween"
3726              ],
3727              "Trailing periods in username" => [
3728                  "username" => "trailingperiods...",
3729                  "confirmationurl" => null,
3730                  "expected" => $CFG->wwwroot . "/login/confirm.php?data=/trailingperiods%2E%2E%2E"
3731              ],
3732              "At symbol in username" => [
3733                  "username" => "at@symbol",
3734                  "confirmationurl" => null,
3735                  "expected" => $CFG->wwwroot . "/login/confirm.php?data=/at%40symbol"
3736              ],
3737              "Dash symbol in username" => [
3738                  "username" => "has-dash",
3739                  "confirmationurl" => null,
3740                  "expected" => $CFG->wwwroot . "/login/confirm.php?data=/has-dash"
3741              ],
3742              "Underscore in username" => [
3743                  "username" => "under_score",
3744                  "confirmationurl" => null,
3745                  "expected" => $CFG->wwwroot . "/login/confirm.php?data=/under_score"
3746              ],
3747              "Many different characters in username" => [
3748                  "username" => "many_-.@characters@_@-..-..",
3749                  "confirmationurl" => null,
3750                  "expected" => $CFG->wwwroot . "/login/confirm.php?data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E"
3751              ],
3752              "Custom relative confirmation url" => [
3753                  "username" => "many_-.@characters@_@-..-..",
3754                  "confirmationurl" => "/custom/local/url.php",
3755                  "expected" => $CFG->wwwroot . "/custom/local/url.php?data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E"
3756              ],
3757              "Custom relative confirmation url with parameters" => [
3758                  "username" => "many_-.@characters@_@-..-..",
3759                  "confirmationurl" => "/custom/local/url.php?with=param",
3760                  "expected" => $CFG->wwwroot . "/custom/local/url.php?with=param&data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E"
3761              ],
3762              "Custom local confirmation url" => [
3763                  "username" => "many_-.@characters@_@-..-..",
3764                  "confirmationurl" => $CFG->wwwroot . "/custom/local/url.php",
3765                  "expected" => $CFG->wwwroot . "/custom/local/url.php?data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E"
3766              ],
3767              "Custom local confirmation url with parameters" => [
3768                  "username" => "many_-.@characters@_@-..-..",
3769                  "confirmationurl" => $CFG->wwwroot . "/custom/local/url.php?with=param",
3770                  "expected" => $CFG->wwwroot . "/custom/local/url.php?with=param&data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E"
3771              ],
3772              "Custom external confirmation url" => [
3773                  "username" => "many_-.@characters@_@-..-..",
3774                  "confirmationurl" => "http://moodle.org/custom/external/url.php",
3775                  "expected" => "http://moodle.org/custom/external/url.php?data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E"
3776              ],
3777              "Custom external confirmation url with parameters" => [
3778                  "username" => "many_-.@characters@_@-..-..",
3779                  "confirmationurl" => "http://moodle.org/ext.php?with=some&param=eters",
3780                  "expected" => "http://moodle.org/ext.php?with=some&param=eters&data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E"
3781              ],
3782              "Custom external confirmation url with parameters" => [
3783                  "username" => "many_-.@characters@_@-..-..",
3784                  "confirmationurl" => "http://moodle.org/ext.php?with=some&data=test",
3785                  "expected" => "http://moodle.org/ext.php?with=some&data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E"
3786              ],
3787          ];
3788      }
3789  
3790      /**
3791       * Test generate_confirmation_link
3792       * @dataProvider generate_confirmation_link_provider
3793       * @param string $username The name of the user
3794       * @param string $confirmationurl The url the user should go to to confirm
3795       * @param string $expected The expected url of the confirmation link
3796       */
3797      public function test_generate_confirmation_link($username, $confirmationurl, $expected) {
3798          $this->resetAfterTest();
3799          $sink = $this->redirectEmails();
3800  
3801          $user = $this->getDataGenerator()->create_user(
3802              [
3803                  "username" => $username,
3804                  "confirmed" => 0,
3805                  "email" => 'test@example.com',
3806              ]
3807          );
3808  
3809          send_confirmation_email($user, $confirmationurl);
3810          $sink->close();
3811          $messages = $sink->get_messages();
3812          $message = array_shift($messages);
3813          $messagebody = quoted_printable_decode($message->body);
3814  
3815          $this->assertStringContainsString($expected, $messagebody);
3816      }
3817  
3818      /**
3819       * Test generate_confirmation_link with custom admin link
3820       */
3821      public function test_generate_confirmation_link_with_custom_admin() {
3822          global $CFG;
3823  
3824          $this->resetAfterTest();
3825          $sink = $this->redirectEmails();
3826  
3827          $admin = $CFG->admin;
3828          $CFG->admin = 'custom/admin/path';
3829  
3830          $user = $this->getDataGenerator()->create_user(
3831              [
3832                  "username" => "many_-.@characters@_@-..-..",
3833                  "confirmed" => 0,
3834                  "email" => 'test@example.com',
3835              ]
3836          );
3837          $confirmationurl = "/admin/test.php?with=params";
3838          $expected = $CFG->wwwroot . "/" . $CFG->admin . "/test.php?with=params&data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E";
3839  
3840          send_confirmation_email($user, $confirmationurl);
3841          $sink->close();
3842          $messages = $sink->get_messages();
3843          $message = array_shift($messages);
3844          $messagebody = quoted_printable_decode($message->body);
3845  
3846          $sink->close();
3847          $this->assertStringContainsString($expected, $messagebody);
3848  
3849          $CFG->admin = $admin;
3850      }
3851  
3852  
3853      /**
3854       * Test remove_course_content deletes course contents
3855       * TODO Add asserts to verify other data related to course is deleted as well.
3856       */
3857      public function test_remove_course_contents() {
3858  
3859          $this->resetAfterTest();
3860  
3861          $course = $this->getDataGenerator()->create_course();
3862          $user = $this->getDataGenerator()->create_user();
3863          $gen = $this->getDataGenerator()->get_plugin_generator('core_notes');
3864          $note = $gen->create_instance(array('courseid' => $course->id, 'userid' => $user->id));
3865  
3866          $this->assertNotEquals(false, note_load($note->id));
3867          remove_course_contents($course->id, false);
3868          $this->assertFalse(note_load($note->id));
3869      }
3870  
3871      /**
3872       * Test function username_load_fields_from_object().
3873       */
3874      public function test_username_load_fields_from_object() {
3875          $this->resetAfterTest();
3876  
3877          // This object represents the information returned from an sql query.
3878          $userinfo = new \stdClass();
3879          $userinfo->userid = 1;
3880          $userinfo->username = 'loosebruce';
3881          $userinfo->firstname = 'Bruce';
3882          $userinfo->lastname = 'Campbell';
3883          $userinfo->firstnamephonetic = 'ブルース';
3884          $userinfo->lastnamephonetic = 'カンベッル';
3885          $userinfo->middlename = '';
3886          $userinfo->alternatename = '';
3887          $userinfo->email = '';
3888          $userinfo->picture = 23;
3889          $userinfo->imagealt = 'Michael Jordan draining another basket.';
3890          $userinfo->idnumber = 3982;
3891  
3892          // Just user name fields.
3893          $user = new \stdClass();
3894          $user = username_load_fields_from_object($user, $userinfo);
3895          $expectedarray = new \stdClass();
3896          $expectedarray->firstname = 'Bruce';
3897          $expectedarray->lastname = 'Campbell';
3898          $expectedarray->firstnamephonetic = 'ブルース';
3899          $expectedarray->lastnamephonetic = 'カンベッル';
3900          $expectedarray->middlename = '';
3901          $expectedarray->alternatename = '';
3902          $this->assertEquals($user, $expectedarray);
3903  
3904          // User information for showing a picture.
3905          $user = new \stdClass();
3906          $additionalfields = explode(',', implode(',', \core_user\fields::get_picture_fields()));
3907          $user = username_load_fields_from_object($user, $userinfo, null, $additionalfields);
3908          $user->id = $userinfo->userid;
3909          $expectedarray = new \stdClass();
3910          $expectedarray->id = 1;
3911          $expectedarray->firstname = 'Bruce';
3912          $expectedarray->lastname = 'Campbell';
3913          $expectedarray->firstnamephonetic = 'ブルース';
3914          $expectedarray->lastnamephonetic = 'カンベッル';
3915          $expectedarray->middlename = '';
3916          $expectedarray->alternatename = '';
3917          $expectedarray->email = '';
3918          $expectedarray->picture = 23;
3919          $expectedarray->imagealt = 'Michael Jordan draining another basket.';
3920          $this->assertEquals($user, $expectedarray);
3921  
3922          // Alter the userinfo object to have a prefix.
3923          $userinfo->authorfirstname = 'Bruce';
3924          $userinfo->authorlastname = 'Campbell';
3925          $userinfo->authorfirstnamephonetic = 'ブルース';
3926          $userinfo->authorlastnamephonetic = 'カンベッル';
3927          $userinfo->authormiddlename = '';
3928          $userinfo->authorpicture = 23;
3929          $userinfo->authorimagealt = 'Michael Jordan draining another basket.';
3930          $userinfo->authoremail = 'test@example.com';
3931  
3932  
3933          // Return an object with user picture information.
3934          $user = new \stdClass();
3935          $additionalfields = explode(',', implode(',', \core_user\fields::get_picture_fields()));
3936          $user = username_load_fields_from_object($user, $userinfo, 'author', $additionalfields);
3937          $user->id = $userinfo->userid;
3938          $expectedarray = new \stdClass();
3939          $expectedarray->id = 1;
3940          $expectedarray->firstname = 'Bruce';
3941          $expectedarray->lastname = 'Campbell';
3942          $expectedarray->firstnamephonetic = 'ブルース';
3943          $expectedarray->lastnamephonetic = 'カンベッル';
3944          $expectedarray->middlename = '';
3945          $expectedarray->alternatename = '';
3946          $expectedarray->email = 'test@example.com';
3947          $expectedarray->picture = 23;
3948          $expectedarray->imagealt = 'Michael Jordan draining another basket.';
3949          $this->assertEquals($user, $expectedarray);
3950      }
3951  
3952      /**
3953       * Test function {@see count_words()}.
3954       *
3955       * @dataProvider count_words_testcases
3956       * @param int $expectedcount number of words in $string.
3957       * @param string $string the test string to count the words of.
3958       * @param int|null $format
3959       */
3960      public function test_count_words(int $expectedcount, string $string, $format = null): void {
3961          $this->assertEquals($expectedcount, count_words($string, $format),
3962              "'$string' with format '$format' does not match count $expectedcount");
3963      }
3964  
3965      /**
3966       * Data provider for {@see test_count_words}.
3967       *
3968       * @return array of test cases.
3969       */
3970      public function count_words_testcases(): array {
3971          // Copy-pasting example from MDL-64240.
3972          $copypasted = <<<EOT
3973  <p onclick="alert('boop');">Snoot is booped</p>
3974   <script>alert('Boop the snoot');</script>
3975   <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">
3976  EOT;
3977  
3978          // The counts here should match MS Word and Libre Office.
3979          return [
3980              [0, ''],
3981              [4, 'one two three four'],
3982              [1, "a'b"],
3983              [1, '1+1=2'],
3984              [1, ' one-sided '],
3985              [2, 'one&nbsp;two'],
3986              [1, 'email@example.com'],
3987              [2, 'first\part second/part'],
3988              [4, '<p>one two<br></br>three four</p>'],
3989              [4, '<p>one two<br>three four</p>'],
3990              [4, '<p>one two<br />three four</p>'], // XHTML style.
3991              [3, ' one ... three '],
3992              [1, 'just...one'],
3993              [3, ' one & three '],
3994              [1, 'just&one'],
3995              [2, 'em—dash'],
3996              [2, 'en–dash'],
3997              [4, '1³ £2 €3.45 $6,789'],
3998              [2, 'ブルース カンベッル'], // MS word counts this as 11, but we don't handle that yet.
3999              [4, '<p>one two</p><p>three four</p>'],
4000              [4, '<p>one two</p><p><br/></p><p>three four</p>'],
4001              [4, '<p>one</p><ul><li>two</li><li>three</li></ul><p>four.</p>'],
4002              [1, '<p>em<b>phas</b>is.</p>'],
4003              [1, '<p>em<i>phas</i>is.</p>'],
4004              [1, '<p>em<strong>phas</strong>is.</p>'],
4005              [1, '<p>em<em>phas</em>is.</p>'],
4006              [2, "one\ntwo"],
4007              [2, "one\rtwo"],
4008              [2, "one\ttwo"],
4009              [2, "one\vtwo"],
4010              [2, "one\ftwo"],
4011              [1, "SO<sub>4</sub><sup>2-</sup>"],
4012              [6, '4+4=8 i.e. O(1) a,b,c,d I’m black&blue_really'],
4013              [1, '<span>a</span><span>b</span>'],
4014              [1, '<span>a</span><span>b</span>', FORMAT_PLAIN],
4015              [1, '<span>a</span><span>b</span>', FORMAT_HTML],
4016              [1, '<span>a</span><span>b</span>', FORMAT_MOODLE],
4017              [1, '<span>a</span><span>b</span>', FORMAT_MARKDOWN],
4018              [1, 'aa <argh <bleh>pokus</bleh>'],
4019              [2, 'aa <argh <bleh>pokus</bleh>', FORMAT_HTML],
4020              [6, $copypasted],
4021              [6, $copypasted, FORMAT_PLAIN],
4022              [3, $copypasted, FORMAT_HTML],
4023              [3, $copypasted, FORMAT_MOODLE],
4024          ];
4025      }
4026  
4027      /**
4028       * Test function {@see count_letters()}.
4029       *
4030       * @dataProvider count_letters_testcases
4031       * @param int $expectedcount number of characters in $string.
4032       * @param string $string the test string to count the letters of.
4033       * @param int|null $format
4034       */
4035      public function test_count_letters(int $expectedcount, string $string, $format = null): void {
4036          $this->assertEquals($expectedcount, count_letters($string, $format),
4037              "'$string' with format '$format' does not match count $expectedcount");
4038      }
4039  
4040      /**
4041       * Data provider for {@see count_letters_testcases}.
4042       *
4043       * @return array of test cases.
4044       */
4045      public function count_letters_testcases(): array {
4046          return [
4047              [0, ''],
4048              [1, 'x'],
4049              [1, '&amp;'],
4050              [4, '<p>frog</p>'],
4051              [4, '<p>frog</p>', FORMAT_PLAIN],
4052              [4, '<p>frog</p>', FORMAT_MOODLE],
4053              [4, '<p>frog</p>', FORMAT_HTML],
4054              [4, '<p>frog</p>', FORMAT_MARKDOWN],
4055              [2, 'aa <argh <bleh>pokus</bleh>'],
4056              [7, 'aa <argh <bleh>pokus</bleh>', FORMAT_HTML],
4057          ];
4058      }
4059  
4060      /**
4061       * Tests the getremoteaddr() function.
4062       */
4063      public function test_getremoteaddr() {
4064          global $CFG;
4065  
4066          $this->resetAfterTest();
4067  
4068          $CFG->getremoteaddrconf = null; // Use default value, GETREMOTEADDR_SKIP_DEFAULT.
4069          $noip = getremoteaddr('1.1.1.1');
4070          $this->assertEquals('1.1.1.1', $noip);
4071  
4072          $remoteaddr = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : null;
4073          $_SERVER['REMOTE_ADDR'] = '127.0.0.1';
4074          $singleip = getremoteaddr();
4075          $this->assertEquals('127.0.0.1', $singleip);
4076  
4077          $_SERVER['REMOTE_ADDR'] = $remoteaddr; // Restore server value.
4078  
4079          $CFG->getremoteaddrconf = 0; // Don't skip any source.
4080          $noip = getremoteaddr('1.1.1.1');
4081          $this->assertEquals('1.1.1.1', $noip);
4082  
4083          // Populate all $_SERVER values to review order.
4084          $ipsources = [
4085              'HTTP_CLIENT_IP' => '2.2.2.2',
4086              'HTTP_X_FORWARDED_FOR' => '3.3.3.3',
4087              'REMOTE_ADDR' => '4.4.4.4',
4088          ];
4089          $originalvalues = [];
4090          foreach ($ipsources as $source => $ip) {
4091              $originalvalues[$source] = isset($_SERVER[$source]) ? $_SERVER[$source] : null; // Saving data to restore later.
4092              $_SERVER[$source] = $ip;
4093          }
4094  
4095          foreach ($ipsources as $source => $expectedip) {
4096              $ip = getremoteaddr();
4097              $this->assertEquals($expectedip, $ip);
4098              unset($_SERVER[$source]); // Removing the value so next time we get the following ip.
4099          }
4100  
4101          // Restore server values.
4102          foreach ($originalvalues as $source => $ip) {
4103              $_SERVER[$source] = $ip;
4104          }
4105  
4106          // All $_SERVER values have been removed, we should get the default again.
4107          $noip = getremoteaddr('1.1.1.1');
4108          $this->assertEquals('1.1.1.1', $noip);
4109  
4110          $CFG->getremoteaddrconf = GETREMOTEADDR_SKIP_HTTP_CLIENT_IP;
4111          $xforwardedfor = isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : null;
4112  
4113          $_SERVER['HTTP_X_FORWARDED_FOR'] = '';
4114          $noip = getremoteaddr('1.1.1.1');
4115          $this->assertEquals('1.1.1.1', $noip);
4116  
4117          $_SERVER['HTTP_X_FORWARDED_FOR'] = '';
4118          $noip = getremoteaddr();
4119          $this->assertEquals('0.0.0.0', $noip);
4120  
4121          $_SERVER['HTTP_X_FORWARDED_FOR'] = '127.0.0.1';
4122          $singleip = getremoteaddr();
4123          $this->assertEquals('127.0.0.1', $singleip);
4124  
4125          $_SERVER['HTTP_X_FORWARDED_FOR'] = '127.0.0.1,127.0.0.2';
4126          $twoip = getremoteaddr();
4127          $this->assertEquals('127.0.0.2', $twoip);
4128  
4129          $_SERVER['HTTP_X_FORWARDED_FOR'] = '127.0.0.1,127.0.0.2,127.0.0.3';
4130          $threeip = getremoteaddr();
4131          $this->assertEquals('127.0.0.3', $threeip);
4132  
4133          $_SERVER['HTTP_X_FORWARDED_FOR'] = '127.0.0.1,127.0.0.2:65535';
4134          $portip = getremoteaddr();
4135          $this->assertEquals('127.0.0.2', $portip);
4136  
4137          $_SERVER['HTTP_X_FORWARDED_FOR'] = '127.0.0.1,0:0:0:0:0:0:0:2';
4138          $portip = getremoteaddr();
4139          $this->assertEquals('0:0:0:0:0:0:0:2', $portip);
4140  
4141          $_SERVER['HTTP_X_FORWARDED_FOR'] = '127.0.0.1,0::2';
4142          $portip = getremoteaddr();
4143          $this->assertEquals('0:0:0:0:0:0:0:2', $portip);
4144  
4145          $_SERVER['HTTP_X_FORWARDED_FOR'] = '127.0.0.1,[0:0:0:0:0:0:0:2]:65535';
4146          $portip = getremoteaddr();
4147          $this->assertEquals('0:0:0:0:0:0:0:2', $portip);
4148  
4149          $_SERVER['HTTP_X_FORWARDED_FOR'] = $xforwardedfor;
4150  
4151      }
4152  
4153      /*
4154       * Test emulation of random_bytes() function.
4155       */
4156      public function test_random_bytes_emulate() {
4157          $result = random_bytes_emulate(10);
4158          $this->assertSame(10, strlen($result));
4159          $this->assertnotSame($result, random_bytes_emulate(10));
4160  
4161          $result = random_bytes_emulate(21);
4162          $this->assertSame(21, strlen($result));
4163          $this->assertnotSame($result, random_bytes_emulate(21));
4164  
4165          $result = random_bytes_emulate(666);
4166          $this->assertSame(666, strlen($result));
4167  
4168          $result = random_bytes_emulate(40);
4169          $this->assertSame(40, strlen($result));
4170  
4171          $this->assertDebuggingNotCalled();
4172  
4173          $result = random_bytes_emulate(0);
4174          $this->assertSame('', $result);
4175          $this->assertDebuggingCalled();
4176  
4177          $result = random_bytes_emulate(-1);
4178          $this->assertSame('', $result);
4179          $this->assertDebuggingCalled();
4180      }
4181  
4182      /**
4183       * Test function for creation of random strings.
4184       */
4185      public function test_random_string() {
4186          $pool = 'a-zA-Z0-9';
4187  
4188          $result = random_string(10);
4189          $this->assertSame(10, strlen($result));
4190          $this->assertMatchesRegularExpression('/^[' . $pool . ']+$/', $result);
4191          $this->assertNotSame($result, random_string(10));
4192  
4193          $result = random_string(21);
4194          $this->assertSame(21, strlen($result));
4195          $this->assertMatchesRegularExpression('/^[' . $pool . ']+$/', $result);
4196          $this->assertNotSame($result, random_string(21));
4197  
4198          $result = random_string(666);
4199          $this->assertSame(666, strlen($result));
4200          $this->assertMatchesRegularExpression('/^[' . $pool . ']+$/', $result);
4201  
4202          $result = random_string();
4203          $this->assertSame(15, strlen($result));
4204          $this->assertMatchesRegularExpression('/^[' . $pool . ']+$/', $result);
4205  
4206          $this->assertDebuggingNotCalled();
4207  
4208          $result = random_string(0);
4209          $this->assertSame('', $result);
4210          $this->assertDebuggingCalled();
4211  
4212          $result = random_string(-1);
4213          $this->assertSame('', $result);
4214          $this->assertDebuggingCalled();
4215      }
4216  
4217      /**
4218       * Test function for creation of complex random strings.
4219       */
4220      public function test_complex_random_string() {
4221          $pool = preg_quote('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789`~!@#%^&*()_+-=[];,./<>?:{} ', '/');
4222  
4223          $result = complex_random_string(10);
4224          $this->assertSame(10, strlen($result));
4225          $this->assertMatchesRegularExpression('/^[' . $pool . ']+$/', $result);
4226          $this->assertNotSame($result, complex_random_string(10));
4227  
4228          $result = complex_random_string(21);
4229          $this->assertSame(21, strlen($result));
4230          $this->assertMatchesRegularExpression('/^[' . $pool . ']+$/', $result);
4231          $this->assertNotSame($result, complex_random_string(21));
4232  
4233          $result = complex_random_string(666);
4234          $this->assertSame(666, strlen($result));
4235          $this->assertMatchesRegularExpression('/^[' . $pool . ']+$/', $result);
4236  
4237          $result = complex_random_string();
4238          $this->assertEqualsWithDelta(28, strlen($result), 4); // Expected length is 24 - 32.
4239          $this->assertMatchesRegularExpression('/^[' . $pool . ']+$/', $result);
4240  
4241          $this->assertDebuggingNotCalled();
4242  
4243          $result = complex_random_string(0);
4244          $this->assertSame('', $result);
4245          $this->assertDebuggingCalled();
4246  
4247          $result = complex_random_string(-1);
4248          $this->assertSame('', $result);
4249          $this->assertDebuggingCalled();
4250      }
4251  
4252      /**
4253       * Data provider for private ips.
4254       */
4255      public function data_private_ips() {
4256          return array(
4257              array('10.0.0.0'),
4258              array('172.16.0.0'),
4259              array('192.168.1.0'),
4260              array('fdfe:dcba:9876:ffff:fdc6:c46b:bb8f:7d4c'),
4261              array('fdc6:c46b:bb8f:7d4c:fdc6:c46b:bb8f:7d4c'),
4262              array('fdc6:c46b:bb8f:7d4c:0000:8a2e:0370:7334'),
4263              array('127.0.0.1'), // This has been buggy in past: https://bugs.php.net/bug.php?id=53150.
4264          );
4265      }
4266  
4267      /**
4268       * Checks ip_is_public returns false for private ips.
4269       *
4270       * @param string $ip the ipaddress to test
4271       * @dataProvider data_private_ips
4272       */
4273      public function test_ip_is_public_private_ips($ip) {
4274          $this->assertFalse(ip_is_public($ip));
4275      }
4276  
4277      /**
4278       * Data provider for public ips.
4279       */
4280      public function data_public_ips() {
4281          return array(
4282              array('2400:cb00:2048:1::8d65:71b3'),
4283              array('2400:6180:0:d0::1b:2001'),
4284              array('141.101.113.179'),
4285              array('123.45.67.178'),
4286          );
4287      }
4288  
4289      /**
4290       * Checks ip_is_public returns true for public ips.
4291       *
4292       * @param string $ip the ipaddress to test
4293       * @dataProvider data_public_ips
4294       */
4295      public function test_ip_is_public_public_ips($ip) {
4296          $this->assertTrue(ip_is_public($ip));
4297      }
4298  
4299      /**
4300       * Test the function can_send_from_real_email_address
4301       *
4302       * @param string $email Email address for the from user.
4303       * @param int $display The user's email display preference.
4304       * @param bool $samecourse Are the users in the same course?
4305       * @param string $config The CFG->allowedemaildomains config values
4306       * @param bool $result The expected result.
4307       * @dataProvider data_can_send_from_real_email_address
4308       */
4309      public function test_can_send_from_real_email_address($email, $display, $samecourse, $config, $result) {
4310          $this->resetAfterTest();
4311  
4312          $fromuser = $this->getDataGenerator()->create_user();
4313          $touser = $this->getDataGenerator()->create_user();
4314          $course = $this->getDataGenerator()->create_course();
4315          set_config('allowedemaildomains', $config);
4316  
4317          $fromuser->email = $email;
4318          $fromuser->maildisplay = $display;
4319          if ($samecourse) {
4320              $this->getDataGenerator()->enrol_user($fromuser->id, $course->id, 'student');
4321              $this->getDataGenerator()->enrol_user($touser->id, $course->id, 'student');
4322          } else {
4323              $this->getDataGenerator()->enrol_user($fromuser->id, $course->id, 'student');
4324          }
4325          $this->assertEquals($result, can_send_from_real_email_address($fromuser, $touser));
4326      }
4327  
4328      /**
4329       * Data provider for test_can_send_from_real_email_address.
4330       *
4331       * @return array Returns an array of test data for the above function.
4332       */
4333      public function data_can_send_from_real_email_address() {
4334          return [
4335              // Test from email is in allowed domain.
4336              // Test that from display is set to show no one.
4337              [
4338                  'email' => 'fromuser@example.com',
4339                  'display' => \core_user::MAILDISPLAY_HIDE,
4340                  'samecourse' => false,
4341                  'config' => "example.com\r\ntest.com",
4342                  'result' => false
4343              ],
4344              // Test that from display is set to course members only (course member).
4345              [
4346                  'email' => 'fromuser@example.com',
4347                  'display' => \core_user::MAILDISPLAY_COURSE_MEMBERS_ONLY,
4348                  'samecourse' => true,
4349                  'config' => "example.com\r\ntest.com",
4350                  'result' => true
4351              ],
4352              // Test that from display is set to course members only (Non course member).
4353              [
4354                  'email' => 'fromuser@example.com',
4355                  'display' => \core_user::MAILDISPLAY_COURSE_MEMBERS_ONLY,
4356                  'samecourse' => false,
4357                  'config' => "example.com\r\ntest.com",
4358                  'result' => false
4359              ],
4360              // Test that from display is set to show everyone.
4361              [
4362                  'email' => 'fromuser@example.com',
4363                  'display' => \core_user::MAILDISPLAY_EVERYONE,
4364                  'samecourse' => false,
4365                  'config' => "example.com\r\ntest.com",
4366                  'result' => true
4367              ],
4368              // Test a few different config value formats for parsing correctness.
4369              [
4370                  'email' => 'fromuser@example.com',
4371                  'display' => \core_user::MAILDISPLAY_EVERYONE,
4372                  'samecourse' => false,
4373                  'config' => "\n test.com\nexample.com \n",
4374                  'result' => true
4375              ],
4376              [
4377                  'email' => 'fromuser@example.com',
4378                  'display' => \core_user::MAILDISPLAY_EVERYONE,
4379                  'samecourse' => false,
4380                  'config' => "\r\n example.com \r\n test.com \r\n",
4381                  'result' => true
4382              ],
4383              [
4384                  'email' => 'fromuser@EXAMPLE.com',
4385                  'display' => \core_user::MAILDISPLAY_EVERYONE,
4386                  'samecourse' => false,
4387                  'config' => "example.com\r\ntest.com",
4388                  'result' => true,
4389              ],
4390              // Test from email is not in allowed domain.
4391              // Test that from display is set to show no one.
4392              [   'email' => 'fromuser@moodle.com',
4393                  'display' => \core_user::MAILDISPLAY_HIDE,
4394                  'samecourse' => false,
4395                  'config' => "example.com\r\ntest.com",
4396                  'result' => false
4397              ],
4398              // Test that from display is set to course members only (course member).
4399              [   'email' => 'fromuser@moodle.com',
4400                  'display' => \core_user::MAILDISPLAY_COURSE_MEMBERS_ONLY,
4401                  'samecourse' => true,
4402                  'config' => "example.com\r\ntest.com",
4403                  'result' => false
4404              ],
4405              // Test that from display is set to course members only (Non course member.
4406              [   'email' => 'fromuser@moodle.com',
4407                  'display' => \core_user::MAILDISPLAY_COURSE_MEMBERS_ONLY,
4408                  'samecourse' => false,
4409                  'config' => "example.com\r\ntest.com",
4410                  'result' => false
4411              ],
4412              // Test that from display is set to show everyone.
4413              [   'email' => 'fromuser@moodle.com',
4414                  'display' => \core_user::MAILDISPLAY_EVERYONE,
4415                  'samecourse' => false,
4416                  'config' => "example.com\r\ntest.com",
4417                  'result' => false
4418              ],
4419              // Test a few erroneous config value and confirm failure.
4420              [   'email' => 'fromuser@moodle.com',
4421                  'display' => \core_user::MAILDISPLAY_EVERYONE,
4422                  'samecourse' => false,
4423                  'config' => "\r\n   \r\n",
4424                  'result' => false
4425              ],
4426              [   'email' => 'fromuser@moodle.com',
4427                  'display' => \core_user::MAILDISPLAY_EVERYONE,
4428                  'samecourse' => false,
4429                  'config' => " \n   \n \n ",
4430                  'result' => false
4431              ],
4432          ];
4433      }
4434  
4435      /**
4436       * Test that generate_email_processing_address() returns valid email address.
4437       */
4438      public function test_generate_email_processing_address() {
4439          global $CFG;
4440          $this->resetAfterTest();
4441  
4442          $data = (object)[
4443              'id' => 42,
4444              'email' => 'my.email+from_moodle@example.com',
4445          ];
4446  
4447          $modargs = 'B'.base64_encode(pack('V', $data->id)).substr(md5($data->email), 0, 16);
4448  
4449          $CFG->maildomain = 'example.com';
4450          $CFG->mailprefix = 'mdl+';
4451          $this->assertTrue(validate_email(generate_email_processing_address(0, $modargs)));
4452  
4453          $CFG->maildomain = 'mail.example.com';
4454          $CFG->mailprefix = 'mdl-';
4455          $this->assertTrue(validate_email(generate_email_processing_address(23, $modargs)));
4456      }
4457  
4458      /**
4459       * Test allowemailaddresses setting.
4460       *
4461       * @param string $email Email address for the from user.
4462       * @param string $config The CFG->allowemailaddresses config values
4463       * @param false/string $result The expected result.
4464       *
4465       * @dataProvider data_email_is_not_allowed_for_allowemailaddresses
4466       */
4467      public function test_email_is_not_allowed_for_allowemailaddresses($email, $config, $result) {
4468          $this->resetAfterTest();
4469  
4470          set_config('allowemailaddresses', $config);
4471          $this->assertEquals($result, email_is_not_allowed($email));
4472      }
4473  
4474      /**
4475       * Data provider for data_email_is_not_allowed_for_allowemailaddresses.
4476       *
4477       * @return array Returns an array of test data for the above function.
4478       */
4479      public function data_email_is_not_allowed_for_allowemailaddresses() {
4480          return [
4481              // Test allowed domain empty list.
4482              [
4483                  'email' => 'fromuser@example.com',
4484                  'config' => '',
4485                  'result' => false
4486              ],
4487              // Test from email is in allowed domain.
4488              [
4489                  'email' => 'fromuser@example.com',
4490                  'config' => 'example.com test.com',
4491                  'result' => false
4492              ],
4493              // Test from email is in allowed domain but uppercase config.
4494              [
4495                  'email' => 'fromuser@example.com',
4496                  'config' => 'EXAMPLE.com test.com',
4497                  'result' => false
4498              ],
4499              // Test from email is in allowed domain but uppercase email.
4500              [
4501                  'email' => 'fromuser@EXAMPLE.com',
4502                  'config' => 'example.com test.com',
4503                  'result' => false
4504              ],
4505              // Test from email is in allowed subdomain.
4506              [
4507                  'email' => 'fromuser@something.example.com',
4508                  'config' => '.example.com test.com',
4509                  'result' => false
4510              ],
4511              // Test from email is in allowed subdomain but uppercase config.
4512              [
4513                  'email' => 'fromuser@something.example.com',
4514                  'config' => '.EXAMPLE.com test.com',
4515                  'result' => false
4516              ],
4517              // Test from email is in allowed subdomain but uppercase email.
4518              [
4519                  'email' => 'fromuser@something.EXAMPLE.com',
4520                  'config' => '.example.com test.com',
4521                  'result' => false
4522              ],
4523              // Test from email is not in allowed domain.
4524              [   'email' => 'fromuser@moodle.com',
4525                  'config' => 'example.com test.com',
4526                  'result' => get_string('emailonlyallowed', '', 'example.com test.com')
4527              ],
4528              // Test from email is not in allowed subdomain.
4529              [   'email' => 'fromuser@something.example.com',
4530                  'config' => 'example.com test.com',
4531                  'result' => get_string('emailonlyallowed', '', 'example.com test.com')
4532              ],
4533          ];
4534      }
4535  
4536      /**
4537       * Test denyemailaddresses setting.
4538       *
4539       * @param string $email Email address for the from user.
4540       * @param string $config The CFG->denyemailaddresses config values
4541       * @param false/string $result The expected result.
4542       *
4543       * @dataProvider data_email_is_not_allowed_for_denyemailaddresses
4544       */
4545      public function test_email_is_not_allowed_for_denyemailaddresses($email, $config, $result) {
4546          $this->resetAfterTest();
4547  
4548          set_config('denyemailaddresses', $config);
4549          $this->assertEquals($result, email_is_not_allowed($email));
4550      }
4551  
4552  
4553      /**
4554       * Data provider for test_email_is_not_allowed_for_denyemailaddresses.
4555       *
4556       * @return array Returns an array of test data for the above function.
4557       */
4558      public function data_email_is_not_allowed_for_denyemailaddresses() {
4559          return [
4560              // Test denied domain empty list.
4561              [
4562                  'email' => 'fromuser@example.com',
4563                  'config' => '',
4564                  'result' => false
4565              ],
4566              // Test from email is in denied domain.
4567              [
4568                  'email' => 'fromuser@example.com',
4569                  'config' => 'example.com test.com',
4570                  'result' => get_string('emailnotallowed', '', 'example.com test.com')
4571              ],
4572              // Test from email is in denied domain but uppercase config.
4573              [
4574                  'email' => 'fromuser@example.com',
4575                  'config' => 'EXAMPLE.com test.com',
4576                  'result' => get_string('emailnotallowed', '', 'EXAMPLE.com test.com')
4577              ],
4578              // Test from email is in denied domain but uppercase email.
4579              [
4580                  'email' => 'fromuser@EXAMPLE.com',
4581                  'config' => 'example.com test.com',
4582                  'result' => get_string('emailnotallowed', '', 'example.com test.com')
4583              ],
4584              // Test from email is in denied subdomain.
4585              [
4586                  'email' => 'fromuser@something.example.com',
4587                  'config' => '.example.com test.com',
4588                  'result' => get_string('emailnotallowed', '', '.example.com test.com')
4589              ],
4590              // Test from email is in denied subdomain but uppercase config.
4591              [
4592                  'email' => 'fromuser@something.example.com',
4593                  'config' => '.EXAMPLE.com test.com',
4594                  'result' => get_string('emailnotallowed', '', '.EXAMPLE.com test.com')
4595              ],
4596              // Test from email is in denied subdomain but uppercase email.
4597              [
4598                  'email' => 'fromuser@something.EXAMPLE.com',
4599                  'config' => '.example.com test.com',
4600                  'result' => get_string('emailnotallowed', '', '.example.com test.com')
4601              ],
4602              // Test from email is not in denied domain.
4603              [   'email' => 'fromuser@moodle.com',
4604                  'config' => 'example.com test.com',
4605                  'result' => false
4606              ],
4607              // Test from email is not in denied subdomain.
4608              [   'email' => 'fromuser@something.example.com',
4609                  'config' => 'example.com test.com',
4610                  'result' => false
4611              ],
4612          ];
4613      }
4614  
4615      /**
4616       * Test safe method unserialize_array().
4617       */
4618      public function test_unserialize_array() {
4619          $a = [1, 2, 3];
4620          $this->assertEquals($a, unserialize_array(serialize($a)));
4621          $a = ['a' => 1, 2 => 2, 'b' => 'cde'];
4622          $this->assertEquals($a, unserialize_array(serialize($a)));
4623          $a = ['a' => 1, 2 => 2, 'b' => 'c"d"e'];
4624          $this->assertEquals($a, unserialize_array(serialize($a)));
4625          $a = ['a' => 1, 2 => ['c' => 'd', 'e' => 'f'], 'b' => 'cde'];
4626          $this->assertEquals($a, unserialize_array(serialize($a)));
4627          $a = ['a' => 1, 2 => ['c' => 'd', 'e' => ['f' => 'g']], 'b' => 'cde'];
4628          $this->assertEquals($a, unserialize_array(serialize($a)));
4629          $a = ['a' => 1, 2 => 2, 'b' => 'c"d";e'];
4630          $this->assertEquals($a, unserialize_array(serialize($a)));
4631  
4632          // Can not unserialize if there are any objects.
4633          $a = (object)['a' => 1, 2 => 2, 'b' => 'cde'];
4634          $this->assertFalse(unserialize_array(serialize($a)));
4635          $a = ['a' => 1, 2 => 2, 'b' => (object)['a' => 'cde']];
4636          $this->assertFalse(unserialize_array(serialize($a)));
4637          $a = ['a' => 1, 2 => 2, 'b' => ['c' => (object)['a' => 'cde']]];
4638          $this->assertFalse(unserialize_array(serialize($a)));
4639          $a = ['a' => 1, 2 => 2, 'b' => ['c' => new lang_string('no')]];
4640          $this->assertFalse(unserialize_array(serialize($a)));
4641  
4642          // Array used in the grader report.
4643          $a = array('aggregatesonly' => [51, 34], 'gradesonly' => [21, 45, 78]);
4644          $this->assertEquals($a, unserialize_array(serialize($a)));
4645      }
4646  
4647      /**
4648       * Test method for safely unserializing a serialized object of type stdClass
4649       */
4650      public function test_unserialize_object(): void {
4651          $object = (object) [
4652              'foo' => 42,
4653              'bar' => 'Hamster',
4654              'innerobject' => (object) [
4655                  'baz' => 'happy',
4656              ],
4657          ];
4658  
4659          // We should get back the same object we serialized.
4660          $serializedobject = serialize($object);
4661          $this->assertEquals($object, unserialize_object($serializedobject));
4662  
4663          // Try serializing a different class, not allowed.
4664          $langstr = new lang_string('no');
4665          $serializedlangstr = serialize($langstr);
4666          $unserializedlangstr = unserialize_object($serializedlangstr);
4667          $this->assertInstanceOf(\stdClass::class, $unserializedlangstr);
4668      }
4669  
4670      /**
4671       * Test that the component_class_callback returns the correct default value when the class was not found.
4672       *
4673       * @dataProvider component_class_callback_default_provider
4674       * @param $default
4675       */
4676      public function test_component_class_callback_not_found($default) {
4677          $this->assertSame($default, component_class_callback('thisIsNotTheClassYouWereLookingFor', 'anymethod', [], $default));
4678      }
4679  
4680      /**
4681       * Test that the component_class_callback returns the correct default value when the class was not found.
4682       *
4683       * @dataProvider component_class_callback_default_provider
4684       * @param $default
4685       */
4686      public function test_component_class_callback_method_not_found($default) {
4687          require_once (__DIR__ . '/fixtures/component_class_callback_example.php');
4688  
4689          $this->assertSame($default, component_class_callback(test_component_class_callback_example::class, 'this_is_not_the_method_you_were_looking_for', ['abc'], $default));
4690      }
4691  
4692      /**
4693       * Test that the component_class_callback returns the default when the method returned null.
4694       *
4695       * @dataProvider component_class_callback_default_provider
4696       * @param $default
4697       */
4698      public function test_component_class_callback_found_returns_null($default) {
4699          require_once (__DIR__ . '/fixtures/component_class_callback_example.php');
4700  
4701          $this->assertSame($default, component_class_callback(\test_component_class_callback_example::class, 'method_returns_value', [null], $default));
4702          $this->assertSame($default, component_class_callback(\test_component_class_callback_child_example::class, 'method_returns_value', [null], $default));
4703      }
4704  
4705      /**
4706       * Test that the component_class_callback returns the expected value and not the default when there was a value.
4707       *
4708       * @dataProvider component_class_callback_data_provider
4709       * @param $default
4710       */
4711      public function test_component_class_callback_found_returns_value($value) {
4712          require_once (__DIR__ . '/fixtures/component_class_callback_example.php');
4713  
4714          $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'));
4715          $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'));
4716      }
4717  
4718      /**
4719       * Test that the component_class_callback handles multiple params correctly.
4720       *
4721       * @dataProvider component_class_callback_multiple_params_provider
4722       * @param $default
4723       */
4724      public function test_component_class_callback_found_accepts_multiple($params, $count) {
4725          require_once (__DIR__ . '/fixtures/component_class_callback_example.php');
4726  
4727          $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'));
4728          $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'));
4729      }
4730  
4731      /**
4732       * Data provider with list of default values for user in component_class_callback tests.
4733       *
4734       * @return array
4735       */
4736      public function component_class_callback_default_provider() {
4737          return [
4738              'null' => [null],
4739              'empty string' => [''],
4740              'string' => ['This is a string'],
4741              'int' => [12345],
4742              'stdClass' => [(object) ['this is my content']],
4743              'array' => [['a' => 'b',]],
4744          ];
4745      }
4746  
4747      /**
4748       * Data provider with list of default values for user in component_class_callback tests.
4749       *
4750       * @return array
4751       */
4752      public function component_class_callback_data_provider() {
4753          return [
4754              'empty string' => [''],
4755              'string' => ['This is a string'],
4756              'int' => [12345],
4757              'stdClass' => [(object) ['this is my content']],
4758              'array' => [['a' => 'b',]],
4759          ];
4760      }
4761  
4762      /**
4763       * Data provider with list of default values for user in component_class_callback tests.
4764       *
4765       * @return array
4766       */
4767      public function component_class_callback_multiple_params_provider() {
4768          return [
4769              'empty array' => [
4770                  [],
4771                  0,
4772              ],
4773              'string value' => [
4774                  ['one'],
4775                  1,
4776              ],
4777              'string values' => [
4778                  ['one', 'two'],
4779                  2,
4780              ],
4781              'arrays' => [
4782                  [[], []],
4783                  2,
4784              ],
4785              'nulls' => [
4786                  [null, null, null, null],
4787                  4,
4788              ],
4789              'mixed' => [
4790                  ['a', 1, null, (object) [], []],
4791                  5,
4792              ],
4793          ];
4794      }
4795  
4796      /**
4797       * Test that {@link get_callable_name()} describes the callable as expected.
4798       *
4799       * @dataProvider callable_names_provider
4800       * @param callable $callable
4801       * @param string $expectedname
4802       */
4803      public function test_get_callable_name($callable, $expectedname) {
4804          $this->assertSame($expectedname, get_callable_name($callable));
4805      }
4806  
4807      /**
4808       * Provides a set of callables and their human readable names.
4809       *
4810       * @return array of (string)case => [(mixed)callable, (string|bool)expected description]
4811       */
4812      public function callable_names_provider() {
4813          return [
4814              'integer' => [
4815                  386,
4816                  false,
4817              ],
4818              'boolean' => [
4819                  true,
4820                  false,
4821              ],
4822              'static_method_as_literal' => [
4823                  'my_foobar_class::my_foobar_method',
4824                  'my_foobar_class::my_foobar_method',
4825              ],
4826              'static_method_of_literal_class' => [
4827                  ['my_foobar_class', 'my_foobar_method'],
4828                  'my_foobar_class::my_foobar_method',
4829              ],
4830              'static_method_of_object' => [
4831                  [$this, 'my_foobar_method'],
4832                  'core\moodlelib_test::my_foobar_method',
4833              ],
4834              'method_of_object' => [
4835                  [new lang_string('parentlanguage', 'core_langconfig'), 'my_foobar_method'],
4836                  'lang_string::my_foobar_method',
4837              ],
4838              'function_as_literal' => [
4839                  'my_foobar_callback',
4840                  'my_foobar_callback',
4841              ],
4842              'function_as_closure' => [
4843                  function($a) { return $a; },
4844                  'Closure::__invoke',
4845              ],
4846          ];
4847      }
4848  
4849      /**
4850       * Data provider for \core_moodlelib_testcase::test_get_complete_user_data().
4851       *
4852       * @return array
4853       */
4854      public function user_data_provider() {
4855          return [
4856              'Fetch data using a valid username' => [
4857                  'username', 's1', true
4858              ],
4859              'Fetch data using a valid username, different case' => [
4860                  'username', 'S1', true
4861              ],
4862              'Fetch data using a valid username, different case for fieldname and value' => [
4863                  'USERNAME', 'S1', true
4864              ],
4865              'Fetch data using an invalid username' => [
4866                  'username', 's2', false
4867              ],
4868              'Fetch by email' => [
4869                  'email', 's1@example.com', true
4870              ],
4871              'Fetch data using a non-existent email' => [
4872                  'email', 's2@example.com', false
4873              ],
4874              'Fetch data using a non-existent email, throw exception' => [
4875                  'email', 's2@example.com', false, \dml_missing_record_exception::class
4876              ],
4877              'Multiple accounts with the same email' => [
4878                  'email', 's1@example.com', false, 1
4879              ],
4880              'Multiple accounts with the same email, throw exception' => [
4881                  'email', 's1@example.com', false, 1, \dml_multiple_records_exception::class
4882              ],
4883              'Fetch data using a valid user ID' => [
4884                  'id', true, true
4885              ],
4886              'Fetch data using a non-existent user ID' => [
4887                  'id', false, false
4888              ],
4889          ];
4890      }
4891  
4892      /**
4893       * Test for get_complete_user_data().
4894       *
4895       * @dataProvider user_data_provider
4896       * @param string $field The field to use for the query.
4897       * @param string|boolean $value The field value. When fetching by ID, set true to fetch valid user ID, false otherwise.
4898       * @param boolean $success Whether we expect for the fetch to succeed or return false.
4899       * @param int $allowaccountssameemail Value for $CFG->allowaccountssameemail.
4900       * @param string $expectedexception The exception to be expected.
4901       */
4902      public function test_get_complete_user_data($field, $value, $success, $allowaccountssameemail = 0, $expectedexception = '') {
4903          $this->resetAfterTest();
4904  
4905          // Set config settings we need for our environment.
4906          set_config('allowaccountssameemail', $allowaccountssameemail);
4907  
4908          // Generate the user data.
4909          $generator = $this->getDataGenerator();
4910          $userdata = [
4911              'username' => 's1',
4912              'email' => 's1@example.com',
4913          ];
4914          $user = $generator->create_user($userdata);
4915  
4916          if ($allowaccountssameemail) {
4917              // Create another user with the same email address.
4918              $generator->create_user(['email' => 's1@example.com']);
4919          }
4920  
4921          // Since the data provider can't know what user ID to use, do a special handling for ID field tests.
4922          if ($field === 'id') {
4923              if ($value) {
4924                  // Test for fetching data using a valid user ID. Use the generated user's ID.
4925                  $value = $user->id;
4926              } else {
4927                  // Test for fetching data using a non-existent user ID.
4928                  $value = $user->id + 1;
4929              }
4930          }
4931  
4932          // When an exception is expected.
4933          $throwexception = false;
4934          if ($expectedexception) {
4935              $this->expectException($expectedexception);
4936              $throwexception = true;
4937          }
4938  
4939          $fetcheduser = get_complete_user_data($field, $value, null, $throwexception);
4940          if ($success) {
4941              $this->assertEquals($user->id, $fetcheduser->id);
4942              $this->assertEquals($user->username, $fetcheduser->username);
4943              $this->assertEquals($user->email, $fetcheduser->email);
4944          } else {
4945              $this->assertFalse($fetcheduser);
4946          }
4947      }
4948  
4949      /**
4950       * Test for send_password_change_().
4951       */
4952      public function test_send_password_change_info() {
4953          $this->resetAfterTest();
4954  
4955          $user = $this->getDataGenerator()->create_user();
4956  
4957          $sink = $this->redirectEmails(); // Make sure we are redirecting emails.
4958          send_password_change_info($user);
4959          $result = $sink->get_messages();
4960          $sink->close();
4961  
4962          $this->assertStringContainsString('passwords cannot be reset on this site', quoted_printable_decode($result[0]->body));
4963      }
4964  
4965      /**
4966       * Test the get_time_interval_string for a range of inputs.
4967       *
4968       * @dataProvider get_time_interval_string_provider
4969       * @param int $time1 the time1 param.
4970       * @param int $time2 the time2 param.
4971       * @param string|null $format the format param.
4972       * @param string $expected the expected string.
4973       */
4974      public function test_get_time_interval_string(int $time1, int $time2, ?string $format, string $expected) {
4975          if (is_null($format)) {
4976              $this->assertEquals($expected, get_time_interval_string($time1, $time2));
4977          } else {
4978              $this->assertEquals($expected, get_time_interval_string($time1, $time2, $format));
4979          }
4980      }
4981  
4982      /**
4983       * Data provider for the test_get_time_interval_string() method.
4984       */
4985      public function get_time_interval_string_provider() {
4986          return [
4987              'Time is after the reference time by 1 minute, omitted format' => [
4988                  'time1' => 12345660,
4989                  'time2' => 12345600,
4990                  'format' => null,
4991                  'expected' => '0d 0h 1m'
4992              ],
4993              'Time is before the reference time by 1 minute, omitted format' => [
4994                  'time1' => 12345540,
4995                  'time2' => 12345600,
4996                  'format' => null,
4997                  'expected' => '0d 0h 1m'
4998              ],
4999              'Time is equal to the reference time, omitted format' => [
5000                  'time1' => 12345600,
5001                  'time2' => 12345600,
5002                  'format' => null,
5003                  'expected' => '0d 0h 0m'
5004              ],
5005              'Time is after the reference time by 1 minute, empty string format' => [
5006                  'time1' => 12345660,
5007                  'time2' => 12345600,
5008                  'format' => '',
5009                  'expected' => '0d 0h 1m'
5010              ],
5011              'Time is before the reference time by 1 minute, empty string format' => [
5012                  'time1' => 12345540,
5013                  'time2' => 12345600,
5014                  'format' => '',
5015                  'expected' => '0d 0h 1m'
5016              ],
5017              'Time is equal to the reference time, empty string format' => [
5018                  'time1' => 12345600,
5019                  'time2' => 12345600,
5020                  'format' => '',
5021                  'expected' => '0d 0h 0m'
5022              ],
5023              'Time is after the reference time by 1 minute, custom format' => [
5024                  'time1' => 12345660,
5025                  'time2' => 12345600,
5026                  'format' => '%R%adays %hhours %imins',
5027                  'expected' => '+0days 0hours 1mins'
5028              ],
5029              'Time is before the reference time by 1 minute, custom format' => [
5030                  'time1' => 12345540,
5031                  'time2' => 12345600,
5032                  'format' => '%R%adays %hhours %imins',
5033                  'expected' => '-0days 0hours 1mins'
5034              ],
5035              'Time is equal to the reference time, custom format' => [
5036                  'time1' => 12345600,
5037                  'time2' => 12345600,
5038                  'format' => '%R%adays %hhours %imins',
5039                  'expected' => '+0days 0hours 0mins'
5040              ],
5041          ];
5042      }
5043  
5044      /**
5045       * Tests the rename_to_unused_name function with a file.
5046       */
5047      public function test_rename_to_unused_name_file() {
5048          global $CFG;
5049  
5050          // Create a new file in dataroot.
5051          $file = $CFG->dataroot . '/argh.txt';
5052          file_put_contents($file, 'Frogs');
5053  
5054          // Rename it.
5055          $newname = rename_to_unused_name($file);
5056  
5057          // Check new name has expected format.
5058          $this->assertMatchesRegularExpression('~/_temp_[a-f0-9]+$~', $newname);
5059  
5060          // Check it's still in the same folder.
5061          $this->assertEquals($CFG->dataroot, dirname($newname));
5062  
5063          // Check file can be loaded.
5064          $this->assertEquals('Frogs', file_get_contents($newname));
5065  
5066          // OK, delete the file.
5067          unlink($newname);
5068      }
5069  
5070      /**
5071       * Tests the rename_to_unused_name function with a directory.
5072       */
5073      public function test_rename_to_unused_name_dir() {
5074          global $CFG;
5075  
5076          // Create a new directory in dataroot.
5077          $file = $CFG->dataroot . '/arghdir';
5078          mkdir($file);
5079  
5080          // Rename it.
5081          $newname = rename_to_unused_name($file);
5082  
5083          // Check new name has expected format.
5084          $this->assertMatchesRegularExpression('~/_temp_[a-f0-9]+$~', $newname);
5085  
5086          // Check it's still in the same folder.
5087          $this->assertEquals($CFG->dataroot, dirname($newname));
5088  
5089          // Check it's still a directory
5090          $this->assertTrue(is_dir($newname));
5091  
5092          // OK, delete the directory.
5093          rmdir($newname);
5094      }
5095  
5096      /**
5097       * Tests the rename_to_unused_name function with error cases.
5098       */
5099      public function test_rename_to_unused_name_failure() {
5100          global $CFG;
5101  
5102          // Rename a file that doesn't exist.
5103          $file = $CFG->dataroot . '/argh.txt';
5104          $this->assertFalse(rename_to_unused_name($file));
5105      }
5106  
5107      /**
5108       * Provider for display_size
5109       *
5110       * @return array of ($size, $expected)
5111       */
5112      public function display_size_provider() {
5113  
5114          return [
5115              [0, '0 bytes'],
5116              [1, '1 bytes'],
5117              [1023, '1023 bytes'],
5118              [1024, '1.0 KB'],
5119              [2222, '2.2 KB'],
5120              [33333, '32.6 KB'],
5121              [444444, '434.0 KB'],
5122              [5555555, '5.3 MB'],
5123              [66666666, '63.6 MB'],
5124              [777777777, '741.7 MB'],
5125              [8888888888, '8.3 GB'],
5126              [99999999999, '93.1 GB'],
5127              [111111111111, '103.5 GB'],
5128              [2222222222222, '2.0 TB'],
5129              [33333333333333, '30.3 TB'],
5130              [444444444444444, '404.2 TB'],
5131              [5555555555555555, '4.9 PB'],
5132              [66666666666666666, '59.2 PB'],
5133              [777777777777777777, '690.8 PB'],
5134          ];
5135      }
5136  
5137      /**
5138       * Test display_size
5139       * @dataProvider display_size_provider
5140       * @param int $size the size in bytes
5141       * @param string $expected the expected string.
5142       */
5143      public function test_display_size($size, $expected) {
5144          $result = display_size($size);
5145          $expected = str_replace(' ', "\xc2\xa0", $expected); // Should be non-breaking space.
5146          $this->assertEquals($expected, $result);
5147      }
5148  
5149      /**
5150       * Provider for display_size using fixed units.
5151       *
5152       * @return array of ($size, $units, $expected)
5153       */
5154      public function display_size_fixed_provider(): array {
5155          return [
5156              [0, 'KB', '0.0 KB'],
5157              [1, 'MB', '0.0 MB'],
5158              [777777777, 'GB', '0.7 GB'],
5159              [8888888888, 'PB', '0.0 PB'],
5160              [99999999999, 'TB', '0.1 TB'],
5161              [99999999999, 'B', '99999999999 bytes'],
5162          ];
5163      }
5164  
5165      /**
5166       * Test display_size using fixed units.
5167       *
5168       * @dataProvider display_size_fixed_provider
5169       * @param int $size Size in bytes
5170       * @param string $units Fixed units
5171       * @param string $expected Expected string.
5172       */
5173      public function test_display_size_fixed(int $size, string $units, string $expected): void {
5174          $result = display_size($size, 1, $units);
5175          $expected = str_replace(' ', "\xc2\xa0", $expected); // Should be non-breaking space.
5176          $this->assertEquals($expected, $result);
5177      }
5178  
5179      /**
5180       * Provider for display_size using specified decimal places.
5181       *
5182       * @return array of ($size, $decimalplaces, $units, $expected)
5183       */
5184      public function display_size_dp_provider(): array {
5185          return [
5186              [0, 1, 'KB', '0.0 KB'],
5187              [1, 6, 'MB', '0.000001 MB'],
5188              [777777777, 0, 'GB', '1 GB'],
5189              [777777777, 0, '', '742 MB'],
5190              [42, 6, '', '42 bytes'],
5191          ];
5192      }
5193  
5194      /**
5195       * Test display_size using specified decimal places.
5196       *
5197       * @dataProvider display_size_dp_provider
5198       * @param int $size Size in bytes
5199       * @param int $places Number of decimal places
5200       * @param string $units Fixed units
5201       * @param string $expected Expected string.
5202       */
5203      public function test_display_size_dp(int $size, int $places, string $units, string $expected): void {
5204          $result = display_size($size, $places, $units);
5205          $expected = str_replace(' ', "\xc2\xa0", $expected); // Should be non-breaking space.
5206          $this->assertEquals($expected, $result);
5207      }
5208  
5209      /**
5210       * Test that the get_list_of_plugins function includes/excludes directories as appropriate.
5211       *
5212       * @dataProvider get_list_of_plugins_provider
5213       * @param   array $expectedlist The expected list of folders
5214       * @param   array $content The list of file content to set up in the virtual file root
5215       * @param   string $dir The base dir to look at in the virtual file root
5216       * @param   string $exclude Any additional folder to exclude
5217       */
5218      public function test_get_list_of_plugins(array $expectedlist, array $content, string $dir, string $exclude): void {
5219          $vfileroot = \org\bovigo\vfs\vfsStream::setup('root', null, $content);
5220          $base = \org\bovigo\vfs\vfsStream::url('root');
5221  
5222          $this->assertEquals($expectedlist, get_list_of_plugins($dir, $exclude, $base));
5223      }
5224  
5225      /**
5226       * Data provider for get_list_of_plugins checks.
5227       *
5228       * @return  array
5229       */
5230      public function get_list_of_plugins_provider(): array {
5231          return [
5232              'Standard excludes' => [
5233                  ['amdd', 'class', 'local', 'test'],
5234                  [
5235                      '.' => [],
5236                      '..' => [],
5237                      'amd' => [],
5238                      'amdd' => [],
5239                      'class' => [],
5240                      'classes' => [],
5241                      'local' => [],
5242                      'test' => [],
5243                      'tests' => [],
5244                      'yui' => [],
5245                  ],
5246                  '',
5247                  '',
5248              ],
5249              'Standard excludes with addition' => [
5250                  ['amdd', 'local', 'test'],
5251                  [
5252                      '.' => [],
5253                      '..' => [],
5254                      'amd' => [],
5255                      'amdd' => [],
5256                      'class' => [],
5257                      'classes' => [],
5258                      'local' => [],
5259                      'test' => [],
5260                      'tests' => [],
5261                      'yui' => [],
5262                  ],
5263                  '',
5264                  'class',
5265              ],
5266              'Files excluded' => [
5267                  ['def'],
5268                  [
5269                      '.' => [],
5270                      '..' => [],
5271                      'abc' => 'File with filename abc',
5272                      'def' => [
5273                          '.' => [],
5274                          '..' => [],
5275                          'example.txt' => 'In a directory called "def"',
5276                      ],
5277                  ],
5278                  '',
5279                  '',
5280              ],
5281              'Subdirectories only' => [
5282                  ['abc'],
5283                  [
5284                      '.' => [],
5285                      '..' => [],
5286                      'foo' => [
5287                          '.' => [],
5288                          '..' => [],
5289                          'abc' => [],
5290                      ],
5291                      'bar' => [
5292                          '.' => [],
5293                          '..' => [],
5294                          'def' => [],
5295                      ],
5296                  ],
5297                  'foo',
5298                  '',
5299              ],
5300          ];
5301      }
5302  
5303      /**
5304       * Test get_home_page() method.
5305       *
5306       * @dataProvider get_home_page_provider
5307       * @param string $user Whether the user is logged, guest or not logged.
5308       * @param int $expected Expected value after calling the get_home_page method.
5309       * @param int $defaulthomepage The $CFG->defaulthomepage setting value.
5310       * @param int $enabledashboard Whether the dashboard should be enabled or not.
5311       * @param int $userpreference User preference for the home page setting.
5312       * @covers ::get_home_page
5313       */
5314      public function test_get_home_page(string $user, int $expected, ?int $defaulthomepage = null, ?int $enabledashboard = null,
5315              ?int $userpreference = null) {
5316          global $CFG, $USER;
5317  
5318          $this->resetAfterTest();
5319  
5320          if ($user == 'guest') {
5321              $this->setGuestUser();
5322          } else if ($user == 'logged') {
5323              $this->setUser($this->getDataGenerator()->create_user());
5324          }
5325  
5326          if (isset($defaulthomepage)) {
5327              $CFG->defaulthomepage = $defaulthomepage;
5328          }
5329          if (isset($enabledashboard)) {
5330              $CFG->enabledashboard = $enabledashboard;
5331          }
5332  
5333          if ($USER) {
5334              set_user_preferences(['user_home_page_preference' => $userpreference], $USER->id);
5335          }
5336  
5337          $homepage = get_home_page();
5338          $this->assertEquals($expected, $homepage);
5339      }
5340  
5341      /**
5342       * Data provider for get_home_page checks.
5343       *
5344       * @return array
5345       */
5346      public function get_home_page_provider(): array {
5347          return [
5348              'No logged user' => [
5349                  'user' => 'nologged',
5350                  'expected' => HOMEPAGE_SITE,
5351              ],
5352              'Guest user' => [
5353                  'user' => 'guest',
5354                  'expected' => HOMEPAGE_SITE,
5355              ],
5356              'Logged user. Dashboard set as default home page and enabled' => [
5357                  'user' => 'logged',
5358                  'expected' => HOMEPAGE_MY,
5359                  'defaulthomepage' => HOMEPAGE_MY,
5360                  'enabledashboard' => 1,
5361              ],
5362              'Logged user. Dashboard set as default home page but disabled' => [
5363                  'user' => 'logged',
5364                  'expected' => HOMEPAGE_MYCOURSES,
5365                  'defaulthomepage' => HOMEPAGE_MY,
5366                  'enabledashboard' => 0,
5367              ],
5368              'Logged user. My courses set as default home page with dashboard enabled' => [
5369                  'user' => 'logged',
5370                  'expected' => HOMEPAGE_MYCOURSES,
5371                  'defaulthomepage' => HOMEPAGE_MYCOURSES,
5372                  'enabledashboard' => 1,
5373              ],
5374              'Logged user. My courses set as default home page with dashboard disabled' => [
5375                  'user' => 'logged',
5376                  'expected' => HOMEPAGE_MYCOURSES,
5377                  'defaulthomepage' => HOMEPAGE_MYCOURSES,
5378                  'enabledashboard' => 0,
5379              ],
5380              'Logged user. Site set as default home page with dashboard enabled' => [
5381                  'user' => 'logged',
5382                  'expected' => HOMEPAGE_SITE,
5383                  'defaulthomepage' => HOMEPAGE_SITE,
5384                  'enabledashboard' => 1,
5385              ],
5386              'Logged user. Site set as default home page with dashboard disabled' => [
5387                  'user' => 'logged',
5388                  'expected' => HOMEPAGE_SITE,
5389                  'defaulthomepage' => HOMEPAGE_SITE,
5390                  'enabledashboard' => 0,
5391              ],
5392              'Logged user. User preference set as default page with dashboard enabled and user preference set to dashboard' => [
5393                  'user' => 'logged',
5394                  'expected' => HOMEPAGE_MY,
5395                  'defaulthomepage' => HOMEPAGE_USER,
5396                  'enabledashboard' => 1,
5397                  'userpreference' => HOMEPAGE_MY,
5398              ],
5399              'Logged user. User preference set as default page with dashboard disabled and user preference set to dashboard' => [
5400                  'user' => 'logged',
5401                  'expected' => HOMEPAGE_MYCOURSES,
5402                  'defaulthomepage' => HOMEPAGE_USER,
5403                  'enabledashboard' => 0,
5404                  'userpreference' => HOMEPAGE_MY,
5405              ],
5406              'Logged user. User preference set as default page with dashboard enabled and user preference set to my courses' => [
5407                  'user' => 'logged',
5408                  'expected' => HOMEPAGE_MYCOURSES,
5409                  'defaulthomepage' => HOMEPAGE_USER,
5410                  'enabledashboard' => 1,
5411                  'userpreference' => HOMEPAGE_MYCOURSES,
5412              ],
5413              'Logged user. User preference set as default page with dashboard disabled and user preference set to my courses' => [
5414                  'user' => 'logged',
5415                  'expected' => HOMEPAGE_MYCOURSES,
5416                  'defaulthomepage' => HOMEPAGE_USER,
5417                  'enabledashboard' => 0,
5418                  'userpreference' => HOMEPAGE_MYCOURSES,
5419              ],
5420          ];
5421      }
5422  
5423      /**
5424       * Test get_default_home_page() method.
5425       *
5426       * @covers ::get_default_home_page
5427       */
5428      public function test_get_default_home_page() {
5429          global $CFG;
5430  
5431          $this->resetAfterTest();
5432  
5433          $CFG->enabledashboard = 1;
5434          $default = get_default_home_page();
5435          $this->assertEquals(HOMEPAGE_MY, $default);
5436  
5437          $CFG->enabledashboard = 0;
5438          $default = get_default_home_page();
5439          $this->assertEquals(HOMEPAGE_MYCOURSES, $default);
5440      }
5441  
5442      /**
5443       * Tests the get_performance_info function with regard to locks.
5444       *
5445       * @covers ::get_performance_info
5446       */
5447      public function test_get_performance_info_locks(): void {
5448          global $PERF;
5449  
5450          // Unset lock data just in case previous tests have set it.
5451          unset($PERF->locks);
5452  
5453          // With no lock data, there should be no information about locks in the results.
5454          $result = get_performance_info();
5455          $this->assertStringNotContainsString('Lock', $result['html']);
5456          $this->assertStringNotContainsString('Lock', $result['txt']);
5457  
5458          // Rather than really do locks, just fill the array with fake data in the right format.
5459          $PERF->locks = [
5460              (object) [
5461                  'type' => 'phpunit',
5462                  'resource' => 'lock1',
5463                  'wait' => 0.59,
5464                  'success' => true,
5465                  'held' => '6.04'
5466              ], (object) [
5467                  'type' => 'phpunit',
5468                  'resource' => 'lock2',
5469                  'wait' => 0.91,
5470                  'success' => false
5471              ]
5472          ];
5473          $result = get_performance_info();
5474  
5475          // Extract HTML table rows.
5476          $this->assertEquals(1, preg_match('~<table class="locktimings.*?</table>~s',
5477                  $result['html'], $matches));
5478          $this->assertEquals(3, preg_match_all('~<tr[> ].*?</tr>~s', $matches[0], $matches2));
5479          $rows = $matches2[0];
5480  
5481          // Check header.
5482          $this->assertMatchesRegularExpression('~Lock.*Waited.*Obtained.*Held~s', $rows[0]);
5483          // Check both locks.
5484          $this->assertMatchesRegularExpression('~phpunit/lock1.*0\.6.*&#x2713;.*6\.0~s', $rows[1]);
5485          $this->assertMatchesRegularExpression('~phpunit/lock2.*0\.9.*&#x274c;.*-~s', $rows[2]);
5486  
5487          $this->assertStringContainsString('Locks (waited/obtained/held): ' .
5488                  'phpunit/lock1 (0.6/y/6.0) phpunit/lock2 (0.9/n/-).', $result['txt']);
5489      }
5490  
5491      /**
5492       * Tests the get_performance_info function with regard to session wait time.
5493       *
5494       * @covers ::get_performance_info
5495       */
5496      public function test_get_performance_info_session_wait(): void {
5497          global $PERF;
5498  
5499          // With no session lock data, there should be no session wait information in the results.
5500          unset($PERF->sessionlock);
5501          $result = get_performance_info();
5502          $this->assertStringNotContainsString('Session wait', $result['html']);
5503          $this->assertStringNotContainsString('sessionwait', $result['txt']);
5504  
5505          // With suitable data, it should be included in the result.
5506          $PERF->sessionlock = ['wait' => 4.2];
5507          $result = get_performance_info();
5508          $this->assertStringContainsString('Session wait: 4.200 secs', $result['html']);
5509          $this->assertStringContainsString('sessionwait: 4.200 secs', $result['txt']);
5510      }
5511  
5512      /**
5513       * Test the html_is_blank() function.
5514       *
5515       * @covers ::html_is_blank
5516       */
5517      public function test_html_is_blank() {
5518          $this->assertEquals(true, html_is_blank(null));
5519          $this->assertEquals(true, html_is_blank(''));
5520          $this->assertEquals(true, html_is_blank('<p> </p>'));
5521          $this->assertEquals(false, html_is_blank('<p>.</p>'));
5522          $this->assertEquals(false, html_is_blank('<img src="#">'));
5523      }
5524  
5525      /**
5526       * Provider for is_proxybypass
5527       *
5528       * @return array of test cases.
5529       */
5530      public function is_proxybypass_provider(): array {
5531  
5532          return [
5533              'Proxybypass contains the same IP as the beginning of the URL' => [
5534                  'http://192.168.5.5-fake-app-7f000101.nip.io',
5535                  '192.168.5.5, 127.0.0.1',
5536                  false
5537              ],
5538              'Proxybypass contains the last part of the URL' => [
5539                  'http://192.168.5.5-fake-app-7f000101.nip.io',
5540                  'app-7f000101.nip.io',
5541                  false
5542              ],
5543              'Proxybypass contains the last part of the URL 2' => [
5544                  'http://store.mydomain.com',
5545                  'mydomain.com',
5546                  false
5547              ],
5548              'Proxybypass contains part of the url' => [
5549                  'http://myweb.com',
5550                  'store.myweb.com',
5551                  false
5552              ],
5553              'Different IPs used in proxybypass' => [
5554                  'http://192.168.5.5',
5555                  '192.168.5.3',
5556                  false
5557              ],
5558              'Proxybypass and URL matchs' => [
5559                  'http://store.mydomain.com',
5560                  'store.mydomain.com',
5561                  true
5562              ],
5563              'IP used in proxybypass' => [
5564                  'http://192.168.5.5',
5565                  '192.168.5.5',
5566                  true
5567              ],
5568          ];
5569      }
5570  
5571      /**
5572       * Check if $url matches anything in proxybypass list
5573       *
5574       * Test function {@see is_proxybypass()}.
5575       * @dataProvider is_proxybypass_provider
5576       * @param string $url url to check
5577       * @param string $proxybypass
5578       * @param bool $expected Expected value.
5579       */
5580      public function test_is_proxybypass(string $url, string $proxybypass, bool $expected): void {
5581          $this->resetAfterTest();
5582  
5583          global $CFG;
5584          $CFG->proxyhost = '192.168.5.5'; // Test with a fake proxy.
5585          $CFG->proxybypass = $proxybypass;
5586  
5587          $this->assertEquals($expected, is_proxybypass($url));
5588      }
5589  
5590  }