Differences Between: [Versions 310 and 403] [Versions 311 and 403] [Versions 39 and 403] [Versions 400 and 403] [Versions 401 and 403] [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 © 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 break there"; 1013 $this->assertSame("some text which shouldn't ...", shorten_text($text, 31)); 1014 $this->assertSame("some text which shouldn't ...", 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> <<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> ...", 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 some critical TZ/DST. 1564 * 1565 * This method tests some special TZ/DST combinations that were fixed 1566 * by MDL-38999. The tests are done by comparing the results of the 1567 * output using Moodle TZ/DST support and PHP native one. 1568 * 1569 * Note: If you don't trust PHP TZ/DST support, can verify the 1570 * harcoded expectations below with: 1571 * http://www.tools4noobs.com/online_tools/unix_timestamp_to_datetime/ 1572 */ 1573 public function test_some_moodle_special_dst() { 1574 $stamp = 1365386400; // 2013/04/08 02:00:00 GMT/UTC. 1575 1576 // In Europe/Tallinn it was 2013/04/08 05:00:00. 1577 $expectation = '2013/04/08 05:00:00'; 1578 $phpdt = \DateTime::createFromFormat('U', $stamp, new \DateTimeZone('UTC')); 1579 $phpdt->setTimezone(new \DateTimeZone('Europe/Tallinn')); 1580 $phpres = $phpdt->format('Y/m/d H:i:s'); // PHP result. 1581 $moodleres = userdate($stamp, '%Y/%m/%d %H:%M:%S', 'Europe/Tallinn', false); // Moodle result. 1582 $this->assertSame($expectation, $phpres); 1583 $this->assertSame($expectation, $moodleres); 1584 1585 // In St. Johns it was 2013/04/07 23:30:00. 1586 $expectation = '2013/04/07 23:30:00'; 1587 $phpdt = \DateTime::createFromFormat('U', $stamp, new \DateTimeZone('UTC')); 1588 $phpdt->setTimezone(new \DateTimeZone('America/St_Johns')); 1589 $phpres = $phpdt->format('Y/m/d H:i:s'); // PHP result. 1590 $moodleres = userdate($stamp, '%Y/%m/%d %H:%M:%S', 'America/St_Johns', false); // Moodle result. 1591 $this->assertSame($expectation, $phpres); 1592 $this->assertSame($expectation, $moodleres); 1593 1594 $stamp = 1383876000; // 2013/11/08 02:00:00 GMT/UTC. 1595 1596 // In Europe/Tallinn it was 2013/11/08 04:00:00. 1597 $expectation = '2013/11/08 04:00:00'; 1598 $phpdt = \DateTime::createFromFormat('U', $stamp, new \DateTimeZone('UTC')); 1599 $phpdt->setTimezone(new \DateTimeZone('Europe/Tallinn')); 1600 $phpres = $phpdt->format('Y/m/d H:i:s'); // PHP result. 1601 $moodleres = userdate($stamp, '%Y/%m/%d %H:%M:%S', 'Europe/Tallinn', false); // Moodle result. 1602 $this->assertSame($expectation, $phpres); 1603 $this->assertSame($expectation, $moodleres); 1604 1605 // In St. Johns it was 2013/11/07 22:30:00. 1606 $expectation = '2013/11/07 22:30:00'; 1607 $phpdt = \DateTime::createFromFormat('U', $stamp, new \DateTimeZone('UTC')); 1608 $phpdt->setTimezone(new \DateTimeZone('America/St_Johns')); 1609 $phpres = $phpdt->format('Y/m/d H:i:s'); // PHP result. 1610 $moodleres = userdate($stamp, '%Y/%m/%d %H:%M:%S', 'America/St_Johns', false); // Moodle result. 1611 $this->assertSame($expectation, $phpres); 1612 $this->assertSame($expectation, $moodleres); 1613 } 1614 1615 public function test_userdate() { 1616 global $USER, $CFG, $DB; 1617 $this->resetAfterTest(); 1618 1619 $this->setAdminUser(); 1620 1621 $testvalues = array( 1622 array( 1623 'time' => '1309514400', 1624 'usertimezone' => 'America/Moncton', 1625 'timezone' => '0.0', // No dst offset. 1626 'expectedoutput' => 'Friday, 1 July 2011, 10:00 AM', 1627 'expectedoutputhtml' => '<time datetime="2011-07-01T07:00:00-03:00">Friday, 1 July 2011, 10:00 AM</time>' 1628 ), 1629 array( 1630 'time' => '1309514400', 1631 'usertimezone' => 'America/Moncton', 1632 'timezone' => '99', // Dst offset and timezone offset. 1633 'expectedoutput' => 'Friday, 1 July 2011, 7:00 AM', 1634 'expectedoutputhtml' => '<time datetime="2011-07-01T07:00:00-03:00">Friday, 1 July 2011, 7:00 AM</time>' 1635 ), 1636 array( 1637 'time' => '1309514400', 1638 'usertimezone' => 'America/Moncton', 1639 'timezone' => 'America/Moncton', // Dst offset and timezone offset. 1640 'expectedoutput' => 'Friday, 1 July 2011, 7:00 AM', 1641 'expectedoutputhtml' => '<time datetime="2011-07-01t07:00:00-03:00">Friday, 1 July 2011, 7:00 AM</time>' 1642 ), 1643 array( 1644 'time' => '1293876000 ', 1645 'usertimezone' => 'America/Moncton', 1646 'timezone' => '0.0', // No dst offset. 1647 'expectedoutput' => 'Saturday, 1 January 2011, 10:00 AM', 1648 'expectedoutputhtml' => '<time datetime="2011-01-01T06:00:00-04:00">Saturday, 1 January 2011, 10:00 AM</time>' 1649 ), 1650 array( 1651 'time' => '1293876000 ', 1652 'usertimezone' => 'America/Moncton', 1653 'timezone' => '99', // No dst offset in jan, so just timezone offset. 1654 'expectedoutput' => 'Saturday, 1 January 2011, 6:00 AM', 1655 'expectedoutputhtml' => '<time datetime="2011-01-01T06:00:00-04:00">Saturday, 1 January 2011, 6:00 AM</time>' 1656 ), 1657 array( 1658 'time' => '1293876000 ', 1659 'usertimezone' => 'America/Moncton', 1660 'timezone' => 'America/Moncton', // No dst offset in jan. 1661 'expectedoutput' => 'Saturday, 1 January 2011, 6:00 AM', 1662 'expectedoutputhtml' => '<time datetime="2011-01-01T06:00:00-04:00">Saturday, 1 January 2011, 6:00 AM</time>' 1663 ), 1664 array( 1665 'time' => '1293876000 ', 1666 'usertimezone' => '2', 1667 'timezone' => '99', // Take user timezone. 1668 'expectedoutput' => 'Saturday, 1 January 2011, 12:00 PM', 1669 'expectedoutputhtml' => '<time datetime="2011-01-01T12:00:00+02:00">Saturday, 1 January 2011, 12:00 PM</time>' 1670 ), 1671 array( 1672 'time' => '1293876000 ', 1673 'usertimezone' => '-2', 1674 'timezone' => '99', // Take user timezone. 1675 'expectedoutput' => 'Saturday, 1 January 2011, 8:00 AM', 1676 'expectedoutputhtml' => '<time datetime="2011-01-01T08:00:00-02:00">Saturday, 1 January 2011, 8:00 AM</time>' 1677 ), 1678 array( 1679 'time' => '1293876000 ', 1680 'usertimezone' => '-10', 1681 'timezone' => '2', // Take this timezone. 1682 'expectedoutput' => 'Saturday, 1 January 2011, 12:00 PM', 1683 'expectedoutputhtml' => '<time datetime="2011-01-01T00:00:00-10:00">Saturday, 1 January 2011, 12:00 PM</time>' 1684 ), 1685 array( 1686 'time' => '1293876000 ', 1687 'usertimezone' => '-10', 1688 'timezone' => '-2', // Take this timezone. 1689 'expectedoutput' => 'Saturday, 1 January 2011, 8:00 AM', 1690 'expectedoutputhtml' => '<time datetime="2011-01-01T00:00:00-10:00">Saturday, 1 January 2011, 8:00 AM</time>' 1691 ), 1692 array( 1693 'time' => '1293876000 ', 1694 'usertimezone' => '-10', 1695 'timezone' => 'random/time', // This should show server time. 1696 'expectedoutput' => 'Saturday, 1 January 2011, 6:00 PM', 1697 'expectedoutputhtml' => '<time datetime="2011-01-01T00:00:00-10:00">Saturday, 1 January 2011, 6:00 PM</time>' 1698 ), 1699 array( 1700 'time' => '1293876000 ', 1701 'usertimezone' => '20', // Fallback to server time zone. 1702 'timezone' => '99', // This should show user time. 1703 'expectedoutput' => 'Saturday, 1 January 2011, 6:00 PM', 1704 'expectedoutputhtml' => '<time datetime="2011-01-01T18:00:00+08:00">Saturday, 1 January 2011, 6:00 PM</time>' 1705 ), 1706 ); 1707 1708 // Set default timezone to Australia/Perth, else time calculated 1709 // will not match expected values. 1710 $this->setTimezone(99, 'Australia/Perth'); 1711 1712 foreach ($testvalues as $vals) { 1713 $USER->timezone = $vals['usertimezone']; 1714 $actualoutput = userdate($vals['time'], '%A, %d %B %Y, %I:%M %p', $vals['timezone']); 1715 $actualoutputhtml = userdate_htmltime($vals['time'], '%A, %d %B %Y, %I:%M %p', $vals['timezone']); 1716 1717 // On different systems case of AM PM changes so compare case insensitive. 1718 $vals['expectedoutput'] = \core_text::strtolower($vals['expectedoutput']); 1719 $vals['expectedoutputhtml'] = \core_text::strtolower($vals['expectedoutputhtml']); 1720 $actualoutput = \core_text::strtolower($actualoutput); 1721 $actualoutputhtml = \core_text::strtolower($actualoutputhtml); 1722 1723 $this->assertSame($vals['expectedoutput'], $actualoutput, 1724 "Expected: {$vals['expectedoutput']} => Actual: {$actualoutput} \ndata: " . var_export($vals, true)); 1725 $this->assertSame($vals['expectedoutputhtml'], $actualoutputhtml, 1726 "Expected: {$vals['expectedoutputhtml']} => Actual: {$actualoutputhtml} \ndata: " . var_export($vals, true)); 1727 } 1728 } 1729 1730 /** 1731 * Make sure the DST changes happen at the right time in Moodle. 1732 */ 1733 public function test_dst_changes() { 1734 // DST switching in Prague. 1735 // From 2AM to 3AM in 1989. 1736 $date = new \DateTime('1989-03-26T01:59:00+01:00'); 1737 $this->assertSame('Sunday, 26 March 1989, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague')); 1738 $date = new \DateTime('1989-03-26T02:01:00+01:00'); 1739 $this->assertSame('Sunday, 26 March 1989, 03:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague')); 1740 // From 3AM to 2AM in 1989 - not the same as the west Europe. 1741 $date = new \DateTime('1989-09-24T01:59:00+01:00'); 1742 $this->assertSame('Sunday, 24 September 1989, 02:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague')); 1743 $date = new \DateTime('1989-09-24T02:01:00+01:00'); 1744 $this->assertSame('Sunday, 24 September 1989, 02:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague')); 1745 // From 2AM to 3AM in 2014. 1746 $date = new \DateTime('2014-03-30T01:59:00+01:00'); 1747 $this->assertSame('Sunday, 30 March 2014, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague')); 1748 $date = new \DateTime('2014-03-30T02:01:00+01:00'); 1749 $this->assertSame('Sunday, 30 March 2014, 03:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague')); 1750 // From 3AM to 2AM in 2014. 1751 $date = new \DateTime('2014-10-26T01:59:00+01:00'); 1752 $this->assertSame('Sunday, 26 October 2014, 02:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague')); 1753 $date = new \DateTime('2014-10-26T02:01:00+01:00'); 1754 $this->assertSame('Sunday, 26 October 2014, 02:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague')); 1755 // From 2AM to 3AM in 2020. 1756 $date = new \DateTime('2020-03-29T01:59:00+01:00'); 1757 $this->assertSame('Sunday, 29 March 2020, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague')); 1758 $date = new \DateTime('2020-03-29T02:01:00+01:00'); 1759 $this->assertSame('Sunday, 29 March 2020, 03:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague')); 1760 // From 3AM to 2AM in 2020. 1761 $date = new \DateTime('2020-10-25T01:59:00+01:00'); 1762 $this->assertSame('Sunday, 25 October 2020, 02:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague')); 1763 $date = new \DateTime('2020-10-25T02:01:00+01:00'); 1764 $this->assertSame('Sunday, 25 October 2020, 02:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague')); 1765 1766 // DST switching in NZ. 1767 // From 3AM to 2AM in 2015. 1768 $date = new \DateTime('2015-04-05T02:59:00+13:00'); 1769 $this->assertSame('Sunday, 5 April 2015, 02:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Pacific/Auckland')); 1770 $date = new \DateTime('2015-04-05T03:01:00+13:00'); 1771 $this->assertSame('Sunday, 5 April 2015, 02:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Pacific/Auckland')); 1772 // From 2AM to 3AM in 2009. 1773 $date = new \DateTime('2015-09-27T01:59:00+12:00'); 1774 $this->assertSame('Sunday, 27 September 2015, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Pacific/Auckland')); 1775 $date = new \DateTime('2015-09-27T02:01:00+12:00'); 1776 $this->assertSame('Sunday, 27 September 2015, 03:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Pacific/Auckland')); 1777 1778 // DST switching in Perth. 1779 // From 3AM to 2AM in 2009. 1780 $date = new \DateTime('2008-03-30T01:59:00+08:00'); 1781 $this->assertSame('Sunday, 30 March 2008, 02:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Australia/Perth')); 1782 $date = new \DateTime('2008-03-30T02:01:00+08:00'); 1783 $this->assertSame('Sunday, 30 March 2008, 02:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Australia/Perth')); 1784 // From 2AM to 3AM in 2009. 1785 $date = new \DateTime('2008-10-26T01:59:00+08:00'); 1786 $this->assertSame('Sunday, 26 October 2008, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Australia/Perth')); 1787 $date = new \DateTime('2008-10-26T02:01:00+08:00'); 1788 $this->assertSame('Sunday, 26 October 2008, 03:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Australia/Perth')); 1789 1790 // DST switching in US. 1791 // From 2AM to 3AM in 2014. 1792 $date = new \DateTime('2014-03-09T01:59:00-05:00'); 1793 $this->assertSame('Sunday, 9 March 2014, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'America/New_York')); 1794 $date = new \DateTime('2014-03-09T02:01:00-05:00'); 1795 $this->assertSame('Sunday, 9 March 2014, 03:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'America/New_York')); 1796 // From 3AM to 2AM in 2014. 1797 $date = new \DateTime('2014-11-02T01:59:00-04:00'); 1798 $this->assertSame('Sunday, 2 November 2014, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'America/New_York')); 1799 $date = new \DateTime('2014-11-02T02:01:00-04:00'); 1800 $this->assertSame('Sunday, 2 November 2014, 01:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'America/New_York')); 1801 } 1802 1803 public function test_make_timestamp() { 1804 global $USER, $CFG, $DB; 1805 $this->resetAfterTest(); 1806 1807 $this->setAdminUser(); 1808 1809 $testvalues = array( 1810 array( 1811 'usertimezone' => 'America/Moncton', 1812 'year' => '2011', 1813 'month' => '7', 1814 'day' => '1', 1815 'hour' => '10', 1816 'minutes' => '00', 1817 'seconds' => '00', 1818 'timezone' => '0.0', 1819 'applydst' => false, // No dst offset. 1820 'expectedoutput' => '1309514400' // 6pm at UTC+0. 1821 ), 1822 array( 1823 'usertimezone' => 'America/Moncton', 1824 'year' => '2011', 1825 'month' => '7', 1826 'day' => '1', 1827 'hour' => '10', 1828 'minutes' => '00', 1829 'seconds' => '00', 1830 'timezone' => '99', // User default timezone. 1831 'applydst' => false, // Don't apply dst. 1832 'expectedoutput' => '1309528800' 1833 ), 1834 array( 1835 'usertimezone' => 'America/Moncton', 1836 'year' => '2011', 1837 'month' => '7', 1838 'day' => '1', 1839 'hour' => '10', 1840 'minutes' => '00', 1841 'seconds' => '00', 1842 'timezone' => '99', // User default timezone. 1843 'applydst' => true, // Apply dst. 1844 'expectedoutput' => '1309525200' 1845 ), 1846 array( 1847 'usertimezone' => 'America/Moncton', 1848 'year' => '2011', 1849 'month' => '7', 1850 'day' => '1', 1851 'hour' => '10', 1852 'minutes' => '00', 1853 'seconds' => '00', 1854 'timezone' => 'America/Moncton', // String timezone. 1855 'applydst' => true, // Apply dst. 1856 'expectedoutput' => '1309525200' 1857 ), 1858 array( 1859 'usertimezone' => '2', // No dst applyed. 1860 'year' => '2011', 1861 'month' => '7', 1862 'day' => '1', 1863 'hour' => '10', 1864 'minutes' => '00', 1865 'seconds' => '00', 1866 'timezone' => '99', // Take user timezone. 1867 'applydst' => true, // Apply dst. 1868 'expectedoutput' => '1309507200' 1869 ), 1870 array( 1871 'usertimezone' => '-2', // No dst applyed. 1872 'year' => '2011', 1873 'month' => '7', 1874 'day' => '1', 1875 'hour' => '10', 1876 'minutes' => '00', 1877 'seconds' => '00', 1878 'timezone' => '99', // Take usertimezone. 1879 'applydst' => true, // Apply dst. 1880 'expectedoutput' => '1309521600' 1881 ), 1882 array( 1883 'usertimezone' => '-10', // No dst applyed. 1884 'year' => '2011', 1885 'month' => '7', 1886 'day' => '1', 1887 'hour' => '10', 1888 'minutes' => '00', 1889 'seconds' => '00', 1890 'timezone' => '2', // Take this timezone. 1891 'applydst' => true, // Apply dst. 1892 'expectedoutput' => '1309507200' 1893 ), 1894 array( 1895 'usertimezone' => '-10', // No dst applyed. 1896 'year' => '2011', 1897 'month' => '7', 1898 'day' => '1', 1899 'hour' => '10', 1900 'minutes' => '00', 1901 'seconds' => '00', 1902 'timezone' => '-2', // Take this timezone. 1903 'applydst' => true, // Apply dst. 1904 'expectedoutput' => '1309521600' 1905 ), 1906 array( 1907 'usertimezone' => '-10', // No dst applyed. 1908 'year' => '2011', 1909 'month' => '7', 1910 'day' => '1', 1911 'hour' => '10', 1912 'minutes' => '00', 1913 'seconds' => '00', 1914 'timezone' => 'random/time', // This should show server time. 1915 'applydst' => true, // Apply dst. 1916 'expectedoutput' => '1309485600' 1917 ), 1918 array( 1919 'usertimezone' => '-14', // Server time. 1920 'year' => '2011', 1921 'month' => '7', 1922 'day' => '1', 1923 'hour' => '10', 1924 'minutes' => '00', 1925 'seconds' => '00', 1926 'timezone' => '99', // Get user time. 1927 'applydst' => true, // Apply dst. 1928 'expectedoutput' => '1309485600' 1929 ) 1930 ); 1931 1932 // Set default timezone to Australia/Perth, else time calculated 1933 // will not match expected values. 1934 $this->setTimezone(99, 'Australia/Perth'); 1935 1936 // Test make_timestamp with all testvals and assert if anything wrong. 1937 foreach ($testvalues as $vals) { 1938 $USER->timezone = $vals['usertimezone']; 1939 $actualoutput = make_timestamp( 1940 $vals['year'], 1941 $vals['month'], 1942 $vals['day'], 1943 $vals['hour'], 1944 $vals['minutes'], 1945 $vals['seconds'], 1946 $vals['timezone'], 1947 $vals['applydst'] 1948 ); 1949 1950 // On different systems case of AM PM changes so compare case insensitive. 1951 $vals['expectedoutput'] = \core_text::strtolower($vals['expectedoutput']); 1952 $actualoutput = \core_text::strtolower($actualoutput); 1953 1954 $this->assertSame($vals['expectedoutput'], $actualoutput, 1955 "Expected: {$vals['expectedoutput']} => Actual: {$actualoutput}, 1956 Please check if timezones are updated (Site adminstration -> location -> update timezone)"); 1957 } 1958 } 1959 1960 /** 1961 * Test get_string and most importantly the implementation of the lang_string 1962 * object. 1963 */ 1964 public function test_get_string() { 1965 global $COURSE; 1966 1967 // Make sure we are using English. 1968 $originallang = $COURSE->lang; 1969 $COURSE->lang = 'en'; 1970 1971 $yes = get_string('yes'); 1972 $yesexpected = 'Yes'; 1973 $this->assertIsString($yes); 1974 $this->assertSame($yesexpected, $yes); 1975 1976 $yes = get_string('yes', 'moodle'); 1977 $this->assertIsString($yes); 1978 $this->assertSame($yesexpected, $yes); 1979 1980 $yes = get_string('yes', 'core'); 1981 $this->assertIsString($yes); 1982 $this->assertSame($yesexpected, $yes); 1983 1984 $yes = get_string('yes', ''); 1985 $this->assertIsString($yes); 1986 $this->assertSame($yesexpected, $yes); 1987 1988 $yes = get_string('yes', null); 1989 $this->assertIsString($yes); 1990 $this->assertSame($yesexpected, $yes); 1991 1992 $yes = get_string('yes', null, 1); 1993 $this->assertIsString($yes); 1994 $this->assertSame($yesexpected, $yes); 1995 1996 $days = 1; 1997 $numdays = get_string('numdays', 'core', '1'); 1998 $numdaysexpected = $days.' days'; 1999 $this->assertIsString($numdays); 2000 $this->assertSame($numdaysexpected, $numdays); 2001 2002 $yes = get_string('yes', null, null, true); 2003 $this->assertInstanceOf('lang_string', $yes); 2004 $this->assertSame($yesexpected, (string)$yes); 2005 2006 // Test lazy loading (returning lang_string) correctly interpolates 0 being used as args. 2007 $numdays = get_string('numdays', 'moodle', 0, true); 2008 $this->assertInstanceOf(lang_string::class, $numdays); 2009 $this->assertSame('0 days', (string) $numdays); 2010 2011 // Test using a lang_string object as the $a argument for a normal 2012 // get_string call (returning string). 2013 $test = new lang_string('yes', null, null, true); 2014 $testexpected = get_string('numdays', 'core', get_string('yes')); 2015 $testresult = get_string('numdays', null, $test); 2016 $this->assertIsString($testresult); 2017 $this->assertSame($testexpected, $testresult); 2018 2019 // Test using a lang_string object as the $a argument for an object 2020 // get_string call (returning lang_string). 2021 $test = new lang_string('yes', null, null, true); 2022 $testexpected = get_string('numdays', 'core', get_string('yes')); 2023 $testresult = get_string('numdays', null, $test, true); 2024 $this->assertInstanceOf('lang_string', $testresult); 2025 $this->assertSame($testexpected, "$testresult"); 2026 2027 // Make sure that object properties that can't be converted don't cause 2028 // errors. 2029 // Level one: This is as deep as current language processing goes. 2030 $test = new \stdClass; 2031 $test->one = 'here'; 2032 $string = get_string('yes', null, $test, true); 2033 $this->assertEquals($yesexpected, $string); 2034 2035 // Make sure that object properties that can't be converted don't cause 2036 // errors. 2037 // Level two: Language processing doesn't currently reach this deep. 2038 // only immediate scalar properties are worked with. 2039 $test = new \stdClass; 2040 $test->one = new \stdClass; 2041 $test->one->two = 'here'; 2042 $string = get_string('yes', null, $test, true); 2043 $this->assertEquals($yesexpected, $string); 2044 2045 // Make sure that object properties that can't be converted don't cause 2046 // errors. 2047 // Level three: It should never ever go this deep, but we're making sure 2048 // it doesn't cause any probs anyway. 2049 $test = new \stdClass; 2050 $test->one = new \stdClass; 2051 $test->one->two = new \stdClass; 2052 $test->one->two->three = 'here'; 2053 $string = get_string('yes', null, $test, true); 2054 $this->assertEquals($yesexpected, $string); 2055 2056 // Make sure that object properties that can't be converted don't cause 2057 // errors and check lang_string properties. 2058 // Level one: This is as deep as current language processing goes. 2059 $test = new \stdClass; 2060 $test->one = new lang_string('yes'); 2061 $string = get_string('yes', null, $test, true); 2062 $this->assertEquals($yesexpected, $string); 2063 2064 // Make sure that object properties that can't be converted don't cause 2065 // errors and check lang_string properties. 2066 // Level two: Language processing doesn't currently reach this deep. 2067 // only immediate scalar properties are worked with. 2068 $test = new \stdClass; 2069 $test->one = new \stdClass; 2070 $test->one->two = new lang_string('yes'); 2071 $string = get_string('yes', null, $test, true); 2072 $this->assertEquals($yesexpected, $string); 2073 2074 // Make sure that object properties that can't be converted don't cause 2075 // errors and check lang_string properties. 2076 // Level three: It should never ever go this deep, but we're making sure 2077 // it doesn't cause any probs anyway. 2078 $test = new \stdClass; 2079 $test->one = new \stdClass; 2080 $test->one->two = new \stdClass; 2081 $test->one->two->three = new lang_string('yes'); 2082 $string = get_string('yes', null, $test, true); 2083 $this->assertEquals($yesexpected, $string); 2084 2085 // Make sure that array properties that can't be converted don't cause 2086 // errors. 2087 $test = array(); 2088 $test['one'] = new \stdClass; 2089 $test['one']->two = 'here'; 2090 $string = get_string('yes', null, $test, true); 2091 $this->assertEquals($yesexpected, $string); 2092 2093 // Same thing but as above except using an object... this is allowed :P. 2094 $string = get_string('yes', null, null, true); 2095 $object = new \stdClass; 2096 $object->$string = 'Yes'; 2097 $this->assertEquals($yesexpected, $string); 2098 $this->assertEquals($yesexpected, $object->$string); 2099 2100 // Reset the language. 2101 $COURSE->lang = $originallang; 2102 } 2103 2104 public function test_lang_string_var_export() { 2105 2106 // Call var_export() on a newly generated lang_string. 2107 $str = new lang_string('no'); 2108 2109 // In PHP 8.2 exported class names are now fully qualified; 2110 // previously, the leading backslash was omitted. 2111 $leadingbackslash = (version_compare(PHP_VERSION, '8.2.0', '>=')) ? '\\' : ''; 2112 2113 $expected1 = <<<EOF 2114 {$leadingbackslash}lang_string::__set_state(array( 2115 'identifier' => 'no', 2116 'component' => 'moodle', 2117 'a' => NULL, 2118 'lang' => NULL, 2119 'string' => NULL, 2120 'forcedstring' => false, 2121 )) 2122 EOF; 2123 2124 $v = var_export($str, true); 2125 $this->assertEquals($expected1, $v); 2126 2127 // Now execute the code that was returned - it should produce a correct string. 2128 $str = lang_string::__set_state(array( 2129 'identifier' => 'no', 2130 'component' => 'moodle', 2131 'a' => NULL, 2132 'lang' => NULL, 2133 'string' => NULL, 2134 'forcedstring' => false, 2135 )); 2136 2137 $this->assertInstanceOf(lang_string::class, $str); 2138 $this->assertEquals('No', $str); 2139 } 2140 2141 public function test_get_string_limitation() { 2142 // This is one of the limitations to the lang_string class. It can't be 2143 // used as a key. 2144 if (PHP_VERSION_ID >= 80000) { 2145 $this->expectException(\TypeError::class); 2146 } else { 2147 $this->expectWarning(); 2148 } 2149 $array = array(get_string('yes', null, null, true) => 'yes'); 2150 } 2151 2152 /** 2153 * Test localised float formatting. 2154 */ 2155 public function test_format_float() { 2156 2157 // Special case for null. 2158 $this->assertEquals('', format_float(null)); 2159 2160 // Default 1 decimal place. 2161 $this->assertEquals('5.4', format_float(5.43)); 2162 $this->assertEquals('5.0', format_float(5.001)); 2163 2164 // Custom number of decimal places. 2165 $this->assertEquals('5.43000', format_float(5.43, 5)); 2166 2167 // Auto detect the number of decimal places. 2168 $this->assertEquals('5.43', format_float(5.43, -1)); 2169 $this->assertEquals('5.43', format_float(5.43000, -1)); 2170 $this->assertEquals('5', format_float(5, -1)); 2171 $this->assertEquals('5', format_float(5.0, -1)); 2172 $this->assertEquals('0.543', format_float('5.43e-1', -1)); 2173 $this->assertEquals('0.543', format_float('5.43000e-1', -1)); 2174 2175 // Option to strip ending zeros after rounding. 2176 $this->assertEquals('5.43', format_float(5.43, 5, true, true)); 2177 $this->assertEquals('5', format_float(5.0001, 3, true, true)); 2178 $this->assertEquals('100', format_float(100, 2, true, true)); 2179 $this->assertEquals('100', format_float(100, 0, true, true)); 2180 2181 // Tests with a localised decimal separator. 2182 $this->define_local_decimal_separator(); 2183 2184 // Localisation on (default). 2185 $this->assertEquals('5X43000', format_float(5.43, 5)); 2186 $this->assertEquals('5X43', format_float(5.43, 5, true, true)); 2187 2188 // Localisation off. 2189 $this->assertEquals('5.43000', format_float(5.43, 5, false)); 2190 $this->assertEquals('5.43', format_float(5.43, 5, false, true)); 2191 2192 // Tests with tilde as localised decimal separator. 2193 $this->define_local_decimal_separator('~'); 2194 2195 // Must also work for '~' as decimal separator. 2196 $this->assertEquals('5', format_float(5.0001, 3, true, true)); 2197 $this->assertEquals('5~43000', format_float(5.43, 5)); 2198 $this->assertEquals('5~43', format_float(5.43, 5, true, true)); 2199 } 2200 2201 /** 2202 * Test localised float unformatting. 2203 */ 2204 public function test_unformat_float() { 2205 2206 // Tests without the localised decimal separator. 2207 2208 // Special case for null, empty or white spaces only strings. 2209 $this->assertEquals(null, unformat_float(null)); 2210 $this->assertEquals(null, unformat_float('')); 2211 $this->assertEquals(null, unformat_float(' ')); 2212 2213 // Regular use. 2214 $this->assertEquals(5.4, unformat_float('5.4')); 2215 $this->assertEquals(5.4, unformat_float('5.4', true)); 2216 2217 // No decimal. 2218 $this->assertEquals(5.0, unformat_float('5')); 2219 2220 // Custom number of decimal. 2221 $this->assertEquals(5.43267, unformat_float('5.43267')); 2222 2223 // Empty decimal. 2224 $this->assertEquals(100.0, unformat_float('100.00')); 2225 2226 // With the thousand separator. 2227 $this->assertEquals(1000.0, unformat_float('1 000')); 2228 $this->assertEquals(1000.32, unformat_float('1 000.32')); 2229 2230 // Negative number. 2231 $this->assertEquals(-100.0, unformat_float('-100')); 2232 2233 // Wrong value. 2234 $this->assertEquals(0.0, unformat_float('Wrong value')); 2235 // Wrong value in strict mode. 2236 $this->assertFalse(unformat_float('Wrong value', true)); 2237 2238 // Combining options. 2239 $this->assertEquals(-1023.862567, unformat_float(' -1 023.862567 ')); 2240 2241 // Bad decimal separator (should crop the decimal). 2242 $this->assertEquals(50.0, unformat_float('50,57')); 2243 // Bad decimal separator in strict mode (should return false). 2244 $this->assertFalse(unformat_float('50,57', true)); 2245 2246 // Tests with a localised decimal separator. 2247 $this->define_local_decimal_separator(); 2248 2249 // We repeat the tests above but with the current decimal separator. 2250 2251 // Regular use without and with the localised separator. 2252 $this->assertEquals (5.4, unformat_float('5.4')); 2253 $this->assertEquals (5.4, unformat_float('5X4')); 2254 2255 // Custom number of decimal. 2256 $this->assertEquals (5.43267, unformat_float('5X43267')); 2257 2258 // Empty decimal. 2259 $this->assertEquals (100.0, unformat_float('100X00')); 2260 2261 // With the thousand separator. 2262 $this->assertEquals (1000.32, unformat_float('1 000X32')); 2263 2264 // Bad different separator (should crop the decimal). 2265 $this->assertEquals (50.0, unformat_float('50Y57')); 2266 // Bad different separator in strict mode (should return false). 2267 $this->assertFalse (unformat_float('50Y57', true)); 2268 2269 // Combining options. 2270 $this->assertEquals (-1023.862567, unformat_float(' -1 023X862567 ')); 2271 // Combining options in strict mode. 2272 $this->assertEquals (-1023.862567, unformat_float(' -1 023X862567 ', true)); 2273 } 2274 2275 /** 2276 * Test deleting of users. 2277 */ 2278 public function test_delete_user() { 2279 global $DB, $CFG; 2280 2281 $this->resetAfterTest(); 2282 2283 $guest = $DB->get_record('user', array('id'=>$CFG->siteguest), '*', MUST_EXIST); 2284 $admin = $DB->get_record('user', array('id'=>$CFG->siteadmins), '*', MUST_EXIST); 2285 $this->assertEquals(0, $DB->count_records('user', array('deleted'=>1))); 2286 2287 $user = $this->getDataGenerator()->create_user(array('idnumber'=>'abc')); 2288 $user2 = $this->getDataGenerator()->create_user(array('idnumber'=>'xyz')); 2289 $usersharedemail1 = $this->getDataGenerator()->create_user(array('email' => 'sharedemail@example.invalid')); 2290 $usersharedemail2 = $this->getDataGenerator()->create_user(array('email' => 'sharedemail@example.invalid')); 2291 $useremptyemail1 = $this->getDataGenerator()->create_user(array('email' => '')); 2292 $useremptyemail2 = $this->getDataGenerator()->create_user(array('email' => '')); 2293 2294 // Delete user and capture event. 2295 $sink = $this->redirectEvents(); 2296 $result = delete_user($user); 2297 $events = $sink->get_events(); 2298 $sink->close(); 2299 $event = array_pop($events); 2300 2301 // Test user is deleted in DB. 2302 $this->assertTrue($result); 2303 $deluser = $DB->get_record('user', array('id'=>$user->id), '*', MUST_EXIST); 2304 $this->assertEquals(1, $deluser->deleted); 2305 $this->assertEquals(0, $deluser->picture); 2306 $this->assertSame('', $deluser->idnumber); 2307 $this->assertSame(md5($user->username), $deluser->email); 2308 $this->assertMatchesRegularExpression('/^'.preg_quote($user->email, '/').'\.\d*$/', $deluser->username); 2309 2310 $this->assertEquals(1, $DB->count_records('user', array('deleted'=>1))); 2311 2312 // Test Event. 2313 $this->assertInstanceOf('\core\event\user_deleted', $event); 2314 $this->assertSame($user->id, $event->objectid); 2315 $eventdata = $event->get_data(); 2316 $this->assertSame($eventdata['other']['username'], $user->username); 2317 $this->assertSame($eventdata['other']['email'], $user->email); 2318 $this->assertSame($eventdata['other']['idnumber'], $user->idnumber); 2319 $this->assertSame($eventdata['other']['picture'], $user->picture); 2320 $this->assertSame($eventdata['other']['mnethostid'], $user->mnethostid); 2321 $this->assertEquals($user, $event->get_record_snapshot('user', $event->objectid)); 2322 $this->assertEventContextNotUsed($event); 2323 2324 // Try invalid params. 2325 $record = new \stdClass(); 2326 $record->grrr = 1; 2327 try { 2328 delete_user($record); 2329 $this->fail('Expecting exception for invalid delete_user() $user parameter'); 2330 } catch (\moodle_exception $ex) { 2331 $this->assertInstanceOf('coding_exception', $ex); 2332 } 2333 $record->id = 1; 2334 try { 2335 delete_user($record); 2336 $this->fail('Expecting exception for invalid delete_user() $user parameter'); 2337 } catch (\moodle_exception $ex) { 2338 $this->assertInstanceOf('coding_exception', $ex); 2339 } 2340 2341 $record = new \stdClass(); 2342 $record->id = 666; 2343 $record->username = 'xx'; 2344 $this->assertFalse($DB->record_exists('user', array('id'=>666))); // Any non-existent id is ok. 2345 $result = delete_user($record); 2346 $this->assertFalse($result); 2347 2348 $result = delete_user($guest); 2349 $this->assertFalse($result); 2350 2351 $result = delete_user($admin); 2352 $this->assertFalse($result); 2353 2354 // Simultaneously deleting users with identical email addresses. 2355 $result1 = delete_user($usersharedemail1); 2356 $result2 = delete_user($usersharedemail2); 2357 2358 $usersharedemail1after = $DB->get_record('user', array('id' => $usersharedemail1->id)); 2359 $usersharedemail2after = $DB->get_record('user', array('id' => $usersharedemail2->id)); 2360 $this->assertTrue($result1); 2361 $this->assertTrue($result2); 2362 $this->assertStringStartsWith($usersharedemail1->email . '.', $usersharedemail1after->username); 2363 $this->assertStringStartsWith($usersharedemail2->email . '.', $usersharedemail2after->username); 2364 2365 // Simultaneously deleting users without email addresses. 2366 $result1 = delete_user($useremptyemail1); 2367 $result2 = delete_user($useremptyemail2); 2368 2369 $useremptyemail1after = $DB->get_record('user', array('id' => $useremptyemail1->id)); 2370 $useremptyemail2after = $DB->get_record('user', array('id' => $useremptyemail2->id)); 2371 $this->assertTrue($result1); 2372 $this->assertTrue($result2); 2373 $this->assertStringStartsWith($useremptyemail1->username . '.' . $useremptyemail1->id . '@unknownemail.invalid.', 2374 $useremptyemail1after->username); 2375 $this->assertStringStartsWith($useremptyemail2->username . '.' . $useremptyemail2->id . '@unknownemail.invalid.', 2376 $useremptyemail2after->username); 2377 2378 $this->resetDebugging(); 2379 } 2380 2381 /** 2382 * Test deletion of user with long username 2383 */ 2384 public function test_delete_user_long_username() { 2385 global $DB; 2386 2387 $this->resetAfterTest(); 2388 2389 // For users without an e-mail, one will be created during deletion using {$username}.{$id}@unknownemail.invalid format. 2390 $user = $this->getDataGenerator()->create_user([ 2391 'username' => str_repeat('a', 75), 2392 'email' => '', 2393 ]); 2394 2395 delete_user($user); 2396 2397 // The username for the deleted user shouldn't exceed 100 characters. 2398 $usernamedeleted = $DB->get_field('user', 'username', ['id' => $user->id]); 2399 $this->assertEquals(100, \core_text::strlen($usernamedeleted)); 2400 2401 $timestrlength = \core_text::strlen((string) time()); 2402 2403 // It should start with the user name, and end with the current time. 2404 $this->assertStringStartsWith("{$user->username}.{$user->id}@", $usernamedeleted); 2405 $this->assertMatchesRegularExpression('/\.\d{' . $timestrlength . '}$/', $usernamedeleted); 2406 } 2407 2408 /** 2409 * Test deletion of user with long email address 2410 */ 2411 public function test_delete_user_long_email() { 2412 global $DB; 2413 2414 $this->resetAfterTest(); 2415 2416 // Create user with 90 character email address. 2417 $user = $this->getDataGenerator()->create_user([ 2418 'email' => str_repeat('a', 78) . '@example.com', 2419 ]); 2420 2421 delete_user($user); 2422 2423 // The username for the deleted user shouldn't exceed 100 characters. 2424 $usernamedeleted = $DB->get_field('user', 'username', ['id' => $user->id]); 2425 $this->assertEquals(100, \core_text::strlen($usernamedeleted)); 2426 2427 $timestrlength = \core_text::strlen((string) time()); 2428 2429 // Max username length is 100 chars. Select up to limit - (length of current time + 1 [period character]) from users email. 2430 $expectedemail = \core_text::substr($user->email, 0, 100 - ($timestrlength + 1)); 2431 $this->assertMatchesRegularExpression('/^' . preg_quote($expectedemail) . '\.\d{' . $timestrlength . '}$/', 2432 $usernamedeleted); 2433 } 2434 2435 /** 2436 * Test function convert_to_array() 2437 */ 2438 public function test_convert_to_array() { 2439 // Check that normal classes are converted to arrays the same way as (array) would do. 2440 $obj = new \stdClass(); 2441 $obj->prop1 = 'hello'; 2442 $obj->prop2 = array('first', 'second', 13); 2443 $obj->prop3 = 15; 2444 $this->assertEquals(convert_to_array($obj), (array)$obj); 2445 2446 // Check that context object (with iterator) is converted to array properly. 2447 $obj = \context_system::instance(); 2448 $ar = array( 2449 'id' => $obj->id, 2450 'contextlevel' => $obj->contextlevel, 2451 'instanceid' => $obj->instanceid, 2452 'path' => $obj->path, 2453 'depth' => $obj->depth, 2454 'locked' => $obj->locked, 2455 ); 2456 $this->assertEquals(convert_to_array($obj), $ar); 2457 } 2458 2459 /** 2460 * Test the function date_format_string(). 2461 */ 2462 public function test_date_format_string() { 2463 global $CFG; 2464 2465 $this->resetAfterTest(); 2466 $this->setTimezone(99, 'Australia/Perth'); 2467 2468 $tests = array( 2469 array( 2470 'tz' => 99, 2471 'str' => '%A, %d %B %Y, %I:%M %p', 2472 'expected' => 'Saturday, 01 January 2011, 06:00 PM' 2473 ), 2474 array( 2475 'tz' => 0, 2476 'str' => '%A, %d %B %Y, %I:%M %p', 2477 'expected' => 'Saturday, 01 January 2011, 10:00 AM' 2478 ), 2479 array( 2480 // Note: this function expected the timestamp in weird format before, 2481 // since 2.9 it uses UTC. 2482 'tz' => 'Pacific/Auckland', 2483 'str' => '%A, %d %B %Y, %I:%M %p', 2484 'expected' => 'Saturday, 01 January 2011, 11:00 PM' 2485 ), 2486 // Following tests pass on Windows only because en lang pack does 2487 // not contain localewincharset, in real life lang pack maintainers 2488 // may use only characters that are present in localewincharset 2489 // in format strings! 2490 array( 2491 'tz' => 99, 2492 'str' => 'Žluťoučký koníček %A', 2493 'expected' => 'Žluťoučký koníček Saturday' 2494 ), 2495 array( 2496 'tz' => 99, 2497 'str' => '言語設定言語 %A', 2498 'expected' => '言語設定言語 Saturday' 2499 ), 2500 array( 2501 'tz' => 99, 2502 'str' => '简体中文简体 %A', 2503 'expected' => '简体中文简体 Saturday' 2504 ), 2505 ); 2506 2507 // Note: date_format_string() uses the timezone only to differenciate 2508 // the server time from the UTC time. It does not modify the timestamp. 2509 // Hence similar results for timezones <= 13. 2510 // On different systems case of AM PM changes so compare case insensitive. 2511 foreach ($tests as $test) { 2512 $str = date_format_string(1293876000, $test['str'], $test['tz']); 2513 $this->assertSame(\core_text::strtolower($test['expected']), \core_text::strtolower($str)); 2514 } 2515 } 2516 2517 public function test_get_config() { 2518 global $CFG; 2519 2520 $this->resetAfterTest(); 2521 2522 // Preparation. 2523 set_config('phpunit_test_get_config_1', 'test 1'); 2524 set_config('phpunit_test_get_config_2', 'test 2', 'mod_forum'); 2525 if (!is_array($CFG->config_php_settings)) { 2526 $CFG->config_php_settings = array(); 2527 } 2528 $CFG->config_php_settings['phpunit_test_get_config_3'] = 'test 3'; 2529 2530 if (!is_array($CFG->forced_plugin_settings)) { 2531 $CFG->forced_plugin_settings = array(); 2532 } 2533 if (!array_key_exists('mod_forum', $CFG->forced_plugin_settings)) { 2534 $CFG->forced_plugin_settings['mod_forum'] = array(); 2535 } 2536 $CFG->forced_plugin_settings['mod_forum']['phpunit_test_get_config_4'] = 'test 4'; 2537 $CFG->phpunit_test_get_config_5 = 'test 5'; 2538 2539 // Testing. 2540 $this->assertSame('test 1', get_config('core', 'phpunit_test_get_config_1')); 2541 $this->assertSame('test 2', get_config('mod_forum', 'phpunit_test_get_config_2')); 2542 $this->assertSame('test 3', get_config('core', 'phpunit_test_get_config_3')); 2543 $this->assertSame('test 4', get_config('mod_forum', 'phpunit_test_get_config_4')); 2544 $this->assertFalse(get_config('core', 'phpunit_test_get_config_5')); 2545 $this->assertFalse(get_config('core', 'phpunit_test_get_config_x')); 2546 $this->assertFalse(get_config('mod_forum', 'phpunit_test_get_config_x')); 2547 2548 // Test config we know to exist. 2549 $this->assertSame($CFG->dataroot, get_config('core', 'dataroot')); 2550 $this->assertSame($CFG->phpunit_dataroot, get_config('core', 'phpunit_dataroot')); 2551 $this->assertSame($CFG->dataroot, get_config('core', 'phpunit_dataroot')); 2552 $this->assertSame(get_config('core', 'dataroot'), get_config('core', 'phpunit_dataroot')); 2553 2554 // Test setting a config var that already exists. 2555 set_config('phpunit_test_get_config_1', 'test a'); 2556 $this->assertSame('test a', $CFG->phpunit_test_get_config_1); 2557 $this->assertSame('test a', get_config('core', 'phpunit_test_get_config_1')); 2558 2559 // Test cache invalidation. 2560 $cache = \cache::make('core', 'config'); 2561 $this->assertIsArray($cache->get('core')); 2562 $this->assertIsArray($cache->get('mod_forum')); 2563 set_config('phpunit_test_get_config_1', 'test b'); 2564 $this->assertFalse($cache->get('core')); 2565 set_config('phpunit_test_get_config_4', 'test c', 'mod_forum'); 2566 $this->assertFalse($cache->get('mod_forum')); 2567 } 2568 2569 public function test_get_max_upload_sizes() { 2570 // Test with very low limits so we are not affected by php upload limits. 2571 // Test activity limit smallest. 2572 $sitebytes = 102400; 2573 $coursebytes = 51200; 2574 $modulebytes = 10240; 2575 $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes); 2576 2577 $nbsp = "\xc2\xa0"; 2578 $this->assertSame("Activity upload limit (10{$nbsp}KB)", $result['0']); 2579 $this->assertCount(2, $result); 2580 2581 // Test course limit smallest. 2582 $sitebytes = 102400; 2583 $coursebytes = 10240; 2584 $modulebytes = 51200; 2585 $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes); 2586 2587 $this->assertSame("Course upload limit (10{$nbsp}KB)", $result['0']); 2588 $this->assertCount(2, $result); 2589 2590 // Test site limit smallest. 2591 $sitebytes = 10240; 2592 $coursebytes = 102400; 2593 $modulebytes = 51200; 2594 $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes); 2595 2596 $this->assertSame("Site upload limit (10{$nbsp}KB)", $result['0']); 2597 $this->assertCount(2, $result); 2598 2599 // Test site limit not set. 2600 $sitebytes = 0; 2601 $coursebytes = 102400; 2602 $modulebytes = 51200; 2603 $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes); 2604 2605 $this->assertSame("Activity upload limit (50{$nbsp}KB)", $result['0']); 2606 $this->assertCount(3, $result); 2607 2608 $sitebytes = 0; 2609 $coursebytes = 51200; 2610 $modulebytes = 102400; 2611 $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes); 2612 2613 $this->assertSame("Course upload limit (50{$nbsp}KB)", $result['0']); 2614 $this->assertCount(3, $result); 2615 2616 // Test custom bytes in range. 2617 $sitebytes = 102400; 2618 $coursebytes = 51200; 2619 $modulebytes = 51200; 2620 $custombytes = 10240; 2621 $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes, $custombytes); 2622 2623 $this->assertCount(3, $result); 2624 2625 // Test custom bytes in range but non-standard. 2626 $sitebytes = 102400; 2627 $coursebytes = 51200; 2628 $modulebytes = 51200; 2629 $custombytes = 25600; 2630 $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes, $custombytes); 2631 2632 $this->assertCount(4, $result); 2633 2634 // Test custom bytes out of range. 2635 $sitebytes = 102400; 2636 $coursebytes = 51200; 2637 $modulebytes = 51200; 2638 $custombytes = 102400; 2639 $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes, $custombytes); 2640 2641 $this->assertCount(3, $result); 2642 2643 // Test custom bytes out of range and non-standard. 2644 $sitebytes = 102400; 2645 $coursebytes = 51200; 2646 $modulebytes = 51200; 2647 $custombytes = 256000; 2648 $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes, $custombytes); 2649 2650 $this->assertCount(3, $result); 2651 2652 // Test site limit only. 2653 $sitebytes = 51200; 2654 $result = get_max_upload_sizes($sitebytes); 2655 2656 $this->assertSame("Site upload limit (50{$nbsp}KB)", $result['0']); 2657 $this->assertSame("50{$nbsp}KB", $result['51200']); 2658 $this->assertSame("10{$nbsp}KB", $result['10240']); 2659 $this->assertCount(3, $result); 2660 2661 // Test no limit. 2662 $result = get_max_upload_sizes(); 2663 $this->assertArrayHasKey('0', $result); 2664 $this->assertArrayHasKey(get_max_upload_file_size(), $result); 2665 } 2666 2667 /** 2668 * Test function password_is_legacy_hash. 2669 * @covers ::password_is_legacy_hash 2670 */ 2671 public function test_password_is_legacy_hash() { 2672 // Well formed bcrypt hashes should be matched. 2673 foreach (array('some', 'strings', 'to_check!') as $password) { 2674 $bcrypt = password_hash($password, '2y'); 2675 $this->assertTrue(password_is_legacy_hash($bcrypt)); 2676 } 2677 // Strings that are not bcrypt should not be matched. 2678 $sha512 = '$6$rounds=5000$somesalt$9nEA35u5h4oDrUdcVFUwXDSwIBiZtuKDHiaI/kxnBSslH4wVXeAhVsDn1UFxBxrnRJva/8dZ8IouaijJdd4cF'; 2679 foreach (array('', AUTH_PASSWORD_NOT_CACHED, $sha512) as $notbcrypt) { 2680 $this->assertFalse(password_is_legacy_hash($notbcrypt)); 2681 } 2682 } 2683 2684 /** 2685 * Test function that calculates password pepper entropy. 2686 * @covers ::calculate_entropy 2687 */ 2688 public function test_calculate_entropy() { 2689 // Test that the function returns 0 with an empty string. 2690 $this->assertEquals(0, calculate_entropy('')); 2691 2692 // Test that the function returns the correct entropy. 2693 $this->assertEquals(132.8814, number_format(calculate_entropy('#GV]NLie|x$H9[$rW%94bXZvJHa%z'), 4)); 2694 } 2695 2696 /** 2697 * Test function to get password peppers. 2698 * @covers ::get_password_peppers 2699 */ 2700 public function test_get_password_peppers() { 2701 global $CFG; 2702 $this->resetAfterTest(); 2703 2704 // First assert that the function returns an empty array, 2705 // when no peppers are set. 2706 $this->assertEquals([], get_password_peppers()); 2707 2708 // Now set some peppers and check that they are returned. 2709 $CFG->passwordpeppers = [ 2710 1 => '#GV]NLie|x$H9[$rW%94bXZvJHa%z', 2711 2 => '#GV]NLie|x$H9[$rW%94bXZvJHa%$' 2712 ]; 2713 $peppers = get_password_peppers(); 2714 $this->assertCount(2, $peppers); 2715 $this->assertEquals($CFG->passwordpeppers, $peppers); 2716 2717 // Check that the peppers are returned in the correct order. 2718 // Highest numerical key first. 2719 $this->assertEquals('#GV]NLie|x$H9[$rW%94bXZvJHa%$', $peppers[2]); 2720 $this->assertEquals('#GV]NLie|x$H9[$rW%94bXZvJHa%z', $peppers[1]); 2721 2722 // Update the latest pepper to be an empty string, 2723 // to test phasing out peppers. 2724 $CFG->passwordpeppers = [ 2725 1 => '#GV]NLie|x$H9[$rW%94bXZvJHa%z', 2726 2 => '#GV]NLie|x$H9[$rW%94bXZvJHa%$', 2727 3 => '' 2728 ]; 2729 $peppers = get_password_peppers(); 2730 $this->assertCount(3, $peppers); 2731 $this->assertEquals($CFG->passwordpeppers, $peppers); 2732 2733 // Finally, check that low entropy peppers throw an exception. 2734 $CFG->passwordpeppers = [ 2735 1 => 'foo', 2736 2 => 'bar' 2737 ]; 2738 $this->expectException(\coding_exception::class); 2739 get_password_peppers(); 2740 } 2741 2742 /** 2743 * Test function to validate password length. 2744 * 2745 * @covers ::exceeds_password_length 2746 * @return void 2747 */ 2748 public function test_exceeds_password_length() { 2749 $this->resetAfterTest(true); 2750 2751 // With password less than equals to MAX_PASSWORD_CHARACTERS. 2752 $this->assertFalse(exceeds_password_length('test')); 2753 2754 // With password more than MAX_PASSWORD_CHARACTERS. 2755 $password = 'thisisapasswordthatcontainscharactersthatcan'; 2756 $password .= 'exeedthepasswordlengthof128thisispasswordthatcont'; 2757 $password .= 'ainscharactersthatcanexeedthelength-----'; 2758 $this->assertTrue(exceeds_password_length($password)); 2759 } 2760 2761 /** 2762 * Test function validate_internal_user_password. 2763 * @covers ::validate_internal_user_password 2764 */ 2765 public function test_validate_internal_user_password() { 2766 $this->resetAfterTest(true); 2767 // Test bcrypt hashes (these will be updated but will still count as valid). 2768 $bcrypthashes = [ 2769 'pw' => '$2y$10$LOSDi5eaQJhutSRun.OVJ.ZSxQZabCMay7TO1KmzMkDMPvU40zGXK', 2770 'abc' => '$2y$10$VWTOhVdsBbWwtdWNDRHSpewjd3aXBQlBQf5rBY/hVhw8hciarFhXa', 2771 'C0mP1eX_&}<?@*&%` |\"' => '$2y$10$3PJf.q.9ywNJlsInPbqc8.IFeSsvXrGvQLKRFBIhVu1h1I3vpIry6', 2772 'ĩńťėŕňăţĩōŋāĹ' => '$2y$10$3A2Y8WpfRAnP3czJiSv6N.6Xp0T8hW3QZz2hUCYhzyWr1kGP1yUve', 2773 ]; 2774 2775 // Test sha512 hashes. 2776 $sha512hashes = [ 2777 'pw2' => '$6$rounds=10000$0rDIzh/4.MMf9Dm8$Zrj6Ulc1JFj0RFXwMJFsngRSNGlqkPlV1wwRVv7wBLrMeQeMZrwsBO62zy63D//6R5sNGVYQwPB0K8jPCScxB/', 2778 'abc2' => '$6$rounds=10000$t0L6PklgpijV4tMB$1vpCRKCImsVqTPMiZTi6zLGbs.hpAU8I2BhD/IFliBnHJkFZCWEBfTCq6pEzo0Q8nXsryrgeZ.qngcW.eifuW.', 2779 'C0mP1eX_&}<?@*&%` |\"2' => '$6$rounds=10000$3TAyVAXN0zmFZ4il$KF8YzduX6Gu0C2xHsY83zoqQ/rLVsb9mLe417wDObo9tO00qeUC68/y2tMq4FL2ixnMPH3OMwzGYo8VJrm8Eq1', 2780 'ĩńťėŕňăţĩōŋāĹ2' => '$6$rounds=10000$SHR/6ctTkfXOy5NP$YPv42hjDjohVWD3B0boyEYTnLcBXBKO933ijHmkPXNL7BpqAcbYMLfTl9rjsPmCt.1GZvEJZ8ikkCPYBC5Sdp.', 2781 ]; 2782 2783 $validhashes = array_merge($bcrypthashes, $sha512hashes); 2784 2785 foreach ($validhashes as $password => $hash) { 2786 $user = $this->getDataGenerator()->create_user(array('auth' => 'manual', 'password' => $password)); 2787 $user->password = $hash; 2788 // The correct password should be validated. 2789 $this->assertTrue(validate_internal_user_password($user, $password)); 2790 // An incorrect password should not be validated. 2791 $this->assertFalse(validate_internal_user_password($user, 'badpw')); 2792 } 2793 } 2794 2795 /** 2796 * Test function validate_internal_user_password() with a peppered password, 2797 * when the pepper no longer exists. 2798 * 2799 * @covers ::validate_internal_user_password 2800 */ 2801 public function test_validate_internal_user_password_bad_pepper() { 2802 global $CFG; 2803 $this->resetAfterTest(); 2804 2805 // Set a pepper. 2806 $CFG->passwordpeppers = [ 2807 1 => '#GV]NLie|x$H9[$rW%94bXZvJHa%z', 2808 2 => '#GV]NLie|x$H9[$rW%94bXZvJHa%$' 2809 ]; 2810 $password = 'test'; 2811 2812 $user = $this->getDataGenerator()->create_user(['auth' => 'manual', 'password' => $password]); 2813 $this->assertTrue(validate_internal_user_password($user, $password)); 2814 $this->assertFalse(validate_internal_user_password($user, 'badpw')); 2815 2816 // Now remove the peppers. 2817 // Things should not work. 2818 unset($CFG->passwordpeppers); 2819 $this->assertFalse(validate_internal_user_password($user, $password)); 2820 } 2821 2822 /** 2823 * Helper method to test hashing passwords. 2824 * 2825 * @param array $passwords 2826 * @return void 2827 * @covers ::hash_internal_user_password 2828 */ 2829 public function validate_hashed_passwords(array $passwords): void { 2830 foreach ($passwords as $password) { 2831 $hash = hash_internal_user_password($password); 2832 $fasthash = hash_internal_user_password($password, true); 2833 $user = $this->getDataGenerator()->create_user(['auth' => 'manual']); 2834 $user->password = $hash; 2835 $this->assertTrue(validate_internal_user_password($user, $password)); 2836 2837 // They should not be in bycrypt format. 2838 $this->assertFalse(password_is_legacy_hash($hash)); 2839 2840 // Check that cost factor in hash is correctly set. 2841 $this->assertMatchesRegularExpression('/\$6\$rounds=10000\$.{103}/', $hash); 2842 $this->assertMatchesRegularExpression('/\$6\$rounds=5000\$.{103}/', $fasthash); 2843 } 2844 } 2845 2846 /** 2847 * Test function update_internal_user_password. 2848 * @covers ::update_internal_user_password 2849 */ 2850 public function test_hash_internal_user_password() { 2851 global $CFG; 2852 $this->resetAfterTest(); 2853 $passwords = ['pw', 'abc123', 'C0mP1eX_&}<?@*&%` |\"', 'ĩńťėŕňăţĩōŋāĹ']; 2854 2855 // Check that some passwords that we convert to hashes can 2856 // be validated. 2857 $this->validate_hashed_passwords($passwords); 2858 2859 // Test again with peppers. 2860 $CFG->passwordpeppers = [ 2861 1 => '#GV]NLie|x$H9[$rW%94bXZvJHa%z', 2862 2 => '#GV]NLie|x$H9[$rW%94bXZvJHa%$' 2863 ]; 2864 $this->validate_hashed_passwords($passwords); 2865 2866 // Add a new pepper and check that things still pass. 2867 $CFG->passwordpeppers = [ 2868 1 => '#GV]NLie|x$H9[$rW%94bXZvJHa%z', 2869 2 => '#GV]NLie|x$H9[$rW%94bXZvJHa%$', 2870 3 => '#GV]NLie|x$H9[$rW%94bXZvJHQ%$' 2871 ]; 2872 $this->validate_hashed_passwords($passwords); 2873 } 2874 2875 /** 2876 * Test function update_internal_user_password(). 2877 */ 2878 public function test_update_internal_user_password() { 2879 global $DB; 2880 $this->resetAfterTest(); 2881 $passwords = array('password', '1234', 'changeme', '****'); 2882 foreach ($passwords as $password) { 2883 $user = $this->getDataGenerator()->create_user(array('auth'=>'manual')); 2884 update_internal_user_password($user, $password); 2885 // The user object should have been updated. 2886 $this->assertTrue(validate_internal_user_password($user, $password)); 2887 // The database field for the user should also have been updated to the 2888 // same value. 2889 $this->assertSame($user->password, $DB->get_field('user', 'password', array('id' => $user->id))); 2890 } 2891 2892 $user = $this->getDataGenerator()->create_user(array('auth'=>'manual')); 2893 // Manually set the user's password to the bcrypt of the string 'password'. 2894 $DB->set_field('user', 'password', '$2y$10$HhNAYmQcU1GqU/psOmZjfOWlhPEcxx9aEgSJqBfEtYVyq1jPKqMAi', ['id' => $user->id]); 2895 2896 $sink = $this->redirectEvents(); 2897 // Update the password. 2898 update_internal_user_password($user, 'password'); 2899 $events = $sink->get_events(); 2900 $sink->close(); 2901 $event = array_pop($events); 2902 2903 // Password should have been updated to a SHA512 hash. 2904 $this->assertFalse(password_is_legacy_hash($user->password)); 2905 2906 // Verify event information. 2907 $this->assertInstanceOf('\core\event\user_password_updated', $event); 2908 $this->assertSame($user->id, $event->relateduserid); 2909 $this->assertEquals(\context_user::instance($user->id), $event->get_context()); 2910 $this->assertEventContextNotUsed($event); 2911 2912 // Verify recovery of property 'auth'. 2913 unset($user->auth); 2914 update_internal_user_password($user, 'newpassword'); 2915 $this->assertDebuggingCalled('User record in update_internal_user_password() must include field auth', 2916 DEBUG_DEVELOPER); 2917 $this->assertEquals('manual', $user->auth); 2918 } 2919 2920 /** 2921 * Testing that if the password is not cached, that it does not update 2922 * the user table and fire event. 2923 */ 2924 public function test_update_internal_user_password_no_cache() { 2925 global $DB; 2926 $this->resetAfterTest(); 2927 2928 $user = $this->getDataGenerator()->create_user(array('auth' => 'cas')); 2929 $DB->update_record('user', ['id' => $user->id, 'password' => AUTH_PASSWORD_NOT_CACHED]); 2930 $user->password = AUTH_PASSWORD_NOT_CACHED; 2931 2932 $sink = $this->redirectEvents(); 2933 update_internal_user_password($user, 'wonkawonka'); 2934 $this->assertEquals(0, $sink->count(), 'User updated event should not fire'); 2935 } 2936 2937 /** 2938 * Test if the user has a password hash, but now their auth method 2939 * says not to cache it. Then it should update. 2940 */ 2941 public function test_update_internal_user_password_update_no_cache() { 2942 $this->resetAfterTest(); 2943 2944 $user = $this->getDataGenerator()->create_user(array('password' => 'test')); 2945 $this->assertNotEquals(AUTH_PASSWORD_NOT_CACHED, $user->password); 2946 $user->auth = 'cas'; // Change to a auth that does not store passwords. 2947 2948 $sink = $this->redirectEvents(); 2949 update_internal_user_password($user, 'wonkawonka'); 2950 $this->assertGreaterThanOrEqual(1, $sink->count(), 'User updated event should fire'); 2951 2952 $this->assertEquals(AUTH_PASSWORD_NOT_CACHED, $user->password); 2953 } 2954 2955 public function test_fullname() { 2956 global $CFG; 2957 2958 $this->resetAfterTest(); 2959 2960 // Create a user to test the name display on. 2961 $record = array(); 2962 $record['firstname'] = 'Scott'; 2963 $record['lastname'] = 'Fletcher'; 2964 $record['firstnamephonetic'] = 'スコット'; 2965 $record['lastnamephonetic'] = 'フレチャー'; 2966 $record['alternatename'] = 'No friends'; 2967 $user = $this->getDataGenerator()->create_user($record); 2968 2969 // Back up config settings for restore later. 2970 $originalcfg = new \stdClass(); 2971 $originalcfg->fullnamedisplay = $CFG->fullnamedisplay; 2972 $originalcfg->alternativefullnameformat = $CFG->alternativefullnameformat; 2973 2974 // Testing existing fullnamedisplay settings. 2975 $CFG->fullnamedisplay = 'firstname'; 2976 $testname = fullname($user); 2977 $this->assertSame($user->firstname, $testname); 2978 2979 $CFG->fullnamedisplay = 'firstname lastname'; 2980 $expectedname = "$user->firstname $user->lastname"; 2981 $testname = fullname($user); 2982 $this->assertSame($expectedname, $testname); 2983 2984 $CFG->fullnamedisplay = 'lastname firstname'; 2985 $expectedname = "$user->lastname $user->firstname"; 2986 $testname = fullname($user); 2987 $this->assertSame($expectedname, $testname); 2988 2989 $expectedname = get_string('fullnamedisplay', null, $user); 2990 $CFG->fullnamedisplay = 'language'; 2991 $testname = fullname($user); 2992 $this->assertSame($expectedname, $testname); 2993 2994 // Test override parameter. 2995 $CFG->fullnamedisplay = 'firstname'; 2996 $expectedname = "$user->firstname $user->lastname"; 2997 $testname = fullname($user, true); 2998 $this->assertSame($expectedname, $testname); 2999 3000 // Test alternativefullnameformat setting. 3001 // Test alternativefullnameformat that has been set to nothing. 3002 $CFG->alternativefullnameformat = ''; 3003 $expectedname = "$user->firstname $user->lastname"; 3004 $testname = fullname($user, true); 3005 $this->assertSame($expectedname, $testname); 3006 3007 // Test alternativefullnameformat that has been set to 'language'. 3008 $CFG->alternativefullnameformat = 'language'; 3009 $expectedname = "$user->firstname $user->lastname"; 3010 $testname = fullname($user, true); 3011 $this->assertSame($expectedname, $testname); 3012 3013 // Test customising the alternativefullnameformat setting with all additional name fields. 3014 $CFG->alternativefullnameformat = 'firstname lastname firstnamephonetic lastnamephonetic middlename alternatename'; 3015 $expectedname = "$user->firstname $user->lastname $user->firstnamephonetic $user->lastnamephonetic $user->middlename $user->alternatename"; 3016 $testname = fullname($user, true); 3017 $this->assertSame($expectedname, $testname); 3018 3019 // Test additional name fields. 3020 $CFG->fullnamedisplay = 'lastname lastnamephonetic firstname firstnamephonetic'; 3021 $expectedname = "$user->lastname $user->lastnamephonetic $user->firstname $user->firstnamephonetic"; 3022 $testname = fullname($user); 3023 $this->assertSame($expectedname, $testname); 3024 3025 // Test for handling missing data. 3026 $user->middlename = null; 3027 // Parenthesis with no data. 3028 $CFG->fullnamedisplay = 'firstname (middlename) lastname'; 3029 $expectedname = "$user->firstname $user->lastname"; 3030 $testname = fullname($user); 3031 $this->assertSame($expectedname, $testname); 3032 3033 // Extra spaces due to no data. 3034 $CFG->fullnamedisplay = 'firstname middlename lastname'; 3035 $expectedname = "$user->firstname $user->lastname"; 3036 $testname = fullname($user); 3037 $this->assertSame($expectedname, $testname); 3038 3039 // Regular expression testing. 3040 // Remove some data from the user fields. 3041 $user->firstnamephonetic = ''; 3042 $user->lastnamephonetic = ''; 3043 3044 // Removing empty brackets and excess whitespace. 3045 // All of these configurations should resolve to just firstname lastname. 3046 $configarray = array(); 3047 $configarray[] = 'firstname lastname [firstnamephonetic lastnamephonetic]'; 3048 $configarray[] = 'firstname lastname \'middlename\''; 3049 $configarray[] = 'firstname "firstnamephonetic" lastname'; 3050 $configarray[] = 'firstname 「firstnamephonetic」 lastname 「lastnamephonetic」'; 3051 3052 foreach ($configarray as $config) { 3053 $CFG->fullnamedisplay = $config; 3054 $expectedname = "$user->firstname $user->lastname"; 3055 $testname = fullname($user); 3056 $this->assertSame($expectedname, $testname); 3057 } 3058 3059 // Check to make sure that other characters are left in place. 3060 $configarray = array(); 3061 $configarray['0'] = new \stdClass(); 3062 $configarray['0']->config = 'lastname firstname, middlename'; 3063 $configarray['0']->expectedname = "$user->lastname $user->firstname,"; 3064 $configarray['1'] = new \stdClass(); 3065 $configarray['1']->config = 'lastname firstname + alternatename'; 3066 $configarray['1']->expectedname = "$user->lastname $user->firstname + $user->alternatename"; 3067 $configarray['2'] = new \stdClass(); 3068 $configarray['2']->config = 'firstname aka: alternatename'; 3069 $configarray['2']->expectedname = "$user->firstname aka: $user->alternatename"; 3070 $configarray['3'] = new \stdClass(); 3071 $configarray['3']->config = 'firstname (alternatename)'; 3072 $configarray['3']->expectedname = "$user->firstname ($user->alternatename)"; 3073 $configarray['4'] = new \stdClass(); 3074 $configarray['4']->config = 'firstname [alternatename]'; 3075 $configarray['4']->expectedname = "$user->firstname [$user->alternatename]"; 3076 $configarray['5'] = new \stdClass(); 3077 $configarray['5']->config = 'firstname "lastname"'; 3078 $configarray['5']->expectedname = "$user->firstname \"$user->lastname\""; 3079 3080 foreach ($configarray as $config) { 3081 $CFG->fullnamedisplay = $config->config; 3082 $expectedname = $config->expectedname; 3083 $testname = fullname($user); 3084 $this->assertSame($expectedname, $testname); 3085 } 3086 3087 // Test debugging message displays when 3088 // fullnamedisplay setting is "normal". 3089 $CFG->fullnamedisplay = 'firstname lastname'; 3090 unset($user); 3091 $user = new \stdClass(); 3092 $user->firstname = 'Stan'; 3093 $user->lastname = 'Lee'; 3094 $namedisplay = fullname($user); 3095 $this->assertDebuggingCalled(); 3096 3097 // Tidy up after we finish testing. 3098 $CFG->fullnamedisplay = $originalcfg->fullnamedisplay; 3099 $CFG->alternativefullnameformat = $originalcfg->alternativefullnameformat; 3100 } 3101 3102 public function test_order_in_string() { 3103 $this->resetAfterTest(); 3104 3105 // Return an array in an order as they are encountered in a string. 3106 $valuearray = array('second', 'firsthalf', 'first'); 3107 $formatstring = 'first firsthalf some other text (second)'; 3108 $expectedarray = array('0' => 'first', '6' => 'firsthalf', '33' => 'second'); 3109 $this->assertEquals($expectedarray, order_in_string($valuearray, $formatstring)); 3110 3111 // Try again with a different order for the format. 3112 $valuearray = array('second', 'firsthalf', 'first'); 3113 $formatstring = 'firsthalf first second'; 3114 $expectedarray = array('0' => 'firsthalf', '10' => 'first', '16' => 'second'); 3115 $this->assertEquals($expectedarray, order_in_string($valuearray, $formatstring)); 3116 3117 // Try again with yet another different order for the format. 3118 $valuearray = array('second', 'firsthalf', 'first'); 3119 $formatstring = 'start seconds away second firstquater first firsthalf'; 3120 $expectedarray = array('19' => 'second', '38' => 'first', '44' => 'firsthalf'); 3121 $this->assertEquals($expectedarray, order_in_string($valuearray, $formatstring)); 3122 } 3123 3124 public function test_complete_user_login() { 3125 global $USER, $DB; 3126 3127 $this->resetAfterTest(); 3128 $user = $this->getDataGenerator()->create_user(); 3129 $this->setUser(0); 3130 3131 $sink = $this->redirectEvents(); 3132 $loginuser = clone($user); 3133 $this->setCurrentTimeStart(); 3134 @complete_user_login($loginuser); // Hide session header errors. 3135 $this->assertSame($loginuser, $USER); 3136 $this->assertEquals($user->id, $USER->id); 3137 $events = $sink->get_events(); 3138 $sink->close(); 3139 3140 $this->assertCount(1, $events); 3141 $event = reset($events); 3142 $this->assertInstanceOf('\core\event\user_loggedin', $event); 3143 $this->assertEquals('user', $event->objecttable); 3144 $this->assertEquals($user->id, $event->objectid); 3145 $this->assertEquals(\context_system::instance()->id, $event->contextid); 3146 $this->assertEventContextNotUsed($event); 3147 3148 $user = $DB->get_record('user', array('id'=>$user->id)); 3149 3150 $this->assertTimeCurrent($user->firstaccess); 3151 $this->assertTimeCurrent($user->lastaccess); 3152 3153 $this->assertTimeCurrent($USER->firstaccess); 3154 $this->assertTimeCurrent($USER->lastaccess); 3155 $this->assertTimeCurrent($USER->currentlogin); 3156 $this->assertSame(sesskey(), $USER->sesskey); 3157 $this->assertTimeCurrent($USER->preference['_lastloaded']); 3158 $this->assertObjectNotHasAttribute('password', $USER); 3159 $this->assertObjectNotHasAttribute('description', $USER); 3160 } 3161 3162 /** 3163 * Test require_logout. 3164 */ 3165 public function test_require_logout() { 3166 $this->resetAfterTest(); 3167 $user = $this->getDataGenerator()->create_user(); 3168 $this->setUser($user); 3169 3170 $this->assertTrue(isloggedin()); 3171 3172 // Logout user and capture event. 3173 $sink = $this->redirectEvents(); 3174 require_logout(); 3175 $events = $sink->get_events(); 3176 $sink->close(); 3177 $event = array_pop($events); 3178 3179 // Check if user is logged out. 3180 $this->assertFalse(isloggedin()); 3181 3182 // Test Event. 3183 $this->assertInstanceOf('\core\event\user_loggedout', $event); 3184 $this->assertSame($user->id, $event->objectid); 3185 $this->assertEventContextNotUsed($event); 3186 } 3187 3188 /** 3189 * A data provider for testing email messageid 3190 */ 3191 public function generate_email_messageid_provider() { 3192 return array( 3193 'nopath' => array( 3194 'wwwroot' => 'http://www.example.com', 3195 'ids' => array( 3196 'a-custom-id' => '<a-custom-id@www.example.com>', 3197 'an-id-with-/-a-slash' => '<an-id-with-%2F-a-slash@www.example.com>', 3198 ), 3199 ), 3200 'path' => array( 3201 'wwwroot' => 'http://www.example.com/path/subdir', 3202 'ids' => array( 3203 'a-custom-id' => '<a-custom-id/path/subdir@www.example.com>', 3204 'an-id-with-/-a-slash' => '<an-id-with-%2F-a-slash/path/subdir@www.example.com>', 3205 ), 3206 ), 3207 ); 3208 } 3209 3210 /** 3211 * Test email message id generation 3212 * 3213 * @dataProvider generate_email_messageid_provider 3214 * 3215 * @param string $wwwroot The wwwroot 3216 * @param array $msgids An array of msgid local parts and the final result 3217 */ 3218 public function test_generate_email_messageid($wwwroot, $msgids) { 3219 global $CFG; 3220 3221 $this->resetAfterTest(); 3222 $CFG->wwwroot = $wwwroot; 3223 3224 foreach ($msgids as $local => $final) { 3225 $this->assertEquals($final, generate_email_messageid($local)); 3226 } 3227 } 3228 3229 /** 3230 * Test email with custom headers 3231 */ 3232 public function test_send_email_with_custom_header() { 3233 global $DB, $CFG; 3234 $this->preventResetByRollback(); 3235 $this->resetAfterTest(); 3236 3237 $touser = $this->getDataGenerator()->create_user(); 3238 $fromuser = $this->getDataGenerator()->create_user(); 3239 $fromuser->customheaders = 'X-Custom-Header: foo'; 3240 3241 set_config('allowedemaildomains', 'example.com'); 3242 set_config('emailheaders', 'X-Fixed-Header: bar'); 3243 3244 $sink = $this->redirectEmails(); 3245 email_to_user($touser, $fromuser, 'subject', 'message'); 3246 3247 $emails = $sink->get_messages(); 3248 $this->assertCount(1, $emails); 3249 $email = reset($emails); 3250 $this->assertStringContainsString('X-Custom-Header: foo', $email->header); 3251 $this->assertStringContainsString("X-Fixed-Header: bar", $email->header); 3252 $sink->clear(); 3253 } 3254 3255 /** 3256 * A data provider for testing email diversion 3257 */ 3258 public function diverted_emails_provider() { 3259 return array( 3260 'nodiverts' => array( 3261 'divertallemailsto' => null, 3262 'divertallemailsexcept' => null, 3263 array( 3264 'foo@example.com', 3265 'test@real.com', 3266 'fred.jones@example.com', 3267 'dev1@dev.com', 3268 'fred@example.com', 3269 'fred+verp@example.com', 3270 ), 3271 false, 3272 ), 3273 'alldiverts' => array( 3274 'divertallemailsto' => 'somewhere@elsewhere.com', 3275 'divertallemailsexcept' => null, 3276 array( 3277 'foo@example.com', 3278 'test@real.com', 3279 'fred.jones@example.com', 3280 'dev1@dev.com', 3281 'fred@example.com', 3282 'fred+verp@example.com', 3283 ), 3284 true, 3285 ), 3286 'alsodiverts' => array( 3287 'divertallemailsto' => 'somewhere@elsewhere.com', 3288 'divertallemailsexcept' => '@dev.com, fred(\+.*)?@example.com', 3289 array( 3290 'foo@example.com', 3291 'test@real.com', 3292 'fred.jones@example.com', 3293 'Fred.Jones@Example.com', 3294 ), 3295 true, 3296 ), 3297 'divertsexceptions' => array( 3298 'divertallemailsto' => 'somewhere@elsewhere.com', 3299 'divertallemailsexcept' => '@dev.com, fred(\+.*)?@example.com', 3300 array( 3301 'dev1@dev.com', 3302 'fred@example.com', 3303 'Fred@Example.com', 3304 'fred+verp@example.com', 3305 ), 3306 false, 3307 ), 3308 'divertsexceptionsnewline' => array( 3309 'divertallemailsto' => 'somewhere@elsewhere.com', 3310 'divertallemailsexcept' => "@dev.com\nfred(\+.*)?@example.com", 3311 array( 3312 'dev1@dev.com', 3313 'fred@example.com', 3314 'fred+verp@example.com', 3315 ), 3316 false, 3317 ), 3318 'alsodivertsnewline' => array( 3319 'divertallemailsto' => 'somewhere@elsewhere.com', 3320 'divertallemailsexcept' => "@dev.com\nfred(\+.*)?@example.com", 3321 array( 3322 'foo@example.com', 3323 'test@real.com', 3324 'fred.jones@example.com', 3325 ), 3326 true, 3327 ), 3328 'alsodivertsblankline' => array( 3329 'divertallemailsto' => 'somewhere@elsewhere.com', 3330 'divertallemailsexcept' => "@dev.com\n", 3331 [ 3332 'lionel@example.com', 3333 ], 3334 true, 3335 ), 3336 'divertsexceptionblankline' => array( 3337 'divertallemailsto' => 'somewhere@elsewhere.com', 3338 'divertallemailsexcept' => "@example.com\n", 3339 [ 3340 'lionel@example.com', 3341 ], 3342 false, 3343 ), 3344 ); 3345 } 3346 3347 /** 3348 * Test email diversion 3349 * 3350 * @dataProvider diverted_emails_provider 3351 * 3352 * @param string $divertallemailsto An optional email address 3353 * @param string $divertallemailsexcept An optional exclusion list 3354 * @param array $addresses An array of test addresses 3355 * @param boolean $expected Expected result 3356 */ 3357 public function test_email_should_be_diverted($divertallemailsto, $divertallemailsexcept, $addresses, $expected) { 3358 global $CFG; 3359 3360 $this->resetAfterTest(); 3361 $CFG->divertallemailsto = $divertallemailsto; 3362 $CFG->divertallemailsexcept = $divertallemailsexcept; 3363 3364 foreach ($addresses as $address) { 3365 $this->assertEquals($expected, email_should_be_diverted($address)); 3366 } 3367 } 3368 3369 public function test_email_to_user() { 3370 global $CFG; 3371 3372 $this->resetAfterTest(); 3373 3374 $user1 = $this->getDataGenerator()->create_user(array('maildisplay' => 1, 'mailformat' => 0)); 3375 $user2 = $this->getDataGenerator()->create_user(array('maildisplay' => 1, 'mailformat' => 1)); 3376 $user3 = $this->getDataGenerator()->create_user(array('maildisplay' => 0)); 3377 set_config('allowedemaildomains', "example.com\r\nmoodle.org"); 3378 3379 $subject = 'subject'; 3380 $messagetext = 'message text'; 3381 $subject2 = 'subject 2'; 3382 $messagetext2 = '<b>message text 2</b>'; 3383 3384 // Close the default email sink. 3385 $sink = $this->redirectEmails(); 3386 $sink->close(); 3387 3388 $CFG->noemailever = true; 3389 $this->assertNotEmpty($CFG->noemailever); 3390 email_to_user($user1, $user2, $subject, $messagetext); 3391 $this->assertDebuggingCalled('Not sending email due to $CFG->noemailever config setting'); 3392 3393 unset_config('noemailever'); 3394 3395 email_to_user($user1, $user2, $subject, $messagetext); 3396 $this->assertDebuggingCalled('Unit tests must not send real emails! Use $this->redirectEmails()'); 3397 3398 $sink = $this->redirectEmails(); 3399 email_to_user($user1, $user2, $subject, $messagetext); 3400 email_to_user($user2, $user1, $subject2, $messagetext2); 3401 $this->assertSame(2, $sink->count()); 3402 $result = $sink->get_messages(); 3403 $this->assertCount(2, $result); 3404 $sink->close(); 3405 3406 $this->assertSame($subject, $result[0]->subject); 3407 $this->assertSame($messagetext, trim($result[0]->body)); 3408 $this->assertSame($user1->email, $result[0]->to); 3409 $this->assertSame($user2->email, $result[0]->from); 3410 $this->assertStringContainsString('Content-Type: text/plain', $result[0]->header); 3411 3412 $this->assertSame($subject2, $result[1]->subject); 3413 $this->assertStringContainsString($messagetext2, quoted_printable_decode($result[1]->body)); 3414 $this->assertSame($user2->email, $result[1]->to); 3415 $this->assertSame($user1->email, $result[1]->from); 3416 $this->assertStringNotContainsString('Content-Type: text/plain', $result[1]->header); 3417 3418 email_to_user($user1, $user2, $subject, $messagetext); 3419 $this->assertDebuggingCalled('Unit tests must not send real emails! Use $this->redirectEmails()'); 3420 3421 // Test that an empty noreplyaddress will default to a no-reply address. 3422 $sink = $this->redirectEmails(); 3423 email_to_user($user1, $user3, $subject, $messagetext); 3424 $result = $sink->get_messages(); 3425 $this->assertEquals($CFG->noreplyaddress, $result[0]->from); 3426 $sink->close(); 3427 set_config('noreplyaddress', ''); 3428 $sink = $this->redirectEmails(); 3429 email_to_user($user1, $user3, $subject, $messagetext); 3430 $result = $sink->get_messages(); 3431 $this->assertEquals('noreply@www.example.com', $result[0]->from); 3432 $sink->close(); 3433 3434 // Test $CFG->allowedemaildomains. 3435 set_config('noreplyaddress', 'noreply@www.example.com'); 3436 $this->assertNotEmpty($CFG->allowedemaildomains); 3437 $sink = $this->redirectEmails(); 3438 email_to_user($user1, $user2, $subject, $messagetext); 3439 unset_config('allowedemaildomains'); 3440 email_to_user($user1, $user2, $subject, $messagetext); 3441 $result = $sink->get_messages(); 3442 $this->assertNotEquals($CFG->noreplyaddress, $result[0]->from); 3443 $this->assertEquals($CFG->noreplyaddress, $result[1]->from); 3444 $sink->close(); 3445 3446 // Try to send an unsafe attachment, we should see an error message in the eventual mail body. 3447 $attachment = '../test.txt'; 3448 $attachname = 'txt'; 3449 3450 $sink = $this->redirectEmails(); 3451 email_to_user($user1, $user2, $subject, $messagetext, '', $attachment, $attachname); 3452 $this->assertSame(1, $sink->count()); 3453 $result = $sink->get_messages(); 3454 $this->assertCount(1, $result); 3455 $this->assertStringContainsString('error.txt', $result[0]->body); 3456 $this->assertStringContainsString('Error in attachment. User attempted to attach a filename with a unsafe name.', $result[0]->body); 3457 $sink->close(); 3458 } 3459 3460 /** 3461 * Data provider for {@see test_email_to_user_attachment} 3462 * 3463 * @return array 3464 */ 3465 public function email_to_user_attachment_provider(): array { 3466 global $CFG; 3467 3468 // Return all paths that can be used to send attachments from. 3469 return [ 3470 'cachedir' => [$CFG->cachedir], 3471 'dataroot' => [$CFG->dataroot], 3472 'dirroot' => [$CFG->dirroot], 3473 'localcachedir' => [$CFG->localcachedir], 3474 'tempdir' => [$CFG->tempdir], 3475 // Paths within $CFG->localrequestdir. 3476 'localrequestdir_request_directory' => [make_request_directory()], 3477 'localrequestdir_request_storage_directory' => [get_request_storage_directory()], 3478 // Pass null to indicate we want to test a path relative to $CFG->dataroot. 3479 'relative' => [null] 3480 ]; 3481 } 3482 3483 /** 3484 * Test sending attachments with email_to_user 3485 * 3486 * @param string|null $filedir 3487 * 3488 * @dataProvider email_to_user_attachment_provider 3489 */ 3490 public function test_email_to_user_attachment(?string $filedir): void { 3491 global $CFG; 3492 3493 // If $filedir is null, then write our test file to $CFG->dataroot. 3494 $filepath = ($filedir ?: $CFG->dataroot) . '/hello.txt'; 3495 file_put_contents($filepath, 'Hello'); 3496 3497 $user = \core_user::get_support_user(); 3498 $message = 'Test attachment path'; 3499 3500 // Create sink to catch all sent e-mails. 3501 $sink = $this->redirectEmails(); 3502 3503 // Attachment path will be that of the test file if $filedir was passed, otherwise the relative path from $CFG->dataroot. 3504 $filename = basename($filepath); 3505 $attachmentpath = $filedir ? $filepath : $filename; 3506 email_to_user($user, $user, $message, $message, $message, $attachmentpath, $filename); 3507 3508 $messages = $sink->get_messages(); 3509 $sink->close(); 3510 3511 $this->assertCount(1, $messages); 3512 3513 // Verify attachment in message body (attachment is in MIME format, but we can detect some Content fields). 3514 $messagebody = reset($messages)->body; 3515 $this->assertStringContainsString('Content-Type: text/plain; name=' . $filename, $messagebody); 3516 $this->assertStringContainsString('Content-Disposition: attachment; filename=' . $filename, $messagebody); 3517 3518 // Cleanup. 3519 unlink($filepath); 3520 } 3521 3522 /** 3523 * Test sending an attachment that doesn't exist to email_to_user 3524 */ 3525 public function test_email_to_user_attachment_missing(): void { 3526 $user = \core_user::get_support_user(); 3527 $message = 'Test attachment path'; 3528 3529 // Create sink to catch all sent e-mails. 3530 $sink = $this->redirectEmails(); 3531 3532 $attachmentpath = '/hola/hello.txt'; 3533 $filename = basename($attachmentpath); 3534 email_to_user($user, $user, $message, $message, $message, $attachmentpath, $filename); 3535 3536 $messages = $sink->get_messages(); 3537 $sink->close(); 3538 3539 $this->assertCount(1, $messages); 3540 3541 // Verify attachment not in message body (attachment is in MIME format, but we can detect some Content fields). 3542 $messagebody = reset($messages)->body; 3543 $this->assertStringNotContainsString('Content-Type: text/plain; name="' . $filename . '"', $messagebody); 3544 $this->assertStringNotContainsString('Content-Disposition: attachment; filename=' . $filename, $messagebody); 3545 } 3546 3547 /** 3548 * Test setnew_password_and_mail. 3549 */ 3550 public function test_setnew_password_and_mail() { 3551 global $DB, $CFG; 3552 3553 $this->resetAfterTest(); 3554 3555 $user = $this->getDataGenerator()->create_user(); 3556 3557 // Update user password. 3558 $sink = $this->redirectEvents(); 3559 $sink2 = $this->redirectEmails(); // Make sure we are redirecting emails. 3560 setnew_password_and_mail($user); 3561 $events = $sink->get_events(); 3562 $sink->close(); 3563 $sink2->close(); 3564 $event = array_pop($events); 3565 3566 // Test updated value. 3567 $dbuser = $DB->get_record('user', array('id' => $user->id)); 3568 $this->assertSame($user->firstname, $dbuser->firstname); 3569 $this->assertNotEmpty($dbuser->password); 3570 3571 // Test event. 3572 $this->assertInstanceOf('\core\event\user_password_updated', $event); 3573 $this->assertSame($user->id, $event->relateduserid); 3574 $this->assertEquals(\context_user::instance($user->id), $event->get_context()); 3575 $this->assertEventContextNotUsed($event); 3576 } 3577 3578 /** 3579 * Data provider for test_generate_confirmation_link 3580 * @return Array of confirmation urls and expected resultant confirmation links 3581 */ 3582 public function generate_confirmation_link_provider() { 3583 global $CFG; 3584 return [ 3585 "Simple name" => [ 3586 "username" => "simplename", 3587 "confirmationurl" => null, 3588 "expected" => $CFG->wwwroot . "/login/confirm.php?data=/simplename" 3589 ], 3590 "Period in between words in username" => [ 3591 "username" => "period.inbetween", 3592 "confirmationurl" => null, 3593 "expected" => $CFG->wwwroot . "/login/confirm.php?data=/period%2Einbetween" 3594 ], 3595 "Trailing periods in username" => [ 3596 "username" => "trailingperiods...", 3597 "confirmationurl" => null, 3598 "expected" => $CFG->wwwroot . "/login/confirm.php?data=/trailingperiods%2E%2E%2E" 3599 ], 3600 "At symbol in username" => [ 3601 "username" => "at@symbol", 3602 "confirmationurl" => null, 3603 "expected" => $CFG->wwwroot . "/login/confirm.php?data=/at%40symbol" 3604 ], 3605 "Dash symbol in username" => [ 3606 "username" => "has-dash", 3607 "confirmationurl" => null, 3608 "expected" => $CFG->wwwroot . "/login/confirm.php?data=/has-dash" 3609 ], 3610 "Underscore in username" => [ 3611 "username" => "under_score", 3612 "confirmationurl" => null, 3613 "expected" => $CFG->wwwroot . "/login/confirm.php?data=/under_score" 3614 ], 3615 "Many different characters in username" => [ 3616 "username" => "many_-.@characters@_@-..-..", 3617 "confirmationurl" => null, 3618 "expected" => $CFG->wwwroot . "/login/confirm.php?data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E" 3619 ], 3620 "Custom relative confirmation url" => [ 3621 "username" => "many_-.@characters@_@-..-..", 3622 "confirmationurl" => "/custom/local/url.php", 3623 "expected" => $CFG->wwwroot . "/custom/local/url.php?data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E" 3624 ], 3625 "Custom relative confirmation url with parameters" => [ 3626 "username" => "many_-.@characters@_@-..-..", 3627 "confirmationurl" => "/custom/local/url.php?with=param", 3628 "expected" => $CFG->wwwroot . "/custom/local/url.php?with=param&data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E" 3629 ], 3630 "Custom local confirmation url" => [ 3631 "username" => "many_-.@characters@_@-..-..", 3632 "confirmationurl" => $CFG->wwwroot . "/custom/local/url.php", 3633 "expected" => $CFG->wwwroot . "/custom/local/url.php?data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E" 3634 ], 3635 "Custom local confirmation url with parameters" => [ 3636 "username" => "many_-.@characters@_@-..-..", 3637 "confirmationurl" => $CFG->wwwroot . "/custom/local/url.php?with=param", 3638 "expected" => $CFG->wwwroot . "/custom/local/url.php?with=param&data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E" 3639 ], 3640 "Custom external confirmation url" => [ 3641 "username" => "many_-.@characters@_@-..-..", 3642 "confirmationurl" => "http://moodle.org/custom/external/url.php", 3643 "expected" => "http://moodle.org/custom/external/url.php?data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E" 3644 ], 3645 "Custom external confirmation url with parameters" => [ 3646 "username" => "many_-.@characters@_@-..-..", 3647 "confirmationurl" => "http://moodle.org/ext.php?with=some¶m=eters", 3648 "expected" => "http://moodle.org/ext.php?with=some¶m=eters&data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E" 3649 ], 3650 "Custom external confirmation url with parameters" => [ 3651 "username" => "many_-.@characters@_@-..-..", 3652 "confirmationurl" => "http://moodle.org/ext.php?with=some&data=test", 3653 "expected" => "http://moodle.org/ext.php?with=some&data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E" 3654 ], 3655 ]; 3656 } 3657 3658 /** 3659 * Test generate_confirmation_link 3660 * @dataProvider generate_confirmation_link_provider 3661 * @param string $username The name of the user 3662 * @param string $confirmationurl The url the user should go to to confirm 3663 * @param string $expected The expected url of the confirmation link 3664 */ 3665 public function test_generate_confirmation_link($username, $confirmationurl, $expected) { 3666 $this->resetAfterTest(); 3667 $sink = $this->redirectEmails(); 3668 3669 $user = $this->getDataGenerator()->create_user( 3670 [ 3671 "username" => $username, 3672 "confirmed" => 0, 3673 "email" => 'test@example.com', 3674 ] 3675 ); 3676 3677 send_confirmation_email($user, $confirmationurl); 3678 $sink->close(); 3679 $messages = $sink->get_messages(); 3680 $message = array_shift($messages); 3681 $messagebody = quoted_printable_decode($message->body); 3682 3683 $this->assertStringContainsString($expected, $messagebody); 3684 } 3685 3686 /** 3687 * Test generate_confirmation_link with custom admin link 3688 */ 3689 public function test_generate_confirmation_link_with_custom_admin() { 3690 global $CFG; 3691 3692 $this->resetAfterTest(); 3693 $sink = $this->redirectEmails(); 3694 3695 $admin = $CFG->admin; 3696 $CFG->admin = 'custom/admin/path'; 3697 3698 $user = $this->getDataGenerator()->create_user( 3699 [ 3700 "username" => "many_-.@characters@_@-..-..", 3701 "confirmed" => 0, 3702 "email" => 'test@example.com', 3703 ] 3704 ); 3705 $confirmationurl = "/admin/test.php?with=params"; 3706 $expected = $CFG->wwwroot . "/" . $CFG->admin . "/test.php?with=params&data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E"; 3707 3708 send_confirmation_email($user, $confirmationurl); 3709 $sink->close(); 3710 $messages = $sink->get_messages(); 3711 $message = array_shift($messages); 3712 $messagebody = quoted_printable_decode($message->body); 3713 3714 $sink->close(); 3715 $this->assertStringContainsString($expected, $messagebody); 3716 3717 $CFG->admin = $admin; 3718 } 3719 3720 3721 /** 3722 * Test remove_course_content deletes course contents 3723 * TODO Add asserts to verify other data related to course is deleted as well. 3724 */ 3725 public function test_remove_course_contents() { 3726 3727 $this->resetAfterTest(); 3728 3729 $course = $this->getDataGenerator()->create_course(); 3730 $user = $this->getDataGenerator()->create_user(); 3731 $gen = $this->getDataGenerator()->get_plugin_generator('core_notes'); 3732 $note = $gen->create_instance(array('courseid' => $course->id, 'userid' => $user->id)); 3733 3734 $this->assertNotEquals(false, note_load($note->id)); 3735 remove_course_contents($course->id, false); 3736 $this->assertFalse(note_load($note->id)); 3737 } 3738 3739 /** 3740 * Test function username_load_fields_from_object(). 3741 */ 3742 public function test_username_load_fields_from_object() { 3743 $this->resetAfterTest(); 3744 3745 // This object represents the information returned from an sql query. 3746 $userinfo = new \stdClass(); 3747 $userinfo->userid = 1; 3748 $userinfo->username = 'loosebruce'; 3749 $userinfo->firstname = 'Bruce'; 3750 $userinfo->lastname = 'Campbell'; 3751 $userinfo->firstnamephonetic = 'ブルース'; 3752 $userinfo->lastnamephonetic = 'カンベッル'; 3753 $userinfo->middlename = ''; 3754 $userinfo->alternatename = ''; 3755 $userinfo->email = ''; 3756 $userinfo->picture = 23; 3757 $userinfo->imagealt = 'Michael Jordan draining another basket.'; 3758 $userinfo->idnumber = 3982; 3759 3760 // Just user name fields. 3761 $user = new \stdClass(); 3762 $user = username_load_fields_from_object($user, $userinfo); 3763 $expectedarray = new \stdClass(); 3764 $expectedarray->firstname = 'Bruce'; 3765 $expectedarray->lastname = 'Campbell'; 3766 $expectedarray->firstnamephonetic = 'ブルース'; 3767 $expectedarray->lastnamephonetic = 'カンベッル'; 3768 $expectedarray->middlename = ''; 3769 $expectedarray->alternatename = ''; 3770 $this->assertEquals($user, $expectedarray); 3771 3772 // User information for showing a picture. 3773 $user = new \stdClass(); 3774 $additionalfields = explode(',', implode(',', \core_user\fields::get_picture_fields())); 3775 $user = username_load_fields_from_object($user, $userinfo, null, $additionalfields); 3776 $user->id = $userinfo->userid; 3777 $expectedarray = new \stdClass(); 3778 $expectedarray->id = 1; 3779 $expectedarray->firstname = 'Bruce'; 3780 $expectedarray->lastname = 'Campbell'; 3781 $expectedarray->firstnamephonetic = 'ブルース'; 3782 $expectedarray->lastnamephonetic = 'カンベッル'; 3783 $expectedarray->middlename = ''; 3784 $expectedarray->alternatename = ''; 3785 $expectedarray->email = ''; 3786 $expectedarray->picture = 23; 3787 $expectedarray->imagealt = 'Michael Jordan draining another basket.'; 3788 $this->assertEquals($user, $expectedarray); 3789 3790 // Alter the userinfo object to have a prefix. 3791 $userinfo->authorfirstname = 'Bruce'; 3792 $userinfo->authorlastname = 'Campbell'; 3793 $userinfo->authorfirstnamephonetic = 'ブルース'; 3794 $userinfo->authorlastnamephonetic = 'カンベッル'; 3795 $userinfo->authormiddlename = ''; 3796 $userinfo->authorpicture = 23; 3797 $userinfo->authorimagealt = 'Michael Jordan draining another basket.'; 3798 $userinfo->authoremail = 'test@example.com'; 3799 3800 3801 // Return an object with user picture information. 3802 $user = new \stdClass(); 3803 $additionalfields = explode(',', implode(',', \core_user\fields::get_picture_fields())); 3804 $user = username_load_fields_from_object($user, $userinfo, 'author', $additionalfields); 3805 $user->id = $userinfo->userid; 3806 $expectedarray = new \stdClass(); 3807 $expectedarray->id = 1; 3808 $expectedarray->firstname = 'Bruce'; 3809 $expectedarray->lastname = 'Campbell'; 3810 $expectedarray->firstnamephonetic = 'ブルース'; 3811 $expectedarray->lastnamephonetic = 'カンベッル'; 3812 $expectedarray->middlename = ''; 3813 $expectedarray->alternatename = ''; 3814 $expectedarray->email = 'test@example.com'; 3815 $expectedarray->picture = 23; 3816 $expectedarray->imagealt = 'Michael Jordan draining another basket.'; 3817 $this->assertEquals($user, $expectedarray); 3818 } 3819 3820 /** 3821 * Test function {@see count_words()}. 3822 * 3823 * @dataProvider count_words_testcases 3824 * @param int $expectedcount number of words in $string. 3825 * @param string $string the test string to count the words of. 3826 * @param int|null $format 3827 */ 3828 public function test_count_words(int $expectedcount, string $string, $format = null): void { 3829 $this->assertEquals($expectedcount, count_words($string, $format), 3830 "'$string' with format '$format' does not match count $expectedcount"); 3831 } 3832 3833 /** 3834 * Data provider for {@see test_count_words}. 3835 * 3836 * @return array of test cases. 3837 */ 3838 public function count_words_testcases(): array { 3839 // Copy-pasting example from MDL-64240. 3840 $copypasted = <<<EOT 3841 <p onclick="alert('boop');">Snoot is booped</p> 3842 <script>alert('Boop the snoot');</script> 3843 <img alt="Boop the Snoot." src="https://proxy.duckduckgo.com/iu/?u=http%3A%2F%2Fwww.geekfill.com%2Fwp-content%2Fuploads%2F2015%2F08%2FBoop-the-Snoot.jpg&f=1"> 3844 EOT; 3845 3846 // The counts here should match MS Word and Libre Office. 3847 return [ 3848 [0, ''], 3849 [4, 'one two three four'], 3850 [1, "a'b"], 3851 [1, '1+1=2'], 3852 [1, ' one-sided '], 3853 [2, 'one two'], 3854 [1, 'email@example.com'], 3855 [2, 'first\part second/part'], 3856 [4, '<p>one two<br></br>three four</p>'], 3857 [4, '<p>one two<br>three four</p>'], 3858 [4, '<p>one two<br />three four</p>'], // XHTML style. 3859 [3, ' one ... three '], 3860 [1, 'just...one'], 3861 [3, ' one & three '], 3862 [1, 'just&one'], 3863 [2, 'em—dash'], 3864 [2, 'en–dash'], 3865 [4, '1³ £2 €3.45 $6,789'], 3866 [2, 'ブルース カンベッル'], // MS word counts this as 11, but we don't handle that yet. 3867 [4, '<p>one two</p><p>three four</p>'], 3868 [4, '<p>one two</p><p><br/></p><p>three four</p>'], 3869 [4, '<p>one</p><ul><li>two</li><li>three</li></ul><p>four.</p>'], 3870 [1, '<p>em<b>phas</b>is.</p>'], 3871 [1, '<p>em<i>phas</i>is.</p>'], 3872 [1, '<p>em<strong>phas</strong>is.</p>'], 3873 [1, '<p>em<em>phas</em>is.</p>'], 3874 [2, "one\ntwo"], 3875 [2, "one\rtwo"], 3876 [2, "one\ttwo"], 3877 [2, "one\vtwo"], 3878 [2, "one\ftwo"], 3879 [1, "SO<sub>4</sub><sup>2-</sup>"], 3880 [6, '4+4=8 i.e. O(1) a,b,c,d I’m black&blue_really'], 3881 [1, '<span>a</span><span>b</span>'], 3882 [1, '<span>a</span><span>b</span>', FORMAT_PLAIN], 3883 [1, '<span>a</span><span>b</span>', FORMAT_HTML], 3884 [1, '<span>a</span><span>b</span>', FORMAT_MOODLE], 3885 [1, '<span>a</span><span>b</span>', FORMAT_MARKDOWN], 3886 [1, 'aa <argh <bleh>pokus</bleh>'], 3887 [2, 'aa <argh <bleh>pokus</bleh>', FORMAT_HTML], 3888 [6, $copypasted], 3889 [6, $copypasted, FORMAT_PLAIN], 3890 [3, $copypasted, FORMAT_HTML], 3891 [3, $copypasted, FORMAT_MOODLE], 3892 ]; 3893 } 3894 3895 /** 3896 * Test function {@see count_letters()}. 3897 * 3898 * @dataProvider count_letters_testcases 3899 * @param int $expectedcount number of characters in $string. 3900 * @param string $string the test string to count the letters of. 3901 * @param int|null $format 3902 */ 3903 public function test_count_letters(int $expectedcount, string $string, $format = null): void { 3904 $this->assertEquals($expectedcount, count_letters($string, $format), 3905 "'$string' with format '$format' does not match count $expectedcount"); 3906 } 3907 3908 /** 3909 * Data provider for {@see count_letters_testcases}. 3910 * 3911 * @return array of test cases. 3912 */ 3913 public function count_letters_testcases(): array { 3914 return [ 3915 [0, ''], 3916 [1, 'x'], 3917 [1, '&'], 3918 [4, '<p>frog</p>'], 3919 [4, '<p>frog</p>', FORMAT_PLAIN], 3920 [4, '<p>frog</p>', FORMAT_MOODLE], 3921 [4, '<p>frog</p>', FORMAT_HTML], 3922 [4, '<p>frog</p>', FORMAT_MARKDOWN], 3923 [2, 'aa <argh <bleh>pokus</bleh>'], 3924 [7, 'aa <argh <bleh>pokus</bleh>', FORMAT_HTML], 3925 ]; 3926 } 3927 3928 /** 3929 * Tests the getremoteaddr() function. 3930 */ 3931 public function test_getremoteaddr() { 3932 global $CFG; 3933 3934 $this->resetAfterTest(); 3935 3936 $CFG->getremoteaddrconf = null; // Use default value, GETREMOTEADDR_SKIP_DEFAULT. 3937 $noip = getremoteaddr('1.1.1.1'); 3938 $this->assertEquals('1.1.1.1', $noip); 3939 3940 $remoteaddr = isset($_SERVER['REMOTE_ADDR']) ? $_SERVER['REMOTE_ADDR'] : null; 3941 $_SERVER['REMOTE_ADDR'] = '127.0.0.1'; 3942 $singleip = getremoteaddr(); 3943 $this->assertEquals('127.0.0.1', $singleip); 3944 3945 $_SERVER['REMOTE_ADDR'] = $remoteaddr; // Restore server value. 3946 3947 $CFG->getremoteaddrconf = 0; // Don't skip any source. 3948 $noip = getremoteaddr('1.1.1.1'); 3949 $this->assertEquals('1.1.1.1', $noip); 3950 3951 // Populate all $_SERVER values to review order. 3952 $ipsources = [ 3953 'HTTP_CLIENT_IP' => '2.2.2.2', 3954 'HTTP_X_FORWARDED_FOR' => '3.3.3.3', 3955 'REMOTE_ADDR' => '4.4.4.4', 3956 ]; 3957 $originalvalues = []; 3958 foreach ($ipsources as $source => $ip) { 3959 $originalvalues[$source] = isset($_SERVER[$source]) ? $_SERVER[$source] : null; // Saving data to restore later. 3960 $_SERVER[$source] = $ip; 3961 } 3962 3963 foreach ($ipsources as $source => $expectedip) { 3964 $ip = getremoteaddr(); 3965 $this->assertEquals($expectedip, $ip); 3966 unset($_SERVER[$source]); // Removing the value so next time we get the following ip. 3967 } 3968 3969 // Restore server values. 3970 foreach ($originalvalues as $source => $ip) { 3971 $_SERVER[$source] = $ip; 3972 } 3973 3974 // All $_SERVER values have been removed, we should get the default again. 3975 $noip = getremoteaddr('1.1.1.1'); 3976 $this->assertEquals('1.1.1.1', $noip); 3977 3978 $CFG->getremoteaddrconf = GETREMOTEADDR_SKIP_HTTP_CLIENT_IP; 3979 $xforwardedfor = isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : null; 3980 3981 $_SERVER['HTTP_X_FORWARDED_FOR'] = ''; 3982 $noip = getremoteaddr('1.1.1.1'); 3983 $this->assertEquals('1.1.1.1', $noip); 3984 3985 $_SERVER['HTTP_X_FORWARDED_FOR'] = ''; 3986 $noip = getremoteaddr(); 3987 $this->assertEquals('0.0.0.0', $noip); 3988 3989 $_SERVER['HTTP_X_FORWARDED_FOR'] = '127.0.0.1'; 3990 $singleip = getremoteaddr(); 3991 $this->assertEquals('127.0.0.1', $singleip); 3992 3993 $_SERVER['HTTP_X_FORWARDED_FOR'] = '127.0.0.1,127.0.0.2'; 3994 $twoip = getremoteaddr(); 3995 $this->assertEquals('127.0.0.2', $twoip); 3996 3997 $_SERVER['HTTP_X_FORWARDED_FOR'] = '127.0.0.1,127.0.0.2,127.0.0.3'; 3998 $threeip = getremoteaddr(); 3999 $this->assertEquals('127.0.0.3', $threeip); 4000 4001 $_SERVER['HTTP_X_FORWARDED_FOR'] = '127.0.0.1,127.0.0.2:65535'; 4002 $portip = getremoteaddr(); 4003 $this->assertEquals('127.0.0.2', $portip); 4004 4005 $_SERVER['HTTP_X_FORWARDED_FOR'] = '127.0.0.1,0:0:0:0:0:0:0:2'; 4006 $portip = getremoteaddr(); 4007 $this->assertEquals('0:0:0:0:0:0:0:2', $portip); 4008 4009 $_SERVER['HTTP_X_FORWARDED_FOR'] = '127.0.0.1,0::2'; 4010 $portip = getremoteaddr(); 4011 $this->assertEquals('0:0:0:0:0:0:0:2', $portip); 4012 4013 $_SERVER['HTTP_X_FORWARDED_FOR'] = '127.0.0.1,[0:0:0:0:0:0:0:2]:65535'; 4014 $portip = getremoteaddr(); 4015 $this->assertEquals('0:0:0:0:0:0:0:2', $portip); 4016 4017 $_SERVER['HTTP_X_FORWARDED_FOR'] = $xforwardedfor; 4018 4019 } 4020 4021 /** 4022 * Test function for creation of random strings. 4023 */ 4024 public function test_random_string() { 4025 $pool = 'a-zA-Z0-9'; 4026 4027 $result = random_string(10); 4028 $this->assertSame(10, strlen($result)); 4029 $this->assertMatchesRegularExpression('/^[' . $pool . ']+$/', $result); 4030 $this->assertNotSame($result, random_string(10)); 4031 4032 $result = random_string(21); 4033 $this->assertSame(21, strlen($result)); 4034 $this->assertMatchesRegularExpression('/^[' . $pool . ']+$/', $result); 4035 $this->assertNotSame($result, random_string(21)); 4036 4037 $result = random_string(666); 4038 $this->assertSame(666, strlen($result)); 4039 $this->assertMatchesRegularExpression('/^[' . $pool . ']+$/', $result); 4040 4041 $result = random_string(); 4042 $this->assertSame(15, strlen($result)); 4043 $this->assertMatchesRegularExpression('/^[' . $pool . ']+$/', $result); 4044 4045 $this->assertDebuggingNotCalled(); 4046 } 4047 4048 /** 4049 * Test function for creation of complex random strings. 4050 */ 4051 public function test_complex_random_string() { 4052 $pool = preg_quote('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789`~!@#%^&*()_+-=[];,./<>?:{} ', '/'); 4053 4054 $result = complex_random_string(10); 4055 $this->assertSame(10, strlen($result)); 4056 $this->assertMatchesRegularExpression('/^[' . $pool . ']+$/', $result); 4057 $this->assertNotSame($result, complex_random_string(10)); 4058 4059 $result = complex_random_string(21); 4060 $this->assertSame(21, strlen($result)); 4061 $this->assertMatchesRegularExpression('/^[' . $pool . ']+$/', $result); 4062 $this->assertNotSame($result, complex_random_string(21)); 4063 4064 $result = complex_random_string(666); 4065 $this->assertSame(666, strlen($result)); 4066 $this->assertMatchesRegularExpression('/^[' . $pool . ']+$/', $result); 4067 4068 $result = complex_random_string(); 4069 $this->assertEqualsWithDelta(28, strlen($result), 4); // Expected length is 24 - 32. 4070 $this->assertMatchesRegularExpression('/^[' . $pool . ']+$/', $result); 4071 4072 $this->assertDebuggingNotCalled(); 4073 } 4074 4075 /** 4076 * Data provider for private ips. 4077 */ 4078 public function data_private_ips() { 4079 return array( 4080 array('10.0.0.0'), 4081 array('172.16.0.0'), 4082 array('192.168.1.0'), 4083 array('fdfe:dcba:9876:ffff:fdc6:c46b:bb8f:7d4c'), 4084 array('fdc6:c46b:bb8f:7d4c:fdc6:c46b:bb8f:7d4c'), 4085 array('fdc6:c46b:bb8f:7d4c:0000:8a2e:0370:7334'), 4086 array('127.0.0.1'), // This has been buggy in past: https://bugs.php.net/bug.php?id=53150. 4087 ); 4088 } 4089 4090 /** 4091 * Checks ip_is_public returns false for private ips. 4092 * 4093 * @param string $ip the ipaddress to test 4094 * @dataProvider data_private_ips 4095 */ 4096 public function test_ip_is_public_private_ips($ip) { 4097 $this->assertFalse(ip_is_public($ip)); 4098 } 4099 4100 /** 4101 * Data provider for public ips. 4102 */ 4103 public function data_public_ips() { 4104 return array( 4105 array('2400:cb00:2048:1::8d65:71b3'), 4106 array('2400:6180:0:d0::1b:2001'), 4107 array('141.101.113.179'), 4108 array('123.45.67.178'), 4109 ); 4110 } 4111 4112 /** 4113 * Checks ip_is_public returns true for public ips. 4114 * 4115 * @param string $ip the ipaddress to test 4116 * @dataProvider data_public_ips 4117 */ 4118 public function test_ip_is_public_public_ips($ip) { 4119 $this->assertTrue(ip_is_public($ip)); 4120 } 4121 4122 /** 4123 * Test the function can_send_from_real_email_address 4124 * 4125 * @param string $email Email address for the from user. 4126 * @param int $display The user's email display preference. 4127 * @param bool $samecourse Are the users in the same course? 4128 * @param string $config The CFG->allowedemaildomains config values 4129 * @param bool $result The expected result. 4130 * @dataProvider data_can_send_from_real_email_address 4131 */ 4132 public function test_can_send_from_real_email_address($email, $display, $samecourse, $config, $result) { 4133 $this->resetAfterTest(); 4134 4135 $fromuser = $this->getDataGenerator()->create_user(); 4136 $touser = $this->getDataGenerator()->create_user(); 4137 $course = $this->getDataGenerator()->create_course(); 4138 set_config('allowedemaildomains', $config); 4139 4140 $fromuser->email = $email; 4141 $fromuser->maildisplay = $display; 4142 if ($samecourse) { 4143 $this->getDataGenerator()->enrol_user($fromuser->id, $course->id, 'student'); 4144 $this->getDataGenerator()->enrol_user($touser->id, $course->id, 'student'); 4145 } else { 4146 $this->getDataGenerator()->enrol_user($fromuser->id, $course->id, 'student'); 4147 } 4148 $this->assertEquals($result, can_send_from_real_email_address($fromuser, $touser)); 4149 } 4150 4151 /** 4152 * Data provider for test_can_send_from_real_email_address. 4153 * 4154 * @return array Returns an array of test data for the above function. 4155 */ 4156 public function data_can_send_from_real_email_address() { 4157 return [ 4158 // Test from email is in allowed domain. 4159 // Test that from display is set to show no one. 4160 [ 4161 'email' => 'fromuser@example.com', 4162 'display' => \core_user::MAILDISPLAY_HIDE, 4163 'samecourse' => false, 4164 'config' => "example.com\r\ntest.com", 4165 'result' => false 4166 ], 4167 // Test that from display is set to course members only (course member). 4168 [ 4169 'email' => 'fromuser@example.com', 4170 'display' => \core_user::MAILDISPLAY_COURSE_MEMBERS_ONLY, 4171 'samecourse' => true, 4172 'config' => "example.com\r\ntest.com", 4173 'result' => true 4174 ], 4175 // Test that from display is set to course members only (Non course member). 4176 [ 4177 'email' => 'fromuser@example.com', 4178 'display' => \core_user::MAILDISPLAY_COURSE_MEMBERS_ONLY, 4179 'samecourse' => false, 4180 'config' => "example.com\r\ntest.com", 4181 'result' => false 4182 ], 4183 // Test that from display is set to show everyone. 4184 [ 4185 'email' => 'fromuser@example.com', 4186 'display' => \core_user::MAILDISPLAY_EVERYONE, 4187 'samecourse' => false, 4188 'config' => "example.com\r\ntest.com", 4189 'result' => true 4190 ], 4191 // Test a few different config value formats for parsing correctness. 4192 [ 4193 'email' => 'fromuser@example.com', 4194 'display' => \core_user::MAILDISPLAY_EVERYONE, 4195 'samecourse' => false, 4196 'config' => "\n test.com\nexample.com \n", 4197 'result' => true 4198 ], 4199 [ 4200 'email' => 'fromuser@example.com', 4201 'display' => \core_user::MAILDISPLAY_EVERYONE, 4202 'samecourse' => false, 4203 'config' => "\r\n example.com \r\n test.com \r\n", 4204 'result' => true 4205 ], 4206 [ 4207 'email' => 'fromuser@EXAMPLE.com', 4208 'display' => \core_user::MAILDISPLAY_EVERYONE, 4209 'samecourse' => false, 4210 'config' => "example.com\r\ntest.com", 4211 'result' => true, 4212 ], 4213 // Test from email is not in allowed domain. 4214 // Test that from display is set to show no one. 4215 [ 'email' => 'fromuser@moodle.com', 4216 'display' => \core_user::MAILDISPLAY_HIDE, 4217 'samecourse' => false, 4218 'config' => "example.com\r\ntest.com", 4219 'result' => false 4220 ], 4221 // Test that from display is set to course members only (course member). 4222 [ 'email' => 'fromuser@moodle.com', 4223 'display' => \core_user::MAILDISPLAY_COURSE_MEMBERS_ONLY, 4224 'samecourse' => true, 4225 'config' => "example.com\r\ntest.com", 4226 'result' => false 4227 ], 4228 // Test that from display is set to course members only (Non course member. 4229 [ 'email' => 'fromuser@moodle.com', 4230 'display' => \core_user::MAILDISPLAY_COURSE_MEMBERS_ONLY, 4231 'samecourse' => false, 4232 'config' => "example.com\r\ntest.com", 4233 'result' => false 4234 ], 4235 // Test that from display is set to show everyone. 4236 [ 'email' => 'fromuser@moodle.com', 4237 'display' => \core_user::MAILDISPLAY_EVERYONE, 4238 'samecourse' => false, 4239 'config' => "example.com\r\ntest.com", 4240 'result' => false 4241 ], 4242 // Test a few erroneous config value and confirm failure. 4243 [ 'email' => 'fromuser@moodle.com', 4244 'display' => \core_user::MAILDISPLAY_EVERYONE, 4245 'samecourse' => false, 4246 'config' => "\r\n \r\n", 4247 'result' => false 4248 ], 4249 [ 'email' => 'fromuser@moodle.com', 4250 'display' => \core_user::MAILDISPLAY_EVERYONE, 4251 'samecourse' => false, 4252 'config' => " \n \n \n ", 4253 'result' => false 4254 ], 4255 ]; 4256 } 4257 4258 /** 4259 * Test that generate_email_processing_address() returns valid email address. 4260 */ 4261 public function test_generate_email_processing_address() { 4262 global $CFG; 4263 $this->resetAfterTest(); 4264 4265 $data = (object)[ 4266 'id' => 42, 4267 'email' => 'my.email+from_moodle@example.com', 4268 ]; 4269 4270 $modargs = 'B'.base64_encode(pack('V', $data->id)).substr(md5($data->email), 0, 16); 4271 4272 $CFG->maildomain = 'example.com'; 4273 $CFG->mailprefix = 'mdl+'; 4274 $this->assertTrue(validate_email(generate_email_processing_address(0, $modargs))); 4275 4276 $CFG->maildomain = 'mail.example.com'; 4277 $CFG->mailprefix = 'mdl-'; 4278 $this->assertTrue(validate_email(generate_email_processing_address(23, $modargs))); 4279 } 4280 4281 /** 4282 * Test allowemailaddresses setting. 4283 * 4284 * @param string $email Email address for the from user. 4285 * @param string $config The CFG->allowemailaddresses config values 4286 * @param false/string $result The expected result. 4287 * 4288 * @dataProvider data_email_is_not_allowed_for_allowemailaddresses 4289 */ 4290 public function test_email_is_not_allowed_for_allowemailaddresses($email, $config, $result) { 4291 $this->resetAfterTest(); 4292 4293 set_config('allowemailaddresses', $config); 4294 $this->assertEquals($result, email_is_not_allowed($email)); 4295 } 4296 4297 /** 4298 * Data provider for data_email_is_not_allowed_for_allowemailaddresses. 4299 * 4300 * @return array Returns an array of test data for the above function. 4301 */ 4302 public function data_email_is_not_allowed_for_allowemailaddresses() { 4303 return [ 4304 // Test allowed domain empty list. 4305 [ 4306 'email' => 'fromuser@example.com', 4307 'config' => '', 4308 'result' => false 4309 ], 4310 // Test from email is in allowed domain. 4311 [ 4312 'email' => 'fromuser@example.com', 4313 'config' => 'example.com test.com', 4314 'result' => false 4315 ], 4316 // Test from email is in allowed domain but uppercase config. 4317 [ 4318 'email' => 'fromuser@example.com', 4319 'config' => 'EXAMPLE.com test.com', 4320 'result' => false 4321 ], 4322 // Test from email is in allowed domain but uppercase email. 4323 [ 4324 'email' => 'fromuser@EXAMPLE.com', 4325 'config' => 'example.com test.com', 4326 'result' => false 4327 ], 4328 // Test from email is in allowed subdomain. 4329 [ 4330 'email' => 'fromuser@something.example.com', 4331 'config' => '.example.com test.com', 4332 'result' => false 4333 ], 4334 // Test from email is in allowed subdomain but uppercase config. 4335 [ 4336 'email' => 'fromuser@something.example.com', 4337 'config' => '.EXAMPLE.com test.com', 4338 'result' => false 4339 ], 4340 // Test from email is in allowed subdomain but uppercase email. 4341 [ 4342 'email' => 'fromuser@something.EXAMPLE.com', 4343 'config' => '.example.com test.com', 4344 'result' => false 4345 ], 4346 // Test from email is not in allowed domain. 4347 [ 'email' => 'fromuser@moodle.com', 4348 'config' => 'example.com test.com', 4349 'result' => get_string('emailonlyallowed', '', 'example.com test.com') 4350 ], 4351 // Test from email is not in allowed subdomain. 4352 [ 'email' => 'fromuser@something.example.com', 4353 'config' => 'example.com test.com', 4354 'result' => get_string('emailonlyallowed', '', 'example.com test.com') 4355 ], 4356 ]; 4357 } 4358 4359 /** 4360 * Test denyemailaddresses setting. 4361 * 4362 * @param string $email Email address for the from user. 4363 * @param string $config The CFG->denyemailaddresses config values 4364 * @param false/string $result The expected result. 4365 * 4366 * @dataProvider data_email_is_not_allowed_for_denyemailaddresses 4367 */ 4368 public function test_email_is_not_allowed_for_denyemailaddresses($email, $config, $result) { 4369 $this->resetAfterTest(); 4370 4371 set_config('denyemailaddresses', $config); 4372 $this->assertEquals($result, email_is_not_allowed($email)); 4373 } 4374 4375 4376 /** 4377 * Data provider for test_email_is_not_allowed_for_denyemailaddresses. 4378 * 4379 * @return array Returns an array of test data for the above function. 4380 */ 4381 public function data_email_is_not_allowed_for_denyemailaddresses() { 4382 return [ 4383 // Test denied domain empty list. 4384 [ 4385 'email' => 'fromuser@example.com', 4386 'config' => '', 4387 'result' => false 4388 ], 4389 // Test from email is in denied domain. 4390 [ 4391 'email' => 'fromuser@example.com', 4392 'config' => 'example.com test.com', 4393 'result' => get_string('emailnotallowed', '', 'example.com test.com') 4394 ], 4395 // Test from email is in denied domain but uppercase config. 4396 [ 4397 'email' => 'fromuser@example.com', 4398 'config' => 'EXAMPLE.com test.com', 4399 'result' => get_string('emailnotallowed', '', 'EXAMPLE.com test.com') 4400 ], 4401 // Test from email is in denied domain but uppercase email. 4402 [ 4403 'email' => 'fromuser@EXAMPLE.com', 4404 'config' => 'example.com test.com', 4405 'result' => get_string('emailnotallowed', '', 'example.com test.com') 4406 ], 4407 // Test from email is in denied subdomain. 4408 [ 4409 'email' => 'fromuser@something.example.com', 4410 'config' => '.example.com test.com', 4411 'result' => get_string('emailnotallowed', '', '.example.com test.com') 4412 ], 4413 // Test from email is in denied subdomain but uppercase config. 4414 [ 4415 'email' => 'fromuser@something.example.com', 4416 'config' => '.EXAMPLE.com test.com', 4417 'result' => get_string('emailnotallowed', '', '.EXAMPLE.com test.com') 4418 ], 4419 // Test from email is in denied subdomain but uppercase email. 4420 [ 4421 'email' => 'fromuser@something.EXAMPLE.com', 4422 'config' => '.example.com test.com', 4423 'result' => get_string('emailnotallowed', '', '.example.com test.com') 4424 ], 4425 // Test from email is not in denied domain. 4426 [ 'email' => 'fromuser@moodle.com', 4427 'config' => 'example.com test.com', 4428 'result' => false 4429 ], 4430 // Test from email is not in denied subdomain. 4431 [ 'email' => 'fromuser@something.example.com', 4432 'config' => 'example.com test.com', 4433 'result' => false 4434 ], 4435 ]; 4436 } 4437 4438 /** 4439 * Test safe method unserialize_array(). 4440 */ 4441 public function test_unserialize_array() { 4442 $a = [1, 2, 3]; 4443 $this->assertEquals($a, unserialize_array(serialize($a))); 4444 $a = ['a' => 1, 2 => 2, 'b' => 'cde']; 4445 $this->assertEquals($a, unserialize_array(serialize($a))); 4446 $a = ['a' => 1, 2 => 2, 'b' => 'c"d"e']; 4447 $this->assertEquals($a, unserialize_array(serialize($a))); 4448 $a = ['a' => 1, 2 => ['c' => 'd', 'e' => 'f'], 'b' => 'cde']; 4449 $this->assertEquals($a, unserialize_array(serialize($a))); 4450 $a = ['a' => 1, 2 => ['c' => 'd', 'e' => ['f' => 'g']], 'b' => 'cde']; 4451 $this->assertEquals($a, unserialize_array(serialize($a))); 4452 $a = ['a' => 1, 2 => 2, 'b' => 'c"d";e']; 4453 $this->assertEquals($a, unserialize_array(serialize($a))); 4454 4455 // Can not unserialize if there are any objects. 4456 $a = (object)['a' => 1, 2 => 2, 'b' => 'cde']; 4457 $this->assertFalse(unserialize_array(serialize($a))); 4458 $a = ['a' => 1, 2 => 2, 'b' => (object)['a' => 'cde']]; 4459 $this->assertFalse(unserialize_array(serialize($a))); 4460 $a = ['a' => 1, 2 => 2, 'b' => ['c' => (object)['a' => 'cde']]]; 4461 $this->assertFalse(unserialize_array(serialize($a))); 4462 $a = ['a' => 1, 2 => 2, 'b' => ['c' => new lang_string('no')]]; 4463 $this->assertFalse(unserialize_array(serialize($a))); 4464 4465 // Array used in the grader report. 4466 $a = array('aggregatesonly' => [51, 34], 'gradesonly' => [21, 45, 78]); 4467 $this->assertEquals($a, unserialize_array(serialize($a))); 4468 } 4469 4470 /** 4471 * Test method for safely unserializing a serialized object of type stdClass 4472 */ 4473 public function test_unserialize_object(): void { 4474 $object = (object) [ 4475 'foo' => 42, 4476 'bar' => 'Hamster', 4477 'innerobject' => (object) [ 4478 'baz' => 'happy', 4479 ], 4480 ]; 4481 4482 // We should get back the same object we serialized. 4483 $serializedobject = serialize($object); 4484 $this->assertEquals($object, unserialize_object($serializedobject)); 4485 4486 // Try serializing a different class, not allowed. 4487 $langstr = new lang_string('no'); 4488 $serializedlangstr = serialize($langstr); 4489 $unserializedlangstr = unserialize_object($serializedlangstr); 4490 $this->assertInstanceOf(\stdClass::class, $unserializedlangstr); 4491 } 4492 4493 /** 4494 * Test that the component_class_callback returns the correct default value when the class was not found. 4495 * 4496 * @dataProvider component_class_callback_default_provider 4497 * @param $default 4498 */ 4499 public function test_component_class_callback_not_found($default) { 4500 $this->assertSame($default, component_class_callback('thisIsNotTheClassYouWereLookingFor', 'anymethod', [], $default)); 4501 } 4502 4503 /** 4504 * Test that the component_class_callback returns the correct default value when the class was not found. 4505 * 4506 * @dataProvider component_class_callback_default_provider 4507 * @param $default 4508 */ 4509 public function test_component_class_callback_method_not_found($default) { 4510 require_once (__DIR__ . '/fixtures/component_class_callback_example.php'); 4511 4512 $this->assertSame($default, component_class_callback(test_component_class_callback_example::class, 'this_is_not_the_method_you_were_looking_for', ['abc'], $default)); 4513 } 4514 4515 /** 4516 * Test that the component_class_callback returns the default when the method returned null. 4517 * 4518 * @dataProvider component_class_callback_default_provider 4519 * @param $default 4520 */ 4521 public function test_component_class_callback_found_returns_null($default) { 4522 require_once (__DIR__ . '/fixtures/component_class_callback_example.php'); 4523 4524 $this->assertSame($default, component_class_callback(\test_component_class_callback_example::class, 'method_returns_value', [null], $default)); 4525 $this->assertSame($default, component_class_callback(\test_component_class_callback_child_example::class, 'method_returns_value', [null], $default)); 4526 } 4527 4528 /** 4529 * Test that the component_class_callback returns the expected value and not the default when there was a value. 4530 * 4531 * @dataProvider component_class_callback_data_provider 4532 * @param $default 4533 */ 4534 public function test_component_class_callback_found_returns_value($value) { 4535 require_once (__DIR__ . '/fixtures/component_class_callback_example.php'); 4536 4537 $this->assertSame($value, component_class_callback(\test_component_class_callback_example::class, 'method_returns_value', [$value], 'This is not the value you were looking for')); 4538 $this->assertSame($value, component_class_callback(\test_component_class_callback_child_example::class, 'method_returns_value', [$value], 'This is not the value you were looking for')); 4539 } 4540 4541 /** 4542 * Test that the component_class_callback handles multiple params correctly. 4543 * 4544 * @dataProvider component_class_callback_multiple_params_provider 4545 * @param $default 4546 */ 4547 public function test_component_class_callback_found_accepts_multiple($params, $count) { 4548 require_once (__DIR__ . '/fixtures/component_class_callback_example.php'); 4549 4550 $this->assertSame($count, component_class_callback(\test_component_class_callback_example::class, 'method_returns_all_params', $params, 'This is not the value you were looking for')); 4551 $this->assertSame($count, component_class_callback(\test_component_class_callback_child_example::class, 'method_returns_all_params', $params, 'This is not the value you were looking for')); 4552 } 4553 4554 /** 4555 * Data provider with list of default values for user in component_class_callback tests. 4556 * 4557 * @return array 4558 */ 4559 public function component_class_callback_default_provider() { 4560 return [ 4561 'null' => [null], 4562 'empty string' => [''], 4563 'string' => ['This is a string'], 4564 'int' => [12345], 4565 'stdClass' => [(object) ['this is my content']], 4566 'array' => [['a' => 'b',]], 4567 ]; 4568 } 4569 4570 /** 4571 * Data provider with list of default values for user in component_class_callback tests. 4572 * 4573 * @return array 4574 */ 4575 public function component_class_callback_data_provider() { 4576 return [ 4577 'empty string' => [''], 4578 'string' => ['This is a string'], 4579 'int' => [12345], 4580 'stdClass' => [(object) ['this is my content']], 4581 'array' => [['a' => 'b',]], 4582 ]; 4583 } 4584 4585 /** 4586 * Data provider with list of default values for user in component_class_callback tests. 4587 * 4588 * @return array 4589 */ 4590 public function component_class_callback_multiple_params_provider() { 4591 return [ 4592 'empty array' => [ 4593 [], 4594 0, 4595 ], 4596 'string value' => [ 4597 ['one'], 4598 1, 4599 ], 4600 'string values' => [ 4601 ['one', 'two'], 4602 2, 4603 ], 4604 'arrays' => [ 4605 [[], []], 4606 2, 4607 ], 4608 'nulls' => [ 4609 [null, null, null, null], 4610 4, 4611 ], 4612 'mixed' => [ 4613 ['a', 1, null, (object) [], []], 4614 5, 4615 ], 4616 ]; 4617 } 4618 4619 /** 4620 * Test that {@link get_callable_name()} describes the callable as expected. 4621 * 4622 * @dataProvider callable_names_provider 4623 * @param callable $callable 4624 * @param string $expectedname 4625 */ 4626 public function test_get_callable_name($callable, $expectedname) { 4627 $this->assertSame($expectedname, get_callable_name($callable)); 4628 } 4629 4630 /** 4631 * Provides a set of callables and their human readable names. 4632 * 4633 * @return array of (string)case => [(mixed)callable, (string|bool)expected description] 4634 */ 4635 public function callable_names_provider() { 4636 return [ 4637 'integer' => [ 4638 386, 4639 false, 4640 ], 4641 'boolean' => [ 4642 true, 4643 false, 4644 ], 4645 'static_method_as_literal' => [ 4646 'my_foobar_class::my_foobar_method', 4647 'my_foobar_class::my_foobar_method', 4648 ], 4649 'static_method_of_literal_class' => [ 4650 ['my_foobar_class', 'my_foobar_method'], 4651 'my_foobar_class::my_foobar_method', 4652 ], 4653 'static_method_of_object' => [ 4654 [$this, 'my_foobar_method'], 4655 'core\moodlelib_test::my_foobar_method', 4656 ], 4657 'method_of_object' => [ 4658 [new lang_string('parentlanguage', 'core_langconfig'), 'my_foobar_method'], 4659 'lang_string::my_foobar_method', 4660 ], 4661 'function_as_literal' => [ 4662 'my_foobar_callback', 4663 'my_foobar_callback', 4664 ], 4665 'function_as_closure' => [ 4666 function($a) { return $a; }, 4667 'Closure::__invoke', 4668 ], 4669 ]; 4670 } 4671 4672 /** 4673 * Data provider for \core_moodlelib_testcase::test_get_complete_user_data(). 4674 * 4675 * @return array 4676 */ 4677 public function user_data_provider() { 4678 return [ 4679 'Fetch data using a valid username' => [ 4680 'username', 's1', true 4681 ], 4682 'Fetch data using a valid username, different case' => [ 4683 'username', 'S1', true 4684 ], 4685 'Fetch data using a valid username, different case for fieldname and value' => [ 4686 'USERNAME', 'S1', true 4687 ], 4688 'Fetch data using an invalid username' => [ 4689 'username', 's2', false 4690 ], 4691 'Fetch by email' => [ 4692 'email', 's1@example.com', true 4693 ], 4694 'Fetch data using a non-existent email' => [ 4695 'email', 's2@example.com', false 4696 ], 4697 'Fetch data using a non-existent email, throw exception' => [ 4698 'email', 's2@example.com', false, \dml_missing_record_exception::class 4699 ], 4700 'Multiple accounts with the same email' => [ 4701 'email', 's1@example.com', false, 1 4702 ], 4703 'Multiple accounts with the same email, throw exception' => [ 4704 'email', 's1@example.com', false, 1, \dml_multiple_records_exception::class 4705 ], 4706 'Fetch data using a valid user ID' => [ 4707 'id', true, true 4708 ], 4709 'Fetch data using a non-existent user ID' => [ 4710 'id', false, false 4711 ], 4712 ]; 4713 } 4714 4715 /** 4716 * Test for get_complete_user_data(). 4717 * 4718 * @dataProvider user_data_provider 4719 * @param string $field The field to use for the query. 4720 * @param string|boolean $value The field value. When fetching by ID, set true to fetch valid user ID, false otherwise. 4721 * @param boolean $success Whether we expect for the fetch to succeed or return false. 4722 * @param int $allowaccountssameemail Value for $CFG->allowaccountssameemail. 4723 * @param string $expectedexception The exception to be expected. 4724 */ 4725 public function test_get_complete_user_data($field, $value, $success, $allowaccountssameemail = 0, $expectedexception = '') { 4726 $this->resetAfterTest(); 4727 4728 // Set config settings we need for our environment. 4729 set_config('allowaccountssameemail', $allowaccountssameemail); 4730 4731 // Generate the user data. 4732 $generator = $this->getDataGenerator(); 4733 $userdata = [ 4734 'username' => 's1', 4735 'email' => 's1@example.com', 4736 ]; 4737 $user = $generator->create_user($userdata); 4738 4739 if ($allowaccountssameemail) { 4740 // Create another user with the same email address. 4741 $generator->create_user(['email' => 's1@example.com']); 4742 } 4743 4744 // Since the data provider can't know what user ID to use, do a special handling for ID field tests. 4745 if ($field === 'id') { 4746 if ($value) { 4747 // Test for fetching data using a valid user ID. Use the generated user's ID. 4748 $value = $user->id; 4749 } else { 4750 // Test for fetching data using a non-existent user ID. 4751 $value = $user->id + 1; 4752 } 4753 } 4754 4755 // When an exception is expected. 4756 $throwexception = false; 4757 if ($expectedexception) { 4758 $this->expectException($expectedexception); 4759 $throwexception = true; 4760 } 4761 4762 $fetcheduser = get_complete_user_data($field, $value, null, $throwexception); 4763 if ($success) { 4764 $this->assertEquals($user->id, $fetcheduser->id); 4765 $this->assertEquals($user->username, $fetcheduser->username); 4766 $this->assertEquals($user->email, $fetcheduser->email); 4767 } else { 4768 $this->assertFalse($fetcheduser); 4769 } 4770 } 4771 4772 /** 4773 * Test for send_password_change_(). 4774 */ 4775 public function test_send_password_change_info() { 4776 $this->resetAfterTest(); 4777 4778 $user = $this->getDataGenerator()->create_user(); 4779 4780 $sink = $this->redirectEmails(); // Make sure we are redirecting emails. 4781 send_password_change_info($user); 4782 $result = $sink->get_messages(); 4783 $sink->close(); 4784 4785 $this->assertStringContainsString('passwords cannot be reset on this site', quoted_printable_decode($result[0]->body)); 4786 } 4787 4788 /** 4789 * Test the get_time_interval_string for a range of inputs. 4790 * 4791 * @dataProvider get_time_interval_string_provider 4792 * @param int $time1 the time1 param. 4793 * @param int $time2 the time2 param. 4794 * @param string|null $format the format param. 4795 * @param string $expected the expected string. 4796 * @param bool $dropzeroes the value passed for the `$dropzeros` param. 4797 * @param bool $fullformat the value passed for the `$fullformat` param. 4798 * @covers \get_time_interval_string 4799 */ 4800 public function test_get_time_interval_string(int $time1, int $time2, ?string $format, string $expected, 4801 bool $dropzeroes = false, bool $fullformat = false) { 4802 if (is_null($format)) { 4803 $this->assertEquals($expected, get_time_interval_string($time1, $time2)); 4804 } else { 4805 $this->assertEquals($expected, get_time_interval_string($time1, $time2, $format, $dropzeroes, $fullformat)); 4806 } 4807 } 4808 4809 /** 4810 * Data provider for the test_get_time_interval_string() method. 4811 */ 4812 public function get_time_interval_string_provider() { 4813 return [ 4814 'Time is after the reference time by 1 minute, omitted format' => [ 4815 'time1' => 12345660, 4816 'time2' => 12345600, 4817 'format' => null, 4818 'expected' => '0d 0h 1m' 4819 ], 4820 'Time is before the reference time by 1 minute, omitted format' => [ 4821 'time1' => 12345540, 4822 'time2' => 12345600, 4823 'format' => null, 4824 'expected' => '0d 0h 1m' 4825 ], 4826 'Time is equal to the reference time, omitted format' => [ 4827 'time1' => 12345600, 4828 'time2' => 12345600, 4829 'format' => null, 4830 'expected' => '0d 0h 0m' 4831 ], 4832 'Time is after the reference time by 1 minute, empty string format' => [ 4833 'time1' => 12345660, 4834 'time2' => 12345600, 4835 'format' => '', 4836 'expected' => '0d 0h 1m' 4837 ], 4838 'Time is before the reference time by 1 minute, empty string format' => [ 4839 'time1' => 12345540, 4840 'time2' => 12345600, 4841 'format' => '', 4842 'expected' => '0d 0h 1m' 4843 ], 4844 'Time is equal to the reference time, empty string format' => [ 4845 'time1' => 12345600, 4846 'time2' => 12345600, 4847 'format' => '', 4848 'expected' => '0d 0h 0m' 4849 ], 4850 'Time is after the reference time by 1 minute, custom format' => [ 4851 'time1' => 12345660, 4852 'time2' => 12345600, 4853 'format' => '%R%adays %hhours %imins', 4854 'expected' => '+0days 0hours 1mins' 4855 ], 4856 'Time is before the reference time by 1 minute, custom format' => [ 4857 'time1' => 12345540, 4858 'time2' => 12345600, 4859 'format' => '%R%adays %hhours %imins', 4860 'expected' => '-0days 0hours 1mins' 4861 ], 4862 'Time is equal to the reference time, custom format' => [ 4863 'time1' => 12345600, 4864 'time2' => 12345600, 4865 'format' => '%R%adays %hhours %imins', 4866 'expected' => '+0days 0hours 0mins' 4867 ], 4868 'Default format, time is after the reference time by 1 minute, drop zeroes, short form' => [ 4869 'time1' => 12345660, 4870 'time2' => 12345600, 4871 'format' => '', 4872 'expected' => '1m', 4873 'dropzeroes' => true, 4874 ], 4875 'Default format, time is after the reference time by 1 minute, drop zeroes, full form' => [ 4876 'time1' => 12345660, 4877 'time2' => 12345600, 4878 'format' => '', 4879 'expected' => '1 minutes', 4880 'dropzeroes' => true, 4881 'fullformat' => true, 4882 ], 4883 'Default format, time is after the reference time by 1 minute, retain zeroes, full form' => [ 4884 'time1' => 12345660, 4885 'time2' => 12345600, 4886 'format' => '', 4887 'expected' => '0 days 0 hours 1 minutes', 4888 'dropzeroes' => false, 4889 'fullformat' => true, 4890 ], 4891 'Empty string format, time is after the reference time by 1 minute, retain zeroes, full form' => [ 4892 'time1' => 12345660, 4893 'time2' => 12345600, 4894 'format' => ' ', 4895 'expected' => '0 days 0 hours 1 minutes', 4896 'dropzeroes' => false, 4897 'fullformat' => true, 4898 ], 4899 ]; 4900 } 4901 4902 /** 4903 * Tests the rename_to_unused_name function with a file. 4904 */ 4905 public function test_rename_to_unused_name_file() { 4906 global $CFG; 4907 4908 // Create a new file in dataroot. 4909 $file = $CFG->dataroot . '/argh.txt'; 4910 file_put_contents($file, 'Frogs'); 4911 4912 // Rename it. 4913 $newname = rename_to_unused_name($file); 4914 4915 // Check new name has expected format. 4916 $this->assertMatchesRegularExpression('~/_temp_[a-f0-9]+$~', $newname); 4917 4918 // Check it's still in the same folder. 4919 $this->assertEquals($CFG->dataroot, dirname($newname)); 4920 4921 // Check file can be loaded. 4922 $this->assertEquals('Frogs', file_get_contents($newname)); 4923 4924 // OK, delete the file. 4925 unlink($newname); 4926 } 4927 4928 /** 4929 * Tests the rename_to_unused_name function with a directory. 4930 */ 4931 public function test_rename_to_unused_name_dir() { 4932 global $CFG; 4933 4934 // Create a new directory in dataroot. 4935 $file = $CFG->dataroot . '/arghdir'; 4936 mkdir($file); 4937 4938 // Rename it. 4939 $newname = rename_to_unused_name($file); 4940 4941 // Check new name has expected format. 4942 $this->assertMatchesRegularExpression('~/_temp_[a-f0-9]+$~', $newname); 4943 4944 // Check it's still in the same folder. 4945 $this->assertEquals($CFG->dataroot, dirname($newname)); 4946 4947 // Check it's still a directory 4948 $this->assertTrue(is_dir($newname)); 4949 4950 // OK, delete the directory. 4951 rmdir($newname); 4952 } 4953 4954 /** 4955 * Tests the rename_to_unused_name function with error cases. 4956 */ 4957 public function test_rename_to_unused_name_failure() { 4958 global $CFG; 4959 4960 // Rename a file that doesn't exist. 4961 $file = $CFG->dataroot . '/argh.txt'; 4962 $this->assertFalse(rename_to_unused_name($file)); 4963 } 4964 4965 /** 4966 * Provider for display_size 4967 * 4968 * @return array of ($size, $expected) 4969 */ 4970 public function display_size_provider() { 4971 4972 return [ 4973 [0, '0 bytes'], 4974 [1, '1 bytes'], 4975 [1023, '1023 bytes'], 4976 [1024, '1.0 KB'], 4977 [2222, '2.2 KB'], 4978 [33333, '32.6 KB'], 4979 [444444, '434.0 KB'], 4980 [5555555, '5.3 MB'], 4981 [66666666, '63.6 MB'], 4982 [777777777, '741.7 MB'], 4983 [8888888888, '8.3 GB'], 4984 [99999999999, '93.1 GB'], 4985 [111111111111, '103.5 GB'], 4986 [2222222222222, '2.0 TB'], 4987 [33333333333333, '30.3 TB'], 4988 [444444444444444, '404.2 TB'], 4989 [5555555555555555, '4.9 PB'], 4990 [66666666666666666, '59.2 PB'], 4991 [777777777777777777, '690.8 PB'], 4992 ]; 4993 } 4994 4995 /** 4996 * Test display_size 4997 * @dataProvider display_size_provider 4998 * @param int $size the size in bytes 4999 * @param string $expected the expected string. 5000 */ 5001 public function test_display_size($size, $expected) { 5002 $result = display_size($size); 5003 $expected = str_replace(' ', "\xc2\xa0", $expected); // Should be non-breaking space. 5004 $this->assertEquals($expected, $result); 5005 } 5006 5007 /** 5008 * Provider for display_size using fixed units. 5009 * 5010 * @return array of ($size, $units, $expected) 5011 */ 5012 public function display_size_fixed_provider(): array { 5013 return [ 5014 [0, 'KB', '0.0 KB'], 5015 [1, 'MB', '0.0 MB'], 5016 [777777777, 'GB', '0.7 GB'], 5017 [8888888888, 'PB', '0.0 PB'], 5018 [99999999999, 'TB', '0.1 TB'], 5019 [99999999999, 'B', '99999999999 bytes'], 5020 ]; 5021 } 5022 5023 /** 5024 * Test display_size using fixed units. 5025 * 5026 * @dataProvider display_size_fixed_provider 5027 * @param int $size Size in bytes 5028 * @param string $units Fixed units 5029 * @param string $expected Expected string. 5030 */ 5031 public function test_display_size_fixed(int $size, string $units, string $expected): void { 5032 $result = display_size($size, 1, $units); 5033 $expected = str_replace(' ', "\xc2\xa0", $expected); // Should be non-breaking space. 5034 $this->assertEquals($expected, $result); 5035 } 5036 5037 /** 5038 * Provider for display_size using specified decimal places. 5039 * 5040 * @return array of ($size, $decimalplaces, $units, $expected) 5041 */ 5042 public function display_size_dp_provider(): array { 5043 return [ 5044 [0, 1, 'KB', '0.0 KB'], 5045 [1, 6, 'MB', '0.000001 MB'], 5046 [777777777, 0, 'GB', '1 GB'], 5047 [777777777, 0, '', '742 MB'], 5048 [42, 6, '', '42 bytes'], 5049 ]; 5050 } 5051 5052 /** 5053 * Test display_size using specified decimal places. 5054 * 5055 * @dataProvider display_size_dp_provider 5056 * @param int $size Size in bytes 5057 * @param int $places Number of decimal places 5058 * @param string $units Fixed units 5059 * @param string $expected Expected string. 5060 */ 5061 public function test_display_size_dp(int $size, int $places, string $units, string $expected): void { 5062 $result = display_size($size, $places, $units); 5063 $expected = str_replace(' ', "\xc2\xa0", $expected); // Should be non-breaking space. 5064 $this->assertEquals($expected, $result); 5065 } 5066 5067 /** 5068 * Test that the get_list_of_plugins function includes/excludes directories as appropriate. 5069 * 5070 * @dataProvider get_list_of_plugins_provider 5071 * @param array $expectedlist The expected list of folders 5072 * @param array $content The list of file content to set up in the virtual file root 5073 * @param string $dir The base dir to look at in the virtual file root 5074 * @param string $exclude Any additional folder to exclude 5075 */ 5076 public function test_get_list_of_plugins(array $expectedlist, array $content, string $dir, string $exclude): void { 5077 $vfileroot = \org\bovigo\vfs\vfsStream::setup('root', null, $content); 5078 $base = \org\bovigo\vfs\vfsStream::url('root'); 5079 5080 $this->assertEquals($expectedlist, get_list_of_plugins($dir, $exclude, $base)); 5081 } 5082 5083 /** 5084 * Data provider for get_list_of_plugins checks. 5085 * 5086 * @return array 5087 */ 5088 public function get_list_of_plugins_provider(): array { 5089 return [ 5090 'Standard excludes' => [ 5091 ['amdd', 'class', 'local', 'test'], 5092 [ 5093 '.' => [], 5094 '..' => [], 5095 'amd' => [], 5096 'amdd' => [], 5097 'class' => [], 5098 'classes' => [], 5099 'local' => [], 5100 'test' => [], 5101 'tests' => [], 5102 'yui' => [], 5103 ], 5104 '', 5105 '', 5106 ], 5107 'Standard excludes with addition' => [ 5108 ['amdd', 'local', 'test'], 5109 [ 5110 '.' => [], 5111 '..' => [], 5112 'amd' => [], 5113 'amdd' => [], 5114 'class' => [], 5115 'classes' => [], 5116 'local' => [], 5117 'test' => [], 5118 'tests' => [], 5119 'yui' => [], 5120 ], 5121 '', 5122 'class', 5123 ], 5124 'Files excluded' => [ 5125 ['def'], 5126 [ 5127 '.' => [], 5128 '..' => [], 5129 'abc' => 'File with filename abc', 5130 'def' => [ 5131 '.' => [], 5132 '..' => [], 5133 'example.txt' => 'In a directory called "def"', 5134 ], 5135 ], 5136 '', 5137 '', 5138 ], 5139 'Subdirectories only' => [ 5140 ['abc'], 5141 [ 5142 '.' => [], 5143 '..' => [], 5144 'foo' => [ 5145 '.' => [], 5146 '..' => [], 5147 'abc' => [], 5148 ], 5149 'bar' => [ 5150 '.' => [], 5151 '..' => [], 5152 'def' => [], 5153 ], 5154 ], 5155 'foo', 5156 '', 5157 ], 5158 ]; 5159 } 5160 5161 /** 5162 * Test get_home_page() method. 5163 * 5164 * @dataProvider get_home_page_provider 5165 * @param string $user Whether the user is logged, guest or not logged. 5166 * @param int $expected Expected value after calling the get_home_page method. 5167 * @param int $defaulthomepage The $CFG->defaulthomepage setting value. 5168 * @param int $enabledashboard Whether the dashboard should be enabled or not. 5169 * @param int $userpreference User preference for the home page setting. 5170 * @covers ::get_home_page 5171 */ 5172 public function test_get_home_page(string $user, int $expected, ?int $defaulthomepage = null, ?int $enabledashboard = null, 5173 ?int $userpreference = null) { 5174 global $CFG, $USER; 5175 5176 $this->resetAfterTest(); 5177 5178 if ($user == 'guest') { 5179 $this->setGuestUser(); 5180 } else if ($user == 'logged') { 5181 $this->setUser($this->getDataGenerator()->create_user()); 5182 } 5183 5184 if (isset($defaulthomepage)) { 5185 $CFG->defaulthomepage = $defaulthomepage; 5186 } 5187 if (isset($enabledashboard)) { 5188 $CFG->enabledashboard = $enabledashboard; 5189 } 5190 5191 if ($USER) { 5192 set_user_preferences(['user_home_page_preference' => $userpreference], $USER->id); 5193 } 5194 5195 $homepage = get_home_page(); 5196 $this->assertEquals($expected, $homepage); 5197 } 5198 5199 /** 5200 * Data provider for get_home_page checks. 5201 * 5202 * @return array 5203 */ 5204 public function get_home_page_provider(): array { 5205 return [ 5206 'No logged user' => [ 5207 'user' => 'nologged', 5208 'expected' => HOMEPAGE_SITE, 5209 ], 5210 'Guest user' => [ 5211 'user' => 'guest', 5212 'expected' => HOMEPAGE_SITE, 5213 ], 5214 'Logged user. Dashboard set as default home page and enabled' => [ 5215 'user' => 'logged', 5216 'expected' => HOMEPAGE_MY, 5217 'defaulthomepage' => HOMEPAGE_MY, 5218 'enabledashboard' => 1, 5219 ], 5220 'Logged user. Dashboard set as default home page but disabled' => [ 5221 'user' => 'logged', 5222 'expected' => HOMEPAGE_MYCOURSES, 5223 'defaulthomepage' => HOMEPAGE_MY, 5224 'enabledashboard' => 0, 5225 ], 5226 'Logged user. My courses set as default home page with dashboard enabled' => [ 5227 'user' => 'logged', 5228 'expected' => HOMEPAGE_MYCOURSES, 5229 'defaulthomepage' => HOMEPAGE_MYCOURSES, 5230 'enabledashboard' => 1, 5231 ], 5232 'Logged user. My courses set as default home page with dashboard disabled' => [ 5233 'user' => 'logged', 5234 'expected' => HOMEPAGE_MYCOURSES, 5235 'defaulthomepage' => HOMEPAGE_MYCOURSES, 5236 'enabledashboard' => 0, 5237 ], 5238 'Logged user. Site set as default home page with dashboard enabled' => [ 5239 'user' => 'logged', 5240 'expected' => HOMEPAGE_SITE, 5241 'defaulthomepage' => HOMEPAGE_SITE, 5242 'enabledashboard' => 1, 5243 ], 5244 'Logged user. Site set as default home page with dashboard disabled' => [ 5245 'user' => 'logged', 5246 'expected' => HOMEPAGE_SITE, 5247 'defaulthomepage' => HOMEPAGE_SITE, 5248 'enabledashboard' => 0, 5249 ], 5250 'Logged user. User preference set as default page with dashboard enabled and user preference set to dashboard' => [ 5251 'user' => 'logged', 5252 'expected' => HOMEPAGE_MY, 5253 'defaulthomepage' => HOMEPAGE_USER, 5254 'enabledashboard' => 1, 5255 'userpreference' => HOMEPAGE_MY, 5256 ], 5257 'Logged user. User preference set as default page with dashboard disabled and user preference set to dashboard' => [ 5258 'user' => 'logged', 5259 'expected' => HOMEPAGE_MYCOURSES, 5260 'defaulthomepage' => HOMEPAGE_USER, 5261 'enabledashboard' => 0, 5262 'userpreference' => HOMEPAGE_MY, 5263 ], 5264 'Logged user. User preference set as default page with dashboard enabled and user preference set to my courses' => [ 5265 'user' => 'logged', 5266 'expected' => HOMEPAGE_MYCOURSES, 5267 'defaulthomepage' => HOMEPAGE_USER, 5268 'enabledashboard' => 1, 5269 'userpreference' => HOMEPAGE_MYCOURSES, 5270 ], 5271 'Logged user. User preference set as default page with dashboard disabled and user preference set to my courses' => [ 5272 'user' => 'logged', 5273 'expected' => HOMEPAGE_MYCOURSES, 5274 'defaulthomepage' => HOMEPAGE_USER, 5275 'enabledashboard' => 0, 5276 'userpreference' => HOMEPAGE_MYCOURSES, 5277 ], 5278 ]; 5279 } 5280 5281 /** 5282 * Test get_default_home_page() method. 5283 * 5284 * @covers ::get_default_home_page 5285 */ 5286 public function test_get_default_home_page() { 5287 global $CFG; 5288 5289 $this->resetAfterTest(); 5290 5291 $CFG->enabledashboard = 1; 5292 $default = get_default_home_page(); 5293 $this->assertEquals(HOMEPAGE_MY, $default); 5294 5295 $CFG->enabledashboard = 0; 5296 $default = get_default_home_page(); 5297 $this->assertEquals(HOMEPAGE_MYCOURSES, $default); 5298 } 5299 5300 /** 5301 * Tests the get_performance_info function with regard to locks. 5302 * 5303 * @covers ::get_performance_info 5304 */ 5305 public function test_get_performance_info_locks(): void { 5306 global $PERF; 5307 5308 // Unset lock data just in case previous tests have set it. 5309 unset($PERF->locks); 5310 5311 // With no lock data, there should be no information about locks in the results. 5312 $result = get_performance_info(); 5313 $this->assertStringNotContainsString('Lock', $result['html']); 5314 $this->assertStringNotContainsString('Lock', $result['txt']); 5315 5316 // Rather than really do locks, just fill the array with fake data in the right format. 5317 $PERF->locks = [ 5318 (object) [ 5319 'type' => 'phpunit', 5320 'resource' => 'lock1', 5321 'wait' => 0.59, 5322 'success' => true, 5323 'held' => '6.04' 5324 ], (object) [ 5325 'type' => 'phpunit', 5326 'resource' => 'lock2', 5327 'wait' => 0.91, 5328 'success' => false 5329 ] 5330 ]; 5331 $result = get_performance_info(); 5332 5333 // Extract HTML table rows. 5334 $this->assertEquals(1, preg_match('~<table class="locktimings.*?</table>~s', 5335 $result['html'], $matches)); 5336 $this->assertEquals(3, preg_match_all('~<tr[> ].*?</tr>~s', $matches[0], $matches2)); 5337 $rows = $matches2[0]; 5338 5339 // Check header. 5340 $this->assertMatchesRegularExpression('~Lock.*Waited.*Obtained.*Held~s', $rows[0]); 5341 // Check both locks. 5342 $this->assertMatchesRegularExpression('~phpunit/lock1.*0\.6.*✓.*6\.0~s', $rows[1]); 5343 $this->assertMatchesRegularExpression('~phpunit/lock2.*0\.9.*❌.*-~s', $rows[2]); 5344 5345 $this->assertStringContainsString('Locks (waited/obtained/held): ' . 5346 'phpunit/lock1 (0.6/y/6.0) phpunit/lock2 (0.9/n/-).', $result['txt']); 5347 } 5348 5349 /** 5350 * Tests the get_performance_info function with regard to session wait time. 5351 * 5352 * @covers ::get_performance_info 5353 */ 5354 public function test_get_performance_info_session_wait(): void { 5355 global $PERF; 5356 5357 // With no session lock data, there should be no session wait information in the results. 5358 unset($PERF->sessionlock); 5359 $result = get_performance_info(); 5360 $this->assertStringNotContainsString('Session wait', $result['html']); 5361 $this->assertStringNotContainsString('sessionwait', $result['txt']); 5362 5363 // With suitable data, it should be included in the result. 5364 $PERF->sessionlock = ['wait' => 4.2]; 5365 $result = get_performance_info(); 5366 $this->assertStringContainsString('Session wait: 4.200 secs', $result['html']); 5367 $this->assertStringContainsString('sessionwait: 4.200 secs', $result['txt']); 5368 } 5369 5370 /** 5371 * Test the html_is_blank() function. 5372 * 5373 * @covers ::html_is_blank 5374 */ 5375 public function test_html_is_blank() { 5376 $this->assertEquals(true, html_is_blank(null)); 5377 $this->assertEquals(true, html_is_blank('')); 5378 $this->assertEquals(true, html_is_blank('<p> </p>')); 5379 $this->assertEquals(false, html_is_blank('<p>.</p>')); 5380 $this->assertEquals(false, html_is_blank('<img src="#">')); 5381 } 5382 5383 /** 5384 * Provider for is_proxybypass 5385 * 5386 * @return array of test cases. 5387 */ 5388 public function is_proxybypass_provider(): array { 5389 5390 return [ 5391 'Proxybypass contains the same IP as the beginning of the URL' => [ 5392 'http://192.168.5.5-fake-app-7f000101.nip.io', 5393 '192.168.5.5, 127.0.0.1', 5394 false 5395 ], 5396 'Proxybypass contains the last part of the URL' => [ 5397 'http://192.168.5.5-fake-app-7f000101.nip.io', 5398 'app-7f000101.nip.io', 5399 false 5400 ], 5401 'Proxybypass contains the last part of the URL 2' => [ 5402 'http://store.mydomain.com', 5403 'mydomain.com', 5404 false 5405 ], 5406 'Proxybypass contains part of the url' => [ 5407 'http://myweb.com', 5408 'store.myweb.com', 5409 false 5410 ], 5411 'Different IPs used in proxybypass' => [ 5412 'http://192.168.5.5', 5413 '192.168.5.3', 5414 false 5415 ], 5416 'Proxybypass and URL matchs' => [ 5417 'http://store.mydomain.com', 5418 'store.mydomain.com', 5419 true 5420 ], 5421 'IP used in proxybypass' => [ 5422 'http://192.168.5.5', 5423 '192.168.5.5', 5424 true 5425 ], 5426 ]; 5427 } 5428 5429 /** 5430 * Check if $url matches anything in proxybypass list 5431 * 5432 * Test function {@see is_proxybypass()}. 5433 * @dataProvider is_proxybypass_provider 5434 * @param string $url url to check 5435 * @param string $proxybypass 5436 * @param bool $expected Expected value. 5437 */ 5438 public function test_is_proxybypass(string $url, string $proxybypass, bool $expected): void { 5439 $this->resetAfterTest(); 5440 5441 global $CFG; 5442 $CFG->proxyhost = '192.168.5.5'; // Test with a fake proxy. 5443 $CFG->proxybypass = $proxybypass; 5444 5445 $this->assertEquals($expected, is_proxybypass($url)); 5446 } 5447 5448 }
title
Description
Body
title
Description
Body
title
Description
Body
title
Body