1<?php 2// This file is part of Moodle - http://moodle.org/ 3// 4// Moodle is free software: you can redistribute it and/or modify 5// it under the terms of the GNU General Public License as published by 6// the Free Software Foundation, either version 3 of the License, or 7// (at your option) any later version. 8// 9// Moodle is distributed in the hope that it will be useful, 10// but WITHOUT ANY WARRANTY; without even the implied warranty of 11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 12// GNU General Public License for more details. 13// 14// You should have received a copy of the GNU General Public License 15// along with Moodle. If not, see <http://www.gnu.org/licenses/>. 16 17/** 18 * Unit tests for setuplib.php 19 * 20 * @package core 21 * @category phpunit 22 * @copyright 2012 The Open University 23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later 24 */ 25 26defined('MOODLE_INTERNAL') || die(); 27 28/** 29 * Unit tests for setuplib.php 30 * 31 * @copyright 2012 The Open University 32 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later 33 */ 34class core_setuplib_testcase extends advanced_testcase { 35 36 /** 37 * Test get_docs_url_standard in the normal case when we should link to Moodle docs. 38 */ 39 public function test_get_docs_url_standard() { 40 global $CFG; 41 if (empty($CFG->docroot)) { 42 $docroot = 'http://docs.moodle.org/'; 43 } else { 44 $docroot = $CFG->docroot; 45 } 46 $this->assertRegExp('~^' . preg_quote($docroot, '') . '/\d{2,3}/' . current_language() . '/course/editing$~', 47 get_docs_url('course/editing')); 48 } 49 50 /** 51 * Test get_docs_url_standard in the special case of an absolute HTTP URL. 52 */ 53 public function test_get_docs_url_http() { 54 $url = 'http://moodle.org/'; 55 $this->assertEquals($url, get_docs_url($url)); 56 } 57 58 /** 59 * Test get_docs_url_standard in the special case of an absolute HTTPS URL. 60 */ 61 public function test_get_docs_url_https() { 62 $url = 'https://moodle.org/'; 63 $this->assertEquals($url, get_docs_url($url)); 64 } 65 66 /** 67 * Test get_docs_url_standard in the special case of a link relative to wwwroot. 68 */ 69 public function test_get_docs_url_wwwroot() { 70 global $CFG; 71 $this->assertSame($CFG->wwwroot . '/lib/tests/setuplib_test.php', 72 get_docs_url('%%WWWROOT%%/lib/tests/setuplib_test.php')); 73 } 74 75 /** 76 * Test if get_exception_info() removes file system paths. 77 */ 78 public function test_exception_info_removes_serverpaths() { 79 global $CFG; 80 81 // This doesn't test them all possible ones, but these are set for unit tests. 82 $cfgnames = array('dataroot', 'dirroot', 'tempdir', 'backuptempdir', 'cachedir', 'localcachedir'); 83 84 $fixture = ''; 85 $expected = ''; 86 foreach ($cfgnames as $cfgname) { 87 if (!empty($CFG->$cfgname)) { 88 $fixture .= $CFG->$cfgname.' '; 89 $expected .= "[$cfgname] "; 90 } 91 } 92 $exception = new moodle_exception('generalexceptionmessage', 'error', '', $fixture, $fixture); 93 $exceptioninfo = get_exception_info($exception); 94 95 $this->assertStringContainsString($expected, $exceptioninfo->message, 'Exception message does not contain system paths'); 96 $this->assertStringContainsString($expected, $exceptioninfo->debuginfo, 'Exception debug info does not contain system paths'); 97 } 98 99 public function test_localcachedir() { 100 global $CFG; 101 102 $this->resetAfterTest(true); 103 104 // Test default location - can not be modified in phpunit tests because we override everything in config.php. 105 $this->assertSame("$CFG->dataroot/localcache", $CFG->localcachedir); 106 107 $this->setCurrentTimeStart(); 108 $timestampfile = "$CFG->localcachedir/.lastpurged"; 109 110 // Delete existing localcache directory, as this is testing first call 111 // to make_localcache_directory. 112 remove_dir($CFG->localcachedir, true); 113 $dir = make_localcache_directory('', false); 114 $this->assertSame($CFG->localcachedir, $dir); 115 $this->assertFileNotExists("$CFG->localcachedir/.htaccess"); 116 $this->assertFileExists($timestampfile); 117 $this->assertTimeCurrent(filemtime($timestampfile)); 118 119 $dir = make_localcache_directory('test/test', false); 120 $this->assertSame("$CFG->localcachedir/test/test", $dir); 121 122 // Test custom location. 123 $CFG->localcachedir = "$CFG->dataroot/testlocalcache"; 124 $this->setCurrentTimeStart(); 125 $timestampfile = "$CFG->localcachedir/.lastpurged"; 126 $this->assertFileNotExists($timestampfile); 127 128 $dir = make_localcache_directory('', false); 129 $this->assertSame($CFG->localcachedir, $dir); 130 $this->assertFileExists("$CFG->localcachedir/.htaccess"); 131 $this->assertFileExists($timestampfile); 132 $this->assertTimeCurrent(filemtime($timestampfile)); 133 134 $dir = make_localcache_directory('test', false); 135 $this->assertSame("$CFG->localcachedir/test", $dir); 136 137 $prevtime = filemtime($timestampfile); 138 $dir = make_localcache_directory('pokus', false); 139 $this->assertSame("$CFG->localcachedir/pokus", $dir); 140 $this->assertSame($prevtime, filemtime($timestampfile)); 141 142 // Test purging. 143 $testfile = "$CFG->localcachedir/test/test.txt"; 144 $this->assertTrue(touch($testfile)); 145 146 $now = $this->setCurrentTimeStart(); 147 set_config('localcachedirpurged', $now - 2); 148 purge_all_caches(); 149 $this->assertFileNotExists($testfile); 150 $this->assertFileNotExists(dirname($testfile)); 151 $this->assertFileExists($timestampfile); 152 $this->assertTimeCurrent(filemtime($timestampfile)); 153 $this->assertTimeCurrent($CFG->localcachedirpurged); 154 155 // Simulates purge_all_caches() on another server node. 156 make_localcache_directory('test', false); 157 $this->assertTrue(touch($testfile)); 158 set_config('localcachedirpurged', $now - 1); 159 $this->assertTrue(touch($timestampfile, $now - 2)); 160 clearstatcache(); 161 $this->assertSame($now - 2, filemtime($timestampfile)); 162 163 $this->setCurrentTimeStart(); 164 $dir = make_localcache_directory('', false); 165 $this->assertSame("$CFG->localcachedir", $dir); 166 $this->assertFileNotExists($testfile); 167 $this->assertFileNotExists(dirname($testfile)); 168 $this->assertFileExists($timestampfile); 169 $this->assertTimeCurrent(filemtime($timestampfile)); 170 } 171 172 public function test_make_unique_directory_basedir_is_file() { 173 global $CFG; 174 175 // Start with a file instead of a directory. 176 $base = $CFG->tempdir . DIRECTORY_SEPARATOR . md5(microtime(true) + rand()); 177 touch($base); 178 179 // First the false test. 180 $this->assertFalse(make_unique_writable_directory($base, false)); 181 182 // Now check for exception. 183 $this->expectException('invalid_dataroot_permissions'); 184 $this->expectExceptionMessage($base . ' is not writable. Unable to create a unique directory within it.'); 185 make_unique_writable_directory($base); 186 187 unlink($base); 188 } 189 190 public function test_make_unique_directory() { 191 global $CFG; 192 193 // Create directories should be both directories, and writable. 194 $firstdir = make_unique_writable_directory($CFG->tempdir); 195 $this->assertTrue(is_dir($firstdir)); 196 $this->assertTrue(is_writable($firstdir)); 197 198 $seconddir = make_unique_writable_directory($CFG->tempdir); 199 $this->assertTrue(is_dir($seconddir)); 200 $this->assertTrue(is_writable($seconddir)); 201 202 // Directories should be different each iteration. 203 $this->assertNotEquals($firstdir, $seconddir); 204 } 205 206 public function test_get_request_storage_directory() { 207 $this->resetAfterTest(true); 208 209 // Making a call to get_request_storage_directory should always give the same result. 210 $firstdir = get_request_storage_directory(); 211 $seconddir = get_request_storage_directory(); 212 $this->assertTrue(is_dir($firstdir)); 213 $this->assertEquals($firstdir, $seconddir); 214 215 // Removing the directory and calling get_request_storage_directory() again should cause a new directory to be created. 216 remove_dir($firstdir); 217 $this->assertFalse(file_exists($firstdir)); 218 $this->assertFalse(is_dir($firstdir)); 219 220 $thirddir = get_request_storage_directory(); 221 $this->assertTrue(is_dir($thirddir)); 222 $this->assertNotEquals($firstdir, $thirddir); 223 224 // Removing it and replacing it with a file should cause it to be regenerated again. 225 remove_dir($thirddir); 226 $this->assertFalse(file_exists($thirddir)); 227 $this->assertFalse(is_dir($thirddir)); 228 touch($thirddir); 229 $this->assertTrue(file_exists($thirddir)); 230 $this->assertFalse(is_dir($thirddir)); 231 232 $fourthdir = get_request_storage_directory(); 233 $this->assertTrue(is_dir($fourthdir)); 234 $this->assertNotEquals($thirddir, $fourthdir); 235 236 $now = $this->setCurrentTimeStart(); 237 set_config('localcachedirpurged', $now - 2); 238 purge_all_caches(); 239 $this->assertTrue(is_dir($fourthdir)); 240 } 241 242 243 public function test_make_request_directory() { 244 // Every request directory should be unique. 245 $firstdir = make_request_directory(); 246 $seconddir = make_request_directory(); 247 $thirddir = make_request_directory(); 248 $fourthdir = make_request_directory(); 249 250 $this->assertNotEquals($firstdir, $seconddir); 251 $this->assertNotEquals($firstdir, $thirddir); 252 $this->assertNotEquals($firstdir, $fourthdir); 253 $this->assertNotEquals($seconddir, $thirddir); 254 $this->assertNotEquals($seconddir, $fourthdir); 255 $this->assertNotEquals($thirddir, $fourthdir); 256 257 // They should also all be within the request storage directory. 258 $requestdir = get_request_storage_directory(); 259 $this->assertEquals(0, strpos($firstdir, $requestdir)); 260 $this->assertEquals(0, strpos($seconddir, $requestdir)); 261 $this->assertEquals(0, strpos($thirddir, $requestdir)); 262 $this->assertEquals(0, strpos($fourthdir, $requestdir)); 263 264 // Removing the requestdir should mean that new request directories are still created successfully. 265 remove_dir($requestdir); 266 $this->assertFalse(file_exists($requestdir)); 267 $this->assertFalse(is_dir($requestdir)); 268 269 $fifthdir = make_request_directory(); 270 $this->assertNotEquals($firstdir, $fifthdir); 271 $this->assertNotEquals($seconddir, $fifthdir); 272 $this->assertNotEquals($thirddir, $fifthdir); 273 $this->assertNotEquals($fourthdir, $fifthdir); 274 $this->assertTrue(is_dir($fifthdir)); 275 $this->assertFalse(strpos($fifthdir, $requestdir)); 276 277 // And it should be within the new request directory. 278 $newrequestdir = get_request_storage_directory(); 279 $this->assertEquals(0, strpos($fifthdir, $newrequestdir)); 280 } 281 282 public function test_merge_query_params() { 283 $original = array( 284 'id' => '1', 285 'course' => '2', 286 'action' => 'delete', 287 'grade' => array( 288 0 => 'a', 289 1 => 'b', 290 2 => 'c', 291 ), 292 'items' => array( 293 'a' => 'aa', 294 'b' => 'bb', 295 ), 296 'mix' => array( 297 0 => '2', 298 ), 299 'numerical' => array( 300 '2' => array('a' => 'b'), 301 '1' => '2', 302 ), 303 ); 304 305 $chunk = array( 306 'numerical' => array( 307 '0' => 'z', 308 '2' => array('d' => 'e'), 309 ), 310 'action' => 'create', 311 'next' => '2', 312 'grade' => array( 313 0 => 'e', 314 1 => 'f', 315 2 => 'g', 316 ), 317 'mix' => 'mix', 318 ); 319 320 $expected = array( 321 'id' => '1', 322 'course' => '2', 323 'action' => 'create', 324 'grade' => array( 325 0 => 'a', 326 1 => 'b', 327 2 => 'c', 328 3 => 'e', 329 4 => 'f', 330 5 => 'g', 331 ), 332 'items' => array( 333 'a' => 'aa', 334 'b' => 'bb', 335 ), 336 'mix' => 'mix', 337 'numerical' => array( 338 '2' => array('a' => 'b', 'd' => 'e'), 339 '1' => '2', 340 '0' => 'z', 341 ), 342 'next' => '2', 343 ); 344 345 $array = $original; 346 merge_query_params($array, $chunk); 347 348 $this->assertSame($expected, $array); 349 $this->assertNotSame($original, $array); 350 351 $query = "id=1&course=2&action=create&grade%5B%5D=a&grade%5B%5D=b&grade%5B%5D=c&grade%5B%5D=e&grade%5B%5D=f&grade%5B%5D=g&items%5Ba%5D=aa&items%5Bb%5D=bb&mix=mix&numerical%5B2%5D%5Ba%5D=b&numerical%5B2%5D%5Bd%5D=e&numerical%5B1%5D=2&numerical%5B0%5D=z&next=2"; 352 $decoded = array(); 353 parse_str($query, $decoded); 354 $this->assertSame($expected, $decoded); 355 356 // Prove that we cannot use array_merge_recursive() instead. 357 $this->assertNotSame($expected, array_merge_recursive($original, $chunk)); 358 } 359 360 /** 361 * Test the link processed by get_exception_info(). 362 */ 363 public function test_get_exception_info_link() { 364 global $CFG, $SESSION; 365 366 $httpswwwroot = str_replace('http:', 'https:', $CFG->wwwroot); 367 368 // Simple local URL. 369 $url = $CFG->wwwroot . '/something/here?really=yes'; 370 $exception = new moodle_exception('none', 'error', $url); 371 $infos = $this->get_exception_info($exception); 372 $this->assertSame($url, $infos->link); 373 374 // Relative local URL. 375 $url = '/something/here?really=yes'; 376 $exception = new moodle_exception('none', 'error', $url); 377 $infos = $this->get_exception_info($exception); 378 $this->assertSame($CFG->wwwroot . '/', $infos->link); 379 380 // HTTPS URL when login HTTPS is not enabled (default) and site is HTTP. 381 $CFG->wwwroot = str_replace('https:', 'http:', $CFG->wwwroot); 382 $url = $httpswwwroot . '/something/here?really=yes'; 383 $exception = new moodle_exception('none', 'error', $url); 384 $infos = $this->get_exception_info($exception); 385 $this->assertSame($CFG->wwwroot . '/', $infos->link); 386 387 // HTTPS URL when login HTTPS is not enabled and site is HTTPS. 388 $CFG->wwwroot = str_replace('http:', 'https:', $CFG->wwwroot); 389 $url = $httpswwwroot . '/something/here?really=yes'; 390 $exception = new moodle_exception('none', 'error', $url); 391 $infos = $this->get_exception_info($exception); 392 $this->assertSame($url, $infos->link); 393 394 // External HTTP URL. 395 $url = 'http://moodle.org/something/here?really=yes'; 396 $exception = new moodle_exception('none', 'error', $url); 397 $infos = $this->get_exception_info($exception); 398 $this->assertSame($CFG->wwwroot . '/', $infos->link); 399 400 // External HTTPS URL. 401 $url = 'https://moodle.org/something/here?really=yes'; 402 $exception = new moodle_exception('none', 'error', $url); 403 $infos = $this->get_exception_info($exception); 404 $this->assertSame($CFG->wwwroot . '/', $infos->link); 405 406 // External URL containing local URL. 407 $url = 'http://moodle.org/something/here?' . $CFG->wwwroot; 408 $exception = new moodle_exception('none', 'error', $url); 409 $infos = $this->get_exception_info($exception); 410 $this->assertSame($CFG->wwwroot . '/', $infos->link); 411 412 // Internal link from fromurl. 413 $SESSION->fromurl = $url = $CFG->wwwroot . '/something/here?really=yes'; 414 $exception = new moodle_exception('none'); 415 $infos = $this->get_exception_info($exception); 416 $this->assertSame($url, $infos->link); 417 418 // Internal HTTPS link from fromurl. 419 $SESSION->fromurl = $url = $httpswwwroot . '/something/here?really=yes'; 420 $exception = new moodle_exception('none'); 421 $infos = $this->get_exception_info($exception); 422 $this->assertSame($url, $infos->link); 423 424 // External link from fromurl. 425 $SESSION->fromurl = 'http://moodle.org/something/here?really=yes'; 426 $exception = new moodle_exception('none'); 427 $infos = $this->get_exception_info($exception); 428 $this->assertSame($CFG->wwwroot . '/', $infos->link); 429 430 // External HTTPS link from fromurl. 431 $SESSION->fromurl = 'https://moodle.org/something/here?really=yes'; 432 $exception = new moodle_exception('none'); 433 $infos = $this->get_exception_info($exception); 434 $this->assertSame($CFG->wwwroot . '/', $infos->link); 435 436 $SESSION->fromurl = ''; 437 } 438 439 /** 440 * Wrapper to call {@link get_exception_info()}. 441 * 442 * @param Exception $ex An exception. 443 * @return stdClass of information. 444 */ 445 public function get_exception_info($ex) { 446 try { 447 throw $ex; 448 } catch (moodle_exception $e) { 449 return get_exception_info($e); 450 } 451 } 452 453 /** 454 * Data provider for test_get_real_size(). 455 * 456 * @return array An array of arrays contain test data 457 */ 458 public function data_for_test_get_real_size() { 459 return array( 460 array('8KB', 8192), 461 array('8Kb', 8192), 462 array('8K', 8192), 463 array('8k', 8192), 464 array('50MB', 52428800), 465 array('50Mb', 52428800), 466 array('50M', 52428800), 467 array('50m', 52428800), 468 array('8GB', 8589934592), 469 array('8Gb', 8589934592), 470 array('8G', 8589934592), 471 array('7T', 7696581394432), 472 array('7TB', 7696581394432), 473 array('7Tb', 7696581394432), 474 array('6P', 6755399441055744), 475 array('6PB', 6755399441055744), 476 array('6Pb', 6755399441055744), 477 ); 478 } 479 480 /** 481 * Test the get_real_size() function. 482 * 483 * @dataProvider data_for_test_get_real_size 484 * 485 * @param string $input the input for get_real_size() 486 * @param int $expectedbytes the expected bytes 487 */ 488 public function test_get_real_size($input, $expectedbytes) { 489 $this->assertEquals($expectedbytes, get_real_size($input)); 490 } 491 492 /** 493 * Validate the given V4 UUID. 494 * 495 * @param string $value The candidate V4 UUID 496 * @return bool True if valid; otherwise, false. 497 */ 498 protected static function is_valid_uuid_v4($value) { 499 // Version 4 UUIDs have the form xxxxxxxx-xxxx-4xxx-Yxxx-xxxxxxxxxxxx 500 // where x is any hexadecimal digit and Y is one of 8, 9, aA, or bB. 501 // First, the size is 36 (32 + 4 dashes). 502 if (strlen($value) != 36) { 503 return false; 504 } 505 // Finally, check the format. 506 $uuidv4pattern = '/^[0-9A-F]{8}-[0-9A-F]{4}-4[0-9A-F]{3}-[89AB][0-9A-F]{3}-[0-9A-F]{12}$/i'; 507 return (preg_match($uuidv4pattern, $value) === 1); 508 } 509 510 /** 511 * Test the \core\uuid::generate_uuid_via_pecl_uuid_extension() function. 512 */ 513 public function test_core_uuid_generate_uuid_via_pecl_uuid_extension() { 514 if (!extension_loaded('uuid')) { 515 $this->markTestSkipped("PHP 'uuid' extension not loaded."); 516 } 517 if (!function_exists('uuid_time')) { 518 $this->markTestSkipped("PHP PECL 'uuid' extension not loaded."); 519 } 520 521 // The \core\uuid::generate_uuid_via_pecl_uuid_extension static method is protected. Use Reflection to call the method. 522 $method = new ReflectionMethod('\core\uuid', 'generate_uuid_via_pecl_uuid_extension'); 523 $method->setAccessible(true); 524 $uuid = $method->invoke(null); 525 $this->assertTrue(self::is_valid_uuid_v4($uuid), "Invalid v4 uuid: '$uuid'"); 526 } 527 528 /** 529 * Test the \core\uuid::generate_uuid_via_random_bytes() function. 530 */ 531 public function test_core_uuid_generate_uuid_via_random_bytes() { 532 try { 533 random_bytes(1); 534 } catch (Exception $e) { 535 $this->markTestSkipped('No source of entropy for random_bytes. ' . $e->getMessage()); 536 } 537 538 // The \core\uuid::generate_uuid_via_random_bytes static method is protected. Use Reflection to call the method. 539 $method = new ReflectionMethod('\core\uuid', 'generate_uuid_via_random_bytes'); 540 $method->setAccessible(true); 541 $uuid = $method->invoke(null); 542 $this->assertTrue(self::is_valid_uuid_v4($uuid), "Invalid v4 uuid: '$uuid'"); 543 } 544 545 /** 546 * Test the \core\uuid::generate() function. 547 */ 548 public function test_core_uuid_generate() { 549 $uuid = \core\uuid::generate(); 550 $this->assertTrue(self::is_valid_uuid_v4($uuid), "Invalid v4 UUID: '$uuid'"); 551 } 552} 553