PageRenderTime 102ms CodeModel.GetById 34ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/tests/moodlelib_test.php

https://github.com/dcai/moodle
PHP | 4690 lines | 3410 code | 542 blank | 738 comment | 18 complexity | 7f786953036f6286f8245824fb854600 MD5 | raw file
Possible License(s): LGPL-2.1, BSD-3-Clause, MIT, GPL-3.0, Apache-2.0
  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. * Unit tests for (some of) ../moodlelib.php.
  18. *
  19. * @package core
  20. * @category phpunit
  21. * @copyright &copy; 2006 The Open University
  22. * @author T.J.Hunt@open.ac.uk
  23. * @author nicolas@moodle.com
  24. */
  25. defined('MOODLE_INTERNAL') || die();
  26. class core_moodlelib_testcase extends advanced_testcase {
  27. public static $includecoverage = array('lib/moodlelib.php');
  28. /**
  29. * Define a local decimal separator.
  30. *
  31. * It is not possible to directly change the result of get_string in
  32. * a unit test. Instead, we create a language pack for language 'xx' in
  33. * dataroot and make langconfig.php with the string we need to change.
  34. * The default example separator used here is 'X'; on PHP 5.3 and before this
  35. * must be a single byte character due to PHP bug/limitation in
  36. * number_format, so you can't use UTF-8 characters.
  37. *
  38. * @param string $decsep Separator character. Defaults to `'X'`.
  39. */
  40. protected function define_local_decimal_separator(string $decsep = 'X') {
  41. global $SESSION, $CFG;
  42. $SESSION->lang = 'xx';
  43. $langconfig = "<?php\n\$string['decsep'] = '$decsep';";
  44. $langfolder = $CFG->dataroot . '/lang/xx';
  45. check_dir_exists($langfolder);
  46. file_put_contents($langfolder . '/langconfig.php', $langconfig);
  47. // Ensure the new value is picked up and not taken from the cache.
  48. $stringmanager = get_string_manager();
  49. $stringmanager->reset_caches(true);
  50. }
  51. public function test_cleanremoteaddr() {
  52. // IPv4.
  53. $this->assertNull(cleanremoteaddr('1023.121.234.1'));
  54. $this->assertSame('123.121.234.1', cleanremoteaddr('123.121.234.01 '));
  55. // IPv6.
  56. $this->assertNull(cleanremoteaddr('0:0:0:0:0:0:0:0:0'));
  57. $this->assertNull(cleanremoteaddr('0:0:0:0:0:0:0:abh'));
  58. $this->assertNull(cleanremoteaddr('0:0:0:::0:0:1'));
  59. $this->assertSame('::', cleanremoteaddr('0:0:0:0:0:0:0:0', true));
  60. $this->assertSame('::1:1', cleanremoteaddr('0:0:0:0:0:0:1:1', true));
  61. $this->assertSame('abcd:ef::', cleanremoteaddr('abcd:00ef:0:0:0:0:0:0', true));
  62. $this->assertSame('1::1', cleanremoteaddr('1:0:0:0:0:0:0:1', true));
  63. $this->assertSame('0:0:0:0:0:0:10:1', cleanremoteaddr('::10:1', false));
  64. $this->assertSame('1:1:0:0:0:0:0:0', cleanremoteaddr('01:1::', false));
  65. $this->assertSame('10:0:0:0:0:0:0:10', cleanremoteaddr('10::10', false));
  66. $this->assertSame('::ffff:c0a8:11', cleanremoteaddr('::ffff:192.168.1.1', true));
  67. }
  68. public function test_address_in_subnet() {
  69. // 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn (number of bits in net mask).
  70. $this->assertTrue(address_in_subnet('123.121.234.1', '123.121.234.1/32'));
  71. $this->assertFalse(address_in_subnet('123.121.23.1', '123.121.23.0/32'));
  72. $this->assertTrue(address_in_subnet('10.10.10.100', '123.121.23.45/0'));
  73. $this->assertTrue(address_in_subnet('123.121.234.1', '123.121.234.0/24'));
  74. $this->assertFalse(address_in_subnet('123.121.34.1', '123.121.234.0/24'));
  75. $this->assertTrue(address_in_subnet('123.121.234.1', '123.121.234.0/30'));
  76. $this->assertFalse(address_in_subnet('123.121.23.8', '123.121.23.0/30'));
  77. $this->assertTrue(address_in_subnet('baba:baba::baba', 'baba:baba::baba/128'));
  78. $this->assertFalse(address_in_subnet('bab:baba::baba', 'bab:baba::cece/128'));
  79. $this->assertTrue(address_in_subnet('baba:baba::baba', 'cece:cece::cece/0'));
  80. $this->assertTrue(address_in_subnet('baba:baba::baba', 'baba:baba::baba/128'));
  81. $this->assertTrue(address_in_subnet('baba:baba::00ba', 'baba:baba::/120'));
  82. $this->assertFalse(address_in_subnet('baba:baba::aba', 'baba:baba::/120'));
  83. $this->assertTrue(address_in_subnet('baba::baba:00ba', 'baba::baba:0/112'));
  84. $this->assertFalse(address_in_subnet('baba::aba:00ba', 'baba::baba:0/112'));
  85. $this->assertFalse(address_in_subnet('aba::baba:0000', 'baba::baba:0/112'));
  86. // Fixed input.
  87. $this->assertTrue(address_in_subnet('123.121.23.1 ', ' 123.121.23.0 / 24'));
  88. $this->assertTrue(address_in_subnet('::ffff:10.1.1.1', ' 0:0:0:000:0:ffff:a1:10 / 126'));
  89. // Incorrect input.
  90. $this->assertFalse(address_in_subnet('123.121.234.1', '123.121.234.1/-2'));
  91. $this->assertFalse(address_in_subnet('123.121.234.1', '123.121.234.1/64'));
  92. $this->assertFalse(address_in_subnet('123.121.234.x', '123.121.234.1/24'));
  93. $this->assertFalse(address_in_subnet('123.121.234.0', '123.121.234.xx/24'));
  94. $this->assertFalse(address_in_subnet('123.121.234.1', '123.121.234.1/xx0'));
  95. $this->assertFalse(address_in_subnet('::1', '::aa:0/xx0'));
  96. $this->assertFalse(address_in_subnet('::1', '::aa:0/-5'));
  97. $this->assertFalse(address_in_subnet('::1', '::aa:0/130'));
  98. $this->assertFalse(address_in_subnet('x:1', '::aa:0/130'));
  99. $this->assertFalse(address_in_subnet('::1', '::ax:0/130'));
  100. // 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).
  101. $this->assertTrue(address_in_subnet('123.121.234.12', '123.121.234.12-14'));
  102. $this->assertTrue(address_in_subnet('123.121.234.13', '123.121.234.12-14'));
  103. $this->assertTrue(address_in_subnet('123.121.234.14', '123.121.234.12-14'));
  104. $this->assertFalse(address_in_subnet('123.121.234.1', '123.121.234.12-14'));
  105. $this->assertFalse(address_in_subnet('123.121.234.20', '123.121.234.12-14'));
  106. $this->assertFalse(address_in_subnet('123.121.23.12', '123.121.234.12-14'));
  107. $this->assertFalse(address_in_subnet('123.12.234.12', '123.121.234.12-14'));
  108. $this->assertTrue(address_in_subnet('baba:baba::baba', 'baba:baba::baba-babe'));
  109. $this->assertTrue(address_in_subnet('baba:baba::babc', 'baba:baba::baba-babe'));
  110. $this->assertTrue(address_in_subnet('baba:baba::babe', 'baba:baba::baba-babe'));
  111. $this->assertFalse(address_in_subnet('bab:baba::bab0', 'bab:baba::baba-babe'));
  112. $this->assertFalse(address_in_subnet('bab:baba::babf', 'bab:baba::baba-babe'));
  113. $this->assertFalse(address_in_subnet('bab:baba::bfbe', 'bab:baba::baba-babe'));
  114. $this->assertFalse(address_in_subnet('bfb:baba::babe', 'bab:baba::baba-babe'));
  115. // Fixed input.
  116. $this->assertTrue(address_in_subnet('123.121.234.12', '123.121.234.12 - 14 '));
  117. $this->assertTrue(address_in_subnet('bab:baba::babe', 'bab:baba::baba - babe '));
  118. // Incorrect input.
  119. $this->assertFalse(address_in_subnet('123.121.234.12', '123.121.234.12-234.14'));
  120. $this->assertFalse(address_in_subnet('123.121.234.12', '123.121.234.12-256'));
  121. $this->assertFalse(address_in_subnet('123.121.234.12', '123.121.234.12--256'));
  122. // 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx. (incomplete address, a bit non-technical ;-).
  123. $this->assertTrue(address_in_subnet('123.121.234.12', '123.121.234.12'));
  124. $this->assertFalse(address_in_subnet('123.121.23.12', '123.121.23.13'));
  125. $this->assertTrue(address_in_subnet('123.121.234.12', '123.121.234.'));
  126. $this->assertTrue(address_in_subnet('123.121.234.12', '123.121.234'));
  127. $this->assertTrue(address_in_subnet('123.121.234.12', '123.121'));
  128. $this->assertTrue(address_in_subnet('123.121.234.12', '123'));
  129. $this->assertFalse(address_in_subnet('123.121.234.1', '12.121.234.'));
  130. $this->assertFalse(address_in_subnet('123.121.234.1', '12.121.234'));
  131. $this->assertTrue(address_in_subnet('baba:baba::bab', 'baba:baba::bab'));
  132. $this->assertFalse(address_in_subnet('baba:baba::ba', 'baba:baba::bc'));
  133. $this->assertTrue(address_in_subnet('baba:baba::bab', 'baba:baba'));
  134. $this->assertTrue(address_in_subnet('baba:baba::bab', 'baba:'));
  135. $this->assertFalse(address_in_subnet('bab:baba::bab', 'baba:'));
  136. // Multiple subnets.
  137. $this->assertTrue(address_in_subnet('123.121.234.12', '::1/64, 124., 123.121.234.10-30'));
  138. $this->assertTrue(address_in_subnet('124.121.234.12', '::1/64, 124., 123.121.234.10-30'));
  139. $this->assertTrue(address_in_subnet('::2', '::1/64, 124., 123.121.234.10-30'));
  140. $this->assertFalse(address_in_subnet('12.121.234.12', '::1/64, 124., 123.121.234.10-30'));
  141. // Other incorrect input.
  142. $this->assertFalse(address_in_subnet('123.123.123.123', ''));
  143. }
  144. public function test_fix_utf8() {
  145. // Make sure valid data including other types is not changed.
  146. $this->assertSame(null, fix_utf8(null));
  147. $this->assertSame(1, fix_utf8(1));
  148. $this->assertSame(1.1, fix_utf8(1.1));
  149. $this->assertSame(true, fix_utf8(true));
  150. $this->assertSame('', fix_utf8(''));
  151. $this->assertSame('abc', fix_utf8('abc'));
  152. $array = array('do', 're', 'mi');
  153. $this->assertSame($array, fix_utf8($array));
  154. $object = new stdClass();
  155. $object->a = 'aa';
  156. $object->b = 'bb';
  157. $this->assertEquals($object, fix_utf8($object));
  158. // valid utf8 string
  159. $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"));
  160. // Invalid utf8 string.
  161. $this->assertSame('aš', fix_utf8('a'.chr(130).'š'), 'This fails with buggy iconv() when mbstring extenstion is not available as fallback.');
  162. }
  163. public function test_optional_param() {
  164. global $CFG;
  165. $_POST['username'] = 'post_user';
  166. $_GET['username'] = 'get_user';
  167. $this->assertSame($_POST['username'], optional_param('username', 'default_user', PARAM_RAW));
  168. unset($_POST['username']);
  169. $this->assertSame($_GET['username'], optional_param('username', 'default_user', PARAM_RAW));
  170. unset($_GET['username']);
  171. $this->assertSame('default_user', optional_param('username', 'default_user', PARAM_RAW));
  172. // Make sure exception is triggered when some params are missing, hide error notices here - new in 2.2.
  173. $_POST['username'] = 'post_user';
  174. try {
  175. optional_param('username', 'default_user', null);
  176. $this->fail('coding_exception expected');
  177. } catch (moodle_exception $ex) {
  178. $this->assertInstanceOf('coding_exception', $ex);
  179. }
  180. try {
  181. @optional_param('username', 'default_user');
  182. $this->fail('coding_exception expected');
  183. } catch (moodle_exception $ex) {
  184. $this->assertInstanceOf('coding_exception', $ex);
  185. } catch (Error $error) {
  186. // PHP 7.1 throws Error even earlier.
  187. $this->assertRegExp('/Too few arguments to function/', $error->getMessage());
  188. }
  189. try {
  190. @optional_param('username');
  191. $this->fail('coding_exception expected');
  192. } catch (moodle_exception $ex) {
  193. $this->assertInstanceOf('coding_exception', $ex);
  194. } catch (Error $error) {
  195. // PHP 7.1 throws Error even earlier.
  196. $this->assertRegExp('/Too few arguments to function/', $error->getMessage());
  197. }
  198. try {
  199. optional_param('', 'default_user', PARAM_RAW);
  200. $this->fail('coding_exception expected');
  201. } catch (moodle_exception $ex) {
  202. $this->assertInstanceOf('coding_exception', $ex);
  203. }
  204. // Make sure warning is displayed if array submitted - TODO: throw exception in Moodle 2.3.
  205. $_POST['username'] = array('a'=>'a');
  206. $this->assertSame($_POST['username'], optional_param('username', 'default_user', PARAM_RAW));
  207. $this->assertDebuggingCalled();
  208. }
  209. public function test_optional_param_array() {
  210. global $CFG;
  211. $_POST['username'] = array('a'=>'post_user');
  212. $_GET['username'] = array('a'=>'get_user');
  213. $this->assertSame($_POST['username'], optional_param_array('username', array('a'=>'default_user'), PARAM_RAW));
  214. unset($_POST['username']);
  215. $this->assertSame($_GET['username'], optional_param_array('username', array('a'=>'default_user'), PARAM_RAW));
  216. unset($_GET['username']);
  217. $this->assertSame(array('a'=>'default_user'), optional_param_array('username', array('a'=>'default_user'), PARAM_RAW));
  218. // Make sure exception is triggered when some params are missing, hide error notices here - new in 2.2.
  219. $_POST['username'] = array('a'=>'post_user');
  220. try {
  221. optional_param_array('username', array('a'=>'default_user'), null);
  222. $this->fail('coding_exception expected');
  223. } catch (moodle_exception $ex) {
  224. $this->assertInstanceOf('coding_exception', $ex);
  225. }
  226. try {
  227. @optional_param_array('username', array('a'=>'default_user'));
  228. $this->fail('coding_exception expected');
  229. } catch (moodle_exception $ex) {
  230. $this->assertInstanceOf('coding_exception', $ex);
  231. } catch (Error $error) {
  232. // PHP 7.1 throws Error even earlier.
  233. $this->assertRegExp('/Too few arguments to function/', $error->getMessage());
  234. }
  235. try {
  236. @optional_param_array('username');
  237. $this->fail('coding_exception expected');
  238. } catch (moodle_exception $ex) {
  239. $this->assertInstanceOf('coding_exception', $ex);
  240. } catch (Error $error) {
  241. // PHP 7.1 throws Error even earlier.
  242. $this->assertRegExp('/Too few arguments to function/', $error->getMessage());
  243. }
  244. try {
  245. optional_param_array('', array('a'=>'default_user'), PARAM_RAW);
  246. $this->fail('coding_exception expected');
  247. } catch (moodle_exception $ex) {
  248. $this->assertInstanceOf('coding_exception', $ex);
  249. }
  250. // Do not allow nested arrays.
  251. try {
  252. $_POST['username'] = array('a'=>array('b'=>'post_user'));
  253. optional_param_array('username', array('a'=>'default_user'), PARAM_RAW);
  254. $this->fail('coding_exception expected');
  255. } catch (coding_exception $ex) {
  256. $this->assertTrue(true);
  257. }
  258. // Do not allow non-arrays.
  259. $_POST['username'] = 'post_user';
  260. $this->assertSame(array('a'=>'default_user'), optional_param_array('username', array('a'=>'default_user'), PARAM_RAW));
  261. $this->assertDebuggingCalled();
  262. // Make sure array keys are sanitised.
  263. $_POST['username'] = array('abc123_;-/*-+ '=>'arrggh', 'a1_-'=>'post_user');
  264. $this->assertSame(array('a1_-'=>'post_user'), optional_param_array('username', array(), PARAM_RAW));
  265. $this->assertDebuggingCalled();
  266. }
  267. public function test_required_param() {
  268. $_POST['username'] = 'post_user';
  269. $_GET['username'] = 'get_user';
  270. $this->assertSame('post_user', required_param('username', PARAM_RAW));
  271. unset($_POST['username']);
  272. $this->assertSame('get_user', required_param('username', PARAM_RAW));
  273. unset($_GET['username']);
  274. try {
  275. $this->assertSame('default_user', required_param('username', PARAM_RAW));
  276. $this->fail('moodle_exception expected');
  277. } catch (moodle_exception $ex) {
  278. $this->assertInstanceOf('moodle_exception', $ex);
  279. }
  280. // Make sure exception is triggered when some params are missing, hide error notices here - new in 2.2.
  281. $_POST['username'] = 'post_user';
  282. try {
  283. @required_param('username');
  284. $this->fail('coding_exception expected');
  285. } catch (moodle_exception $ex) {
  286. $this->assertInstanceOf('coding_exception', $ex);
  287. } catch (Error $error) {
  288. // PHP 7.1 throws Error even earlier.
  289. $this->assertRegExp('/Too few arguments to function/', $error->getMessage());
  290. }
  291. try {
  292. required_param('username', '');
  293. $this->fail('coding_exception expected');
  294. } catch (moodle_exception $ex) {
  295. $this->assertInstanceOf('coding_exception', $ex);
  296. }
  297. try {
  298. required_param('', PARAM_RAW);
  299. $this->fail('coding_exception expected');
  300. } catch (moodle_exception $ex) {
  301. $this->assertInstanceOf('coding_exception', $ex);
  302. }
  303. // Make sure warning is displayed if array submitted - TODO: throw exception in Moodle 2.3.
  304. $_POST['username'] = array('a'=>'a');
  305. $this->assertSame($_POST['username'], required_param('username', PARAM_RAW));
  306. $this->assertDebuggingCalled();
  307. }
  308. public function test_required_param_array() {
  309. global $CFG;
  310. $_POST['username'] = array('a'=>'post_user');
  311. $_GET['username'] = array('a'=>'get_user');
  312. $this->assertSame($_POST['username'], required_param_array('username', PARAM_RAW));
  313. unset($_POST['username']);
  314. $this->assertSame($_GET['username'], required_param_array('username', PARAM_RAW));
  315. // Make sure exception is triggered when some params are missing, hide error notices here - new in 2.2.
  316. $_POST['username'] = array('a'=>'post_user');
  317. try {
  318. required_param_array('username', null);
  319. $this->fail('coding_exception expected');
  320. } catch (moodle_exception $ex) {
  321. $this->assertInstanceOf('coding_exception', $ex);
  322. }
  323. try {
  324. @required_param_array('username');
  325. $this->fail('coding_exception expected');
  326. } catch (moodle_exception $ex) {
  327. $this->assertInstanceOf('coding_exception', $ex);
  328. } catch (Error $error) {
  329. // PHP 7.1 throws Error.
  330. $this->assertRegExp('/Too few arguments to function/', $error->getMessage());
  331. }
  332. try {
  333. required_param_array('', PARAM_RAW);
  334. $this->fail('coding_exception expected');
  335. } catch (moodle_exception $ex) {
  336. $this->assertInstanceOf('coding_exception', $ex);
  337. }
  338. // Do not allow nested arrays.
  339. try {
  340. $_POST['username'] = array('a'=>array('b'=>'post_user'));
  341. required_param_array('username', PARAM_RAW);
  342. $this->fail('coding_exception expected');
  343. } catch (moodle_exception $ex) {
  344. $this->assertInstanceOf('coding_exception', $ex);
  345. }
  346. // Do not allow non-arrays.
  347. try {
  348. $_POST['username'] = 'post_user';
  349. required_param_array('username', PARAM_RAW);
  350. $this->fail('moodle_exception expected');
  351. } catch (moodle_exception $ex) {
  352. $this->assertInstanceOf('moodle_exception', $ex);
  353. }
  354. // Make sure array keys are sanitised.
  355. $_POST['username'] = array('abc123_;-/*-+ '=>'arrggh', 'a1_-'=>'post_user');
  356. $this->assertSame(array('a1_-'=>'post_user'), required_param_array('username', PARAM_RAW));
  357. $this->assertDebuggingCalled();
  358. }
  359. public function test_clean_param() {
  360. // Forbid objects and arrays.
  361. try {
  362. clean_param(array('x', 'y'), PARAM_RAW);
  363. $this->fail('coding_exception expected');
  364. } catch (moodle_exception $ex) {
  365. $this->assertInstanceOf('coding_exception', $ex);
  366. }
  367. try {
  368. $param = new stdClass();
  369. $param->id = 1;
  370. clean_param($param, PARAM_RAW);
  371. $this->fail('coding_exception expected');
  372. } catch (moodle_exception $ex) {
  373. $this->assertInstanceOf('coding_exception', $ex);
  374. }
  375. // Require correct type.
  376. try {
  377. clean_param('x', 'xxxxxx');
  378. $this->fail('moodle_exception expected');
  379. } catch (moodle_exception $ex) {
  380. $this->assertInstanceOf('moodle_exception', $ex);
  381. }
  382. try {
  383. @clean_param('x');
  384. $this->fail('moodle_exception expected');
  385. } catch (moodle_exception $ex) {
  386. $this->assertInstanceOf('moodle_exception', $ex);
  387. } catch (Error $error) {
  388. // PHP 7.1 throws Error even earlier.
  389. $this->assertRegExp('/Too few arguments to function/', $error->getMessage());
  390. }
  391. }
  392. public function test_clean_param_array() {
  393. $this->assertSame(array(), clean_param_array(null, PARAM_RAW));
  394. $this->assertSame(array('a', 'b'), clean_param_array(array('a', 'b'), PARAM_RAW));
  395. $this->assertSame(array('a', array('b')), clean_param_array(array('a', array('b')), PARAM_RAW, true));
  396. // Require correct type.
  397. try {
  398. clean_param_array(array('x'), 'xxxxxx');
  399. $this->fail('moodle_exception expected');
  400. } catch (moodle_exception $ex) {
  401. $this->assertInstanceOf('moodle_exception', $ex);
  402. }
  403. try {
  404. @clean_param_array(array('x'));
  405. $this->fail('moodle_exception expected');
  406. } catch (moodle_exception $ex) {
  407. $this->assertInstanceOf('moodle_exception', $ex);
  408. } catch (Error $error) {
  409. // PHP 7.1 throws Error even earlier.
  410. $this->assertRegExp('/Too few arguments to function/', $error->getMessage());
  411. }
  412. try {
  413. clean_param_array(array('x', array('y')), PARAM_RAW);
  414. $this->fail('coding_exception expected');
  415. } catch (moodle_exception $ex) {
  416. $this->assertInstanceOf('coding_exception', $ex);
  417. }
  418. // Test recursive.
  419. }
  420. public function test_clean_param_raw() {
  421. $this->assertSame(
  422. '#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)',
  423. clean_param('#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)', PARAM_RAW));
  424. }
  425. public function test_clean_param_trim() {
  426. $this->assertSame('Frog toad', clean_param(" Frog toad \r\n ", PARAM_RAW_TRIMMED));
  427. }
  428. public function test_clean_param_clean() {
  429. // PARAM_CLEAN is an ugly hack, do not use in new code (skodak),
  430. // instead use more specific type, or submit sothing that can be verified properly.
  431. $this->assertSame('xx', clean_param('xx<script>', PARAM_CLEAN));
  432. }
  433. public function test_clean_param_alpha() {
  434. $this->assertSame('DSFMOSDJ', clean_param('#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)', PARAM_ALPHA));
  435. }
  436. public function test_clean_param_alphanum() {
  437. $this->assertSame('978942897DSFMOSDJ', clean_param('#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)', PARAM_ALPHANUM));
  438. }
  439. public function test_clean_param_alphaext() {
  440. $this->assertSame('DSFMOSDJ', clean_param('#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)', PARAM_ALPHAEXT));
  441. }
  442. public function test_clean_param_sequence() {
  443. $this->assertSame(',9789,42897', clean_param('#()*#,9789\'".,<42897></?$(*DSFMO#$*)(SDJ)($*)', PARAM_SEQUENCE));
  444. }
  445. public function test_clean_param_component() {
  446. // Please note the cleaning of component names is very strict, no guessing here.
  447. $this->assertSame('mod_forum', clean_param('mod_forum', PARAM_COMPONENT));
  448. $this->assertSame('block_online_users', clean_param('block_online_users', PARAM_COMPONENT));
  449. $this->assertSame('block_blond_online_users', clean_param('block_blond_online_users', PARAM_COMPONENT));
  450. $this->assertSame('mod_something2', clean_param('mod_something2', PARAM_COMPONENT));
  451. $this->assertSame('forum', clean_param('forum', PARAM_COMPONENT));
  452. $this->assertSame('user', clean_param('user', PARAM_COMPONENT));
  453. $this->assertSame('rating', clean_param('rating', PARAM_COMPONENT));
  454. $this->assertSame('feedback360', clean_param('feedback360', PARAM_COMPONENT));
  455. $this->assertSame('mod_feedback360', clean_param('mod_feedback360', PARAM_COMPONENT));
  456. $this->assertSame('', clean_param('mod_2something', PARAM_COMPONENT));
  457. $this->assertSame('', clean_param('2mod_something', PARAM_COMPONENT));
  458. $this->assertSame('', clean_param('mod_something_xx', PARAM_COMPONENT));
  459. $this->assertSame('', clean_param('auth_something__xx', PARAM_COMPONENT));
  460. $this->assertSame('', clean_param('mod_Something', PARAM_COMPONENT));
  461. $this->assertSame('', clean_param('mod_somethíng', PARAM_COMPONENT));
  462. $this->assertSame('', clean_param('mod__something', PARAM_COMPONENT));
  463. $this->assertSame('', clean_param('auth_xx-yy', PARAM_COMPONENT));
  464. $this->assertSame('', clean_param('_auth_xx', PARAM_COMPONENT));
  465. $this->assertSame('a2uth_xx', clean_param('a2uth_xx', PARAM_COMPONENT));
  466. $this->assertSame('', clean_param('auth_xx_', PARAM_COMPONENT));
  467. $this->assertSame('', clean_param('auth_xx.old', PARAM_COMPONENT));
  468. $this->assertSame('', clean_param('_user', PARAM_COMPONENT));
  469. $this->assertSame('', clean_param('2rating', PARAM_COMPONENT));
  470. $this->assertSame('', clean_param('user_', PARAM_COMPONENT));
  471. }
  472. public function test_clean_param_localisedfloat() {
  473. $this->assertSame(0.5, clean_param('0.5', PARAM_LOCALISEDFLOAT));
  474. $this->assertSame(false, clean_param('0X5', PARAM_LOCALISEDFLOAT));
  475. $this->assertSame(0.5, clean_param('.5', PARAM_LOCALISEDFLOAT));
  476. $this->assertSame(false, clean_param('X5', PARAM_LOCALISEDFLOAT));
  477. $this->assertSame(10.5, clean_param('10.5', PARAM_LOCALISEDFLOAT));
  478. $this->assertSame(false, clean_param('10X5', PARAM_LOCALISEDFLOAT));
  479. $this->assertSame(1000.5, clean_param('1 000.5', PARAM_LOCALISEDFLOAT));
  480. $this->assertSame(false, clean_param('1 000X5', PARAM_LOCALISEDFLOAT));
  481. $this->assertSame(false, clean_param('1.000.5', PARAM_LOCALISEDFLOAT));
  482. $this->assertSame(false, clean_param('1X000X5', PARAM_LOCALISEDFLOAT));
  483. $this->assertSame(false, clean_param('nan', PARAM_LOCALISEDFLOAT));
  484. $this->assertSame(false, clean_param('10.6blah', PARAM_LOCALISEDFLOAT));
  485. // Tests with a localised decimal separator.
  486. $this->define_local_decimal_separator();
  487. $this->assertSame(0.5, clean_param('0.5', PARAM_LOCALISEDFLOAT));
  488. $this->assertSame(0.5, clean_param('0X5', PARAM_LOCALISEDFLOAT));
  489. $this->assertSame(0.5, clean_param('.5', PARAM_LOCALISEDFLOAT));
  490. $this->assertSame(0.5, clean_param('X5', PARAM_LOCALISEDFLOAT));
  491. $this->assertSame(10.5, clean_param('10.5', PARAM_LOCALISEDFLOAT));
  492. $this->assertSame(10.5, clean_param('10X5', PARAM_LOCALISEDFLOAT));
  493. $this->assertSame(1000.5, clean_param('1 000.5', PARAM_LOCALISEDFLOAT));
  494. $this->assertSame(1000.5, clean_param('1 000X5', PARAM_LOCALISEDFLOAT));
  495. $this->assertSame(false, clean_param('1.000.5', PARAM_LOCALISEDFLOAT));
  496. $this->assertSame(false, clean_param('1X000X5', PARAM_LOCALISEDFLOAT));
  497. $this->assertSame(false, clean_param('nan', PARAM_LOCALISEDFLOAT));
  498. $this->assertSame(false, clean_param('10X6blah', PARAM_LOCALISEDFLOAT));
  499. }
  500. public function test_is_valid_plugin_name() {
  501. $this->assertTrue(is_valid_plugin_name('forum'));
  502. $this->assertTrue(is_valid_plugin_name('forum2'));
  503. $this->assertTrue(is_valid_plugin_name('feedback360'));
  504. $this->assertTrue(is_valid_plugin_name('online_users'));
  505. $this->assertTrue(is_valid_plugin_name('blond_online_users'));
  506. $this->assertFalse(is_valid_plugin_name('online__users'));
  507. $this->assertFalse(is_valid_plugin_name('forum '));
  508. $this->assertFalse(is_valid_plugin_name('forum.old'));
  509. $this->assertFalse(is_valid_plugin_name('xx-yy'));
  510. $this->assertFalse(is_valid_plugin_name('2xx'));
  511. $this->assertFalse(is_valid_plugin_name('Xx'));
  512. $this->assertFalse(is_valid_plugin_name('_xx'));
  513. $this->assertFalse(is_valid_plugin_name('xx_'));
  514. }
  515. public function test_clean_param_plugin() {
  516. // Please note the cleaning of plugin names is very strict, no guessing here.
  517. $this->assertSame('forum', clean_param('forum', PARAM_PLUGIN));
  518. $this->assertSame('forum2', clean_param('forum2', PARAM_PLUGIN));
  519. $this->assertSame('feedback360', clean_param('feedback360', PARAM_PLUGIN));
  520. $this->assertSame('online_users', clean_param('online_users', PARAM_PLUGIN));
  521. $this->assertSame('blond_online_users', clean_param('blond_online_users', PARAM_PLUGIN));
  522. $this->assertSame('', clean_param('online__users', PARAM_PLUGIN));
  523. $this->assertSame('', clean_param('forum ', PARAM_PLUGIN));
  524. $this->assertSame('', clean_param('forum.old', PARAM_PLUGIN));
  525. $this->assertSame('', clean_param('xx-yy', PARAM_PLUGIN));
  526. $this->assertSame('', clean_param('2xx', PARAM_PLUGIN));
  527. $this->assertSame('', clean_param('Xx', PARAM_PLUGIN));
  528. $this->assertSame('', clean_param('_xx', PARAM_PLUGIN));
  529. $this->assertSame('', clean_param('xx_', PARAM_PLUGIN));
  530. }
  531. public function test_clean_param_area() {
  532. // Please note the cleaning of area names is very strict, no guessing here.
  533. $this->assertSame('something', clean_param('something', PARAM_AREA));
  534. $this->assertSame('something2', clean_param('something2', PARAM_AREA));
  535. $this->assertSame('some_thing', clean_param('some_thing', PARAM_AREA));
  536. $this->assertSame('some_thing_xx', clean_param('some_thing_xx', PARAM_AREA));
  537. $this->assertSame('feedback360', clean_param('feedback360', PARAM_AREA));
  538. $this->assertSame('', clean_param('_something', PARAM_AREA));
  539. $this->assertSame('', clean_param('something_', PARAM_AREA));
  540. $this->assertSame('', clean_param('2something', PARAM_AREA));
  541. $this->assertSame('', clean_param('Something', PARAM_AREA));
  542. $this->assertSame('', clean_param('some-thing', PARAM_AREA));
  543. $this->assertSame('', clean_param('somethííng', PARAM_AREA));
  544. $this->assertSame('', clean_param('something.x', PARAM_AREA));
  545. }
  546. public function test_clean_param_text() {
  547. $this->assertSame(PARAM_TEXT, PARAM_MULTILANG);
  548. // Standard.
  549. $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));
  550. $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));
  551. $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));
  552. // Malformed.
  553. $this->assertSame('<span lang="en" class="multilang">aa</span>', clean_param('<span lang="en" class="multilang">aa</span>', PARAM_TEXT));
  554. $this->assertSame('aa', clean_param('<span lang="en" class="nothing" class="multilang">aa</span>', PARAM_TEXT));
  555. $this->assertSame('aa', clean_param('<lang lang="en" class="multilang">aa</lang>', PARAM_TEXT));
  556. $this->assertSame('aa', clean_param('<lang lang="en!!">aa</lang>', PARAM_TEXT));
  557. $this->assertSame('aa', clean_param('<span lang="en==" class="multilang">aa</span>', PARAM_TEXT));
  558. $this->assertSame('abc', clean_param('a<em>b</em>c', PARAM_TEXT));
  559. $this->assertSame('a>c>', clean_param('a><xx >c>', PARAM_TEXT)); // Standard strip_tags() behaviour.
  560. $this->assertSame('a', clean_param('a<b', PARAM_TEXT));
  561. $this->assertSame('a>b', clean_param('a>b', PARAM_TEXT));
  562. $this->assertSame('<lang lang="en">a>a</lang>', clean_param('<lang lang="en">a>a</lang>', PARAM_TEXT)); // Standard strip_tags() behaviour.
  563. $this->assertSame('a', clean_param('<lang lang="en">a<a</lang>', PARAM_TEXT));
  564. $this->assertSame('<lang lang="en">aa</lang>', clean_param('<lang lang="en">a<br>a</lang>', PARAM_TEXT));
  565. }
  566. public function test_clean_param_url() {
  567. // Test PARAM_URL and PARAM_LOCALURL a bit.
  568. // Valid URLs.
  569. $this->assertSame('http://google.com/', clean_param('http://google.com/', PARAM_URL));
  570. $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));
  571. $this->assertSame('http://localhost/', clean_param('http://localhost/', PARAM_URL));
  572. $this->assertSame('http://0.255.1.1/numericip.php', clean_param('http://0.255.1.1/numericip.php', PARAM_URL));
  573. $this->assertSame('https://google.com/', clean_param('https://google.com/', PARAM_URL));
  574. $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));
  575. $this->assertSame('https://localhost/', clean_param('https://localhost/', PARAM_URL));
  576. $this->assertSame('https://0.255.1.1/numericip.php', clean_param('https://0.255.1.1/numericip.php', PARAM_URL));
  577. $this->assertSame('ftp://ftp.debian.org/debian/', clean_param('ftp://ftp.debian.org/debian/', PARAM_URL));
  578. $this->assertSame('/just/a/path', clean_param('/just/a/path', PARAM_URL));
  579. // Invalid URLs.
  580. $this->assertSame('', clean_param('funny:thing', PARAM_URL));
  581. $this->assertSame('', clean_param('http://example.ee/sdsf"f', PARAM_URL));
  582. $this->assertSame('', clean_param('javascript://comment%0Aalert(1)', PARAM_URL));
  583. $this->assertSame('', clean_param('rtmp://example.com/livestream', PARAM_URL));
  584. $this->assertSame('', clean_param('rtmp://example.com/live&foo', PARAM_URL));
  585. $this->assertSame('', clean_param('rtmp://example.com/fms&mp4:path/to/file.mp4', PARAM_URL));
  586. $this->assertSame('', clean_param('mailto:support@moodle.org', PARAM_URL));
  587. $this->assertSame('', clean_param('mailto:support@moodle.org?subject=Hello%20Moodle', PARAM_URL));
  588. $this->assertSame('', clean_param('mailto:support@moodle.org?subject=Hello%20Moodle&cc=feedback@moodle.org', PARAM_URL));
  589. }
  590. public function test_clean_param_localurl() {
  591. global $CFG;
  592. $this->resetAfterTest();
  593. // External, invalid.
  594. $this->assertSame('', clean_param('funny:thing', PARAM_LOCALURL));
  595. $this->assertSame('', clean_param('http://google.com/', PARAM_LOCALURL));
  596. $this->assertSame('', clean_param('https://google.com/?test=true', PARAM_LOCALURL));
  597. $this->assertSame('', clean_param('http://some.very.long.and.silly.domain/with/a/path/', PARAM_LOCALURL));
  598. // Local absolute.
  599. $this->assertSame(clean_param($CFG->wwwroot, PARAM_LOCALURL), $CFG->wwwroot);
  600. $this->assertSame($CFG->wwwroot . '/with/something?else=true',
  601. clean_param($CFG->wwwroot . '/with/something?else=true', PARAM_LOCALURL));
  602. // Local relative.
  603. $this->assertSame('/just/a/path', clean_param('/just/a/path', PARAM_LOCALURL));
  604. $this->assertSame('course/view.php?id=3', clean_param('course/view.php?id=3', PARAM_LOCALURL));
  605. // Local absolute HTTPS in a non HTTPS site.
  606. $CFG->wwwroot = str_replace('https:', 'http:', $CFG->wwwroot); // Need to simulate non-https site.
  607. $httpsroot = str_replace('http:', 'https:', $CFG->wwwroot);
  608. $this->assertSame('', clean_param($httpsroot, PARAM_LOCALURL));
  609. $this->assertSame('', clean_param($httpsroot . '/with/something?else=true', PARAM_LOCALURL));
  610. // Local absolute HTTPS in a HTTPS site.
  611. $CFG->wwwroot = str_replace('http:', 'https:', $CFG->wwwroot);
  612. $httpsroot = $CFG->wwwroot;
  613. $this->assertSame($httpsroot, clean_param($httpsroot, PARAM_LOCALURL));
  614. $this->assertSame($httpsroot . '/with/something?else=true',
  615. clean_param($httpsroot . '/with/something?else=true', PARAM_LOCALURL));
  616. // Test open redirects are not possible.
  617. $CFG->wwwroot = 'http://www.example.com';
  618. $this->assertSame('', clean_param('http://www.example.com.evil.net/hack.php', PARAM_LOCALURL));
  619. $CFG->wwwroot = 'https://www.example.com';
  620. $this->assertSame('', clean_param('https://www.example.com.evil.net/hack.php', PARAM_LOCALURL));
  621. }
  622. public function test_clean_param_file() {
  623. $this->assertSame('correctfile.txt', clean_param('correctfile.txt', PARAM_FILE));
  624. $this->assertSame('badfile.txt', clean_param('b\'a<d`\\/fi:l>e.t"x|t', PARAM_FILE));
  625. $this->assertSame('..parentdirfile.txt', clean_param('../parentdirfile.txt', PARAM_FILE));
  626. $this->assertSame('....grandparentdirfile.txt', clean_param('../../grandparentdirfile.txt', PARAM_FILE));
  627. $this->assertSame('..winparentdirfile.txt', clean_param('..\winparentdirfile.txt', PARAM_FILE));
  628. $this->assertSame('....wingrandparentdir.txt', clean_param('..\..\wingrandparentdir.txt', PARAM_FILE));
  629. $this->assertSame('myfile.a.b.txt', clean_param('myfile.a.b.txt', PARAM_FILE));
  630. $this->assertSame('myfile..a..b.txt', clean_param('myfile..a..b.txt', PARAM_FILE));
  631. $this->assertSame('myfile.a..b...txt', clean_param('myfile.a..b...txt', PARAM_FILE));
  632. $this->assertSame('myfile.a.txt', clean_param('myfile.a.txt', PARAM_FILE));
  633. $this->assertSame('myfile...txt', clean_param('myfile...txt', PARAM_FILE));
  634. $this->assertSame('...jpg', clean_param('...jpg', PARAM_FILE));
  635. $this->assertSame('.a.b.', clean_param('.a.b.', PARAM_FILE));
  636. $this->assertSame('', clean_param('.', PARAM_FILE));
  637. $this->assertSame('', clean_param('..', PARAM_FILE));
  638. $this->assertSame('...', clean_param('...', PARAM_FILE));
  639. $this->assertSame('. . . .', clean_param('. . . .', PARAM_FILE));
  640. $this->assertSame('dontrtrim.me. .. .. . ', clean_param('dontrtrim.me. .. .. . ', PARAM_FILE));
  641. $this->assertSame(' . .dontltrim.me', clean_param(' . .dontltrim.me', PARAM_FILE));
  642. $this->assertSame('here is a tab.txt', clean_param("here is a tab\t.txt", PARAM_FILE));
  643. $this->assertSame('here is a linebreak.txt', clean_param("here is a line\r\nbreak.txt", PARAM_FILE));
  644. // The following behaviours have been maintained although they seem a little odd.
  645. $this->assertSame('funnything', clean_param('funny:thing', PARAM_FILE));
  646. $this->assertSame('.currentdirfile.txt', clean_param('./currentdirfile.txt', PARAM_FILE));
  647. $this->assertSame('ctempwindowsfile.txt', clean_param('c:\temp\windowsfile.txt', PARAM_FILE));
  648. $this->assertSame('homeuserlinuxfile.txt', clean_param('/home/user/linuxfile.txt', PARAM_FILE));
  649. $this->assertSame('~myfile.txt', clean_param('~/myfile.txt', PARAM_FILE));
  650. }
  651. public function test_clean_param_path() {
  652. $this->assertSame('correctfile.txt', clean_param('correctfile.txt', PARAM_PATH));
  653. $this->assertSame('bad/file.txt', clean_param('b\'a<d`\\/fi:l>e.t"x|t', PARAM_PATH));
  654. $this->assertSame('/parentdirfile.txt', clean_param('../parentdirfile.txt', PARAM_PATH));
  655. $this->assertSame('/grandparentdirfile.txt', clean_param('../../grandparentdirfile.txt', PARAM_PATH));
  656. $this->assertSame('/winparentdirfile.txt', clean_param('..\winparentdirfile.txt', PARAM_PATH));
  657. $this->assertSame('/wingrandparentdir.txt', clean_param('..\..\wingrandparentdir.txt', PARAM_PATH));
  658. $this->assertSame('funnything', clean_param('funny:thing', PARAM_PATH));
  659. $this->assertSame('./here', clean_param('./././here', PARAM_PATH));
  660. $this->assertSame('./currentdirfile.txt', clean_param('./currentdirfile.txt', PARAM_PATH));
  661. $this->assertSame('c/temp/windowsfile.txt', clean_param('c:\temp\windowsfile.txt', PARAM_PATH));
  662. $this->assertSame('/home/user/linuxfile.txt', clean_param('/home/user/linuxfile.txt', PARAM_PATH));
  663. $this->assertSame('/home../user ./.linuxfile.txt', clean_param('/home../user ./.linuxfile.txt', PARAM_PATH));
  664. $this->assertSame('~/myfile.txt', clean_param('~/myfile.txt', PARAM_PATH));
  665. $this->assertSame('~/myfile.txt', clean_param('~/../myfile.txt', PARAM_PATH));
  666. $this->assertSame('/..b../.../myfile.txt', clean_param('/..b../.../myfile.txt', PARAM_PATH));
  667. $this->assertSame('..b../.../myfile.txt', clean_param('..b../.../myfile.txt', PARAM_PATH));
  668. $this->assertSame('/super/slashes/', clean_param('/super//slashes///', PARAM_PATH));
  669. }
  670. public function test_clean_param_username() {
  671. global $CFG;
  672. $currentstatus = $CFG->extendedusernamechars;
  673. // Run tests with extended character == false;.
  674. $CFG->extendedusernamechars = false;
  675. $this->assertSame('johndoe123', clean_param('johndoe123', PARAM_USERNAME) );
  676. $this->assertSame('john.doe', clean_param('john.doe', PARAM_USERNAME));
  677. $this->assertSame('john-doe', clean_param('john-doe', PARAM_USERNAME));
  678. $this->assertSame('john-doe', clean_param('john- doe', PARAM_USERNAME));
  679. $this->assertSame('john_doe', clean_param('john_doe', PARAM_USERNAME));
  680. $this->assertSame('john@doe', clean_param('john@doe', PARAM_USERNAME));
  681. $this->assertSame('johndoe', clean_param('john~doe', PARAM_USERNAME));
  682. $this->assertSame('johndoe', clean_param('john´doe', PARAM_USERNAME));
  683. $this->assertSame(clean_param('john# $%&()+_^', PARAM_USERNAME), 'john_');
  684. $this->assertSame(clean_param(' john# $%&()+_^ ', PARAM_USERNAME), 'john_');
  685. $this->assertSame(clean_param('john#$%&() ', PARAM_USERNAME), 'john');
  686. $this->assertSame('johnd', clean_param('JOHNdóé ', PARAM_USERNAME));
  687. $this->assertSame(clean_param('john.,:;-_/|\ñÑ[]A_X-,D {} ~!@#$%^&*()_+ ?><[] ščřžžý ?ýáž?žý??šdoe ', PARAM_USERNAME), 'john.-_a_x-d@_doe');
  688. // Test success condition, if extendedusernamechars == ENABLE;.
  689. $CFG->extendedusernamechars = true;
  690. $this->assertSame('john_doe', clean_param('john_doe', PARAM_USERNAME));
  691. $this->assertSame('john@doe', clean_param('john@doe', PARAM_USERNAME));
  692. $this->assertSame(clean_param('john# $%&()+_^', PARAM_USERNAME), 'john# $%&()+_^');
  693. $this->assertSame(clean_param(' john# $%&()+_^ ', PARAM_USERNAME), 'john# $%&()+_^');
  694. $this->assertSame('john~doe', clean_param('john~doe', PARAM_USERNAME));
  695. $this->assertSame('john´doe', clean_param('joHN´doe', PARAM_USERNAME));
  696. $this->assertSame('johndoe', clean_param('johnDOE', PARAM_USERNAME));
  697. $this->assertSame('johndóé', clean_param('johndóé ', PARAM_USERNAME));
  698. $CFG->extendedusernamechars = $currentstatus;
  699. }
  700. public function test_clean_param_stringid() {
  701. // Test string identifiers validation.
  702. // Valid strings.
  703. $this->assertSame('validstring', clean_param('validstring', PARAM_STRINGID));
  704. $this->assertSame('mod/foobar:valid_capability', clean_param('mod/foobar:valid_capability', PARAM_STRINGID));
  705. $this->assertSame('CZ', clean_param('CZ', PARAM_STRINGID));
  706. $this->assertSame('application/vnd.ms-powerpoint', clean_param('application/vnd.ms-powerpoint', PARAM_STRINGID));
  707. $this->assertSame('grade2', clean_param('grade2', PARAM_STRINGID));
  708. // Invalid strings.
  709. $this->assertSame('', clean_param('trailing ', PARAM_STRINGID));
  710. $this->assertSame('', clean_param('space bar', PARAM_STRINGID));
  711. $this->assertSame('', clean_param('0numeric', PARAM_STRINGID));
  712. $this->assertSame('', clean_param('*', PARAM_STRINGID));
  713. $this->assertSame('', clean_param(' ', PARAM_STRINGID));
  714. }
  715. public function test_clean_param_timezone() {
  716. // Test timezone validation.
  717. $testvalues = array (
  718. 'America/Jamaica' => 'America/Jamaica',
  719. 'America/Argentina/Cordoba' => 'America/Argentina/Cordoba',
  720. 'America/Port-au-Prince' => 'America/Port-au-Prince',
  721. 'America/Argentina/Buenos_Aires' => 'America/Argentina/Buenos_Aires',
  722. 'PST8PDT' => 'PST8PDT',
  723. 'Wrong.Value' => '',
  724. 'Wrong/.Value' => '',
  725. 'Wrong(Value)' => '',
  726. '0' => '0',
  727. '0.0' => '0.0',
  728. '0.5' => '0.5',
  729. '9.0' => '9.0',
  730. '-9.0' => '-9.0',
  731. '+9.0' => '+9.0',
  732. '9.5' => '9.5',
  733. '-9.5' => '-9.5',
  734. '+9.5' => '+9.5',
  735. '12.0' => '12.0',
  736. '-12.0' => '-12.0',
  737. '+12.0' => '+12.0',
  738. '12.5' => '12.5',
  739. '-12.5' => '-12.5',
  740. '+12.5' => '+12.5',
  741. '13.0' => '13.0',
  742. '-13.0' => '-13.0',
  743. '+13.0' => '+13.0',
  744. '13.5' => '',
  745. '+13.5' => '',
  746. '-13.5' => '',
  747. '0.2' => '');
  748. foreach ($testvalues as $testvalue => $expectedvalue) {
  749. $actualvalue = clean_param($testvalue, PARAM_TIMEZONE);
  750. $this->assertEquals($expectedvalue, $actualvalue);
  751. }
  752. }
  753. public function test_validate_param() {
  754. try {
  755. $param = validate_param('11a', PARAM_INT);
  756. $this->fail('invalid_parameter_exception expected');
  757. } catch (moodle_exception $ex) {
  758. $this->assertInstanceOf('invalid_parameter_exception', $ex);
  759. }
  760. $param = validate_param('11', PARAM_INT);
  761. $this->assertSame(11, $param);
  762. try {
  763. $param = validate_param(null, PARAM_INT, false);
  764. $this->fail('invalid_parameter_exception expected');
  765. } catch (moodle_exception $ex) {
  766. $this->assertInstanceOf('invalid_parameter_exception', $ex);
  767. }
  768. $param = validate_param(null, PARAM_INT, true);
  769. $this->assertSame(null, $param);
  770. try {
  771. $param = validate_param(array(), PARAM_INT);
  772. $this->fail('invalid_parameter_exception expected');
  773. } catch (moodle_exception $ex) {
  774. $this->assertInstanceOf('invalid_parameter_exception', $ex);
  775. }
  776. try {
  777. $param = validate_param(new stdClass, PARAM_INT);
  778. $this->fail('invalid_parameter_exception expected');
  779. } catch (moodle_exception $ex) {
  780. $this->assertInstanceOf('invalid_parameter_exception', $ex);
  781. }
  782. $param = validate_param('1.0', PARAM_FLOAT);
  783. $this->assertSame(1.0, $param);
  784. // Make sure valid floats do not cause exception.
  785. validate_param(1.0, PARAM_FLOAT);
  786. validate_param(10, PARAM_FLOAT);
  787. validate_param('0', PARAM_FLOAT);
  788. validate_param('119813454.545464564564546564545646556564465465456465465465645645465645645645', PARAM_FLOAT);
  789. validate_param('011.1', PARAM_FLOAT);
  790. validate_param('11', PARAM_FLOAT);
  791. validate_param('+.1', PARAM_FLOAT);
  792. validate_param('-.1', PARAM_FLOAT);
  793. validate_param('1e10', PARAM_FLOAT);
  794. validate_param('.1e+10', PARAM_FLOAT);
  795. validate_param('1E-1', PARAM_FLOAT);
  796. try {
  797. $param = validate_param('1,2', PARAM_FLOAT);
  798. $this->fail('invalid_parameter_exception expected');
  799. } catch (moodle_exception $ex) {
  800. $this->assertInstanceOf('invalid_parameter_exception', $ex);
  801. }
  802. try {
  803. $param = validate_param('', PARAM_FLOAT);
  804. $this->fail('invalid_parameter_exception expected');
  805. } catch (moodle_exception $ex) {
  806. $this->assertInstanceOf('invalid_parameter_exception', $ex);
  807. }
  808. try {
  809. $param = validate_param('.', PARAM_FLOAT);
  810. $this->fail('invalid_parameter_exception expected');
  811. } catch (moodle_exception $ex) {
  812. $this->assertInstanceOf('invalid_parameter_exception', $ex);
  813. }
  814. try {
  815. $param = validate_param('e10', PARAM_FLOAT);
  816. $this->fail('invalid_parameter_exception expected');
  817. } catch (moodle_exception $ex) {
  818. $this->assertInstanceOf('invalid_parameter_exception', $ex);
  819. }
  820. try {
  821. $param = validate_param('abc', PARAM_FLOAT);
  822. $this->fail('invalid_parameter_exception expected');
  823. } catch (moodle_exception $ex) {
  824. $this->assertInstanceOf('invalid_parameter_exception', $ex);
  825. }
  826. }
  827. public function test_shorten_text_no_tags_already_short_enough() {
  828. // ......12345678901234567890123456.
  829. $text = "short text already no tags";
  830. $this->assertSame($text, shorten_text($text));
  831. }
  832. public function test_shorten_text_with_tags_already_short_enough() {
  833. // .........123456...7890....12345678.......901234567.
  834. $text = "<p>short <b>text</b> already</p><p>with tags</p>";
  835. $this->assertSame($text, shorten_text($text));
  836. }
  837. public function test_shorten_text_no_tags_needs_shortening() {
  838. // Default truncation is after 30 chars, but allowing 3 for the final '...'.
  839. // ......12345678901234567890123456789023456789012345678901234.
  840. $text = "long text without any tags blah de blah blah blah what";
  841. $this->assertSame('long text without any tags ...', shorten_text($text));
  842. }
  843. public function test_shorten_text_with_tags_needs_shortening() {
  844. // .......................................123456789012345678901234567890...
  845. $text = "<div class='frog'><p><blockquote>Long text with tags that will ".
  846. "be chopped off but <b>should be added back again</b></blockquote></p></div>";
  847. $this->assertEquals("<div class='frog'><p><blockquote>Long text with " .
  848. "tags that ...</blockquote></p></div>", shorten_text($text));
  849. }
  850. public function test_shorten_text_with_tags_and_html_comment() {
  851. $text = "<div class='frog'><p><blockquote><!--[if !IE]><!-->Long text with ".
  852. "tags that will<!--<![endif]--> ".
  853. "be chopped off but <b>should be added back again</b></blockquote></p></div>";
  854. $this->assertEquals("<div class='frog'><p><blockquote><!--[if !IE]><!-->Long text with " .
  855. "tags that ...<!--<![endif]--></blockquote></p></div>", shorten_text($text));
  856. }
  857. public function test_shorten_text_with_entities() {
  858. // Remember to allow 3 chars for the final '...'.
  859. // ......123456789012345678901234567_____890...
  860. $text = "some text which shouldn't &nbsp; break there";
  861. $this->assertSame("some text which shouldn't &nbsp; ...", shorten_text($text, 31));
  862. $this->assertSame("some text which shouldn't &nbsp;...", shorten_text($text, 30));
  863. $this->assertSame("some text which shouldn't ...", shorten_text($text, 29));
  864. }
  865. public function test_shorten_text_known_tricky_case() {
  866. // This case caused a bug up to 1.9.5
  867. // ..........123456789012345678901234567890123456789.....0_____1___2___...
  868. $text = "<h3>standard 'break-out' sub groups in TGs?</h3>&nbsp;&lt;&lt;There are several";
  869. $this->assertSame("<h3>standard 'break-out' sub groups in ...</h3>",
  870. shorten_text($text, 41));
  871. $this->assertSame("<h3>standard 'break-out' sub groups in TGs?...</h3>",
  872. shorten_text($text, 42));
  873. $this->assertSame("<h3>standard 'break-out' sub groups in TGs?</h3>&nbsp;...",
  874. shorten_text($text, 43));
  875. }
  876. public function test_shorten_text_no_spaces() {
  877. // ..........123456789.
  878. $text = "<h1>123456789</h1>"; // A string with no convenient breaks.
  879. $this->assertSame("<h1>12345...</h1>", shorten_text($text, 8));
  880. }
  881. public function test_shorten_text_utf8_european() {
  882. // Text without tags.
  883. // ......123456789012345678901234567.
  884. $text = "Žluťoučký koníček přeskočil";
  885. $this->assertSame($text, shorten_text($text)); // 30 chars by default.
  886. $this->assertSame("Žluťoučký koníče...", shorten_text($text, 19, true));
  887. $this->assertSame("Žluťoučký ...", shorten_text($text, 19, false));
  888. // And try it with 2-less (that are, in bytes, the middle of a sequence).
  889. $this->assertSame("Žluťoučký koní...", shorten_text($text, 17, true));
  890. $this->assertSame("Žluťoučký ...", shorten_text($text, 17, false));
  891. // .........123456789012345678...901234567....89012345.
  892. $text = "<p>Žluťoučký koníček <b>přeskočil</b> potůček</p>";
  893. $this->assertSame($text, shorten_text($text, 60));
  894. $this->assertSame("<p>Žluťoučký koníček ...</p>", shorten_text($text, 21));
  895. $this->assertSame("<p>Žluťoučký koníče...</p>", shorten_text($text, 19, true));
  896. $this->assertSame("<p>Žluťoučký ...</p>", shorten_text($text, 19, false));
  897. // And try it with 2 fewer (that are, in bytes, the middle of a sequence).
  898. $this->assertSame("<p>Žluťoučký koní...</p>", shorten_text($text, 17, true));
  899. $this->assertSame("<p>Žluťoučký ...</p>", shorten_text($text, 17, false));
  900. // And try over one tag (start/end), it does proper text len.
  901. $this->assertSame("<p>Žluťoučký koníček <b>př...</b></p>", shorten_text($text, 23, true));
  902. $this->assertSame("<p>Žluťoučký koníček <b>přeskočil</b> pot...</p>", shorten_text($text, 34, true));
  903. // And in the middle of one tag.
  904. $this->assertSame("<p>Žluťoučký koníček <b>přeskočil...</b></p>", shorten_text($text, 30, true));
  905. }
  906. public function test_shorten_text_utf8_oriental() {
  907. // Japanese
  908. // text without tags
  909. // ......123456789012345678901234.
  910. $text = '言語設定言語設定abcdefghijkl';
  911. $this->assertSame($text, shorten_text($text)); // 30 chars by default.
  912. $this->assertSame("言語設定言語...", shorten_text($text, 9, true));
  913. $this->assertSame("言語設定言語...", shorten_text($text, 9, false));
  914. $this->assertSame("言語設定言語設定ab...", shorten_text($text, 13, true));
  915. $this->assertSame("言語設定言語設定...", shorten_text($text, 13, false));
  916. // Chinese
  917. // text without tags
  918. // ......123456789012345678901234.
  919. $text = '简体中文简体中文abcdefghijkl';
  920. $this->assertSame($text, shorten_text($text)); // 30 chars by default.
  921. $this->assertSame("简体中文简体...", shorten_text($text, 9, true));
  922. $this->assertSame("简体中文简体...", shorten_text($text, 9, false));
  923. $this->assertSame("简体中文简体中文ab...", shorten_text($text, 13, true));
  924. $this->assertSame("简体中文简体中文...", shorten_text($text, 13, false));
  925. }
  926. public function test_shorten_text_multilang() {
  927. // This is not necessaryily specific to multilang. The issue is really
  928. // tags with attributes, where before we were generating invalid HTML
  929. // output like shorten_text('<span id="x" class="y">A</span> B', 1)
  930. // returning '<span id="x" ...</span>'. It is just that multilang
  931. // requires the sort of HTML that is quite likely to trigger this.
  932. // ........................................1...
  933. $text = '<span lang="en" class="multilang">A</span>' .
  934. '<span lang="fr" class="multilang">B</span>';
  935. $this->assertSame('<span lang="en" class="multilang">...</span>',
  936. shorten_text($text, 1));
  937. }
  938. /**
  939. * Provider for long filenames and its expected result, with and without hash.
  940. *
  941. * @return array of ($filename, $length, $expected, $includehash)
  942. */
  943. public function shorten_filename_provider() {
  944. $filename = 'sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium totam rem';
  945. $shortfilename = 'sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque';
  946. return [
  947. 'More than 100 characters' => [
  948. $filename,
  949. null,
  950. 'sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium tot',
  951. false,
  952. ],
  953. 'More than 100 characters with hash' => [
  954. $filename,
  955. null,
  956. 'sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque l - 3bec1da8b8',
  957. true,
  958. ],
  959. 'More than 100 characters with extension' => [
  960. "{$filename}.zip",
  961. null,
  962. 'sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium tot.zip',
  963. false,
  964. ],
  965. 'More than 100 characters with extension and hash' => [
  966. "{$filename}.zip",
  967. null,
  968. 'sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque l - 3bec1da8b8.zip',
  969. true,
  970. ],
  971. 'Limit filename to 50 chars' => [
  972. $filename,
  973. 50,
  974. 'sed ut perspiciatis unde omnis iste natus error si',
  975. false,
  976. ],
  977. 'Limit filename to 50 chars with hash' => [
  978. $filename,
  979. 50,
  980. 'sed ut perspiciatis unde omnis iste n - 3bec1da8b8',
  981. true,
  982. ],
  983. 'Limit filename to 50 chars with extension' => [
  984. "{$filename}.zip",
  985. 50,
  986. 'sed ut perspiciatis unde omnis iste natus error si.zip',
  987. false,
  988. ],
  989. 'Limit filename to 50 chars with extension and hash' => [
  990. "{$filename}.zip",
  991. 50,
  992. 'sed ut perspiciatis unde omnis iste n - 3bec1da8b8.zip',
  993. true,
  994. ],
  995. 'Test filename that contains less than 100 characters' => [
  996. $shortfilename,
  997. null,
  998. $shortfilename,
  999. false,
  1000. ],
  1001. 'Test filename that contains less than 100 characters and hash' => [
  1002. $shortfilename,
  1003. null,
  1004. $shortfilename,
  1005. true,
  1006. ],
  1007. 'Test filename that contains less than 100 characters with extension' => [
  1008. "{$shortfilename}.zip",
  1009. null,
  1010. "{$shortfilename}.zip",
  1011. false,
  1012. ],
  1013. 'Test filename that contains less than 100 characters with extension and hash' => [
  1014. "{$shortfilename}.zip",
  1015. null,
  1016. "{$shortfilename}.zip",
  1017. true,
  1018. ],
  1019. ];
  1020. }
  1021. /**
  1022. * Test the {@link shorten_filename()} method.
  1023. *
  1024. * @dataProvider shorten_filename_provider
  1025. *
  1026. * @param string $filename
  1027. * @param int $length
  1028. * @param string $expected
  1029. * @param boolean $includehash
  1030. */
  1031. public function test_shorten_filename($filename, $length, $expected, $includehash) {
  1032. if (null === $length) {
  1033. $length = MAX_FILENAME_SIZE;
  1034. }
  1035. $this->assertSame($expected, shorten_filename($filename, $length, $includehash));
  1036. }
  1037. /**
  1038. * Provider for long filenames and its expected result, with and without hash.
  1039. *
  1040. * @return array of ($filename, $length, $expected, $includehash)
  1041. */
  1042. public function shorten_filenames_provider() {
  1043. $shortfilename = 'sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque';
  1044. $longfilename = 'sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium totam rem';
  1045. $extfilename = $longfilename.'.zip';
  1046. $expected = 'sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium tot';
  1047. $expectedwithhash = 'sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque l - 3bec1da8b8';
  1048. $expectedext = 'sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium tot.zip';
  1049. $expectedextwithhash = 'sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque l - 3bec1da8b8.zip';
  1050. $expected50 = 'sed ut perspiciatis unde omnis iste natus error si';
  1051. $expected50withhash = 'sed ut perspiciatis unde omnis iste n - 3bec1da8b8';
  1052. $expected50ext = 'sed ut perspiciatis unde omnis iste natus error si.zip';
  1053. $expected50extwithhash = 'sed ut perspiciatis unde omnis iste n - 3bec1da8b8.zip';
  1054. $expected50short = 'sed ut perspiciatis unde omnis iste n - 5fb6543490';
  1055. return [
  1056. 'Empty array without hash' => [
  1057. [],
  1058. null,
  1059. [],
  1060. false,
  1061. ],
  1062. 'Empty array with hash' => [
  1063. [],
  1064. null,
  1065. [],
  1066. true,
  1067. ],
  1068. 'Array with less than 100 characters' => [
  1069. [$shortfilename, $shortfilename, $shortfilename],
  1070. null,
  1071. [$shortfilename, $shortfilename, $shortfilename],
  1072. false,
  1073. ],
  1074. 'Array with more than 100 characters without hash' => [
  1075. [$longfilename, $longfilename, $longfilename],
  1076. null,
  1077. [$expected, $expected, $expected],
  1078. false,
  1079. ],
  1080. 'Array with more than 100 characters with hash' => [
  1081. [$longfilename, $longfilename, $longfilename],
  1082. null,
  1083. [$expectedwithhash, $expectedwithhash, $expectedwithhash],
  1084. true,
  1085. ],
  1086. 'Array with more than 100 characters with extension' => [
  1087. [$extfilename, $extfilename, $extfilename],
  1088. null,
  1089. [$expectedext, $expectedext, $expectedext],
  1090. false,
  1091. ],
  1092. 'Array with more than 100 characters with extension and hash' => [
  1093. [$extfilename, $extfilename, $extfilename],
  1094. null,
  1095. [$expectedextwithhash, $expectedextwithhash, $expectedextwithhash],
  1096. true,
  1097. ],
  1098. 'Array with more than 100 characters mix (short, long, with extension) without hash' => [
  1099. [$shortfilename, $longfilename, $extfilename],
  1100. null,
  1101. [$shortfilename, $expected, $expectedext],
  1102. false,
  1103. ],
  1104. 'Array with more than 100 characters mix (short, long, with extension) with hash' => [
  1105. [$shortfilename, $longfilename, $extfilename],
  1106. null,
  1107. [$shortfilename, $expectedwithhash, $expectedextwithhash],
  1108. true,
  1109. ],
  1110. 'Array with less than 50 characters without hash' => [
  1111. [$longfilename, $longfilename, $longfilename],
  1112. 50,
  1113. [$expected50, $expected50, $expected50],
  1114. false,
  1115. ],
  1116. 'Array with less than 50 characters with hash' => [
  1117. [$longfilename, $longfilename, $longfilename],
  1118. 50,
  1119. [$expected50withhash, $expected50withhash, $expected50withhash],
  1120. true,
  1121. ],
  1122. 'Array with less than 50 characters with extension' => [
  1123. [$extfilename, $extfilename, $extfilename],
  1124. 50,
  1125. [$expected50ext, $expected50ext, $expected50ext],
  1126. false,
  1127. ],
  1128. 'Array with less than 50 characters with extension and hash' => [
  1129. [$extfilename, $extfilename, $extfilename],
  1130. 50,
  1131. [$expected50extwithhash, $expected50extwithhash, $expected50extwithhash],
  1132. true,
  1133. ],
  1134. 'Array with less than 50 characters mix (short, long, with extension) without hash' => [
  1135. [$shortfilename, $longfilename, $extfilename],
  1136. 50,
  1137. [$expected50, $expected50, $expected50ext],
  1138. false,
  1139. ],
  1140. 'Array with less than 50 characters mix (short, long, with extension) with hash' => [
  1141. [$shortfilename, $longfilename, $extfilename],
  1142. 50,
  1143. [$expected50short, $expected50withhash, $expected50extwithhash],
  1144. true,
  1145. ],
  1146. ];
  1147. }
  1148. /**
  1149. * Test the {@link shorten_filenames()} method.
  1150. *
  1151. * @dataProvider shorten_filenames_provider
  1152. *
  1153. * @param string $filenames
  1154. * @param int $length
  1155. * @param string $expected
  1156. * @param boolean $includehash
  1157. */
  1158. public function test_shorten_filenames($filenames, $length, $expected, $includehash) {
  1159. if (null === $length) {
  1160. $length = MAX_FILENAME_SIZE;
  1161. }
  1162. $this->assertSame($expected, shorten_filenames($filenames, $length, $includehash));
  1163. }
  1164. public function test_usergetdate() {
  1165. global $USER, $CFG, $DB;
  1166. $this->resetAfterTest();
  1167. $this->setAdminUser();
  1168. $USER->timezone = 2;// Set the timezone to a known state.
  1169. $ts = 1261540267; // The time this function was created.
  1170. $arr = usergetdate($ts, 1); // Specify the timezone as an argument.
  1171. $arr = array_values($arr);
  1172. list($seconds, $minutes, $hours, $mday, $wday, $mon, $year, $yday, $weekday, $month) = $arr;
  1173. $this->assertSame(7, $seconds);
  1174. $this->assertSame(51, $minutes);
  1175. $this->assertSame(4, $hours);
  1176. $this->assertSame(23, $mday);
  1177. $this->assertSame(3, $wday);
  1178. $this->assertSame(12, $mon);
  1179. $this->assertSame(2009, $year);
  1180. $this->assertSame(356, $yday);
  1181. $this->assertSame('Wednesday', $weekday);
  1182. $this->assertSame('December', $month);
  1183. $arr = usergetdate($ts); // Gets the timezone from the $USER object.
  1184. $arr = array_values($arr);
  1185. list($seconds, $minutes, $hours, $mday, $wday, $mon, $year, $yday, $weekday, $month) = $arr;
  1186. $this->assertSame(7, $seconds);
  1187. $this->assertSame(51, $minutes);
  1188. $this->assertSame(5, $hours);
  1189. $this->assertSame(23, $mday);
  1190. $this->assertSame(3, $wday);
  1191. $this->assertSame(12, $mon);
  1192. $this->assertSame(2009, $year);
  1193. $this->assertSame(356, $yday);
  1194. $this->assertSame('Wednesday', $weekday);
  1195. $this->assertSame('December', $month);
  1196. }
  1197. public function test_mark_user_preferences_changed() {
  1198. $this->resetAfterTest();
  1199. $otheruser = $this->getDataGenerator()->create_user();
  1200. $otheruserid = $otheruser->id;
  1201. set_cache_flag('userpreferenceschanged', $otheruserid, null);
  1202. mark_user_preferences_changed($otheruserid);
  1203. $this->assertEquals(get_cache_flag('userpreferenceschanged', $otheruserid, time()-10), 1);
  1204. set_cache_flag('userpreferenceschanged', $otheruserid, null);
  1205. }
  1206. public function test_check_user_preferences_loaded() {
  1207. global $DB;
  1208. $this->resetAfterTest();
  1209. $otheruser = $this->getDataGenerator()->create_user();
  1210. $otheruserid = $otheruser->id;
  1211. $DB->delete_records('user_preferences', array('userid'=>$otheruserid));
  1212. set_cache_flag('userpreferenceschanged', $otheruserid, null);
  1213. $user = new stdClass();
  1214. $user->id = $otheruserid;
  1215. // Load.
  1216. check_user_preferences_loaded($user);
  1217. $this->assertTrue(isset($user->preference));
  1218. $this->assertTrue(is_array($user->preference));
  1219. $this->assertArrayHasKey('_lastloaded', $user->preference);
  1220. $this->assertCount(1, $user->preference);
  1221. // Add preference via direct call.
  1222. $DB->insert_record('user_preferences', array('name'=>'xxx', 'value'=>'yyy', 'userid'=>$user->id));
  1223. // No cache reload yet.
  1224. check_user_preferences_loaded($user);
  1225. $this->assertCount(1, $user->preference);
  1226. // Forced reloading of cache.
  1227. unset($user->preference);
  1228. check_user_preferences_loaded($user);
  1229. $this->assertCount(2, $user->preference);
  1230. $this->assertSame('yyy', $user->preference['xxx']);
  1231. // Add preference via direct call.
  1232. $DB->insert_record('user_preferences', array('name'=>'aaa', 'value'=>'bbb', 'userid'=>$user->id));
  1233. // Test timeouts and modifications from different session.
  1234. set_cache_flag('userpreferenceschanged', $user->id, 1, time() + 1000);
  1235. $user->preference['_lastloaded'] = $user->preference['_lastloaded'] - 20;
  1236. check_user_preferences_loaded($user);
  1237. $this->assertCount(2, $user->preference);
  1238. check_user_preferences_loaded($user, 10);
  1239. $this->assertCount(3, $user->preference);
  1240. $this->assertSame('bbb', $user->preference['aaa']);
  1241. set_cache_flag('userpreferenceschanged', $user->id, null);
  1242. }
  1243. public function test_set_user_preference() {
  1244. global $DB, $USER;
  1245. $this->resetAfterTest();
  1246. $this->setAdminUser();
  1247. $otheruser = $this->getDataGenerator()->create_user();
  1248. $otheruserid = $otheruser->id;
  1249. $DB->delete_records('user_preferences', array('userid'=>$otheruserid));
  1250. set_cache_flag('userpreferenceschanged', $otheruserid, null);
  1251. $user = new stdClass();
  1252. $user->id = $otheruserid;
  1253. set_user_preference('aaa', 'bbb', $otheruserid);
  1254. $this->assertSame('bbb', $DB->get_field('user_preferences', 'value', array('userid'=>$otheruserid, 'name'=>'aaa')));
  1255. $this->assertSame('bbb', get_user_preferences('aaa', null, $otheruserid));
  1256. set_user_preference('xxx', 'yyy', $user);
  1257. $this->assertSame('yyy', $DB->get_field('user_preferences', 'value', array('userid'=>$otheruserid, 'name'=>'xxx')));
  1258. $this->assertSame('yyy', get_user_preferences('xxx', null, $otheruserid));
  1259. $this->assertTrue(is_array($user->preference));
  1260. $this->assertSame('bbb', $user->preference['aaa']);
  1261. $this->assertSame('yyy', $user->preference['xxx']);
  1262. set_user_preference('xxx', null, $user);
  1263. $this->assertFalse($DB->get_field('user_preferences', 'value', array('userid'=>$otheruserid, 'name'=>'xxx')));
  1264. $this->assertNull(get_user_preferences('xxx', null, $otheruserid));
  1265. set_user_preference('ooo', true, $user);
  1266. $prefs = get_user_preferences(null, null, $otheruserid);
  1267. $this->assertSame($user->preference['aaa'], $prefs['aaa']);
  1268. $this->assertSame($user->preference['ooo'], $prefs['ooo']);
  1269. $this->assertSame('1', $prefs['ooo']);
  1270. set_user_preference('null', 0, $user);
  1271. $this->assertSame('0', get_user_preferences('null', null, $otheruserid));
  1272. $this->assertSame('lala', get_user_preferences('undefined', 'lala', $otheruserid));
  1273. $DB->delete_records('user_preferences', array('userid'=>$otheruserid));
  1274. set_cache_flag('userpreferenceschanged', $otheruserid, null);
  1275. // Test $USER default.
  1276. set_user_preference('_test_user_preferences_pref', 'ok');
  1277. $this->assertSame('ok', $USER->preference['_test_user_preferences_pref']);
  1278. unset_user_preference('_test_user_preferences_pref');
  1279. $this->assertTrue(!isset($USER->preference['_test_user_preferences_pref']));
  1280. // Test 1333 char values (no need for unicode, there are already tests for that in DB tests).
  1281. $longvalue = str_repeat('a', 1333);
  1282. set_user_preference('_test_long_user_preference', $longvalue);
  1283. $this->assertEquals($longvalue, get_user_preferences('_test_long_user_preference'));
  1284. $this->assertEquals($longvalue,
  1285. $DB->get_field('user_preferences', 'value', array('userid' => $USER->id, 'name' => '_test_long_user_preference')));
  1286. // Test > 1333 char values, coding_exception expected.
  1287. $longvalue = str_repeat('a', 1334);
  1288. try {
  1289. set_user_preference('_test_long_user_preference', $longvalue);
  1290. $this->fail('Exception expected - longer than 1333 chars not allowed as preference value');
  1291. } catch (moodle_exception $ex) {
  1292. $this->assertInstanceOf('coding_exception', $ex);
  1293. }
  1294. // Test invalid params.
  1295. try {
  1296. set_user_preference('_test_user_preferences_pref', array());
  1297. $this->fail('Exception expected - array not valid preference value');
  1298. } catch (moodle_exception $ex) {
  1299. $this->assertInstanceOf('coding_exception', $ex);
  1300. }
  1301. try {
  1302. set_user_preference('_test_user_preferences_pref', new stdClass);
  1303. $this->fail('Exception expected - class not valid preference value');
  1304. } catch (moodle_exception $ex) {
  1305. $this->assertInstanceOf('coding_exception', $ex);
  1306. }
  1307. try {
  1308. set_user_preference('_test_user_preferences_pref', 1, array('xx' => 1));
  1309. $this->fail('Exception expected - user instance expected');
  1310. } catch (moodle_exception $ex) {
  1311. $this->assertInstanceOf('coding_exception', $ex);
  1312. }
  1313. try {
  1314. set_user_preference('_test_user_preferences_pref', 1, 'abc');
  1315. $this->fail('Exception expected - user instance expected');
  1316. } catch (moodle_exception $ex) {
  1317. $this->assertInstanceOf('coding_exception', $ex);
  1318. }
  1319. try {
  1320. set_user_preference('', 1);
  1321. $this->fail('Exception expected - invalid name accepted');
  1322. } catch (moodle_exception $ex) {
  1323. $this->assertInstanceOf('coding_exception', $ex);
  1324. }
  1325. try {
  1326. set_user_preference('1', 1);
  1327. $this->fail('Exception expected - invalid name accepted');
  1328. } catch (moodle_exception $ex) {
  1329. $this->assertInstanceOf('coding_exception', $ex);
  1330. }
  1331. }
  1332. public function test_set_user_preference_for_current_user() {
  1333. global $USER;
  1334. $this->resetAfterTest();
  1335. $this->setAdminUser();
  1336. set_user_preference('test_pref', 2);
  1337. set_user_preference('test_pref', 1, $USER->id);
  1338. $this->assertEquals(1, get_user_preferences('test_pref'));
  1339. }
  1340. public function test_unset_user_preference_for_current_user() {
  1341. global $USER;
  1342. $this->resetAfterTest();
  1343. $this->setAdminUser();
  1344. set_user_preference('test_pref', 1);
  1345. unset_user_preference('test_pref', $USER->id);
  1346. $this->assertNull(get_user_preferences('test_pref'));
  1347. }
  1348. /**
  1349. * Test essential features implementation of {@link get_extra_user_fields()} as the admin user with all capabilities.
  1350. */
  1351. public function test_get_extra_user_fields_essentials() {
  1352. global $CFG, $USER, $DB;
  1353. $this->resetAfterTest();
  1354. $this->setAdminUser();
  1355. $context = context_system::instance();
  1356. // No fields.
  1357. $CFG->showuseridentity = '';
  1358. $this->assertEquals(array(), get_extra_user_fields($context));
  1359. // One field.
  1360. $CFG->showuseridentity = 'frog';
  1361. $this->assertEquals(array('frog'), get_extra_user_fields($context));
  1362. // Two fields.
  1363. $CFG->showuseridentity = 'frog,zombie';
  1364. $this->assertEquals(array('frog', 'zombie'), get_extra_user_fields($context));
  1365. // No fields, except.
  1366. $CFG->showuseridentity = '';
  1367. $this->assertEquals(array(), get_extra_user_fields($context, array('frog')));
  1368. // One field.
  1369. $CFG->showuseridentity = 'frog';
  1370. $this->assertEquals(array(), get_extra_user_fields($context, array('frog')));
  1371. // Two fields.
  1372. $CFG->showuseridentity = 'frog,zombie';
  1373. $this->assertEquals(array('zombie'), get_extra_user_fields($context, array('frog')));
  1374. }
  1375. /**
  1376. * Prepare environment for couple of tests related to permission checks in {@link get_extra_user_fields()}.
  1377. *
  1378. * @return stdClass
  1379. */
  1380. protected function environment_for_get_extra_user_fields_tests() {
  1381. global $CFG, $DB;
  1382. $CFG->showuseridentity = 'idnumber,country,city';
  1383. $CFG->hiddenuserfields = 'country,city';
  1384. $env = new stdClass();
  1385. $env->course = $this->getDataGenerator()->create_course();
  1386. $env->coursecontext = context_course::instance($env->course->id);
  1387. $env->teacherrole = $DB->get_record('role', array('shortname' => 'teacher'));
  1388. $env->studentrole = $DB->get_record('role', array('shortname' => 'student'));
  1389. $env->managerrole = $DB->get_record('role', array('shortname' => 'manager'));
  1390. $env->student = $this->getDataGenerator()->create_user();
  1391. $env->teacher = $this->getDataGenerator()->create_user();
  1392. $env->manager = $this->getDataGenerator()->create_user();
  1393. role_assign($env->studentrole->id, $env->student->id, $env->coursecontext->id);
  1394. role_assign($env->teacherrole->id, $env->teacher->id, $env->coursecontext->id);
  1395. role_assign($env->managerrole->id, $env->manager->id, SYSCONTEXTID);
  1396. return $env;
  1397. }
  1398. /**
  1399. * No identity fields shown to student user (no permission to view identity fields).
  1400. */
  1401. public function test_get_extra_user_fields_no_access() {
  1402. $this->resetAfterTest();
  1403. $env = $this->environment_for_get_extra_user_fields_tests();
  1404. $this->setUser($env->student);
  1405. $this->assertEquals(array(), get_extra_user_fields($env->coursecontext));
  1406. $this->assertEquals(array(), get_extra_user_fields(context_system::instance()));
  1407. }
  1408. /**
  1409. * Teacher can see students' identity fields only within the course.
  1410. */
  1411. public function test_get_extra_user_fields_course_only_access() {
  1412. $this->resetAfterTest();
  1413. $env = $this->environment_for_get_extra_user_fields_tests();
  1414. $this->setUser($env->teacher);
  1415. $this->assertEquals(array('idnumber', 'country', 'city'), get_extra_user_fields($env->coursecontext));
  1416. $this->assertEquals(array(), get_extra_user_fields(context_system::instance()));
  1417. }
  1418. /**
  1419. * Teacher can be prevented from seeing students' identity fields even within the course.
  1420. */
  1421. public function test_get_extra_user_fields_course_prevented_access() {
  1422. $this->resetAfterTest();
  1423. $env = $this->environment_for_get_extra_user_fields_tests();
  1424. $this->setUser($env->teacher);
  1425. assign_capability('moodle/course:viewhiddenuserfields', CAP_PREVENT, $env->teacherrole->id, $env->coursecontext->id);
  1426. $this->assertEquals(array('idnumber'), get_extra_user_fields($env->coursecontext));
  1427. }
  1428. /**
  1429. * Manager can see students' identity fields anywhere.
  1430. */
  1431. public function test_get_extra_user_fields_anywhere_access() {
  1432. $this->resetAfterTest();
  1433. $env = $this->environment_for_get_extra_user_fields_tests();
  1434. $this->setUser($env->manager);
  1435. $this->assertEquals(array('idnumber', 'country', 'city'), get_extra_user_fields($env->coursecontext));
  1436. $this->assertEquals(array('idnumber', 'country', 'city'), get_extra_user_fields(context_system::instance()));
  1437. }
  1438. /**
  1439. * Manager can be prevented from seeing hidden fields outside the course.
  1440. */
  1441. public function test_get_extra_user_fields_schismatic_access() {
  1442. $this->resetAfterTest();
  1443. $env = $this->environment_for_get_extra_user_fields_tests();
  1444. $this->setUser($env->manager);
  1445. assign_capability('moodle/user:viewhiddendetails', CAP_PREVENT, $env->managerrole->id, SYSCONTEXTID, true);
  1446. $this->assertEquals(array('idnumber'), get_extra_user_fields(context_system::instance()));
  1447. // Note that inside the course, the manager can still see the hidden identifiers as this is currently
  1448. // controlled by a separate capability for legacy reasons.
  1449. $this->assertEquals(array('idnumber', 'country', 'city'), get_extra_user_fields($env->coursecontext));
  1450. }
  1451. /**
  1452. * Two capabilities must be currently set to prevent manager from seeing hidden fields.
  1453. */
  1454. public function test_get_extra_user_fields_hard_to_prevent_access() {
  1455. $this->resetAfterTest();
  1456. $env = $this->environment_for_get_extra_user_fields_tests();
  1457. $this->setUser($env->manager);
  1458. assign_capability('moodle/user:viewhiddendetails', CAP_PREVENT, $env->managerrole->id, SYSCONTEXTID, true);
  1459. assign_capability('moodle/course:viewhiddenuserfields', CAP_PREVENT, $env->managerrole->id, SYSCONTEXTID, true);
  1460. $this->assertEquals(array('idnumber'), get_extra_user_fields(context_system::instance()));
  1461. $this->assertEquals(array('idnumber'), get_extra_user_fields($env->coursecontext));
  1462. }
  1463. public function test_get_extra_user_fields_sql() {
  1464. global $CFG, $USER, $DB;
  1465. $this->resetAfterTest();
  1466. $this->setAdminUser();
  1467. $context = context_system::instance();
  1468. // No fields.
  1469. $CFG->showuseridentity = '';
  1470. $this->assertSame('', get_extra_user_fields_sql($context));
  1471. // One field.
  1472. $CFG->showuseridentity = 'frog';
  1473. $this->assertSame(', frog', get_extra_user_fields_sql($context));
  1474. // Two fields with table prefix.
  1475. $CFG->showuseridentity = 'frog,zombie';
  1476. $this->assertSame(', u1.frog, u1.zombie', get_extra_user_fields_sql($context, 'u1'));
  1477. // Two fields with field prefix.
  1478. $CFG->showuseridentity = 'frog,zombie';
  1479. $this->assertSame(', frog AS u_frog, zombie AS u_zombie',
  1480. get_extra_user_fields_sql($context, '', 'u_'));
  1481. // One field excluded.
  1482. $CFG->showuseridentity = 'frog';
  1483. $this->assertSame('', get_extra_user_fields_sql($context, '', '', array('frog')));
  1484. // Two fields, one excluded, table+field prefix.
  1485. $CFG->showuseridentity = 'frog,zombie';
  1486. $this->assertEquals(', u1.zombie AS u_zombie',
  1487. get_extra_user_fields_sql($context, 'u1', 'u_', array('frog')));
  1488. }
  1489. /**
  1490. * Test some critical TZ/DST.
  1491. *
  1492. * This method tests some special TZ/DST combinations that were fixed
  1493. * by MDL-38999. The tests are done by comparing the results of the
  1494. * output using Moodle TZ/DST support and PHP native one.
  1495. *
  1496. * Note: If you don't trust PHP TZ/DST support, can verify the
  1497. * harcoded expectations below with:
  1498. * http://www.tools4noobs.com/online_tools/unix_timestamp_to_datetime/
  1499. */
  1500. public function test_some_moodle_special_dst() {
  1501. $stamp = 1365386400; // 2013/04/08 02:00:00 GMT/UTC.
  1502. // In Europe/Tallinn it was 2013/04/08 05:00:00.
  1503. $expectation = '2013/04/08 05:00:00';
  1504. $phpdt = DateTime::createFromFormat('U', $stamp, new DateTimeZone('UTC'));
  1505. $phpdt->setTimezone(new DateTimeZone('Europe/Tallinn'));
  1506. $phpres = $phpdt->format('Y/m/d H:i:s'); // PHP result.
  1507. $moodleres = userdate($stamp, '%Y/%m/%d %H:%M:%S', 'Europe/Tallinn', false); // Moodle result.
  1508. $this->assertSame($expectation, $phpres);
  1509. $this->assertSame($expectation, $moodleres);
  1510. // In St. Johns it was 2013/04/07 23:30:00.
  1511. $expectation = '2013/04/07 23:30:00';
  1512. $phpdt = DateTime::createFromFormat('U', $stamp, new DateTimeZone('UTC'));
  1513. $phpdt->setTimezone(new DateTimeZone('America/St_Johns'));
  1514. $phpres = $phpdt->format('Y/m/d H:i:s'); // PHP result.
  1515. $moodleres = userdate($stamp, '%Y/%m/%d %H:%M:%S', 'America/St_Johns', false); // Moodle result.
  1516. $this->assertSame($expectation, $phpres);
  1517. $this->assertSame($expectation, $moodleres);
  1518. $stamp = 1383876000; // 2013/11/08 02:00:00 GMT/UTC.
  1519. // In Europe/Tallinn it was 2013/11/08 04:00:00.
  1520. $expectation = '2013/11/08 04:00:00';
  1521. $phpdt = DateTime::createFromFormat('U', $stamp, new DateTimeZone('UTC'));
  1522. $phpdt->setTimezone(new DateTimeZone('Europe/Tallinn'));
  1523. $phpres = $phpdt->format('Y/m/d H:i:s'); // PHP result.
  1524. $moodleres = userdate($stamp, '%Y/%m/%d %H:%M:%S', 'Europe/Tallinn', false); // Moodle result.
  1525. $this->assertSame($expectation, $phpres);
  1526. $this->assertSame($expectation, $moodleres);
  1527. // In St. Johns it was 2013/11/07 22:30:00.
  1528. $expectation = '2013/11/07 22:30:00';
  1529. $phpdt = DateTime::createFromFormat('U', $stamp, new DateTimeZone('UTC'));
  1530. $phpdt->setTimezone(new DateTimeZone('America/St_Johns'));
  1531. $phpres = $phpdt->format('Y/m/d H:i:s'); // PHP result.
  1532. $moodleres = userdate($stamp, '%Y/%m/%d %H:%M:%S', 'America/St_Johns', false); // Moodle result.
  1533. $this->assertSame($expectation, $phpres);
  1534. $this->assertSame($expectation, $moodleres);
  1535. }
  1536. public function test_userdate() {
  1537. global $USER, $CFG, $DB;
  1538. $this->resetAfterTest();
  1539. $this->setAdminUser();
  1540. $testvalues = array(
  1541. array(
  1542. 'time' => '1309514400',
  1543. 'usertimezone' => 'America/Moncton',
  1544. 'timezone' => '0.0', // No dst offset.
  1545. 'expectedoutput' => 'Friday, 1 July 2011, 10:00 AM',
  1546. 'expectedoutputhtml' => '<time datetime="2011-07-01T07:00:00-03:00">Friday, 1 July 2011, 10:00 AM</time>'
  1547. ),
  1548. array(
  1549. 'time' => '1309514400',
  1550. 'usertimezone' => 'America/Moncton',
  1551. 'timezone' => '99', // Dst offset and timezone offset.
  1552. 'expectedoutput' => 'Friday, 1 July 2011, 7:00 AM',
  1553. 'expectedoutputhtml' => '<time datetime="2011-07-01T07:00:00-03:00">Friday, 1 July 2011, 7:00 AM</time>'
  1554. ),
  1555. array(
  1556. 'time' => '1309514400',
  1557. 'usertimezone' => 'America/Moncton',
  1558. 'timezone' => 'America/Moncton', // Dst offset and timezone offset.
  1559. 'expectedoutput' => 'Friday, 1 July 2011, 7:00 AM',
  1560. 'expectedoutputhtml' => '<time datetime="2011-07-01t07:00:00-03:00">Friday, 1 July 2011, 7:00 AM</time>'
  1561. ),
  1562. array(
  1563. 'time' => '1293876000 ',
  1564. 'usertimezone' => 'America/Moncton',
  1565. 'timezone' => '0.0', // No dst offset.
  1566. 'expectedoutput' => 'Saturday, 1 January 2011, 10:00 AM',
  1567. 'expectedoutputhtml' => '<time datetime="2011-01-01T06:00:00-04:00">Saturday, 1 January 2011, 10:00 AM</time>'
  1568. ),
  1569. array(
  1570. 'time' => '1293876000 ',
  1571. 'usertimezone' => 'America/Moncton',
  1572. 'timezone' => '99', // No dst offset in jan, so just timezone offset.
  1573. 'expectedoutput' => 'Saturday, 1 January 2011, 6:00 AM',
  1574. 'expectedoutputhtml' => '<time datetime="2011-01-01T06:00:00-04:00">Saturday, 1 January 2011, 6:00 AM</time>'
  1575. ),
  1576. array(
  1577. 'time' => '1293876000 ',
  1578. 'usertimezone' => 'America/Moncton',
  1579. 'timezone' => 'America/Moncton', // No dst offset in jan.
  1580. 'expectedoutput' => 'Saturday, 1 January 2011, 6:00 AM',
  1581. 'expectedoutputhtml' => '<time datetime="2011-01-01T06:00:00-04:00">Saturday, 1 January 2011, 6:00 AM</time>'
  1582. ),
  1583. array(
  1584. 'time' => '1293876000 ',
  1585. 'usertimezone' => '2',
  1586. 'timezone' => '99', // Take user timezone.
  1587. 'expectedoutput' => 'Saturday, 1 January 2011, 12:00 PM',
  1588. 'expectedoutputhtml' => '<time datetime="2011-01-01T12:00:00+02:00">Saturday, 1 January 2011, 12:00 PM</time>'
  1589. ),
  1590. array(
  1591. 'time' => '1293876000 ',
  1592. 'usertimezone' => '-2',
  1593. 'timezone' => '99', // Take user timezone.
  1594. 'expectedoutput' => 'Saturday, 1 January 2011, 8:00 AM',
  1595. 'expectedoutputhtml' => '<time datetime="2011-01-01T08:00:00-02:00">Saturday, 1 January 2011, 8:00 AM</time>'
  1596. ),
  1597. array(
  1598. 'time' => '1293876000 ',
  1599. 'usertimezone' => '-10',
  1600. 'timezone' => '2', // Take this timezone.
  1601. 'expectedoutput' => 'Saturday, 1 January 2011, 12:00 PM',
  1602. 'expectedoutputhtml' => '<time datetime="2011-01-01T00:00:00-10:00">Saturday, 1 January 2011, 12:00 PM</time>'
  1603. ),
  1604. array(
  1605. 'time' => '1293876000 ',
  1606. 'usertimezone' => '-10',
  1607. 'timezone' => '-2', // Take this timezone.
  1608. 'expectedoutput' => 'Saturday, 1 January 2011, 8:00 AM',
  1609. 'expectedoutputhtml' => '<time datetime="2011-01-01T00:00:00-10:00">Saturday, 1 January 2011, 8:00 AM</time>'
  1610. ),
  1611. array(
  1612. 'time' => '1293876000 ',
  1613. 'usertimezone' => '-10',
  1614. 'timezone' => 'random/time', // This should show server time.
  1615. 'expectedoutput' => 'Saturday, 1 January 2011, 6:00 PM',
  1616. 'expectedoutputhtml' => '<time datetime="2011-01-01T00:00:00-10:00">Saturday, 1 January 2011, 6:00 PM</time>'
  1617. ),
  1618. array(
  1619. 'time' => '1293876000 ',
  1620. 'usertimezone' => '20', // Fallback to server time zone.
  1621. 'timezone' => '99', // This should show user time.
  1622. 'expectedoutput' => 'Saturday, 1 January 2011, 6:00 PM',
  1623. 'expectedoutputhtml' => '<time datetime="2011-01-01T18:00:00+08:00">Saturday, 1 January 2011, 6:00 PM</time>'
  1624. ),
  1625. );
  1626. // Set default timezone to Australia/Perth, else time calculated
  1627. // will not match expected values.
  1628. $this->setTimezone(99, 'Australia/Perth');
  1629. foreach ($testvalues as $vals) {
  1630. $USER->timezone = $vals['usertimezone'];
  1631. $actualoutput = userdate($vals['time'], '%A, %d %B %Y, %I:%M %p', $vals['timezone']);
  1632. $actualoutputhtml = userdate_htmltime($vals['time'], '%A, %d %B %Y, %I:%M %p', $vals['timezone']);
  1633. // On different systems case of AM PM changes so compare case insensitive.
  1634. $vals['expectedoutput'] = core_text::strtolower($vals['expectedoutput']);
  1635. $vals['expectedoutputhtml'] = core_text::strtolower($vals['expectedoutputhtml']);
  1636. $actualoutput = core_text::strtolower($actualoutput);
  1637. $actualoutputhtml = core_text::strtolower($actualoutputhtml);
  1638. $this->assertSame($vals['expectedoutput'], $actualoutput,
  1639. "Expected: {$vals['expectedoutput']} => Actual: {$actualoutput} \ndata: " . var_export($vals, true));
  1640. $this->assertSame($vals['expectedoutputhtml'], $actualoutputhtml,
  1641. "Expected: {$vals['expectedoutputhtml']} => Actual: {$actualoutputhtml} \ndata: " . var_export($vals, true));
  1642. }
  1643. }
  1644. /**
  1645. * Make sure the DST changes happen at the right time in Moodle.
  1646. */
  1647. public function test_dst_changes() {
  1648. // DST switching in Prague.
  1649. // From 2AM to 3AM in 1989.
  1650. $date = new DateTime('1989-03-26T01:59:00+01:00');
  1651. $this->assertSame('Sunday, 26 March 1989, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
  1652. $date = new DateTime('1989-03-26T02:01:00+01:00');
  1653. $this->assertSame('Sunday, 26 March 1989, 03:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
  1654. // From 3AM to 2AM in 1989 - not the same as the west Europe.
  1655. $date = new DateTime('1989-09-24T01:59:00+01:00');
  1656. $this->assertSame('Sunday, 24 September 1989, 02:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
  1657. $date = new DateTime('1989-09-24T02:01:00+01:00');
  1658. $this->assertSame('Sunday, 24 September 1989, 02:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
  1659. // From 2AM to 3AM in 2014.
  1660. $date = new DateTime('2014-03-30T01:59:00+01:00');
  1661. $this->assertSame('Sunday, 30 March 2014, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
  1662. $date = new DateTime('2014-03-30T02:01:00+01:00');
  1663. $this->assertSame('Sunday, 30 March 2014, 03:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
  1664. // From 3AM to 2AM in 2014.
  1665. $date = new DateTime('2014-10-26T01:59:00+01:00');
  1666. $this->assertSame('Sunday, 26 October 2014, 02:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
  1667. $date = new DateTime('2014-10-26T02:01:00+01:00');
  1668. $this->assertSame('Sunday, 26 October 2014, 02:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
  1669. // From 2AM to 3AM in 2020.
  1670. $date = new DateTime('2020-03-29T01:59:00+01:00');
  1671. $this->assertSame('Sunday, 29 March 2020, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
  1672. $date = new DateTime('2020-03-29T02:01:00+01:00');
  1673. $this->assertSame('Sunday, 29 March 2020, 03:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
  1674. // From 3AM to 2AM in 2020.
  1675. $date = new DateTime('2020-10-25T01:59:00+01:00');
  1676. $this->assertSame('Sunday, 25 October 2020, 02:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
  1677. $date = new DateTime('2020-10-25T02:01:00+01:00');
  1678. $this->assertSame('Sunday, 25 October 2020, 02:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Europe/Prague'));
  1679. // DST switching in NZ.
  1680. // From 3AM to 2AM in 2015.
  1681. $date = new DateTime('2015-04-05T02:59:00+13:00');
  1682. $this->assertSame('Sunday, 5 April 2015, 02:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Pacific/Auckland'));
  1683. $date = new DateTime('2015-04-05T03:01:00+13:00');
  1684. $this->assertSame('Sunday, 5 April 2015, 02:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Pacific/Auckland'));
  1685. // From 2AM to 3AM in 2009.
  1686. $date = new DateTime('2015-09-27T01:59:00+12:00');
  1687. $this->assertSame('Sunday, 27 September 2015, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Pacific/Auckland'));
  1688. $date = new DateTime('2015-09-27T02:01:00+12:00');
  1689. $this->assertSame('Sunday, 27 September 2015, 03:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Pacific/Auckland'));
  1690. // DST switching in Perth.
  1691. // From 3AM to 2AM in 2009.
  1692. $date = new DateTime('2008-03-30T01:59:00+08:00');
  1693. $this->assertSame('Sunday, 30 March 2008, 02:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Australia/Perth'));
  1694. $date = new DateTime('2008-03-30T02:01:00+08:00');
  1695. $this->assertSame('Sunday, 30 March 2008, 02:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Australia/Perth'));
  1696. // From 2AM to 3AM in 2009.
  1697. $date = new DateTime('2008-10-26T01:59:00+08:00');
  1698. $this->assertSame('Sunday, 26 October 2008, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Australia/Perth'));
  1699. $date = new DateTime('2008-10-26T02:01:00+08:00');
  1700. $this->assertSame('Sunday, 26 October 2008, 03:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'Australia/Perth'));
  1701. // DST switching in US.
  1702. // From 2AM to 3AM in 2014.
  1703. $date = new DateTime('2014-03-09T01:59:00-05:00');
  1704. $this->assertSame('Sunday, 9 March 2014, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'America/New_York'));
  1705. $date = new DateTime('2014-03-09T02:01:00-05:00');
  1706. $this->assertSame('Sunday, 9 March 2014, 03:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'America/New_York'));
  1707. // From 3AM to 2AM in 2014.
  1708. $date = new DateTime('2014-11-02T01:59:00-04:00');
  1709. $this->assertSame('Sunday, 2 November 2014, 01:59', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'America/New_York'));
  1710. $date = new DateTime('2014-11-02T02:01:00-04:00');
  1711. $this->assertSame('Sunday, 2 November 2014, 01:01', userdate($date->getTimestamp(), '%A, %d %B %Y, %H:%M', 'America/New_York'));
  1712. }
  1713. public function test_make_timestamp() {
  1714. global $USER, $CFG, $DB;
  1715. $this->resetAfterTest();
  1716. $this->setAdminUser();
  1717. $testvalues = array(
  1718. array(
  1719. 'usertimezone' => 'America/Moncton',
  1720. 'year' => '2011',
  1721. 'month' => '7',
  1722. 'day' => '1',
  1723. 'hour' => '10',
  1724. 'minutes' => '00',
  1725. 'seconds' => '00',
  1726. 'timezone' => '0.0',
  1727. 'applydst' => false, // No dst offset.
  1728. 'expectedoutput' => '1309514400' // 6pm at UTC+0.
  1729. ),
  1730. array(
  1731. 'usertimezone' => 'America/Moncton',
  1732. 'year' => '2011',
  1733. 'month' => '7',
  1734. 'day' => '1',
  1735. 'hour' => '10',
  1736. 'minutes' => '00',
  1737. 'seconds' => '00',
  1738. 'timezone' => '99', // User default timezone.
  1739. 'applydst' => false, // Don't apply dst.
  1740. 'expectedoutput' => '1309528800'
  1741. ),
  1742. array(
  1743. 'usertimezone' => 'America/Moncton',
  1744. 'year' => '2011',
  1745. 'month' => '7',
  1746. 'day' => '1',
  1747. 'hour' => '10',
  1748. 'minutes' => '00',
  1749. 'seconds' => '00',
  1750. 'timezone' => '99', // User default timezone.
  1751. 'applydst' => true, // Apply dst.
  1752. 'expectedoutput' => '1309525200'
  1753. ),
  1754. array(
  1755. 'usertimezone' => 'America/Moncton',
  1756. 'year' => '2011',
  1757. 'month' => '7',
  1758. 'day' => '1',
  1759. 'hour' => '10',
  1760. 'minutes' => '00',
  1761. 'seconds' => '00',
  1762. 'timezone' => 'America/Moncton', // String timezone.
  1763. 'applydst' => true, // Apply dst.
  1764. 'expectedoutput' => '1309525200'
  1765. ),
  1766. array(
  1767. 'usertimezone' => '2', // No dst applyed.
  1768. 'year' => '2011',
  1769. 'month' => '7',
  1770. 'day' => '1',
  1771. 'hour' => '10',
  1772. 'minutes' => '00',
  1773. 'seconds' => '00',
  1774. 'timezone' => '99', // Take user timezone.
  1775. 'applydst' => true, // Apply dst.
  1776. 'expectedoutput' => '1309507200'
  1777. ),
  1778. array(
  1779. 'usertimezone' => '-2', // No dst applyed.
  1780. 'year' => '2011',
  1781. 'month' => '7',
  1782. 'day' => '1',
  1783. 'hour' => '10',
  1784. 'minutes' => '00',
  1785. 'seconds' => '00',
  1786. 'timezone' => '99', // Take usertimezone.
  1787. 'applydst' => true, // Apply dst.
  1788. 'expectedoutput' => '1309521600'
  1789. ),
  1790. array(
  1791. 'usertimezone' => '-10', // No dst applyed.
  1792. 'year' => '2011',
  1793. 'month' => '7',
  1794. 'day' => '1',
  1795. 'hour' => '10',
  1796. 'minutes' => '00',
  1797. 'seconds' => '00',
  1798. 'timezone' => '2', // Take this timezone.
  1799. 'applydst' => true, // Apply dst.
  1800. 'expectedoutput' => '1309507200'
  1801. ),
  1802. array(
  1803. 'usertimezone' => '-10', // No dst applyed.
  1804. 'year' => '2011',
  1805. 'month' => '7',
  1806. 'day' => '1',
  1807. 'hour' => '10',
  1808. 'minutes' => '00',
  1809. 'seconds' => '00',
  1810. 'timezone' => '-2', // Take this timezone.
  1811. 'applydst' => true, // Apply dst.
  1812. 'expectedoutput' => '1309521600'
  1813. ),
  1814. array(
  1815. 'usertimezone' => '-10', // No dst applyed.
  1816. 'year' => '2011',
  1817. 'month' => '7',
  1818. 'day' => '1',
  1819. 'hour' => '10',
  1820. 'minutes' => '00',
  1821. 'seconds' => '00',
  1822. 'timezone' => 'random/time', // This should show server time.
  1823. 'applydst' => true, // Apply dst.
  1824. 'expectedoutput' => '1309485600'
  1825. ),
  1826. array(
  1827. 'usertimezone' => '-14', // Server time.
  1828. 'year' => '2011',
  1829. 'month' => '7',
  1830. 'day' => '1',
  1831. 'hour' => '10',
  1832. 'minutes' => '00',
  1833. 'seconds' => '00',
  1834. 'timezone' => '99', // Get user time.
  1835. 'applydst' => true, // Apply dst.
  1836. 'expectedoutput' => '1309485600'
  1837. )
  1838. );
  1839. // Set default timezone to Australia/Perth, else time calculated
  1840. // will not match expected values.
  1841. $this->setTimezone(99, 'Australia/Perth');
  1842. // Test make_timestamp with all testvals and assert if anything wrong.
  1843. foreach ($testvalues as $vals) {
  1844. $USER->timezone = $vals['usertimezone'];
  1845. $actualoutput = make_timestamp(
  1846. $vals['year'],
  1847. $vals['month'],
  1848. $vals['day'],
  1849. $vals['hour'],
  1850. $vals['minutes'],
  1851. $vals['seconds'],
  1852. $vals['timezone'],
  1853. $vals['applydst']
  1854. );
  1855. // On different systems case of AM PM changes so compare case insensitive.
  1856. $vals['expectedoutput'] = core_text::strtolower($vals['expectedoutput']);
  1857. $actualoutput = core_text::strtolower($actualoutput);
  1858. $this->assertSame($vals['expectedoutput'], $actualoutput,
  1859. "Expected: {$vals['expectedoutput']} => Actual: {$actualoutput},
  1860. Please check if timezones are updated (Site adminstration -> location -> update timezone)");
  1861. }
  1862. }
  1863. /**
  1864. * Test get_string and most importantly the implementation of the lang_string
  1865. * object.
  1866. */
  1867. public function test_get_string() {
  1868. global $COURSE;
  1869. // Make sure we are using English.
  1870. $originallang = $COURSE->lang;
  1871. $COURSE->lang = 'en';
  1872. $yes = get_string('yes');
  1873. $yesexpected = 'Yes';
  1874. $this->assertInternalType('string', $yes);
  1875. $this->assertSame($yesexpected, $yes);
  1876. $yes = get_string('yes', 'moodle');
  1877. $this->assertInternalType('string', $yes);
  1878. $this->assertSame($yesexpected, $yes);
  1879. $yes = get_string('yes', 'core');
  1880. $this->assertInternalType('string', $yes);
  1881. $this->assertSame($yesexpected, $yes);
  1882. $yes = get_string('yes', '');
  1883. $this->assertInternalType('string', $yes);
  1884. $this->assertSame($yesexpected, $yes);
  1885. $yes = get_string('yes', null);
  1886. $this->assertInternalType('string', $yes);
  1887. $this->assertSame($yesexpected, $yes);
  1888. $yes = get_string('yes', null, 1);
  1889. $this->assertInternalType('string', $yes);
  1890. $this->assertSame($yesexpected, $yes);
  1891. $days = 1;
  1892. $numdays = get_string('numdays', 'core', '1');
  1893. $numdaysexpected = $days.' days';
  1894. $this->assertInternalType('string', $numdays);
  1895. $this->assertSame($numdaysexpected, $numdays);
  1896. $yes = get_string('yes', null, null, true);
  1897. $this->assertInstanceOf('lang_string', $yes);
  1898. $this->assertSame($yesexpected, (string)$yes);
  1899. // Test using a lang_string object as the $a argument for a normal
  1900. // get_string call (returning string).
  1901. $test = new lang_string('yes', null, null, true);
  1902. $testexpected = get_string('numdays', 'core', get_string('yes'));
  1903. $testresult = get_string('numdays', null, $test);
  1904. $this->assertInternalType('string', $testresult);
  1905. $this->assertSame($testexpected, $testresult);
  1906. // Test using a lang_string object as the $a argument for an object
  1907. // get_string call (returning lang_string).
  1908. $test = new lang_string('yes', null, null, true);
  1909. $testexpected = get_string('numdays', 'core', get_string('yes'));
  1910. $testresult = get_string('numdays', null, $test, true);
  1911. $this->assertInstanceOf('lang_string', $testresult);
  1912. $this->assertSame($testexpected, "$testresult");
  1913. // Make sure that object properties that can't be converted don't cause
  1914. // errors.
  1915. // Level one: This is as deep as current language processing goes.
  1916. $test = new stdClass;
  1917. $test->one = 'here';
  1918. $string = get_string('yes', null, $test, true);
  1919. $this->assertEquals($yesexpected, $string);
  1920. // Make sure that object properties that can't be converted don't cause
  1921. // errors.
  1922. // Level two: Language processing doesn't currently reach this deep.
  1923. // only immediate scalar properties are worked with.
  1924. $test = new stdClass;
  1925. $test->one = new stdClass;
  1926. $test->one->two = 'here';
  1927. $string = get_string('yes', null, $test, true);
  1928. $this->assertEquals($yesexpected, $string);
  1929. // Make sure that object properties that can't be converted don't cause
  1930. // errors.
  1931. // Level three: It should never ever go this deep, but we're making sure
  1932. // it doesn't cause any probs anyway.
  1933. $test = new stdClass;
  1934. $test->one = new stdClass;
  1935. $test->one->two = new stdClass;
  1936. $test->one->two->three = 'here';
  1937. $string = get_string('yes', null, $test, true);
  1938. $this->assertEquals($yesexpected, $string);
  1939. // Make sure that object properties that can't be converted don't cause
  1940. // errors and check lang_string properties.
  1941. // Level one: This is as deep as current language processing goes.
  1942. $test = new stdClass;
  1943. $test->one = new lang_string('yes');
  1944. $string = get_string('yes', null, $test, true);
  1945. $this->assertEquals($yesexpected, $string);
  1946. // Make sure that object properties that can't be converted don't cause
  1947. // errors and check lang_string properties.
  1948. // Level two: Language processing doesn't currently reach this deep.
  1949. // only immediate scalar properties are worked with.
  1950. $test = new stdClass;
  1951. $test->one = new stdClass;
  1952. $test->one->two = new lang_string('yes');
  1953. $string = get_string('yes', null, $test, true);
  1954. $this->assertEquals($yesexpected, $string);
  1955. // Make sure that object properties that can't be converted don't cause
  1956. // errors and check lang_string properties.
  1957. // Level three: It should never ever go this deep, but we're making sure
  1958. // it doesn't cause any probs anyway.
  1959. $test = new stdClass;
  1960. $test->one = new stdClass;
  1961. $test->one->two = new stdClass;
  1962. $test->one->two->three = new lang_string('yes');
  1963. $string = get_string('yes', null, $test, true);
  1964. $this->assertEquals($yesexpected, $string);
  1965. // Make sure that array properties that can't be converted don't cause
  1966. // errors.
  1967. $test = array();
  1968. $test['one'] = new stdClass;
  1969. $test['one']->two = 'here';
  1970. $string = get_string('yes', null, $test, true);
  1971. $this->assertEquals($yesexpected, $string);
  1972. // Same thing but as above except using an object... this is allowed :P.
  1973. $string = get_string('yes', null, null, true);
  1974. $object = new stdClass;
  1975. $object->$string = 'Yes';
  1976. $this->assertEquals($yesexpected, $string);
  1977. $this->assertEquals($yesexpected, $object->$string);
  1978. // Reset the language.
  1979. $COURSE->lang = $originallang;
  1980. }
  1981. /**
  1982. * @expectedException PHPUnit\Framework\Error\Warning
  1983. */
  1984. public function test_get_string_limitation() {
  1985. // This is one of the limitations to the lang_string class. It can't be
  1986. // used as a key.
  1987. $array = array(get_string('yes', null, null, true) => 'yes');
  1988. }
  1989. /**
  1990. * Test localised float formatting.
  1991. */
  1992. public function test_format_float() {
  1993. // Special case for null.
  1994. $this->assertEquals('', format_float(null));
  1995. // Default 1 decimal place.
  1996. $this->assertEquals('5.4', format_float(5.43));
  1997. $this->assertEquals('5.0', format_float(5.001));
  1998. // Custom number of decimal places.
  1999. $this->assertEquals('5.43000', format_float(5.43, 5));
  2000. // Auto detect the number of decimal places.
  2001. $this->assertEquals('5.43', format_float(5.43, -1));
  2002. $this->assertEquals('5.43', format_float(5.43000, -1));
  2003. $this->assertEquals('5', format_float(5, -1));
  2004. $this->assertEquals('5', format_float(5.0, -1));
  2005. $this->assertEquals('0.543', format_float('5.43e-1', -1));
  2006. $this->assertEquals('0.543', format_float('5.43000e-1', -1));
  2007. // Option to strip ending zeros after rounding.
  2008. $this->assertEquals('5.43', format_float(5.43, 5, true, true));
  2009. $this->assertEquals('5', format_float(5.0001, 3, true, true));
  2010. // Tests with a localised decimal separator.
  2011. $this->define_local_decimal_separator();
  2012. // Localisation on (default).
  2013. $this->assertEquals('5X43000', format_float(5.43, 5));
  2014. $this->assertEquals('5X43', format_float(5.43, 5, true, true));
  2015. // Localisation off.
  2016. $this->assertEquals('5.43000', format_float(5.43, 5, false));
  2017. $this->assertEquals('5.43', format_float(5.43, 5, false, true));
  2018. // Tests with tilde as localised decimal separator.
  2019. $this->define_local_decimal_separator('~');
  2020. // Must also work for '~' as decimal separator.
  2021. $this->assertEquals('5', format_float(5.0001, 3, true, true));
  2022. $this->assertEquals('5~43000', format_float(5.43, 5));
  2023. $this->assertEquals('5~43', format_float(5.43, 5, true, true));
  2024. }
  2025. /**
  2026. * Test localised float unformatting.
  2027. */
  2028. public function test_unformat_float() {
  2029. // Tests without the localised decimal separator.
  2030. // Special case for null, empty or white spaces only strings.
  2031. $this->assertEquals(null, unformat_float(null));
  2032. $this->assertEquals(null, unformat_float(''));
  2033. $this->assertEquals(null, unformat_float(' '));
  2034. // Regular use.
  2035. $this->assertEquals(5.4, unformat_float('5.4'));
  2036. $this->assertEquals(5.4, unformat_float('5.4', true));
  2037. // No decimal.
  2038. $this->assertEquals(5.0, unformat_float('5'));
  2039. // Custom number of decimal.
  2040. $this->assertEquals(5.43267, unformat_float('5.43267'));
  2041. // Empty decimal.
  2042. $this->assertEquals(100.0, unformat_float('100.00'));
  2043. // With the thousand separator.
  2044. $this->assertEquals(1000.0, unformat_float('1 000'));
  2045. $this->assertEquals(1000.32, unformat_float('1 000.32'));
  2046. // Negative number.
  2047. $this->assertEquals(-100.0, unformat_float('-100'));
  2048. // Wrong value.
  2049. $this->assertEquals(0.0, unformat_float('Wrong value'));
  2050. // Wrong value in strict mode.
  2051. $this->assertFalse(unformat_float('Wrong value', true));
  2052. // Combining options.
  2053. $this->assertEquals(-1023.862567, unformat_float(' -1 023.862567 '));
  2054. // Bad decimal separator (should crop the decimal).
  2055. $this->assertEquals(50.0, unformat_float('50,57'));
  2056. // Bad decimal separator in strict mode (should return false).
  2057. $this->assertFalse(unformat_float('50,57', true));
  2058. // Tests with a localised decimal separator.
  2059. $this->define_local_decimal_separator();
  2060. // We repeat the tests above but with the current decimal separator.
  2061. // Regular use without and with the localised separator.
  2062. $this->assertEquals (5.4, unformat_float('5.4'));
  2063. $this->assertEquals (5.4, unformat_float('5X4'));
  2064. // Custom number of decimal.
  2065. $this->assertEquals (5.43267, unformat_float('5X43267'));
  2066. // Empty decimal.
  2067. $this->assertEquals (100.0, unformat_float('100X00'));
  2068. // With the thousand separator.
  2069. $this->assertEquals (1000.32, unformat_float('1 000X32'));
  2070. // Bad different separator (should crop the decimal).
  2071. $this->assertEquals (50.0, unformat_float('50Y57'));
  2072. // Bad different separator in strict mode (should return false).
  2073. $this->assertFalse (unformat_float('50Y57', true));
  2074. // Combining options.
  2075. $this->assertEquals (-1023.862567, unformat_float(' -1 023X862567 '));
  2076. // Combining options in strict mode.
  2077. $this->assertEquals (-1023.862567, unformat_float(' -1 023X862567 ', true));
  2078. }
  2079. /**
  2080. * Test deleting of users.
  2081. */
  2082. public function test_delete_user() {
  2083. global $DB, $CFG;
  2084. $this->resetAfterTest();
  2085. $guest = $DB->get_record('user', array('id'=>$CFG->siteguest), '*', MUST_EXIST);
  2086. $admin = $DB->get_record('user', array('id'=>$CFG->siteadmins), '*', MUST_EXIST);
  2087. $this->assertEquals(0, $DB->count_records('user', array('deleted'=>1)));
  2088. $user = $this->getDataGenerator()->create_user(array('idnumber'=>'abc'));
  2089. $user2 = $this->getDataGenerator()->create_user(array('idnumber'=>'xyz'));
  2090. $usersharedemail1 = $this->getDataGenerator()->create_user(array('email' => 'sharedemail@example.invalid'));
  2091. $usersharedemail2 = $this->getDataGenerator()->create_user(array('email' => 'sharedemail@example.invalid'));
  2092. $useremptyemail1 = $this->getDataGenerator()->create_user(array('email' => ''));
  2093. $useremptyemail2 = $this->getDataGenerator()->create_user(array('email' => ''));
  2094. // Delete user and capture event.
  2095. $sink = $this->redirectEvents();
  2096. $result = delete_user($user);
  2097. $events = $sink->get_events();
  2098. $sink->close();
  2099. $event = array_pop($events);
  2100. // Test user is deleted in DB.
  2101. $this->assertTrue($result);
  2102. $deluser = $DB->get_record('user', array('id'=>$user->id), '*', MUST_EXIST);
  2103. $this->assertEquals(1, $deluser->deleted);
  2104. $this->assertEquals(0, $deluser->picture);
  2105. $this->assertSame('', $deluser->idnumber);
  2106. $this->assertSame(md5($user->username), $deluser->email);
  2107. $this->assertRegExp('/^'.preg_quote($user->email, '/').'\.\d*$/', $deluser->username);
  2108. $this->assertEquals(1, $DB->count_records('user', array('deleted'=>1)));
  2109. // Test Event.
  2110. $this->assertInstanceOf('\core\event\user_deleted', $event);
  2111. $this->assertSame($user->id, $event->objectid);
  2112. $this->assertSame('user_deleted', $event->get_legacy_eventname());
  2113. $this->assertEventLegacyData($user, $event);
  2114. $expectedlogdata = array(SITEID, 'user', 'delete', "view.php?id=$user->id", $user->firstname.' '.$user->lastname);
  2115. $this->assertEventLegacyLogData($expectedlogdata, $event);
  2116. $eventdata = $event->get_data();
  2117. $this->assertSame($eventdata['other']['username'], $user->username);
  2118. $this->assertSame($eventdata['other']['email'], $user->email);
  2119. $this->assertSame($eventdata['other']['idnumber'], $user->idnumber);
  2120. $this->assertSame($eventdata['other']['picture'], $user->picture);
  2121. $this->assertSame($eventdata['other']['mnethostid'], $user->mnethostid);
  2122. $this->assertEquals($user, $event->get_record_snapshot('user', $event->objectid));
  2123. $this->assertEventContextNotUsed($event);
  2124. // Try invalid params.
  2125. $record = new stdClass();
  2126. $record->grrr = 1;
  2127. try {
  2128. delete_user($record);
  2129. $this->fail('Expecting exception for invalid delete_user() $user parameter');
  2130. } catch (moodle_exception $ex) {
  2131. $this->assertInstanceOf('coding_exception', $ex);
  2132. }
  2133. $record->id = 1;
  2134. try {
  2135. delete_user($record);
  2136. $this->fail('Expecting exception for invalid delete_user() $user parameter');
  2137. } catch (moodle_exception $ex) {
  2138. $this->assertInstanceOf('coding_exception', $ex);
  2139. }
  2140. $record = new stdClass();
  2141. $record->id = 666;
  2142. $record->username = 'xx';
  2143. $this->assertFalse($DB->record_exists('user', array('id'=>666))); // Any non-existent id is ok.
  2144. $result = delete_user($record);
  2145. $this->assertFalse($result);
  2146. $result = delete_user($guest);
  2147. $this->assertFalse($result);
  2148. $result = delete_user($admin);
  2149. $this->assertFalse($result);
  2150. // Simultaneously deleting users with identical email addresses.
  2151. $result1 = delete_user($usersharedemail1);
  2152. $result2 = delete_user($usersharedemail2);
  2153. $usersharedemail1after = $DB->get_record('user', array('id' => $usersharedemail1->id));
  2154. $usersharedemail2after = $DB->get_record('user', array('id' => $usersharedemail2->id));
  2155. $this->assertTrue($result1);
  2156. $this->assertTrue($result2);
  2157. $this->assertStringStartsWith($usersharedemail1->email . '.', $usersharedemail1after->username);
  2158. $this->assertStringStartsWith($usersharedemail2->email . '.', $usersharedemail2after->username);
  2159. // Simultaneously deleting users without email addresses.
  2160. $result1 = delete_user($useremptyemail1);
  2161. $result2 = delete_user($useremptyemail2);
  2162. $useremptyemail1after = $DB->get_record('user', array('id' => $useremptyemail1->id));
  2163. $useremptyemail2after = $DB->get_record('user', array('id' => $useremptyemail2->id));
  2164. $this->assertTrue($result1);
  2165. $this->assertTrue($result2);
  2166. $this->assertStringStartsWith($useremptyemail1->username . '.' . $useremptyemail1->id . '@unknownemail.invalid.',
  2167. $useremptyemail1after->username);
  2168. $this->assertStringStartsWith($useremptyemail2->username . '.' . $useremptyemail2->id . '@unknownemail.invalid.',
  2169. $useremptyemail2after->username);
  2170. $this->resetDebugging();
  2171. }
  2172. /**
  2173. * Test deletion of user with long username
  2174. */
  2175. public function test_delete_user_long_username() {
  2176. global $DB;
  2177. $this->resetAfterTest();
  2178. // For users without an e-mail, one will be created during deletion using {$username}.{$id}@unknownemail.invalid format.
  2179. $user = $this->getDataGenerator()->create_user([
  2180. 'username' => str_repeat('a', 75),
  2181. 'email' => '',
  2182. ]);
  2183. delete_user($user);
  2184. // The username for the deleted user shouldn't exceed 100 characters.
  2185. $usernamedeleted = $DB->get_field('user', 'username', ['id' => $user->id]);
  2186. $this->assertEquals(100, core_text::strlen($usernamedeleted));
  2187. $timestrlength = core_text::strlen((string) time());
  2188. // It should start with the user name, and end with the current time.
  2189. $this->assertStringStartsWith("{$user->username}.{$user->id}@", $usernamedeleted);
  2190. $this->assertRegExp('/\.\d{' . $timestrlength . '}$/', $usernamedeleted);
  2191. }
  2192. /**
  2193. * Test deletion of user with long email address
  2194. */
  2195. public function test_delete_user_long_email() {
  2196. global $DB;
  2197. $this->resetAfterTest();
  2198. // Create user with 90 character email address.
  2199. $user = $this->getDataGenerator()->create_user([
  2200. 'email' => str_repeat('a', 78) . '@example.com',
  2201. ]);
  2202. delete_user($user);
  2203. // The username for the deleted user shouldn't exceed 100 characters.
  2204. $usernamedeleted = $DB->get_field('user', 'username', ['id' => $user->id]);
  2205. $this->assertEquals(100, core_text::strlen($usernamedeleted));
  2206. $timestrlength = core_text::strlen((string) time());
  2207. // Max username length is 100 chars. Select up to limit - (length of current time + 1 [period character]) from users email.
  2208. $expectedemail = core_text::substr($user->email, 0, 100 - ($timestrlength + 1));
  2209. $this->assertRegExp('/^' . preg_quote($expectedemail) . '\.\d{' . $timestrlength . '}$/', $usernamedeleted);
  2210. }
  2211. /**
  2212. * Test function convert_to_array()
  2213. */
  2214. public function test_convert_to_array() {
  2215. // Check that normal classes are converted to arrays the same way as (array) would do.
  2216. $obj = new stdClass();
  2217. $obj->prop1 = 'hello';
  2218. $obj->prop2 = array('first', 'second', 13);
  2219. $obj->prop3 = 15;
  2220. $this->assertEquals(convert_to_array($obj), (array)$obj);
  2221. // Check that context object (with iterator) is converted to array properly.
  2222. $obj = context_system::instance();
  2223. $ar = array(
  2224. 'id' => $obj->id,
  2225. 'contextlevel' => $obj->contextlevel,
  2226. 'instanceid' => $obj->instanceid,
  2227. 'path' => $obj->path,
  2228. 'depth' => $obj->depth,
  2229. 'locked' => $obj->locked,
  2230. );
  2231. $this->assertEquals(convert_to_array($obj), $ar);
  2232. }
  2233. /**
  2234. * Test the function date_format_string().
  2235. */
  2236. public function test_date_format_string() {
  2237. global $CFG;
  2238. $this->resetAfterTest();
  2239. $this->setTimezone(99, 'Australia/Perth');
  2240. $tests = array(
  2241. array(
  2242. 'tz' => 99,
  2243. 'str' => '%A, %d %B %Y, %I:%M %p',
  2244. 'expected' => 'Saturday, 01 January 2011, 06:00 PM'
  2245. ),
  2246. array(
  2247. 'tz' => 0,
  2248. 'str' => '%A, %d %B %Y, %I:%M %p',
  2249. 'expected' => 'Saturday, 01 January 2011, 10:00 AM'
  2250. ),
  2251. array(
  2252. // Note: this function expected the timestamp in weird format before,
  2253. // since 2.9 it uses UTC.
  2254. 'tz' => 'Pacific/Auckland',
  2255. 'str' => '%A, %d %B %Y, %I:%M %p',
  2256. 'expected' => 'Saturday, 01 January 2011, 11:00 PM'
  2257. ),
  2258. // Following tests pass on Windows only because en lang pack does
  2259. // not contain localewincharset, in real life lang pack maintainers
  2260. // may use only characters that are present in localewincharset
  2261. // in format strings!
  2262. array(
  2263. 'tz' => 99,
  2264. 'str' => 'Žluťoučký koníček %A',
  2265. 'expected' => 'Žluťoučký koníček Saturday'
  2266. ),
  2267. array(
  2268. 'tz' => 99,
  2269. 'str' => '言語設定言語 %A',
  2270. 'expected' => '言語設定言語 Saturday'
  2271. ),
  2272. array(
  2273. 'tz' => 99,
  2274. 'str' => '简体中文简体 %A',
  2275. 'expected' => '简体中文简体 Saturday'
  2276. ),
  2277. );
  2278. // Note: date_format_string() uses the timezone only to differenciate
  2279. // the server time from the UTC time. It does not modify the timestamp.
  2280. // Hence similar results for timezones <= 13.
  2281. // On different systems case of AM PM changes so compare case insensitive.
  2282. foreach ($tests as $test) {
  2283. $str = date_format_string(1293876000, $test['str'], $test['tz']);
  2284. $this->assertSame(core_text::strtolower($test['expected']), core_text::strtolower($str));
  2285. }
  2286. }
  2287. public function test_get_config() {
  2288. global $CFG;
  2289. $this->resetAfterTest();
  2290. // Preparation.
  2291. set_config('phpunit_test_get_config_1', 'test 1');
  2292. set_config('phpunit_test_get_config_2', 'test 2', 'mod_forum');
  2293. if (!is_array($CFG->config_php_settings)) {
  2294. $CFG->config_php_settings = array();
  2295. }
  2296. $CFG->config_php_settings['phpunit_test_get_config_3'] = 'test 3';
  2297. if (!is_array($CFG->forced_plugin_settings)) {
  2298. $CFG->forced_plugin_settings = array();
  2299. }
  2300. if (!array_key_exists('mod_forum', $CFG->forced_plugin_settings)) {
  2301. $CFG->forced_plugin_settings['mod_forum'] = array();
  2302. }
  2303. $CFG->forced_plugin_settings['mod_forum']['phpunit_test_get_config_4'] = 'test 4';
  2304. $CFG->phpunit_test_get_config_5 = 'test 5';
  2305. // Testing.
  2306. $this->assertSame('test 1', get_config('core', 'phpunit_test_get_config_1'));
  2307. $this->assertSame('test 2', get_config('mod_forum', 'phpunit_test_get_config_2'));
  2308. $this->assertSame('test 3', get_config('core', 'phpunit_test_get_config_3'));
  2309. $this->assertSame('test 4', get_config('mod_forum', 'phpunit_test_get_config_4'));
  2310. $this->assertFalse(get_config('core', 'phpunit_test_get_config_5'));
  2311. $this->assertFalse(get_config('core', 'phpunit_test_get_config_x'));
  2312. $this->assertFalse(get_config('mod_forum', 'phpunit_test_get_config_x'));
  2313. // Test config we know to exist.
  2314. $this->assertSame($CFG->dataroot, get_config('core', 'dataroot'));
  2315. $this->assertSame($CFG->phpunit_dataroot, get_config('core', 'phpunit_dataroot'));
  2316. $this->assertSame($CFG->dataroot, get_config('core', 'phpunit_dataroot'));
  2317. $this->assertSame(get_config('core', 'dataroot'), get_config('core', 'phpunit_dataroot'));
  2318. // Test setting a config var that already exists.
  2319. set_config('phpunit_test_get_config_1', 'test a');
  2320. $this->assertSame('test a', $CFG->phpunit_test_get_config_1);
  2321. $this->assertSame('test a', get_config('core', 'phpunit_test_get_config_1'));
  2322. // Test cache invalidation.
  2323. $cache = cache::make('core', 'config');
  2324. $this->assertInternalType('array', $cache->get('core'));
  2325. $this->assertInternalType('array', $cache->get('mod_forum'));
  2326. set_config('phpunit_test_get_config_1', 'test b');
  2327. $this->assertFalse($cache->get('core'));
  2328. set_config('phpunit_test_get_config_4', 'test c', 'mod_forum');
  2329. $this->assertFalse($cache->get('mod_forum'));
  2330. }
  2331. public function test_get_max_upload_sizes() {
  2332. // Test with very low limits so we are not affected by php upload limits.
  2333. // Test activity limit smallest.
  2334. $sitebytes = 102400;
  2335. $coursebytes = 51200;
  2336. $modulebytes = 10240;
  2337. $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
  2338. $this->assertSame('Activity upload limit (10KB)', $result['0']);
  2339. $this->assertCount(2, $result);
  2340. // Test course limit smallest.
  2341. $sitebytes = 102400;
  2342. $coursebytes = 10240;
  2343. $modulebytes = 51200;
  2344. $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
  2345. $this->assertSame('Course upload limit (10KB)', $result['0']);
  2346. $this->assertCount(2, $result);
  2347. // Test site limit smallest.
  2348. $sitebytes = 10240;
  2349. $coursebytes = 102400;
  2350. $modulebytes = 51200;
  2351. $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
  2352. $this->assertSame('Site upload limit (10KB)', $result['0']);
  2353. $this->assertCount(2, $result);
  2354. // Test site limit not set.
  2355. $sitebytes = 0;
  2356. $coursebytes = 102400;
  2357. $modulebytes = 51200;
  2358. $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
  2359. $this->assertSame('Activity upload limit (50KB)', $result['0']);
  2360. $this->assertCount(3, $result);
  2361. $sitebytes = 0;
  2362. $coursebytes = 51200;
  2363. $modulebytes = 102400;
  2364. $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes);
  2365. $this->assertSame('Course upload limit (50KB)', $result['0']);
  2366. $this->assertCount(3, $result);
  2367. // Test custom bytes in range.
  2368. $sitebytes = 102400;
  2369. $coursebytes = 51200;
  2370. $modulebytes = 51200;
  2371. $custombytes = 10240;
  2372. $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes, $custombytes);
  2373. $this->assertCount(3, $result);
  2374. // Test custom bytes in range but non-standard.
  2375. $sitebytes = 102400;
  2376. $coursebytes = 51200;
  2377. $modulebytes = 51200;
  2378. $custombytes = 25600;
  2379. $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes, $custombytes);
  2380. $this->assertCount(4, $result);
  2381. // Test custom bytes out of range.
  2382. $sitebytes = 102400;
  2383. $coursebytes = 51200;
  2384. $modulebytes = 51200;
  2385. $custombytes = 102400;
  2386. $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes, $custombytes);
  2387. $this->assertCount(3, $result);
  2388. // Test custom bytes out of range and non-standard.
  2389. $sitebytes = 102400;
  2390. $coursebytes = 51200;
  2391. $modulebytes = 51200;
  2392. $custombytes = 256000;
  2393. $result = get_max_upload_sizes($sitebytes, $coursebytes, $modulebytes, $custombytes);
  2394. $this->assertCount(3, $result);
  2395. // Test site limit only.
  2396. $sitebytes = 51200;
  2397. $result = get_max_upload_sizes($sitebytes);
  2398. $this->assertSame('Site upload limit (50KB)', $result['0']);
  2399. $this->assertSame('50KB', $result['51200']);
  2400. $this->assertSame('10KB', $result['10240']);
  2401. $this->assertCount(3, $result);
  2402. // Test no limit.
  2403. $result = get_max_upload_sizes();
  2404. $this->assertArrayHasKey('0', $result);
  2405. $this->assertArrayHasKey(get_max_upload_file_size(), $result);
  2406. }
  2407. /**
  2408. * Test function password_is_legacy_hash().
  2409. */
  2410. public function test_password_is_legacy_hash() {
  2411. // Well formed md5s should be matched.
  2412. foreach (array('some', 'strings', 'to_check!') as $string) {
  2413. $md5 = md5($string);
  2414. $this->assertTrue(password_is_legacy_hash($md5));
  2415. }
  2416. // Strings that are not md5s should not be matched.
  2417. foreach (array('', AUTH_PASSWORD_NOT_CACHED, 'IPW8WTcsWNgAWcUS1FBVHegzJnw5M2jOmYkmfc8z.xdBOyC4Caeum') as $notmd5) {
  2418. $this->assertFalse(password_is_legacy_hash($notmd5));
  2419. }
  2420. }
  2421. /**
  2422. * Test function validate_internal_user_password().
  2423. */
  2424. public function test_validate_internal_user_password() {
  2425. // Test bcrypt hashes.
  2426. $validhashes = array(
  2427. 'pw' => '$2y$10$LOSDi5eaQJhutSRun.OVJ.ZSxQZabCMay7TO1KmzMkDMPvU40zGXK',
  2428. 'abc' => '$2y$10$VWTOhVdsBbWwtdWNDRHSpewjd3aXBQlBQf5rBY/hVhw8hciarFhXa',
  2429. 'C0mP1eX_&}<?@*&%` |\"' => '$2y$10$3PJf.q.9ywNJlsInPbqc8.IFeSsvXrGvQLKRFBIhVu1h1I3vpIry6',
  2430. 'ĩńťėŕňăţĩōŋāĹ' => '$2y$10$3A2Y8WpfRAnP3czJiSv6N.6Xp0T8hW3QZz2hUCYhzyWr1kGP1yUve'
  2431. );
  2432. foreach ($validhashes as $password => $hash) {
  2433. $user = new stdClass();
  2434. $user->auth = 'manual';
  2435. $user->password = $hash;
  2436. // The correct password should be validated.
  2437. $this->assertTrue(validate_internal_user_password($user, $password));
  2438. // An incorrect password should not be validated.
  2439. $this->assertFalse(validate_internal_user_password($user, 'badpw'));
  2440. }
  2441. }
  2442. /**
  2443. * Test function hash_internal_user_password().
  2444. */
  2445. public function test_hash_internal_user_password() {
  2446. $passwords = array('pw', 'abc123', 'C0mP1eX_&}<?@*&%` |\"', 'ĩńťėŕňăţĩōŋāĹ');
  2447. // Check that some passwords that we convert to hashes can
  2448. // be validated.
  2449. foreach ($passwords as $password) {
  2450. $hash = hash_internal_user_password($password);
  2451. $fasthash = hash_internal_user_password($password, true);
  2452. $user = new stdClass();
  2453. $user->auth = 'manual';
  2454. $user->password = $hash;
  2455. $this->assertTrue(validate_internal_user_password($user, $password));
  2456. // They should not be in md5 format.
  2457. $this->assertFalse(password_is_legacy_hash($hash));
  2458. // Check that cost factor in hash is correctly set.
  2459. $this->assertRegExp('/\$10\$/', $hash);
  2460. $this->assertRegExp('/\$04\$/', $fasthash);
  2461. }
  2462. }
  2463. /**
  2464. * Test function update_internal_user_password().
  2465. */
  2466. public function test_update_internal_user_password() {
  2467. global $DB;
  2468. $this->resetAfterTest();
  2469. $passwords = array('password', '1234', 'changeme', '****');
  2470. foreach ($passwords as $password) {
  2471. $user = $this->getDataGenerator()->create_user(array('auth'=>'manual'));
  2472. update_internal_user_password($user, $password);
  2473. // The user object should have been updated.
  2474. $this->assertTrue(validate_internal_user_password($user, $password));
  2475. // The database field for the user should also have been updated to the
  2476. // same value.
  2477. $this->assertSame($user->password, $DB->get_field('user', 'password', array('id' => $user->id)));
  2478. }
  2479. $user = $this->getDataGenerator()->create_user(array('auth'=>'manual'));
  2480. // Manually set the user's password to the md5 of the string 'password'.
  2481. $DB->set_field('user', 'password', '5f4dcc3b5aa765d61d8327deb882cf99', array('id' => $user->id));
  2482. $sink = $this->redirectEvents();
  2483. // Update the password.
  2484. update_internal_user_password($user, 'password');
  2485. $events = $sink->get_events();
  2486. $sink->close();
  2487. $event = array_pop($events);
  2488. // Password should have been updated to a bcrypt hash.
  2489. $this->assertFalse(password_is_legacy_hash($user->password));
  2490. // Verify event information.
  2491. $this->assertInstanceOf('\core\event\user_password_updated', $event);
  2492. $this->assertSame($user->id, $event->relateduserid);
  2493. $this->assertEquals(context_user::instance($user->id), $event->get_context());
  2494. $this->assertEventContextNotUsed($event);
  2495. // Verify recovery of property 'auth'.
  2496. unset($user->auth);
  2497. update_internal_user_password($user, 'newpassword');
  2498. $this->assertDebuggingCalled('User record in update_internal_user_password() must include field auth',
  2499. DEBUG_DEVELOPER);
  2500. $this->assertEquals('manual', $user->auth);
  2501. }
  2502. /**
  2503. * Testing that if the password is not cached, that it does not update
  2504. * the user table and fire event.
  2505. */
  2506. public function test_update_internal_user_password_no_cache() {
  2507. global $DB;
  2508. $this->resetAfterTest();
  2509. $user = $this->getDataGenerator()->create_user(array('auth' => 'cas'));
  2510. $DB->update_record('user', ['id' => $user->id, 'password' => AUTH_PASSWORD_NOT_CACHED]);
  2511. $user->password = AUTH_PASSWORD_NOT_CACHED;
  2512. $sink = $this->redirectEvents();
  2513. update_internal_user_password($user, 'wonkawonka');
  2514. $this->assertEquals(0, $sink->count(), 'User updated event should not fire');
  2515. }
  2516. /**
  2517. * Test if the user has a password hash, but now their auth method
  2518. * says not to cache it. Then it should update.
  2519. */
  2520. public function test_update_internal_user_password_update_no_cache() {
  2521. $this->resetAfterTest();
  2522. $user = $this->getDataGenerator()->create_user(array('password' => 'test'));
  2523. $this->assertNotEquals(AUTH_PASSWORD_NOT_CACHED, $user->password);
  2524. $user->auth = 'cas'; // Change to a auth that does not store passwords.
  2525. $sink = $this->redirectEvents();
  2526. update_internal_user_password($user, 'wonkawonka');
  2527. $this->assertGreaterThanOrEqual(1, $sink->count(), 'User updated event should fire');
  2528. $this->assertEquals(AUTH_PASSWORD_NOT_CACHED, $user->password);
  2529. }
  2530. public function test_fullname() {
  2531. global $CFG;
  2532. $this->resetAfterTest();
  2533. // Create a user to test the name display on.
  2534. $record = array();
  2535. $record['firstname'] = 'Scott';
  2536. $record['lastname'] = 'Fletcher';
  2537. $record['firstnamephonetic'] = 'スコット';
  2538. $record['lastnamephonetic'] = 'フレチャー';
  2539. $record['alternatename'] = 'No friends';
  2540. $user = $this->getDataGenerator()->create_user($record);
  2541. // Back up config settings for restore later.
  2542. $originalcfg = new stdClass();
  2543. $originalcfg->fullnamedisplay = $CFG->fullnamedisplay;
  2544. $originalcfg->alternativefullnameformat = $CFG->alternativefullnameformat;
  2545. // Testing existing fullnamedisplay settings.
  2546. $CFG->fullnamedisplay = 'firstname';
  2547. $testname = fullname($user);
  2548. $this->assertSame($user->firstname, $testname);
  2549. $CFG->fullnamedisplay = 'firstname lastname';
  2550. $expectedname = "$user->firstname $user->lastname";
  2551. $testname = fullname($user);
  2552. $this->assertSame($expectedname, $testname);
  2553. $CFG->fullnamedisplay = 'lastname firstname';
  2554. $expectedname = "$user->lastname $user->firstname";
  2555. $testname = fullname($user);
  2556. $this->assertSame($expectedname, $testname);
  2557. $expectedname = get_string('fullnamedisplay', null, $user);
  2558. $CFG->fullnamedisplay = 'language';
  2559. $testname = fullname($user);
  2560. $this->assertSame($expectedname, $testname);
  2561. // Test override parameter.
  2562. $CFG->fullnamedisplay = 'firstname';
  2563. $expectedname = "$user->firstname $user->lastname";
  2564. $testname = fullname($user, true);
  2565. $this->assertSame($expectedname, $testname);
  2566. // Test alternativefullnameformat setting.
  2567. // Test alternativefullnameformat that has been set to nothing.
  2568. $CFG->alternativefullnameformat = '';
  2569. $expectedname = "$user->firstname $user->lastname";
  2570. $testname = fullname($user, true);
  2571. $this->assertSame($expectedname, $testname);
  2572. // Test alternativefullnameformat that has been set to 'language'.
  2573. $CFG->alternativefullnameformat = 'language';
  2574. $expectedname = "$user->firstname $user->lastname";
  2575. $testname = fullname($user, true);
  2576. $this->assertSame($expectedname, $testname);
  2577. // Test customising the alternativefullnameformat setting with all additional name fields.
  2578. $CFG->alternativefullnameformat = 'firstname lastname firstnamephonetic lastnamephonetic middlename alternatename';
  2579. $expectedname = "$user->firstname $user->lastname $user->firstnamephonetic $user->lastnamephonetic $user->middlename $user->alternatename";
  2580. $testname = fullname($user, true);
  2581. $this->assertSame($expectedname, $testname);
  2582. // Test additional name fields.
  2583. $CFG->fullnamedisplay = 'lastname lastnamephonetic firstname firstnamephonetic';
  2584. $expectedname = "$user->lastname $user->lastnamephonetic $user->firstname $user->firstnamephonetic";
  2585. $testname = fullname($user);
  2586. $this->assertSame($expectedname, $testname);
  2587. // Test for handling missing data.
  2588. $user->middlename = null;
  2589. // Parenthesis with no data.
  2590. $CFG->fullnamedisplay = 'firstname (middlename) lastname';
  2591. $expectedname = "$user->firstname $user->lastname";
  2592. $testname = fullname($user);
  2593. $this->assertSame($expectedname, $testname);
  2594. // Extra spaces due to no data.
  2595. $CFG->fullnamedisplay = 'firstname middlename lastname';
  2596. $expectedname = "$user->firstname $user->lastname";
  2597. $testname = fullname($user);
  2598. $this->assertSame($expectedname, $testname);
  2599. // Regular expression testing.
  2600. // Remove some data from the user fields.
  2601. $user->firstnamephonetic = '';
  2602. $user->lastnamephonetic = '';
  2603. // Removing empty brackets and excess whitespace.
  2604. // All of these configurations should resolve to just firstname lastname.
  2605. $configarray = array();
  2606. $configarray[] = 'firstname lastname [firstnamephonetic lastnamephonetic]';
  2607. $configarray[] = 'firstname lastname \'middlename\'';
  2608. $configarray[] = 'firstname "firstnamephonetic" lastname';
  2609. $configarray[] = 'firstname 「firstnamephonetic」 lastname 「lastnamephonetic」';
  2610. foreach ($configarray as $config) {
  2611. $CFG->fullnamedisplay = $config;
  2612. $expectedname = "$user->firstname $user->lastname";
  2613. $testname = fullname($user);
  2614. $this->assertSame($expectedname, $testname);
  2615. }
  2616. // Check to make sure that other characters are left in place.
  2617. $configarray = array();
  2618. $configarray['0'] = new stdClass();
  2619. $configarray['0']->config = 'lastname firstname, middlename';
  2620. $configarray['0']->expectedname = "$user->lastname $user->firstname,";
  2621. $configarray['1'] = new stdClass();
  2622. $configarray['1']->config = 'lastname firstname + alternatename';
  2623. $configarray['1']->expectedname = "$user->lastname $user->firstname + $user->alternatename";
  2624. $configarray['2'] = new stdClass();
  2625. $configarray['2']->config = 'firstname aka: alternatename';
  2626. $configarray['2']->expectedname = "$user->firstname aka: $user->alternatename";
  2627. $configarray['3'] = new stdClass();
  2628. $configarray['3']->config = 'firstname (alternatename)';
  2629. $configarray['3']->expectedname = "$user->firstname ($user->alternatename)";
  2630. $configarray['4'] = new stdClass();
  2631. $configarray['4']->config = 'firstname [alternatename]';
  2632. $configarray['4']->expectedname = "$user->firstname [$user->alternatename]";
  2633. $configarray['5'] = new stdClass();
  2634. $configarray['5']->config = 'firstname "lastname"';
  2635. $configarray['5']->expectedname = "$user->firstname \"$user->lastname\"";
  2636. foreach ($configarray as $config) {
  2637. $CFG->fullnamedisplay = $config->config;
  2638. $expectedname = $config->expectedname;
  2639. $testname = fullname($user);
  2640. $this->assertSame($expectedname, $testname);
  2641. }
  2642. // Test debugging message displays when
  2643. // fullnamedisplay setting is "normal".
  2644. $CFG->fullnamedisplay = 'firstname lastname';
  2645. unset($user);
  2646. $user = new stdClass();
  2647. $user->firstname = 'Stan';
  2648. $user->lastname = 'Lee';
  2649. $namedisplay = fullname($user);
  2650. $this->assertDebuggingCalled();
  2651. // Tidy up after we finish testing.
  2652. $CFG->fullnamedisplay = $originalcfg->fullnamedisplay;
  2653. $CFG->alternativefullnameformat = $originalcfg->alternativefullnameformat;
  2654. }
  2655. public function test_get_all_user_name_fields() {
  2656. $this->resetAfterTest();
  2657. // Additional names in an array.
  2658. $testarray = array('firstnamephonetic' => 'firstnamephonetic',
  2659. 'lastnamephonetic' => 'lastnamephonetic',
  2660. 'middlename' => 'middlename',
  2661. 'alternatename' => 'alternatename',
  2662. 'firstname' => 'firstname',
  2663. 'lastname' => 'lastname');
  2664. $this->assertEquals($testarray, get_all_user_name_fields());
  2665. // Additional names as a string.
  2666. $teststring = 'firstnamephonetic,lastnamephonetic,middlename,alternatename,firstname,lastname';
  2667. $this->assertEquals($teststring, get_all_user_name_fields(true));
  2668. // Additional names as a string with an alias.
  2669. $teststring = 't.firstnamephonetic,t.lastnamephonetic,t.middlename,t.alternatename,t.firstname,t.lastname';
  2670. $this->assertEquals($teststring, get_all_user_name_fields(true, 't'));
  2671. // Additional name fields with a prefix - object.
  2672. $testarray = array('firstnamephonetic' => 'authorfirstnamephonetic',
  2673. 'lastnamephonetic' => 'authorlastnamephonetic',
  2674. 'middlename' => 'authormiddlename',
  2675. 'alternatename' => 'authoralternatename',
  2676. 'firstname' => 'authorfirstname',
  2677. 'lastname' => 'authorlastname');
  2678. $this->assertEquals($testarray, get_all_user_name_fields(false, null, 'author'));
  2679. // Additional name fields with an alias and a title - string.
  2680. $teststring = 'u.firstnamephonetic AS authorfirstnamephonetic,u.lastnamephonetic AS authorlastnamephonetic,u.middlename AS authormiddlename,u.alternatename AS authoralternatename,u.firstname AS authorfirstname,u.lastname AS authorlastname';
  2681. $this->assertEquals($teststring, get_all_user_name_fields(true, 'u', null, 'author'));
  2682. // Test the order parameter of the function.
  2683. // Returning an array.
  2684. $testarray = array('firstname' => 'firstname',
  2685. 'lastname' => 'lastname',
  2686. 'firstnamephonetic' => 'firstnamephonetic',
  2687. 'lastnamephonetic' => 'lastnamephonetic',
  2688. 'middlename' => 'middlename',
  2689. 'alternatename' => 'alternatename'
  2690. );
  2691. $this->assertEquals($testarray, get_all_user_name_fields(false, null, null, null, true));
  2692. // Returning a string.
  2693. $teststring = 'firstname,lastname,firstnamephonetic,lastnamephonetic,middlename,alternatename';
  2694. $this->assertEquals($teststring, get_all_user_name_fields(true, null, null, null, true));
  2695. }
  2696. public function test_order_in_string() {
  2697. $this->resetAfterTest();
  2698. // Return an array in an order as they are encountered in a string.
  2699. $valuearray = array('second', 'firsthalf', 'first');
  2700. $formatstring = 'first firsthalf some other text (second)';
  2701. $expectedarray = array('0' => 'first', '6' => 'firsthalf', '33' => 'second');
  2702. $this->assertEquals($expectedarray, order_in_string($valuearray, $formatstring));
  2703. // Try again with a different order for the format.
  2704. $valuearray = array('second', 'firsthalf', 'first');
  2705. $formatstring = 'firsthalf first second';
  2706. $expectedarray = array('0' => 'firsthalf', '10' => 'first', '16' => 'second');
  2707. $this->assertEquals($expectedarray, order_in_string($valuearray, $formatstring));
  2708. // Try again with yet another different order for the format.
  2709. $valuearray = array('second', 'firsthalf', 'first');
  2710. $formatstring = 'start seconds away second firstquater first firsthalf';
  2711. $expectedarray = array('19' => 'second', '38' => 'first', '44' => 'firsthalf');
  2712. $this->assertEquals($expectedarray, order_in_string($valuearray, $formatstring));
  2713. }
  2714. public function test_complete_user_login() {
  2715. global $USER, $DB;
  2716. $this->resetAfterTest();
  2717. $user = $this->getDataGenerator()->create_user();
  2718. $this->setUser(0);
  2719. $sink = $this->redirectEvents();
  2720. $loginuser = clone($user);
  2721. $this->setCurrentTimeStart();
  2722. @complete_user_login($loginuser); // Hide session header errors.
  2723. $this->assertSame($loginuser, $USER);
  2724. $this->assertEquals($user->id, $USER->id);
  2725. $events = $sink->get_events();
  2726. $sink->close();
  2727. $this->assertCount(1, $events);
  2728. $event = reset($events);
  2729. $this->assertInstanceOf('\core\event\user_loggedin', $event);
  2730. $this->assertEquals('user', $event->objecttable);
  2731. $this->assertEquals($user->id, $event->objectid);
  2732. $this->assertEquals(context_system::instance()->id, $event->contextid);
  2733. $this->assertEventContextNotUsed($event);
  2734. $user = $DB->get_record('user', array('id'=>$user->id));
  2735. $this->assertTimeCurrent($user->firstaccess);
  2736. $this->assertTimeCurrent($user->lastaccess);
  2737. $this->assertTimeCurrent($USER->firstaccess);
  2738. $this->assertTimeCurrent($USER->lastaccess);
  2739. $this->assertTimeCurrent($USER->currentlogin);
  2740. $this->assertSame(sesskey(), $USER->sesskey);
  2741. $this->assertTimeCurrent($USER->preference['_lastloaded']);
  2742. $this->assertObjectNotHasAttribute('password', $USER);
  2743. $this->assertObjectNotHasAttribute('description', $USER);
  2744. }
  2745. /**
  2746. * Test require_logout.
  2747. */
  2748. public function test_require_logout() {
  2749. $this->resetAfterTest();
  2750. $user = $this->getDataGenerator()->create_user();
  2751. $this->setUser($user);
  2752. $this->assertTrue(isloggedin());
  2753. // Logout user and capture event.
  2754. $sink = $this->redirectEvents();
  2755. require_logout();
  2756. $events = $sink->get_events();
  2757. $sink->close();
  2758. $event = array_pop($events);
  2759. // Check if user is logged out.
  2760. $this->assertFalse(isloggedin());
  2761. // Test Event.
  2762. $this->assertInstanceOf('\core\event\user_loggedout', $event);
  2763. $this->assertSame($user->id, $event->objectid);
  2764. $this->assertSame('user_logout', $event->get_legacy_eventname());
  2765. $this->assertEventLegacyData($user, $event);
  2766. $expectedlogdata = array(SITEID, 'user', 'logout', 'view.php?id='.$event->objectid.'&course='.SITEID, $event->objectid, 0,
  2767. $event->objectid);
  2768. $this->assertEventLegacyLogData($expectedlogdata, $event);
  2769. $this->assertEventContextNotUsed($event);
  2770. }
  2771. /**
  2772. * A data provider for testing email messageid
  2773. */
  2774. public function generate_email_messageid_provider() {
  2775. return array(
  2776. 'nopath' => array(
  2777. 'wwwroot' => 'http://www.example.com',
  2778. 'ids' => array(
  2779. 'a-custom-id' => '<a-custom-id@www.example.com>',
  2780. 'an-id-with-/-a-slash' => '<an-id-with-%2F-a-slash@www.example.com>',
  2781. ),
  2782. ),
  2783. 'path' => array(
  2784. 'wwwroot' => 'http://www.example.com/path/subdir',
  2785. 'ids' => array(
  2786. 'a-custom-id' => '<a-custom-id/path/subdir@www.example.com>',
  2787. 'an-id-with-/-a-slash' => '<an-id-with-%2F-a-slash/path/subdir@www.example.com>',
  2788. ),
  2789. ),
  2790. );
  2791. }
  2792. /**
  2793. * Test email message id generation
  2794. *
  2795. * @dataProvider generate_email_messageid_provider
  2796. *
  2797. * @param string $wwwroot The wwwroot
  2798. * @param array $msgids An array of msgid local parts and the final result
  2799. */
  2800. public function test_generate_email_messageid($wwwroot, $msgids) {
  2801. global $CFG;
  2802. $this->resetAfterTest();
  2803. $CFG->wwwroot = $wwwroot;
  2804. foreach ($msgids as $local => $final) {
  2805. $this->assertEquals($final, generate_email_messageid($local));
  2806. }
  2807. }
  2808. /**
  2809. * A data provider for testing email diversion
  2810. */
  2811. public function diverted_emails_provider() {
  2812. return array(
  2813. 'nodiverts' => array(
  2814. 'divertallemailsto' => null,
  2815. 'divertallemailsexcept' => null,
  2816. array(
  2817. 'foo@example.com',
  2818. 'test@real.com',
  2819. 'fred.jones@example.com',
  2820. 'dev1@dev.com',
  2821. 'fred@example.com',
  2822. 'fred+verp@example.com',
  2823. ),
  2824. false,
  2825. ),
  2826. 'alldiverts' => array(
  2827. 'divertallemailsto' => 'somewhere@elsewhere.com',
  2828. 'divertallemailsexcept' => null,
  2829. array(
  2830. 'foo@example.com',
  2831. 'test@real.com',
  2832. 'fred.jones@example.com',
  2833. 'dev1@dev.com',
  2834. 'fred@example.com',
  2835. 'fred+verp@example.com',
  2836. ),
  2837. true,
  2838. ),
  2839. 'alsodiverts' => array(
  2840. 'divertallemailsto' => 'somewhere@elsewhere.com',
  2841. 'divertallemailsexcept' => '@dev.com, fred(\+.*)?@example.com',
  2842. array(
  2843. 'foo@example.com',
  2844. 'test@real.com',
  2845. 'fred.jones@example.com',
  2846. ),
  2847. true,
  2848. ),
  2849. 'divertsexceptions' => array(
  2850. 'divertallemailsto' => 'somewhere@elsewhere.com',
  2851. 'divertallemailsexcept' => '@dev.com, fred(\+.*)?@example.com',
  2852. array(
  2853. 'dev1@dev.com',
  2854. 'fred@example.com',
  2855. 'fred+verp@example.com',
  2856. ),
  2857. false,
  2858. ),
  2859. );
  2860. }
  2861. /**
  2862. * Test email diversion
  2863. *
  2864. * @dataProvider diverted_emails_provider
  2865. *
  2866. * @param string $divertallemailsto An optional email address
  2867. * @param string $divertallemailsexcept An optional exclusion list
  2868. * @param array $addresses An array of test addresses
  2869. * @param boolean $expected Expected result
  2870. */
  2871. public function test_email_should_be_diverted($divertallemailsto, $divertallemailsexcept, $addresses, $expected) {
  2872. global $CFG;
  2873. $this->resetAfterTest();
  2874. $CFG->divertallemailsto = $divertallemailsto;
  2875. $CFG->divertallemailsexcept = $divertallemailsexcept;
  2876. foreach ($addresses as $address) {
  2877. $this->assertEquals($expected, email_should_be_diverted($address));
  2878. }
  2879. }
  2880. public function test_email_to_user() {
  2881. global $CFG;
  2882. $this->resetAfterTest();
  2883. $user1 = $this->getDataGenerator()->create_user(array('maildisplay' => 1, 'mailformat' => 0));
  2884. $user2 = $this->getDataGenerator()->create_user(array('maildisplay' => 1, 'mailformat' => 1));
  2885. $user3 = $this->getDataGenerator()->create_user(array('maildisplay' => 0));
  2886. set_config('allowedemaildomains', "example.com\r\nmoodle.org");
  2887. $subject = 'subject';
  2888. $messagetext = 'message text';
  2889. $subject2 = 'subject 2';
  2890. $messagetext2 = '<b>message text 2</b>';
  2891. // Close the default email sink.
  2892. $sink = $this->redirectEmails();
  2893. $sink->close();
  2894. $CFG->noemailever = true;
  2895. $this->assertNotEmpty($CFG->noemailever);
  2896. email_to_user($user1, $user2, $subject, $messagetext);
  2897. $this->assertDebuggingCalled('Not sending email due to $CFG->noemailever config setting');
  2898. unset_config('noemailever');
  2899. email_to_user($user1, $user2, $subject, $messagetext);
  2900. $this->assertDebuggingCalled('Unit tests must not send real emails! Use $this->redirectEmails()');
  2901. $sink = $this->redirectEmails();
  2902. email_to_user($user1, $user2, $subject, $messagetext);
  2903. email_to_user($user2, $user1, $subject2, $messagetext2);
  2904. $this->assertSame(2, $sink->count());
  2905. $result = $sink->get_messages();
  2906. $this->assertCount(2, $result);
  2907. $sink->close();
  2908. $this->assertSame($subject, $result[0]->subject);
  2909. $this->assertSame($messagetext, trim($result[0]->body));
  2910. $this->assertSame($user1->email, $result[0]->to);
  2911. $this->assertSame($user2->email, $result[0]->from);
  2912. $this->assertContains('Content-Type: text/plain', $result[0]->header);
  2913. $this->assertSame($subject2, $result[1]->subject);
  2914. $this->assertContains($messagetext2, quoted_printable_decode($result[1]->body));
  2915. $this->assertSame($user2->email, $result[1]->to);
  2916. $this->assertSame($user1->email, $result[1]->from);
  2917. $this->assertNotContains('Content-Type: text/plain', $result[1]->header);
  2918. email_to_user($user1, $user2, $subject, $messagetext);
  2919. $this->assertDebuggingCalled('Unit tests must not send real emails! Use $this->redirectEmails()');
  2920. // Test that an empty noreplyaddress will default to a no-reply address.
  2921. $sink = $this->redirectEmails();
  2922. email_to_user($user1, $user3, $subject, $messagetext);
  2923. $result = $sink->get_messages();
  2924. $this->assertEquals($CFG->noreplyaddress, $result[0]->from);
  2925. $sink->close();
  2926. set_config('noreplyaddress', '');
  2927. $sink = $this->redirectEmails();
  2928. email_to_user($user1, $user3, $subject, $messagetext);
  2929. $result = $sink->get_messages();
  2930. $this->assertEquals('noreply@www.example.com', $result[0]->from);
  2931. $sink->close();
  2932. // Test $CFG->allowedemaildomains.
  2933. set_config('noreplyaddress', 'noreply@www.example.com');
  2934. $this->assertNotEmpty($CFG->allowedemaildomains);
  2935. $sink = $this->redirectEmails();
  2936. email_to_user($user1, $user2, $subject, $messagetext);
  2937. unset_config('allowedemaildomains');
  2938. email_to_user($user1, $user2, $subject, $messagetext);
  2939. $result = $sink->get_messages();
  2940. $this->assertNotEquals($CFG->noreplyaddress, $result[0]->from);
  2941. $this->assertEquals($CFG->noreplyaddress, $result[1]->from);
  2942. $sink->close();
  2943. // Try to send an unsafe attachment, we should see an error message in the eventual mail body.
  2944. $attachment = '../test.txt';
  2945. $attachname = 'txt';
  2946. $sink = $this->redirectEmails();
  2947. email_to_user($user1, $user2, $subject, $messagetext, '', $attachment, $attachname);
  2948. $this->assertSame(1, $sink->count());
  2949. $result = $sink->get_messages();
  2950. $this->assertCount(1, $result);
  2951. $this->assertContains('error.txt', $result[0]->body);
  2952. $this->assertContains('Error in attachment. User attempted to attach a filename with a unsafe name.', $result[0]->body);
  2953. $sink->close();
  2954. }
  2955. /**
  2956. * Data provider for {@see test_email_to_user_attachment}
  2957. *
  2958. * @return array
  2959. */
  2960. public function email_to_user_attachment_provider(): array {
  2961. global $CFG;
  2962. // Return all paths that can be used to send attachments from.
  2963. return [
  2964. 'cachedir' => [$CFG->cachedir],
  2965. 'dataroot' => [$CFG->dataroot],
  2966. 'dirroot' => [$CFG->dirroot],
  2967. 'localcachedir' => [$CFG->localcachedir],
  2968. 'tempdir' => [$CFG->tempdir],
  2969. // Pass null to indicate we want to test a path relative to $CFG->dataroot.
  2970. 'relative' => [null]
  2971. ];
  2972. }
  2973. /**
  2974. * Test sending attachments with email_to_user
  2975. *
  2976. * @param string|null $filedir
  2977. *
  2978. * @dataProvider email_to_user_attachment_provider
  2979. */
  2980. public function test_email_to_user_attachment(?string $filedir): void {
  2981. global $CFG;
  2982. // If $filedir is null, then write our test file to $CFG->dataroot.
  2983. $filepath = ($filedir ?: $CFG->dataroot) . '/hello.txt';
  2984. file_put_contents($filepath, 'Hello');
  2985. $user = core_user::get_support_user();
  2986. $message = 'Test attachment path';
  2987. // Create sink to catch all sent e-mails.
  2988. $sink = $this->redirectEmails();
  2989. // Attachment path will be that of the test file if $filedir was passed, otherwise the relative path from $CFG->dataroot.
  2990. $filename = basename($filepath);
  2991. $attachmentpath = $filedir ? $filepath : $filename;
  2992. email_to_user($user, $user, $message, $message, $message, $attachmentpath, $filename);
  2993. $messages = $sink->get_messages();
  2994. $sink->close();
  2995. $this->assertCount(1, $messages);
  2996. // Verify attachment in message body (attachment is in MIME format, but we can detect some Content fields).
  2997. $messagebody = reset($messages)->body;
  2998. $this->assertContains('Content-Type: text/plain; name="' . $filename . '"', $messagebody);
  2999. $this->assertContains('Content-Disposition: attachment; filename=' . $filename, $messagebody);
  3000. // Cleanup.
  3001. unlink($filepath);
  3002. }
  3003. /**
  3004. * Test sending an attachment that doesn't exist to email_to_user
  3005. */
  3006. public function test_email_to_user_attachment_missing(): void {
  3007. $user = core_user::get_support_user();
  3008. $message = 'Test attachment path';
  3009. // Create sink to catch all sent e-mails.
  3010. $sink = $this->redirectEmails();
  3011. $attachmentpath = '/hola/hello.txt';
  3012. $filename = basename($attachmentpath);
  3013. email_to_user($user, $user, $message, $message, $message, $attachmentpath, $filename);
  3014. $messages = $sink->get_messages();
  3015. $sink->close();
  3016. $this->assertCount(1, $messages);
  3017. // Verify attachment not in message body (attachment is in MIME format, but we can detect some Content fields).
  3018. $messagebody = reset($messages)->body;
  3019. $this->assertNotContains('Content-Type: text/plain; name="' . $filename . '"', $messagebody);
  3020. $this->assertNotContains('Content-Disposition: attachment; filename=' . $filename, $messagebody);
  3021. }
  3022. /**
  3023. * Test setnew_password_and_mail.
  3024. */
  3025. public function test_setnew_password_and_mail() {
  3026. global $DB, $CFG;
  3027. $this->resetAfterTest();
  3028. $user = $this->getDataGenerator()->create_user();
  3029. // Update user password.
  3030. $sink = $this->redirectEvents();
  3031. $sink2 = $this->redirectEmails(); // Make sure we are redirecting emails.
  3032. setnew_password_and_mail($user);
  3033. $events = $sink->get_events();
  3034. $sink->close();
  3035. $sink2->close();
  3036. $event = array_pop($events);
  3037. // Test updated value.
  3038. $dbuser = $DB->get_record('user', array('id' => $user->id));
  3039. $this->assertSame($user->firstname, $dbuser->firstname);
  3040. $this->assertNotEmpty($dbuser->password);
  3041. // Test event.
  3042. $this->assertInstanceOf('\core\event\user_password_updated', $event);
  3043. $this->assertSame($user->id, $event->relateduserid);
  3044. $this->assertEquals(context_user::instance($user->id), $event->get_context());
  3045. $this->assertEventContextNotUsed($event);
  3046. }
  3047. /**
  3048. * Data provider for test_generate_confirmation_link
  3049. * @return Array of confirmation urls and expected resultant confirmation links
  3050. */
  3051. public function generate_confirmation_link_provider() {
  3052. global $CFG;
  3053. return [
  3054. "Simple name" => [
  3055. "username" => "simplename",
  3056. "confirmationurl" => null,
  3057. "expected" => $CFG->wwwroot . "/login/confirm.php?data=/simplename"
  3058. ],
  3059. "Period in between words in username" => [
  3060. "username" => "period.inbetween",
  3061. "confirmationurl" => null,
  3062. "expected" => $CFG->wwwroot . "/login/confirm.php?data=/period%2Einbetween"
  3063. ],
  3064. "Trailing periods in username" => [
  3065. "username" => "trailingperiods...",
  3066. "confirmationurl" => null,
  3067. "expected" => $CFG->wwwroot . "/login/confirm.php?data=/trailingperiods%2E%2E%2E"
  3068. ],
  3069. "At symbol in username" => [
  3070. "username" => "at@symbol",
  3071. "confirmationurl" => null,
  3072. "expected" => $CFG->wwwroot . "/login/confirm.php?data=/at%40symbol"
  3073. ],
  3074. "Dash symbol in username" => [
  3075. "username" => "has-dash",
  3076. "confirmationurl" => null,
  3077. "expected" => $CFG->wwwroot . "/login/confirm.php?data=/has-dash"
  3078. ],
  3079. "Underscore in username" => [
  3080. "username" => "under_score",
  3081. "confirmationurl" => null,
  3082. "expected" => $CFG->wwwroot . "/login/confirm.php?data=/under_score"
  3083. ],
  3084. "Many different characters in username" => [
  3085. "username" => "many_-.@characters@_@-..-..",
  3086. "confirmationurl" => null,
  3087. "expected" => $CFG->wwwroot . "/login/confirm.php?data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E"
  3088. ],
  3089. "Custom relative confirmation url" => [
  3090. "username" => "many_-.@characters@_@-..-..",
  3091. "confirmationurl" => "/custom/local/url.php",
  3092. "expected" => $CFG->wwwroot . "/custom/local/url.php?data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E"
  3093. ],
  3094. "Custom relative confirmation url with parameters" => [
  3095. "username" => "many_-.@characters@_@-..-..",
  3096. "confirmationurl" => "/custom/local/url.php?with=param",
  3097. "expected" => $CFG->wwwroot . "/custom/local/url.php?with=param&data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E"
  3098. ],
  3099. "Custom local confirmation url" => [
  3100. "username" => "many_-.@characters@_@-..-..",
  3101. "confirmationurl" => $CFG->wwwroot . "/custom/local/url.php",
  3102. "expected" => $CFG->wwwroot . "/custom/local/url.php?data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E"
  3103. ],
  3104. "Custom local confirmation url with parameters" => [
  3105. "username" => "many_-.@characters@_@-..-..",
  3106. "confirmationurl" => $CFG->wwwroot . "/custom/local/url.php?with=param",
  3107. "expected" => $CFG->wwwroot . "/custom/local/url.php?with=param&data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E"
  3108. ],
  3109. "Custom external confirmation url" => [
  3110. "username" => "many_-.@characters@_@-..-..",
  3111. "confirmationurl" => "http://moodle.org/custom/external/url.php",
  3112. "expected" => "http://moodle.org/custom/external/url.php?data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E"
  3113. ],
  3114. "Custom external confirmation url with parameters" => [
  3115. "username" => "many_-.@characters@_@-..-..",
  3116. "confirmationurl" => "http://moodle.org/ext.php?with=some&param=eters",
  3117. "expected" => "http://moodle.org/ext.php?with=some&param=eters&data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E"
  3118. ],
  3119. "Custom external confirmation url with parameters" => [
  3120. "username" => "many_-.@characters@_@-..-..",
  3121. "confirmationurl" => "http://moodle.org/ext.php?with=some&data=test",
  3122. "expected" => "http://moodle.org/ext.php?with=some&data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E"
  3123. ],
  3124. ];
  3125. }
  3126. /**
  3127. * Test generate_confirmation_link
  3128. * @dataProvider generate_confirmation_link_provider
  3129. * @param string $username The name of the user
  3130. * @param string $confirmationurl The url the user should go to to confirm
  3131. * @param string $expected The expected url of the confirmation link
  3132. */
  3133. public function test_generate_confirmation_link($username, $confirmationurl, $expected) {
  3134. $this->resetAfterTest();
  3135. $sink = $this->redirectEmails();
  3136. $user = $this->getDataGenerator()->create_user(
  3137. [
  3138. "username" => $username,
  3139. "confirmed" => 0,
  3140. "email" => 'test@example.com',
  3141. ]
  3142. );
  3143. send_confirmation_email($user, $confirmationurl);
  3144. $sink->close();
  3145. $messages = $sink->get_messages();
  3146. $message = array_shift($messages);
  3147. $messagebody = quoted_printable_decode($message->body);
  3148. $this->assertContains($expected, $messagebody);
  3149. }
  3150. /**
  3151. * Test generate_confirmation_link with custom admin link
  3152. */
  3153. public function test_generate_confirmation_link_with_custom_admin() {
  3154. global $CFG;
  3155. $this->resetAfterTest();
  3156. $sink = $this->redirectEmails();
  3157. $admin = $CFG->admin;
  3158. $CFG->admin = 'custom/admin/path';
  3159. $user = $this->getDataGenerator()->create_user(
  3160. [
  3161. "username" => "many_-.@characters@_@-..-..",
  3162. "confirmed" => 0,
  3163. "email" => 'test@example.com',
  3164. ]
  3165. );
  3166. $confirmationurl = "/admin/test.php?with=params";
  3167. $expected = $CFG->wwwroot . "/" . $CFG->admin . "/test.php?with=params&data=/many_-%2E%40characters%40_%40-%2E%2E-%2E%2E";
  3168. send_confirmation_email($user, $confirmationurl);
  3169. $sink->close();
  3170. $messages = $sink->get_messages();
  3171. $message = array_shift($messages);
  3172. $messagebody = quoted_printable_decode($message->body);
  3173. $sink->close();
  3174. $this->assertContains($expected, $messagebody);
  3175. $CFG->admin = $admin;
  3176. }
  3177. /**
  3178. * Test remove_course_content deletes course contents
  3179. * TODO Add asserts to verify other data related to course is deleted as well.
  3180. */
  3181. public function test_remove_course_contents() {
  3182. $this->resetAfterTest();
  3183. $course = $this->getDataGenerator()->create_course();
  3184. $user = $this->getDataGenerator()->create_user();
  3185. $gen = $this->getDataGenerator()->get_plugin_generator('core_notes');
  3186. $note = $gen->create_instance(array('courseid' => $course->id, 'userid' => $user->id));
  3187. $this->assertNotEquals(false, note_load($note->id));
  3188. remove_course_contents($course->id, false);
  3189. $this->assertFalse(note_load($note->id));
  3190. }
  3191. /**
  3192. * Test function username_load_fields_from_object().
  3193. */
  3194. public function test_username_load_fields_from_object() {
  3195. $this->resetAfterTest();
  3196. // This object represents the information returned from an sql query.
  3197. $userinfo = new stdClass();
  3198. $userinfo->userid = 1;
  3199. $userinfo->username = 'loosebruce';
  3200. $userinfo->firstname = 'Bruce';
  3201. $userinfo->lastname = 'Campbell';
  3202. $userinfo->firstnamephonetic = 'ブルース';
  3203. $userinfo->lastnamephonetic = 'カンベッル';
  3204. $userinfo->middlename = '';
  3205. $userinfo->alternatename = '';
  3206. $userinfo->email = '';
  3207. $userinfo->picture = 23;
  3208. $userinfo->imagealt = 'Michael Jordan draining another basket.';
  3209. $userinfo->idnumber = 3982;
  3210. // Just user name fields.
  3211. $user = new stdClass();
  3212. $user = username_load_fields_from_object($user, $userinfo);
  3213. $expectedarray = new stdClass();
  3214. $expectedarray->firstname = 'Bruce';
  3215. $expectedarray->lastname = 'Campbell';
  3216. $expectedarray->firstnamephonetic = 'ブルース';
  3217. $expectedarray->lastnamephonetic = 'カンベッル';
  3218. $expectedarray->middlename = '';
  3219. $expectedarray->alternatename = '';
  3220. $this->assertEquals($user, $expectedarray);
  3221. // User information for showing a picture.
  3222. $user = new stdClass();
  3223. $additionalfields = explode(',', user_picture::fields());
  3224. $user = username_load_fields_from_object($user, $userinfo, null, $additionalfields);
  3225. $user->id = $userinfo->userid;
  3226. $expectedarray = new stdClass();
  3227. $expectedarray->id = 1;
  3228. $expectedarray->firstname = 'Bruce';
  3229. $expectedarray->lastname = 'Campbell';
  3230. $expectedarray->firstnamephonetic = 'ブルース';
  3231. $expectedarray->lastnamephonetic = 'カンベッル';
  3232. $expectedarray->middlename = '';
  3233. $expectedarray->alternatename = '';
  3234. $expectedarray->email = '';
  3235. $expectedarray->picture = 23;
  3236. $expectedarray->imagealt = 'Michael Jordan draining another basket.';
  3237. $this->assertEquals($user, $expectedarray);
  3238. // Alter the userinfo object to have a prefix.
  3239. $userinfo->authorfirstname = 'Bruce';
  3240. $userinfo->authorlastname = 'Campbell';
  3241. $userinfo->authorfirstnamephonetic = 'ブルース';
  3242. $userinfo->authorlastnamephonetic = 'カンベッル';
  3243. $userinfo->authormiddlename = '';
  3244. $userinfo->authorpicture = 23;
  3245. $userinfo->authorimagealt = 'Michael Jordan draining another basket.';
  3246. $userinfo->authoremail = 'test@example.com';
  3247. // Return an object with user picture information.
  3248. $user = new stdClass();
  3249. $additionalfields = explode(',', user_picture::fields());
  3250. $user = username_load_fields_from_object($user, $userinfo, 'author', $additionalfields);
  3251. $user->id = $userinfo->userid;
  3252. $expectedarray = new stdClass();
  3253. $expectedarray->id = 1;
  3254. $expectedarray->firstname = 'Bruce';
  3255. $expectedarray->lastname = 'Campbell';
  3256. $expectedarray->firstnamephonetic = 'ブルース';
  3257. $expectedarray->lastnamephonetic = 'カンベッル';
  3258. $expectedarray->middlename = '';
  3259. $expectedarray->alternatename = '';
  3260. $expectedarray->email = 'test@example.com';
  3261. $expectedarray->picture = 23;
  3262. $expectedarray->imagealt = 'Michael Jordan draining another basket.';
  3263. $this->assertEquals($user, $expectedarray);
  3264. }
  3265. /**
  3266. * Test function count_words().
  3267. */
  3268. public function test_count_words() {
  3269. $count = count_words("one two three'four");
  3270. $this->assertEquals(3, $count);
  3271. $count = count_words('one+two three’four');
  3272. $this->assertEquals(3, $count);
  3273. $count = count_words('one"two three-four');
  3274. $this->assertEquals(2, $count);
  3275. $count = count_words('one@two three_four');
  3276. $this->assertEquals(4, $count);
  3277. $count = count_words('one\two three/four');
  3278. $this->assertEquals(4, $count);
  3279. $count = count_words(' one ... two &nbsp; three...four ');
  3280. $this->assertEquals(4, $count);
  3281. $count = count_words('one.2 3,four');
  3282. $this->assertEquals(4, $count);
  3283. $count = count_words('1³ £2 €3.45 $6,789');
  3284. $this->assertEquals(4, $count);
  3285. $count = count_words('one—two ブルース カンベッル');
  3286. $this->assertEquals(4, $count);
  3287. $count = count_words('one…two ブルース … カンベッル');
  3288. $this->assertEquals(4, $count);
  3289. }
  3290. /**
  3291. * Tests the getremoteaddr() function.
  3292. */
  3293. public function test_getremoteaddr() {
  3294. global $CFG;
  3295. $this->resetAfterTest();
  3296. $CFG->getremoteaddrconf = GETREMOTEADDR_SKIP_HTTP_CLIENT_IP;
  3297. $xforwardedfor = isset($_SERVER['HTTP_X_FORWARDED_FOR']) ? $_SERVER['HTTP_X_FORWARDED_FOR'] : null;
  3298. $_SERVER['HTTP_X_FORWARDED_FOR'] = '';
  3299. $noip = getremoteaddr('1.1.1.1');
  3300. $this->assertEquals('1.1.1.1', $noip);
  3301. $_SERVER['HTTP_X_FORWARDED_FOR'] = '';
  3302. $noip = getremoteaddr();
  3303. $this->assertEquals('0.0.0.0', $noip);
  3304. $_SERVER['HTTP_X_FORWARDED_FOR'] = '127.0.0.1';
  3305. $singleip = getremoteaddr();
  3306. $this->assertEquals('127.0.0.1', $singleip);
  3307. $_SERVER['HTTP_X_FORWARDED_FOR'] = '127.0.0.1,127.0.0.2';
  3308. $twoip = getremoteaddr();
  3309. $this->assertEquals('127.0.0.2', $twoip);
  3310. $_SERVER['HTTP_X_FORWARDED_FOR'] = '127.0.0.1,127.0.0.2,127.0.0.3';
  3311. $threeip = getremoteaddr();
  3312. $this->assertEquals('127.0.0.3', $threeip);
  3313. $_SERVER['HTTP_X_FORWARDED_FOR'] = '127.0.0.1,127.0.0.2:65535';
  3314. $portip = getremoteaddr();
  3315. $this->assertEquals('127.0.0.2', $portip);
  3316. $_SERVER['HTTP_X_FORWARDED_FOR'] = '127.0.0.1,0:0:0:0:0:0:0:2';
  3317. $portip = getremoteaddr();
  3318. $this->assertEquals('0:0:0:0:0:0:0:2', $portip);
  3319. $_SERVER['HTTP_X_FORWARDED_FOR'] = '127.0.0.1,0::2';
  3320. $portip = getremoteaddr();
  3321. $this->assertEquals('0:0:0:0:0:0:0:2', $portip);
  3322. $_SERVER['HTTP_X_FORWARDED_FOR'] = '127.0.0.1,[0:0:0:0:0:0:0:2]:65535';
  3323. $portip = getremoteaddr();
  3324. $this->assertEquals('0:0:0:0:0:0:0:2', $portip);
  3325. $_SERVER['HTTP_X_FORWARDED_FOR'] = $xforwardedfor;
  3326. }
  3327. /*
  3328. * Test emulation of random_bytes() function.
  3329. */
  3330. public function test_random_bytes_emulate() {
  3331. $result = random_bytes_emulate(10);
  3332. $this->assertSame(10, strlen($result));
  3333. $this->assertnotSame($result, random_bytes_emulate(10));
  3334. $result = random_bytes_emulate(21);
  3335. $this->assertSame(21, strlen($result));
  3336. $this->assertnotSame($result, random_bytes_emulate(21));
  3337. $result = random_bytes_emulate(666);
  3338. $this->assertSame(666, strlen($result));
  3339. $result = random_bytes_emulate(40);
  3340. $this->assertSame(40, strlen($result));
  3341. $this->assertDebuggingNotCalled();
  3342. $result = random_bytes_emulate(0);
  3343. $this->assertSame('', $result);
  3344. $this->assertDebuggingCalled();
  3345. $result = random_bytes_emulate(-1);
  3346. $this->assertSame('', $result);
  3347. $this->assertDebuggingCalled();
  3348. }
  3349. /**
  3350. * Test function for creation of random strings.
  3351. */
  3352. public function test_random_string() {
  3353. $pool = 'a-zA-Z0-9';
  3354. $result = random_string(10);
  3355. $this->assertSame(10, strlen($result));
  3356. $this->assertRegExp('/^[' . $pool . ']+$/', $result);
  3357. $this->assertNotSame($result, random_string(10));
  3358. $result = random_string(21);
  3359. $this->assertSame(21, strlen($result));
  3360. $this->assertRegExp('/^[' . $pool . ']+$/', $result);
  3361. $this->assertNotSame($result, random_string(21));
  3362. $result = random_string(666);
  3363. $this->assertSame(666, strlen($result));
  3364. $this->assertRegExp('/^[' . $pool . ']+$/', $result);
  3365. $result = random_string();
  3366. $this->assertSame(15, strlen($result));
  3367. $this->assertRegExp('/^[' . $pool . ']+$/', $result);
  3368. $this->assertDebuggingNotCalled();
  3369. $result = random_string(0);
  3370. $this->assertSame('', $result);
  3371. $this->assertDebuggingCalled();
  3372. $result = random_string(-1);
  3373. $this->assertSame('', $result);
  3374. $this->assertDebuggingCalled();
  3375. }
  3376. /**
  3377. * Test function for creation of complex random strings.
  3378. */
  3379. public function test_complex_random_string() {
  3380. $pool = preg_quote('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789`~!@#%^&*()_+-=[];,./<>?:{} ', '/');
  3381. $result = complex_random_string(10);
  3382. $this->assertSame(10, strlen($result));
  3383. $this->assertRegExp('/^[' . $pool . ']+$/', $result);
  3384. $this->assertNotSame($result, complex_random_string(10));
  3385. $result = complex_random_string(21);
  3386. $this->assertSame(21, strlen($result));
  3387. $this->assertRegExp('/^[' . $pool . ']+$/', $result);
  3388. $this->assertNotSame($result, complex_random_string(21));
  3389. $result = complex_random_string(666);
  3390. $this->assertSame(666, strlen($result));
  3391. $this->assertRegExp('/^[' . $pool . ']+$/', $result);
  3392. $result = complex_random_string();
  3393. $this->assertEquals(28, strlen($result), '', 4); // Expected length is 24 - 32.
  3394. $this->assertRegExp('/^[' . $pool . ']+$/', $result);
  3395. $this->assertDebuggingNotCalled();
  3396. $result = complex_random_string(0);
  3397. $this->assertSame('', $result);
  3398. $this->assertDebuggingCalled();
  3399. $result = complex_random_string(-1);
  3400. $this->assertSame('', $result);
  3401. $this->assertDebuggingCalled();
  3402. }
  3403. /**
  3404. * Data provider for private ips.
  3405. */
  3406. public function data_private_ips() {
  3407. return array(
  3408. array('10.0.0.0'),
  3409. array('172.16.0.0'),
  3410. array('192.168.1.0'),
  3411. array('fdfe:dcba:9876:ffff:fdc6:c46b:bb8f:7d4c'),
  3412. array('fdc6:c46b:bb8f:7d4c:fdc6:c46b:bb8f:7d4c'),
  3413. array('fdc6:c46b:bb8f:7d4c:0000:8a2e:0370:7334'),
  3414. array('127.0.0.1'), // This has been buggy in past: https://bugs.php.net/bug.php?id=53150.
  3415. );
  3416. }
  3417. /**
  3418. * Checks ip_is_public returns false for private ips.
  3419. *
  3420. * @param string $ip the ipaddress to test
  3421. * @dataProvider data_private_ips
  3422. */
  3423. public function test_ip_is_public_private_ips($ip) {
  3424. $this->assertFalse(ip_is_public($ip));
  3425. }
  3426. /**
  3427. * Data provider for public ips.
  3428. */
  3429. public function data_public_ips() {
  3430. return array(
  3431. array('2400:cb00:2048:1::8d65:71b3'),
  3432. array('2400:6180:0:d0::1b:2001'),
  3433. array('141.101.113.179'),
  3434. array('123.45.67.178'),
  3435. );
  3436. }
  3437. /**
  3438. * Checks ip_is_public returns true for public ips.
  3439. *
  3440. * @param string $ip the ipaddress to test
  3441. * @dataProvider data_public_ips
  3442. */
  3443. public function test_ip_is_public_public_ips($ip) {
  3444. $this->assertTrue(ip_is_public($ip));
  3445. }
  3446. /**
  3447. * Test the function can_send_from_real_email_address
  3448. *
  3449. * @param string $email Email address for the from user.
  3450. * @param int $display The user's email display preference.
  3451. * @param bool $samecourse Are the users in the same course?
  3452. * @param string $config The CFG->allowedemaildomains config values
  3453. * @param bool $result The expected result.
  3454. * @dataProvider data_can_send_from_real_email_address
  3455. */
  3456. public function test_can_send_from_real_email_address($email, $display, $samecourse, $config, $result) {
  3457. $this->resetAfterTest();
  3458. $fromuser = $this->getDataGenerator()->create_user();
  3459. $touser = $this->getDataGenerator()->create_user();
  3460. $course = $this->getDataGenerator()->create_course();
  3461. set_config('allowedemaildomains', $config);
  3462. $fromuser->email = $email;
  3463. $fromuser->maildisplay = $display;
  3464. if ($samecourse) {
  3465. $this->getDataGenerator()->enrol_user($fromuser->id, $course->id, 'student');
  3466. $this->getDataGenerator()->enrol_user($touser->id, $course->id, 'student');
  3467. } else {
  3468. $this->getDataGenerator()->enrol_user($fromuser->id, $course->id, 'student');
  3469. }
  3470. $this->assertEquals($result, can_send_from_real_email_address($fromuser, $touser));
  3471. }
  3472. /**
  3473. * Data provider for test_can_send_from_real_email_address.
  3474. *
  3475. * @return array Returns an array of test data for the above function.
  3476. */
  3477. public function data_can_send_from_real_email_address() {
  3478. return [
  3479. // Test from email is in allowed domain.
  3480. // Test that from display is set to show no one.
  3481. [
  3482. 'email' => 'fromuser@example.com',
  3483. 'display' => core_user::MAILDISPLAY_HIDE,
  3484. 'samecourse' => false,
  3485. 'config' => "example.com\r\ntest.com",
  3486. 'result' => false
  3487. ],
  3488. // Test that from display is set to course members only (course member).
  3489. [
  3490. 'email' => 'fromuser@example.com',
  3491. 'display' => core_user::MAILDISPLAY_COURSE_MEMBERS_ONLY,
  3492. 'samecourse' => true,
  3493. 'config' => "example.com\r\ntest.com",
  3494. 'result' => true
  3495. ],
  3496. // Test that from display is set to course members only (Non course member).
  3497. [
  3498. 'email' => 'fromuser@example.com',
  3499. 'display' => core_user::MAILDISPLAY_COURSE_MEMBERS_ONLY,
  3500. 'samecourse' => false,
  3501. 'config' => "example.com\r\ntest.com",
  3502. 'result' => false
  3503. ],
  3504. // Test that from display is set to show everyone.
  3505. [
  3506. 'email' => 'fromuser@example.com',
  3507. 'display' => core_user::MAILDISPLAY_EVERYONE,
  3508. 'samecourse' => false,
  3509. 'config' => "example.com\r\ntest.com",
  3510. 'result' => true
  3511. ],
  3512. // Test a few different config value formats for parsing correctness.
  3513. [
  3514. 'email' => 'fromuser@example.com',
  3515. 'display' => core_user::MAILDISPLAY_EVERYONE,
  3516. 'samecourse' => false,
  3517. 'config' => "\n test.com\nexample.com \n",
  3518. 'result' => true
  3519. ],
  3520. [
  3521. 'email' => 'fromuser@example.com',
  3522. 'display' => core_user::MAILDISPLAY_EVERYONE,
  3523. 'samecourse' => false,
  3524. 'config' => "\r\n example.com \r\n test.com \r\n",
  3525. 'result' => true
  3526. ],
  3527. // Test from email is not in allowed domain.
  3528. // Test that from display is set to show no one.
  3529. [ 'email' => 'fromuser@moodle.com',
  3530. 'display' => core_user::MAILDISPLAY_HIDE,
  3531. 'samecourse' => false,
  3532. 'config' => "example.com\r\ntest.com",
  3533. 'result' => false
  3534. ],
  3535. // Test that from display is set to course members only (course member).
  3536. [ 'email' => 'fromuser@moodle.com',
  3537. 'display' => core_user::MAILDISPLAY_COURSE_MEMBERS_ONLY,
  3538. 'samecourse' => true,
  3539. 'config' => "example.com\r\ntest.com",
  3540. 'result' => false
  3541. ],
  3542. // Test that from display is set to course members only (Non course member.
  3543. [ 'email' => 'fromuser@moodle.com',
  3544. 'display' => core_user::MAILDISPLAY_COURSE_MEMBERS_ONLY,
  3545. 'samecourse' => false,
  3546. 'config' => "example.com\r\ntest.com",
  3547. 'result' => false
  3548. ],
  3549. // Test that from display is set to show everyone.
  3550. [ 'email' => 'fromuser@moodle.com',
  3551. 'display' => core_user::MAILDISPLAY_EVERYONE,
  3552. 'samecourse' => false,
  3553. 'config' => "example.com\r\ntest.com",
  3554. 'result' => false
  3555. ],
  3556. // Test a few erroneous config value and confirm failure.
  3557. [ 'email' => 'fromuser@moodle.com',
  3558. 'display' => core_user::MAILDISPLAY_EVERYONE,
  3559. 'samecourse' => false,
  3560. 'config' => "\r\n \r\n",
  3561. 'result' => false
  3562. ],
  3563. [ 'email' => 'fromuser@moodle.com',
  3564. 'display' => core_user::MAILDISPLAY_EVERYONE,
  3565. 'samecourse' => false,
  3566. 'config' => " \n \n \n ",
  3567. 'result' => false
  3568. ],
  3569. ];
  3570. }
  3571. /**
  3572. * Test that generate_email_processing_address() returns valid email address.
  3573. */
  3574. public function test_generate_email_processing_address() {
  3575. global $CFG;
  3576. $this->resetAfterTest();
  3577. $data = (object)[
  3578. 'id' => 42,
  3579. 'email' => 'my.email+from_moodle@example.com',
  3580. ];
  3581. $modargs = 'B'.base64_encode(pack('V', $data->id)).substr(md5($data->email), 0, 16);
  3582. $CFG->maildomain = 'example.com';
  3583. $CFG->mailprefix = 'mdl+';
  3584. $this->assertTrue(validate_email(generate_email_processing_address(0, $modargs)));
  3585. $CFG->maildomain = 'mail.example.com';
  3586. $CFG->mailprefix = 'mdl-';
  3587. $this->assertTrue(validate_email(generate_email_processing_address(23, $modargs)));
  3588. }
  3589. /**
  3590. * Test allowemailaddresses setting.
  3591. *
  3592. * @param string $email Email address for the from user.
  3593. * @param string $config The CFG->allowemailaddresses config values
  3594. * @param false/string $result The expected result.
  3595. *
  3596. * @dataProvider data_email_is_not_allowed_for_allowemailaddresses
  3597. */
  3598. public function test_email_is_not_allowed_for_allowemailaddresses($email, $config, $result) {
  3599. $this->resetAfterTest();
  3600. set_config('allowemailaddresses', $config);
  3601. $this->assertEquals($result, email_is_not_allowed($email));
  3602. }
  3603. /**
  3604. * Data provider for data_email_is_not_allowed_for_allowemailaddresses.
  3605. *
  3606. * @return array Returns an array of test data for the above function.
  3607. */
  3608. public function data_email_is_not_allowed_for_allowemailaddresses() {
  3609. return [
  3610. // Test allowed domain empty list.
  3611. [
  3612. 'email' => 'fromuser@example.com',
  3613. 'config' => '',
  3614. 'result' => false
  3615. ],
  3616. // Test from email is in allowed domain.
  3617. [
  3618. 'email' => 'fromuser@example.com',
  3619. 'config' => 'example.com test.com',
  3620. 'result' => false
  3621. ],
  3622. // Test from email is in allowed domain but uppercase config.
  3623. [
  3624. 'email' => 'fromuser@example.com',
  3625. 'config' => 'EXAMPLE.com test.com',
  3626. 'result' => false
  3627. ],
  3628. // Test from email is in allowed domain but uppercase email.
  3629. [
  3630. 'email' => 'fromuser@EXAMPLE.com',
  3631. 'config' => 'example.com test.com',
  3632. 'result' => false
  3633. ],
  3634. // Test from email is in allowed subdomain.
  3635. [
  3636. 'email' => 'fromuser@something.example.com',
  3637. 'config' => '.example.com test.com',
  3638. 'result' => false
  3639. ],
  3640. // Test from email is in allowed subdomain but uppercase config.
  3641. [
  3642. 'email' => 'fromuser@something.example.com',
  3643. 'config' => '.EXAMPLE.com test.com',
  3644. 'result' => false
  3645. ],
  3646. // Test from email is in allowed subdomain but uppercase email.
  3647. [
  3648. 'email' => 'fromuser@something.EXAMPLE.com',
  3649. 'config' => '.example.com test.com',
  3650. 'result' => false
  3651. ],
  3652. // Test from email is not in allowed domain.
  3653. [ 'email' => 'fromuser@moodle.com',
  3654. 'config' => 'example.com test.com',
  3655. 'result' => get_string('emailonlyallowed', '', 'example.com test.com')
  3656. ],
  3657. // Test from email is not in allowed subdomain.
  3658. [ 'email' => 'fromuser@something.example.com',
  3659. 'config' => 'example.com test.com',
  3660. 'result' => get_string('emailonlyallowed', '', 'example.com test.com')
  3661. ],
  3662. ];
  3663. }
  3664. /**
  3665. * Test denyemailaddresses setting.
  3666. *
  3667. * @param string $email Email address for the from user.
  3668. * @param string $config The CFG->denyemailaddresses config values
  3669. * @param false/string $result The expected result.
  3670. *
  3671. * @dataProvider data_email_is_not_allowed_for_denyemailaddresses
  3672. */
  3673. public function test_email_is_not_allowed_for_denyemailaddresses($email, $config, $result) {
  3674. $this->resetAfterTest();
  3675. set_config('denyemailaddresses', $config);
  3676. $this->assertEquals($result, email_is_not_allowed($email));
  3677. }
  3678. /**
  3679. * Data provider for test_email_is_not_allowed_for_denyemailaddresses.
  3680. *
  3681. * @return array Returns an array of test data for the above function.
  3682. */
  3683. public function data_email_is_not_allowed_for_denyemailaddresses() {
  3684. return [
  3685. // Test denied domain empty list.
  3686. [
  3687. 'email' => 'fromuser@example.com',
  3688. 'config' => '',
  3689. 'result' => false
  3690. ],
  3691. // Test from email is in denied domain.
  3692. [
  3693. 'email' => 'fromuser@example.com',
  3694. 'config' => 'example.com test.com',
  3695. 'result' => get_string('emailnotallowed', '', 'example.com test.com')
  3696. ],
  3697. // Test from email is in denied domain but uppercase config.
  3698. [
  3699. 'email' => 'fromuser@example.com',
  3700. 'config' => 'EXAMPLE.com test.com',
  3701. 'result' => get_string('emailnotallowed', '', 'EXAMPLE.com test.com')
  3702. ],
  3703. // Test from email is in denied domain but uppercase email.
  3704. [
  3705. 'email' => 'fromuser@EXAMPLE.com',
  3706. 'config' => 'example.com test.com',
  3707. 'result' => get_string('emailnotallowed', '', 'example.com test.com')
  3708. ],
  3709. // Test from email is in denied subdomain.
  3710. [
  3711. 'email' => 'fromuser@something.example.com',
  3712. 'config' => '.example.com test.com',
  3713. 'result' => get_string('emailnotallowed', '', '.example.com test.com')
  3714. ],
  3715. // Test from email is in denied subdomain but uppercase config.
  3716. [
  3717. 'email' => 'fromuser@something.example.com',
  3718. 'config' => '.EXAMPLE.com test.com',
  3719. 'result' => get_string('emailnotallowed', '', '.EXAMPLE.com test.com')
  3720. ],
  3721. // Test from email is in denied subdomain but uppercase email.
  3722. [
  3723. 'email' => 'fromuser@something.EXAMPLE.com',
  3724. 'config' => '.example.com test.com',
  3725. 'result' => get_string('emailnotallowed', '', '.example.com test.com')
  3726. ],
  3727. // Test from email is not in denied domain.
  3728. [ 'email' => 'fromuser@moodle.com',
  3729. 'config' => 'example.com test.com',
  3730. 'result' => false
  3731. ],
  3732. // Test from email is not in denied subdomain.
  3733. [ 'email' => 'fromuser@something.example.com',
  3734. 'config' => 'example.com test.com',
  3735. 'result' => false
  3736. ],
  3737. ];
  3738. }
  3739. /**
  3740. * Test safe method unserialize_array().
  3741. */
  3742. public function test_unserialize_array() {
  3743. $a = [1, 2, 3];
  3744. $this->assertEquals($a, unserialize_array(serialize($a)));
  3745. $this->assertEquals($a, unserialize_array(serialize($a)));
  3746. $a = ['a' => 1, 2 => 2, 'b' => 'cde'];
  3747. $this->assertEquals($a, unserialize_array(serialize($a)));
  3748. $this->assertEquals($a, unserialize_array(serialize($a)));
  3749. $a = ['a' => 1, 2 => 2, 'b' => 'c"d"e'];
  3750. $this->assertEquals($a, unserialize_array(serialize($a)));
  3751. $a = ['a' => 1, 2 => ['c' => 'd', 'e' => 'f'], 'b' => 'cde'];
  3752. $this->assertEquals($a, unserialize_array(serialize($a)));
  3753. // Can not unserialize if any string contains semicolons.
  3754. $a = ['a' => 1, 2 => 2, 'b' => 'c"d";e'];
  3755. $this->assertEquals(false, unserialize_array(serialize($a)));
  3756. // Can not unserialize if there are any objects.
  3757. $a = (object)['a' => 1, 2 => 2, 'b' => 'cde'];
  3758. $this->assertEquals(false, unserialize_array(serialize($a)));
  3759. $a = ['a' => 1, 2 => 2, 'b' => (object)['a' => 'cde']];
  3760. $this->assertEquals(false, unserialize_array(serialize($a)));
  3761. // Array used in the grader report.
  3762. $a = array('aggregatesonly' => [51, 34], 'gradesonly' => [21, 45, 78]);
  3763. $this->assertEquals($a, unserialize_array(serialize($a)));
  3764. }
  3765. /**
  3766. * Test that the component_class_callback returns the correct default value when the class was not found.
  3767. *
  3768. * @dataProvider component_class_callback_default_provider
  3769. * @param $default
  3770. */
  3771. public function test_component_class_callback_not_found($default) {
  3772. $this->assertSame($default, component_class_callback('thisIsNotTheClassYouWereLookingFor', 'anymethod', [], $default));
  3773. }
  3774. /**
  3775. * Test that the component_class_callback returns the correct default value when the class was not found.
  3776. *
  3777. * @dataProvider component_class_callback_default_provider
  3778. * @param $default
  3779. */
  3780. public function test_component_class_callback_method_not_found($default) {
  3781. require_once(__DIR__ . '/fixtures/component_class_callback_example.php');
  3782. $this->assertSame($default, component_class_callback(test_component_class_callback_example::class, 'this_is_not_the_method_you_were_looking_for', ['abc'], $default));
  3783. }
  3784. /**
  3785. * Test that the component_class_callback returns the default when the method returned null.
  3786. *
  3787. * @dataProvider component_class_callback_default_provider
  3788. * @param $default
  3789. */
  3790. public function test_component_class_callback_found_returns_null($default) {
  3791. require_once(__DIR__ . '/fixtures/component_class_callback_example.php');
  3792. $this->assertSame($default, component_class_callback(test_component_class_callback_example::class, 'method_returns_value', [null], $default));
  3793. $this->assertSame($default, component_class_callback(test_component_class_callback_child_example::class, 'method_returns_value', [null], $default));
  3794. }
  3795. /**
  3796. * Test that the component_class_callback returns the expected value and not the default when there was a value.
  3797. *
  3798. * @dataProvider component_class_callback_data_provider
  3799. * @param $default
  3800. */
  3801. public function test_component_class_callback_found_returns_value($value) {
  3802. require_once(__DIR__ . '/fixtures/component_class_callback_example.php');
  3803. $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'));
  3804. $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'));
  3805. }
  3806. /**
  3807. * Test that the component_class_callback handles multiple params correctly.
  3808. *
  3809. * @dataProvider component_class_callback_multiple_params_provider
  3810. * @param $default
  3811. */
  3812. public function test_component_class_callback_found_accepts_multiple($params, $count) {
  3813. require_once(__DIR__ . '/fixtures/component_class_callback_example.php');
  3814. $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'));
  3815. $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'));
  3816. }
  3817. /**
  3818. * Data provider with list of default values for user in component_class_callback tests.
  3819. *
  3820. * @return array
  3821. */
  3822. public function component_class_callback_default_provider() {
  3823. return [
  3824. 'null' => [null],
  3825. 'empty string' => [''],
  3826. 'string' => ['This is a string'],
  3827. 'int' => [12345],
  3828. 'stdClass' => [(object) ['this is my content']],
  3829. 'array' => [['a' => 'b',]],
  3830. ];
  3831. }
  3832. /**
  3833. * Data provider with list of default values for user in component_class_callback tests.
  3834. *
  3835. * @return array
  3836. */
  3837. public function component_class_callback_data_provider() {
  3838. return [
  3839. 'empty string' => [''],
  3840. 'string' => ['This is a string'],
  3841. 'int' => [12345],
  3842. 'stdClass' => [(object) ['this is my content']],
  3843. 'array' => [['a' => 'b',]],
  3844. ];
  3845. }
  3846. /**
  3847. * Data provider with list of default values for user in component_class_callback tests.
  3848. *
  3849. * @return array
  3850. */
  3851. public function component_class_callback_multiple_params_provider() {
  3852. return [
  3853. 'empty array' => [
  3854. [],
  3855. 0,
  3856. ],
  3857. 'string value' => [
  3858. ['one'],
  3859. 1,
  3860. ],
  3861. 'string values' => [
  3862. ['one', 'two'],
  3863. 2,
  3864. ],
  3865. 'arrays' => [
  3866. [[], []],
  3867. 2,
  3868. ],
  3869. 'nulls' => [
  3870. [null, null, null, null],
  3871. 4,
  3872. ],
  3873. 'mixed' => [
  3874. ['a', 1, null, (object) [], []],
  3875. 5,
  3876. ],
  3877. ];
  3878. }
  3879. /**
  3880. * Test that {@link get_callable_name()} describes the callable as expected.
  3881. *
  3882. * @dataProvider callable_names_provider
  3883. * @param callable $callable
  3884. * @param string $expectedname
  3885. */
  3886. public function test_get_callable_name($callable, $expectedname) {
  3887. $this->assertSame($expectedname, get_callable_name($callable));
  3888. }
  3889. /**
  3890. * Provides a set of callables and their human readable names.
  3891. *
  3892. * @return array of (string)case => [(mixed)callable, (string|bool)expected description]
  3893. */
  3894. public function callable_names_provider() {
  3895. return [
  3896. 'integer' => [
  3897. 386,
  3898. false,
  3899. ],
  3900. 'boolean' => [
  3901. true,
  3902. false,
  3903. ],
  3904. 'static_method_as_literal' => [
  3905. 'my_foobar_class::my_foobar_method',
  3906. 'my_foobar_class::my_foobar_method',
  3907. ],
  3908. 'static_method_of_literal_class' => [
  3909. ['my_foobar_class', 'my_foobar_method'],
  3910. 'my_foobar_class::my_foobar_method',
  3911. ],
  3912. 'static_method_of_object' => [
  3913. [$this, 'my_foobar_method'],
  3914. 'core_moodlelib_testcase::my_foobar_method',
  3915. ],
  3916. 'method_of_object' => [
  3917. [new lang_string('parentlanguage', 'core_langconfig'), 'my_foobar_method'],
  3918. 'lang_string::my_foobar_method',
  3919. ],
  3920. 'function_as_literal' => [
  3921. 'my_foobar_callback',
  3922. 'my_foobar_callback',
  3923. ],
  3924. 'function_as_closure' => [
  3925. function($a) { return $a; },
  3926. 'Closure::__invoke',
  3927. ],
  3928. ];
  3929. }
  3930. /**
  3931. * Data provider for \core_moodlelib_testcase::test_get_complete_user_data().
  3932. *
  3933. * @return array
  3934. */
  3935. public function user_data_provider() {
  3936. return [
  3937. 'Fetch data using a valid username' => [
  3938. 'username', 's1', true
  3939. ],
  3940. 'Fetch data using a valid username, different case' => [
  3941. 'username', 'S1', true
  3942. ],
  3943. 'Fetch data using a valid username, different case for fieldname and value' => [
  3944. 'USERNAME', 'S1', true
  3945. ],
  3946. 'Fetch data using an invalid username' => [
  3947. 'username', 's2', false
  3948. ],
  3949. 'Fetch by email' => [
  3950. 'email', 's1@example.com', true
  3951. ],
  3952. 'Fetch data using a non-existent email' => [
  3953. 'email', 's2@example.com', false
  3954. ],
  3955. 'Fetch data using a non-existent email, throw exception' => [
  3956. 'email', 's2@example.com', false, dml_missing_record_exception::class
  3957. ],
  3958. 'Multiple accounts with the same email' => [
  3959. 'email', 's1@example.com', false, 1
  3960. ],
  3961. 'Multiple accounts with the same email, throw exception' => [
  3962. 'email', 's1@example.com', false, 1, dml_multiple_records_exception::class
  3963. ],
  3964. 'Fetch data using a valid user ID' => [
  3965. 'id', true, true
  3966. ],
  3967. 'Fetch data using a non-existent user ID' => [
  3968. 'id', false, false
  3969. ],
  3970. ];
  3971. }
  3972. /**
  3973. * Test for get_complete_user_data().
  3974. *
  3975. * @dataProvider user_data_provider
  3976. * @param string $field The field to use for the query.
  3977. * @param string|boolean $value The field value. When fetching by ID, set true to fetch valid user ID, false otherwise.
  3978. * @param boolean $success Whether we expect for the fetch to succeed or return false.
  3979. * @param int $allowaccountssameemail Value for $CFG->allowaccountssameemail.
  3980. * @param string $expectedexception The exception to be expected.
  3981. */
  3982. public function test_get_complete_user_data($field, $value, $success, $allowaccountssameemail = 0, $expectedexception = '') {
  3983. $this->resetAfterTest();
  3984. // Set config settings we need for our environment.
  3985. set_config('allowaccountssameemail', $allowaccountssameemail);
  3986. // Generate the user data.
  3987. $generator = $this->getDataGenerator();
  3988. $userdata = [
  3989. 'username' => 's1',
  3990. 'email' => 's1@example.com',
  3991. ];
  3992. $user = $generator->create_user($userdata);
  3993. if ($allowaccountssameemail) {
  3994. // Create another user with the same email address.
  3995. $generator->create_user(['email' => 's1@example.com']);
  3996. }
  3997. // Since the data provider can't know what user ID to use, do a special handling for ID field tests.
  3998. if ($field === 'id') {
  3999. if ($value) {
  4000. // Test for fetching data using a valid user ID. Use the generated user's ID.
  4001. $value = $user->id;
  4002. } else {
  4003. // Test for fetching data using a non-existent user ID.
  4004. $value = $user->id + 1;
  4005. }
  4006. }
  4007. // When an exception is expected.
  4008. $throwexception = false;
  4009. if ($expectedexception) {
  4010. $this->expectException($expectedexception);
  4011. $throwexception = true;
  4012. }
  4013. $fetcheduser = get_complete_user_data($field, $value, null, $throwexception);
  4014. if ($success) {
  4015. $this->assertEquals($user->id, $fetcheduser->id);
  4016. $this->assertEquals($user->username, $fetcheduser->username);
  4017. $this->assertEquals($user->email, $fetcheduser->email);
  4018. } else {
  4019. $this->assertFalse($fetcheduser);
  4020. }
  4021. }
  4022. /**
  4023. * Test for send_password_change_().
  4024. */
  4025. public function test_send_password_change_info() {
  4026. $this->resetAfterTest();
  4027. $user = $this->getDataGenerator()->create_user();
  4028. $sink = $this->redirectEmails(); // Make sure we are redirecting emails.
  4029. send_password_change_info($user);
  4030. $result = $sink->get_messages();
  4031. $sink->close();
  4032. $this->assertContains('passwords cannot be reset on this site', quoted_printable_decode($result[0]->body));
  4033. }
  4034. /**
  4035. * Test the get_time_interval_string for a range of inputs.
  4036. *
  4037. * @dataProvider get_time_interval_string_provider
  4038. * @param int $time1 the time1 param.
  4039. * @param int $time2 the time2 param.
  4040. * @param string|null $format the format param.
  4041. * @param string $expected the expected string.
  4042. */
  4043. public function test_get_time_interval_string(int $time1, int $time2, ?string $format, string $expected) {
  4044. if (is_null($format)) {
  4045. $this->assertEquals($expected, get_time_interval_string($time1, $time2));
  4046. } else {
  4047. $this->assertEquals($expected, get_time_interval_string($time1, $time2, $format));
  4048. }
  4049. }
  4050. /**
  4051. * Data provider for the test_get_time_interval_string() method.
  4052. */
  4053. public function get_time_interval_string_provider() {
  4054. return [
  4055. 'Time is after the reference time by 1 minute, omitted format' => [
  4056. 'time1' => 12345660,
  4057. 'time2' => 12345600,
  4058. 'format' => null,
  4059. 'expected' => '0d 0h 1m'
  4060. ],
  4061. 'Time is before the reference time by 1 minute, omitted format' => [
  4062. 'time1' => 12345540,
  4063. 'time2' => 12345600,
  4064. 'format' => null,
  4065. 'expected' => '0d 0h 1m'
  4066. ],
  4067. 'Time is equal to the reference time, omitted format' => [
  4068. 'time1' => 12345600,
  4069. 'time2' => 12345600,
  4070. 'format' => null,
  4071. 'expected' => '0d 0h 0m'
  4072. ],
  4073. 'Time is after the reference time by 1 minute, empty string format' => [
  4074. 'time1' => 12345660,
  4075. 'time2' => 12345600,
  4076. 'format' => '',
  4077. 'expected' => '0d 0h 1m'
  4078. ],
  4079. 'Time is before the reference time by 1 minute, empty string format' => [
  4080. 'time1' => 12345540,
  4081. 'time2' => 12345600,
  4082. 'format' => '',
  4083. 'expected' => '0d 0h 1m'
  4084. ],
  4085. 'Time is equal to the reference time, empty string format' => [
  4086. 'time1' => 12345600,
  4087. 'time2' => 12345600,
  4088. 'format' => '',
  4089. 'expected' => '0d 0h 0m'
  4090. ],
  4091. 'Time is after the reference time by 1 minute, custom format' => [
  4092. 'time1' => 12345660,
  4093. 'time2' => 12345600,
  4094. 'format' => '%R%adays %hhours %imins',
  4095. 'expected' => '+0days 0hours 1mins'
  4096. ],
  4097. 'Time is before the reference time by 1 minute, custom format' => [
  4098. 'time1' => 12345540,
  4099. 'time2' => 12345600,
  4100. 'format' => '%R%adays %hhours %imins',
  4101. 'expected' => '-0days 0hours 1mins'
  4102. ],
  4103. 'Time is equal to the reference time, custom format' => [
  4104. 'time1' => 12345600,
  4105. 'time2' => 12345600,
  4106. 'format' => '%R%adays %hhours %imins',
  4107. 'expected' => '+0days 0hours 0mins'
  4108. ],
  4109. ];
  4110. }
  4111. }