PageRenderTime 57ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/tests/filelib_test.php

https://bitbucket.org/moodle/moodle
PHP | 1770 lines | 1200 code | 278 blank | 292 comment | 18 complexity | 01173e40aa2e5a84a73613766bcca0d2 MD5 | raw file
Possible License(s): Apache-2.0, LGPL-2.1, BSD-3-Clause, MIT, GPL-3.0

Large files files are truncated, but you can click here to view the full file

  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 /lib/filelib.php.
  18. *
  19. * @package core_files
  20. * @category phpunit
  21. * @copyright 2009 Jerome Mouneyrac
  22. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  23. */
  24. defined('MOODLE_INTERNAL') || die();
  25. global $CFG;
  26. require_once($CFG->libdir . '/filelib.php');
  27. require_once($CFG->dirroot . '/repository/lib.php');
  28. class core_filelib_testcase extends advanced_testcase {
  29. public function test_format_postdata_for_curlcall() {
  30. // POST params with just simple types.
  31. $postdatatoconvert = array( 'userid' => 1, 'roleid' => 22, 'name' => 'john');
  32. $expectedresult = "userid=1&roleid=22&name=john";
  33. $postdata = format_postdata_for_curlcall($postdatatoconvert);
  34. $this->assertEquals($expectedresult, $postdata);
  35. // POST params with a string containing & character.
  36. $postdatatoconvert = array( 'name' => 'john&emilie', 'roleid' => 22);
  37. $expectedresult = "name=john%26emilie&roleid=22"; // Urlencode: '%26' => '&'.
  38. $postdata = format_postdata_for_curlcall($postdatatoconvert);
  39. $this->assertEquals($expectedresult, $postdata);
  40. // POST params with an empty value.
  41. $postdatatoconvert = array( 'name' => null, 'roleid' => 22);
  42. $expectedresult = "name=&roleid=22";
  43. $postdata = format_postdata_for_curlcall($postdatatoconvert);
  44. $this->assertEquals($expectedresult, $postdata);
  45. // POST params with complex types.
  46. $postdatatoconvert = array( 'users' => array(
  47. array(
  48. 'id' => 2,
  49. 'customfields' => array(
  50. array
  51. (
  52. 'type' => 'Color',
  53. 'value' => 'violet'
  54. )
  55. )
  56. )
  57. )
  58. );
  59. $expectedresult = "users[0][id]=2&users[0][customfields][0][type]=Color&users[0][customfields][0][value]=violet";
  60. $postdata = format_postdata_for_curlcall($postdatatoconvert);
  61. $this->assertEquals($expectedresult, $postdata);
  62. // POST params with other complex types.
  63. $postdatatoconvert = array ('members' =>
  64. array(
  65. array('groupid' => 1, 'userid' => 1)
  66. , array('groupid' => 1, 'userid' => 2)
  67. )
  68. );
  69. $expectedresult = "members[0][groupid]=1&members[0][userid]=1&members[1][groupid]=1&members[1][userid]=2";
  70. $postdata = format_postdata_for_curlcall($postdatatoconvert);
  71. $this->assertEquals($expectedresult, $postdata);
  72. }
  73. public function test_download_file_content() {
  74. global $CFG;
  75. // Test http success first.
  76. $testhtml = $this->getExternalTestFileUrl('/test.html');
  77. $contents = download_file_content($testhtml);
  78. $this->assertSame('47250a973d1b88d9445f94db4ef2c97a', md5($contents));
  79. $tofile = "$CFG->tempdir/test.html";
  80. @unlink($tofile);
  81. $result = download_file_content($testhtml, null, null, false, 300, 20, false, $tofile);
  82. $this->assertTrue($result);
  83. $this->assertFileExists($tofile);
  84. $this->assertSame(file_get_contents($tofile), $contents);
  85. @unlink($tofile);
  86. $result = download_file_content($testhtml, null, null, false, 300, 20, false, null, true);
  87. $this->assertSame($contents, $result);
  88. $response = download_file_content($testhtml, null, null, true);
  89. $this->assertInstanceOf('stdClass', $response);
  90. $this->assertSame('200', $response->status);
  91. $this->assertTrue(is_array($response->headers));
  92. $this->assertMatchesRegularExpression('|^HTTP/1\.[01] 200 OK$|', rtrim($response->response_code));
  93. $this->assertSame($contents, $response->results);
  94. $this->assertSame('', $response->error);
  95. // Test https success.
  96. $testhtml = $this->getExternalTestFileUrl('/test.html', true);
  97. $contents = download_file_content($testhtml, null, null, false, 300, 20, true);
  98. $this->assertSame('47250a973d1b88d9445f94db4ef2c97a', md5($contents));
  99. $contents = download_file_content($testhtml);
  100. $this->assertSame('47250a973d1b88d9445f94db4ef2c97a', md5($contents));
  101. // Now 404.
  102. $testhtml = $this->getExternalTestFileUrl('/test.html_nonexistent');
  103. $contents = download_file_content($testhtml);
  104. $this->assertFalse($contents);
  105. $this->assertDebuggingCalled();
  106. $response = download_file_content($testhtml, null, null, true);
  107. $this->assertInstanceOf('stdClass', $response);
  108. $this->assertSame('404', $response->status);
  109. $this->assertTrue(is_array($response->headers));
  110. $this->assertMatchesRegularExpression('|^HTTP/1\.[01] 404 Not Found$|', rtrim($response->response_code));
  111. // Do not test the response starts with DOCTYPE here because some servers may return different headers.
  112. $this->assertSame('', $response->error);
  113. // Invalid url.
  114. $testhtml = $this->getExternalTestFileUrl('/test.html');
  115. $testhtml = str_replace('http://', 'ftp://', $testhtml);
  116. $contents = download_file_content($testhtml);
  117. $this->assertFalse($contents);
  118. // Test standard redirects.
  119. $testurl = $this->getExternalTestFileUrl('/test_redir.php');
  120. $contents = download_file_content("$testurl?redir=2");
  121. $this->assertSame('done', $contents);
  122. $response = download_file_content("$testurl?redir=2", null, null, true);
  123. $this->assertInstanceOf('stdClass', $response);
  124. $this->assertSame('200', $response->status);
  125. $this->assertTrue(is_array($response->headers));
  126. $this->assertMatchesRegularExpression('|^HTTP/1\.[01] 200 OK$|', rtrim($response->response_code));
  127. $this->assertSame('done', $response->results);
  128. $this->assertSame('', $response->error);
  129. // Commented out this block if there are performance problems.
  130. /*
  131. $contents = download_file_content("$testurl?redir=6");
  132. $this->assertFalse(false, $contents);
  133. $this->assertDebuggingCalled();
  134. $response = download_file_content("$testurl?redir=6", null, null, true);
  135. $this->assertInstanceOf('stdClass', $response);
  136. $this->assertSame('0', $response->status);
  137. $this->assertTrue(is_array($response->headers));
  138. $this->assertFalse($response->results);
  139. $this->assertNotEmpty($response->error);
  140. */
  141. // Test relative redirects.
  142. $testurl = $this->getExternalTestFileUrl('/test_relative_redir.php');
  143. $contents = download_file_content("$testurl");
  144. $this->assertSame('done', $contents);
  145. $contents = download_file_content("$testurl?unused=xxx");
  146. $this->assertSame('done', $contents);
  147. }
  148. /**
  149. * Test curl basics.
  150. */
  151. public function test_curl_basics() {
  152. global $CFG;
  153. // Test HTTP success.
  154. $testhtml = $this->getExternalTestFileUrl('/test.html');
  155. $curl = new curl();
  156. $contents = $curl->get($testhtml);
  157. $this->assertSame('47250a973d1b88d9445f94db4ef2c97a', md5($contents));
  158. $this->assertSame(0, $curl->get_errno());
  159. $curl = new curl();
  160. $tofile = "$CFG->tempdir/test.html";
  161. @unlink($tofile);
  162. $fp = fopen($tofile, 'w');
  163. $result = $curl->get($testhtml, array(), array('CURLOPT_FILE'=>$fp));
  164. $this->assertTrue($result);
  165. fclose($fp);
  166. $this->assertFileExists($tofile);
  167. $this->assertSame($contents, file_get_contents($tofile));
  168. @unlink($tofile);
  169. $curl = new curl();
  170. $tofile = "$CFG->tempdir/test.html";
  171. @unlink($tofile);
  172. $result = $curl->download_one($testhtml, array(), array('filepath'=>$tofile));
  173. $this->assertTrue($result);
  174. $this->assertFileExists($tofile);
  175. $this->assertSame($contents, file_get_contents($tofile));
  176. @unlink($tofile);
  177. // Test 404 request.
  178. $curl = new curl();
  179. $contents = $curl->get($this->getExternalTestFileUrl('/i.do.not.exist'));
  180. $response = $curl->getResponse();
  181. $this->assertSame('404 Not Found', reset($response));
  182. $this->assertSame(0, $curl->get_errno());
  183. }
  184. /**
  185. * Test a curl basic request with security enabled.
  186. */
  187. public function test_curl_basics_with_security_helper() {
  188. $this->resetAfterTest();
  189. // Test a request with a basic hostname filter applied.
  190. $testhtml = $this->getExternalTestFileUrl('/test.html');
  191. $url = new moodle_url($testhtml);
  192. $host = $url->get_host();
  193. set_config('curlsecurityblockedhosts', $host); // Blocks $host.
  194. // Create curl with the default security enabled. We expect this to be blocked.
  195. $curl = new curl();
  196. $contents = $curl->get($testhtml);
  197. $expected = $curl->get_security()->get_blocked_url_string();
  198. $this->assertSame($expected, $contents);
  199. $this->assertSame(0, $curl->get_errno());
  200. // Now, create a curl using the 'ignoresecurity' override.
  201. // We expect this request to pass, despite the admin setting having been set earlier.
  202. $curl = new curl(['ignoresecurity' => true]);
  203. $contents = $curl->get($testhtml);
  204. $this->assertSame('47250a973d1b88d9445f94db4ef2c97a', md5($contents));
  205. $this->assertSame(0, $curl->get_errno());
  206. // Now, try injecting a mock security helper into curl. This will override the default helper.
  207. $mockhelper = $this->getMockBuilder('\core\files\curl_security_helper')->getMock();
  208. // Make the mock return a different string.
  209. $mockhelper->expects($this->any())->method('get_blocked_url_string')->will($this->returnValue('You shall not pass'));
  210. // And make the mock security helper block all URLs. This helper instance doesn't care about config.
  211. $mockhelper->expects($this->any())->method('url_is_blocked')->will($this->returnValue(true));
  212. $curl = new curl(['securityhelper' => $mockhelper]);
  213. $contents = $curl->get($testhtml);
  214. $this->assertSame('You shall not pass', $curl->get_security()->get_blocked_url_string());
  215. $this->assertSame($curl->get_security()->get_blocked_url_string(), $contents);
  216. }
  217. public function test_curl_redirects() {
  218. global $CFG;
  219. $testurl = $this->getExternalTestFileUrl('/test_redir.php');
  220. $curl = new curl();
  221. $contents = $curl->get("$testurl?redir=2", array(), array('CURLOPT_MAXREDIRS'=>2));
  222. $response = $curl->getResponse();
  223. $this->assertSame('200 OK', reset($response));
  224. $this->assertSame(0, $curl->get_errno());
  225. $this->assertSame(2, $curl->info['redirect_count']);
  226. $this->assertSame('done', $contents);
  227. // All redirects are emulated now. Enabling "emulateredirects" explicitly does not have effect.
  228. $curl = new curl();
  229. $curl->emulateredirects = true;
  230. $contents = $curl->get("$testurl?redir=2", array(), array('CURLOPT_MAXREDIRS'=>2));
  231. $response = $curl->getResponse();
  232. $this->assertSame('200 OK', reset($response));
  233. $this->assertSame(0, $curl->get_errno());
  234. $this->assertSame(2, $curl->info['redirect_count']);
  235. $this->assertSame('done', $contents);
  236. // All redirects are emulated now. Attempting to disable "emulateredirects" explicitly causes warning.
  237. $curl = new curl();
  238. $curl->emulateredirects = false;
  239. $contents = $curl->get("$testurl?redir=2", array(), array('CURLOPT_MAXREDIRS' => 2));
  240. $response = $curl->getResponse();
  241. $this->assertDebuggingCalled('Attempting to disable emulated redirects has no effect any more!');
  242. $this->assertSame('200 OK', reset($response));
  243. $this->assertSame(0, $curl->get_errno());
  244. $this->assertSame(2, $curl->info['redirect_count']);
  245. $this->assertSame('done', $contents);
  246. // This test was failing for people behind Squid proxies. Squid does not
  247. // fully support HTTP 1.1, so converts things to HTTP 1.0, where the name
  248. // of the status code is different.
  249. reset($response);
  250. if (key($response) === 'HTTP/1.0') {
  251. $responsecode302 = '302 Moved Temporarily';
  252. } else {
  253. $responsecode302 = '302 Found';
  254. }
  255. $curl = new curl();
  256. $contents = $curl->get("$testurl?redir=3", array(), array('CURLOPT_FOLLOWLOCATION'=>0));
  257. $response = $curl->getResponse();
  258. $this->assertSame($responsecode302, reset($response));
  259. $this->assertSame(0, $curl->get_errno());
  260. $this->assertSame(302, $curl->info['http_code']);
  261. $this->assertSame('', $contents);
  262. $curl = new curl();
  263. $contents = $curl->get("$testurl?redir=2", array(), array('CURLOPT_MAXREDIRS'=>1));
  264. $this->assertSame(CURLE_TOO_MANY_REDIRECTS, $curl->get_errno());
  265. $this->assertNotEmpty($contents);
  266. $curl = new curl();
  267. $tofile = "$CFG->tempdir/test.html";
  268. @unlink($tofile);
  269. $fp = fopen($tofile, 'w');
  270. $result = $curl->get("$testurl?redir=1", array(), array('CURLOPT_FILE'=>$fp));
  271. $this->assertTrue($result);
  272. fclose($fp);
  273. $this->assertFileExists($tofile);
  274. $this->assertSame('done', file_get_contents($tofile));
  275. @unlink($tofile);
  276. $curl = new curl();
  277. $tofile = "$CFG->tempdir/test.html";
  278. @unlink($tofile);
  279. $result = $curl->download_one("$testurl?redir=1", array(), array('filepath'=>$tofile));
  280. $this->assertTrue($result);
  281. $this->assertFileExists($tofile);
  282. $this->assertSame('done', file_get_contents($tofile));
  283. @unlink($tofile);
  284. }
  285. /**
  286. * Test that redirects to blocked hosts are blocked.
  287. */
  288. public function test_curl_blocked_redirect() {
  289. $this->resetAfterTest();
  290. $testurl = $this->getExternalTestFileUrl('/test_redir.php');
  291. // Block a host.
  292. // Note: moodle.com is the URL redirected to when test_redir.php has the param extdest=1 set.
  293. set_config('curlsecurityblockedhosts', 'moodle.com');
  294. // Redirecting to a non-blocked host should resolve.
  295. $curl = new curl();
  296. $contents = $curl->get("{$testurl}?redir=2");
  297. $response = $curl->getResponse();
  298. $this->assertSame('200 OK', reset($response));
  299. $this->assertSame(0, $curl->get_errno());
  300. // Redirecting to the blocked host should fail.
  301. $curl = new curl();
  302. $blockedstring = $curl->get_security()->get_blocked_url_string();
  303. $contents = $curl->get("{$testurl}?redir=1&extdest=1");
  304. $this->assertSame($blockedstring, $contents);
  305. $this->assertSame(0, $curl->get_errno());
  306. // Redirecting to the blocked host after multiple successful redirects should also fail.
  307. $curl = new curl();
  308. $contents = $curl->get("{$testurl}?redir=3&extdest=1");
  309. $this->assertSame($blockedstring, $contents);
  310. $this->assertSame(0, $curl->get_errno());
  311. }
  312. public function test_curl_relative_redirects() {
  313. // Test relative location redirects.
  314. $testurl = $this->getExternalTestFileUrl('/test_relative_redir.php');
  315. $curl = new curl();
  316. $contents = $curl->get($testurl);
  317. $response = $curl->getResponse();
  318. $this->assertSame('200 OK', reset($response));
  319. $this->assertSame(0, $curl->get_errno());
  320. $this->assertSame(1, $curl->info['redirect_count']);
  321. $this->assertSame('done', $contents);
  322. // Test different redirect types.
  323. $testurl = $this->getExternalTestFileUrl('/test_relative_redir.php');
  324. $curl = new curl();
  325. $contents = $curl->get("$testurl?type=301");
  326. $response = $curl->getResponse();
  327. $this->assertSame('200 OK', reset($response));
  328. $this->assertSame(0, $curl->get_errno());
  329. $this->assertSame(1, $curl->info['redirect_count']);
  330. $this->assertSame('done', $contents);
  331. $curl = new curl();
  332. $contents = $curl->get("$testurl?type=302");
  333. $response = $curl->getResponse();
  334. $this->assertSame('200 OK', reset($response));
  335. $this->assertSame(0, $curl->get_errno());
  336. $this->assertSame(1, $curl->info['redirect_count']);
  337. $this->assertSame('done', $contents);
  338. $curl = new curl();
  339. $contents = $curl->get("$testurl?type=303");
  340. $response = $curl->getResponse();
  341. $this->assertSame('200 OK', reset($response));
  342. $this->assertSame(0, $curl->get_errno());
  343. $this->assertSame(1, $curl->info['redirect_count']);
  344. $this->assertSame('done', $contents);
  345. $curl = new curl();
  346. $contents = $curl->get("$testurl?type=307");
  347. $response = $curl->getResponse();
  348. $this->assertSame('200 OK', reset($response));
  349. $this->assertSame(0, $curl->get_errno());
  350. $this->assertSame(1, $curl->info['redirect_count']);
  351. $this->assertSame('done', $contents);
  352. $curl = new curl();
  353. $contents = $curl->get("$testurl?type=308");
  354. $response = $curl->getResponse();
  355. $this->assertSame('200 OK', reset($response));
  356. $this->assertSame(0, $curl->get_errno());
  357. $this->assertSame(1, $curl->info['redirect_count']);
  358. $this->assertSame('done', $contents);
  359. }
  360. public function test_curl_proxybypass() {
  361. global $CFG;
  362. $testurl = $this->getExternalTestFileUrl('/test.html');
  363. $oldproxy = $CFG->proxyhost;
  364. $oldproxybypass = $CFG->proxybypass;
  365. // Test without proxy bypass and inaccessible proxy.
  366. $CFG->proxyhost = 'i.do.not.exist';
  367. $CFG->proxybypass = '';
  368. $curl = new curl();
  369. $contents = $curl->get($testurl);
  370. $this->assertNotEquals(0, $curl->get_errno());
  371. $this->assertNotEquals('47250a973d1b88d9445f94db4ef2c97a', md5($contents));
  372. // Test with proxy bypass.
  373. $testurlhost = parse_url($testurl, PHP_URL_HOST);
  374. $CFG->proxybypass = $testurlhost;
  375. $curl = new curl();
  376. $contents = $curl->get($testurl);
  377. $this->assertSame(0, $curl->get_errno());
  378. $this->assertSame('47250a973d1b88d9445f94db4ef2c97a', md5($contents));
  379. $CFG->proxyhost = $oldproxy;
  380. $CFG->proxybypass = $oldproxybypass;
  381. }
  382. /**
  383. * Test that duplicate lines in the curl header are removed.
  384. */
  385. public function test_duplicate_curl_header() {
  386. $testurl = $this->getExternalTestFileUrl('/test_post.php');
  387. $curl = new curl();
  388. $headerdata = 'Accept: application/json';
  389. $header = [$headerdata, $headerdata];
  390. $this->assertCount(2, $header);
  391. $curl->setHeader($header);
  392. $this->assertCount(1, $curl->header);
  393. $this->assertEquals($headerdata, $curl->header[0]);
  394. }
  395. public function test_curl_post() {
  396. $testurl = $this->getExternalTestFileUrl('/test_post.php');
  397. // Test post request.
  398. $curl = new curl();
  399. $contents = $curl->post($testurl, 'data=moodletest');
  400. $response = $curl->getResponse();
  401. $this->assertSame('200 OK', reset($response));
  402. $this->assertSame(0, $curl->get_errno());
  403. $this->assertSame('OK', $contents);
  404. // Test 100 requests.
  405. $curl = new curl();
  406. $curl->setHeader('Expect: 100-continue');
  407. $contents = $curl->post($testurl, 'data=moodletest');
  408. $response = $curl->getResponse();
  409. $this->assertSame('200 OK', reset($response));
  410. $this->assertSame(0, $curl->get_errno());
  411. $this->assertSame('OK', $contents);
  412. }
  413. public function test_curl_file() {
  414. $this->resetAfterTest();
  415. $testurl = $this->getExternalTestFileUrl('/test_file.php');
  416. $fs = get_file_storage();
  417. $filerecord = array(
  418. 'contextid' => context_system::instance()->id,
  419. 'component' => 'test',
  420. 'filearea' => 'curl_post',
  421. 'itemid' => 0,
  422. 'filepath' => '/',
  423. 'filename' => 'test.txt'
  424. );
  425. $teststring = 'moodletest';
  426. $testfile = $fs->create_file_from_string($filerecord, $teststring);
  427. // Test post with file.
  428. $data = array('testfile' => $testfile);
  429. $curl = new curl();
  430. $contents = $curl->post($testurl, $data);
  431. $this->assertSame('OK', $contents);
  432. }
  433. public function test_curl_file_name() {
  434. $this->resetAfterTest();
  435. $testurl = $this->getExternalTestFileUrl('/test_file_name.php');
  436. $fs = get_file_storage();
  437. $filerecord = array(
  438. 'contextid' => context_system::instance()->id,
  439. 'component' => 'test',
  440. 'filearea' => 'curl_post',
  441. 'itemid' => 0,
  442. 'filepath' => '/',
  443. 'filename' => 'test.txt'
  444. );
  445. $teststring = 'moodletest';
  446. $testfile = $fs->create_file_from_string($filerecord, $teststring);
  447. // Test post with file.
  448. $data = array('testfile' => $testfile);
  449. $curl = new curl();
  450. $contents = $curl->post($testurl, $data);
  451. $this->assertSame('OK', $contents);
  452. }
  453. public function test_curl_protocols() {
  454. // HTTP and HTTPS requests were verified in previous requests. Now check
  455. // that we can selectively disable some protocols.
  456. $curl = new curl();
  457. // Other protocols than HTTP(S) are disabled by default.
  458. $testurl = 'file:///';
  459. $curl->get($testurl);
  460. $this->assertNotEmpty($curl->error);
  461. $this->assertEquals(CURLE_UNSUPPORTED_PROTOCOL, $curl->errno);
  462. $testurl = 'ftp://nowhere';
  463. $curl->get($testurl);
  464. $this->assertNotEmpty($curl->error);
  465. $this->assertEquals(CURLE_UNSUPPORTED_PROTOCOL, $curl->errno);
  466. $testurl = 'telnet://somewhere';
  467. $curl->get($testurl);
  468. $this->assertNotEmpty($curl->error);
  469. $this->assertEquals(CURLE_UNSUPPORTED_PROTOCOL, $curl->errno);
  470. // Protocols are also disabled during redirections.
  471. $testurl = $this->getExternalTestFileUrl('/test_redir_proto.php');
  472. $curl->get($testurl, array('proto' => 'file'));
  473. $this->assertNotEmpty($curl->error);
  474. $this->assertEquals(CURLE_UNSUPPORTED_PROTOCOL, $curl->errno);
  475. $testurl = $this->getExternalTestFileUrl('/test_redir_proto.php');
  476. $curl->get($testurl, array('proto' => 'ftp'));
  477. $this->assertNotEmpty($curl->error);
  478. $this->assertEquals(CURLE_UNSUPPORTED_PROTOCOL, $curl->errno);
  479. $testurl = $this->getExternalTestFileUrl('/test_redir_proto.php');
  480. $curl->get($testurl, array('proto' => 'telnet'));
  481. $this->assertNotEmpty($curl->error);
  482. $this->assertEquals(CURLE_UNSUPPORTED_PROTOCOL, $curl->errno);
  483. }
  484. /**
  485. * Testing prepare draft area
  486. *
  487. * @copyright 2012 Dongsheng Cai {@link http://dongsheng.org}
  488. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  489. */
  490. public function test_prepare_draft_area() {
  491. global $USER, $DB;
  492. $this->resetAfterTest(true);
  493. $generator = $this->getDataGenerator();
  494. $user = $generator->create_user();
  495. $usercontext = context_user::instance($user->id);
  496. $USER = $DB->get_record('user', array('id'=>$user->id));
  497. $repositorypluginname = 'user';
  498. $args = array();
  499. $args['type'] = $repositorypluginname;
  500. $repos = repository::get_instances($args);
  501. $userrepository = reset($repos);
  502. $this->assertInstanceOf('repository', $userrepository);
  503. $fs = get_file_storage();
  504. $syscontext = context_system::instance();
  505. $component = 'core';
  506. $filearea = 'unittest';
  507. $itemid = 0;
  508. $filepath = '/';
  509. $filename = 'test.txt';
  510. $sourcefield = 'Copyright stuff';
  511. $filerecord = array(
  512. 'contextid' => $syscontext->id,
  513. 'component' => $component,
  514. 'filearea' => $filearea,
  515. 'itemid' => $itemid,
  516. 'filepath' => $filepath,
  517. 'filename' => $filename,
  518. 'source' => $sourcefield,
  519. );
  520. $ref = $fs->pack_reference($filerecord);
  521. $originalfile = $fs->create_file_from_string($filerecord, 'Test content');
  522. $fileid = $originalfile->get_id();
  523. $this->assertInstanceOf('stored_file', $originalfile);
  524. // Create a user private file.
  525. $userfilerecord = new stdClass;
  526. $userfilerecord->contextid = $usercontext->id;
  527. $userfilerecord->component = 'user';
  528. $userfilerecord->filearea = 'private';
  529. $userfilerecord->itemid = 0;
  530. $userfilerecord->filepath = '/';
  531. $userfilerecord->filename = 'userfile.txt';
  532. $userfilerecord->source = 'test';
  533. $userfile = $fs->create_file_from_string($userfilerecord, 'User file content');
  534. $userfileref = $fs->pack_reference($userfilerecord);
  535. $filerefrecord = clone((object)$filerecord);
  536. $filerefrecord->filename = 'testref.txt';
  537. // Create a file reference.
  538. $fileref = $fs->create_file_from_reference($filerefrecord, $userrepository->id, $userfileref);
  539. $this->assertInstanceOf('stored_file', $fileref);
  540. $this->assertEquals($userrepository->id, $fileref->get_repository_id());
  541. $this->assertSame($userfile->get_contenthash(), $fileref->get_contenthash());
  542. $this->assertEquals($userfile->get_filesize(), $fileref->get_filesize());
  543. $this->assertMatchesRegularExpression('#' . $userfile->get_filename(). '$#', $fileref->get_reference_details());
  544. $draftitemid = 0;
  545. file_prepare_draft_area($draftitemid, $syscontext->id, $component, $filearea, $itemid);
  546. $draftfiles = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftitemid);
  547. $this->assertCount(3, $draftfiles);
  548. $draftfile = $fs->get_file($usercontext->id, 'user', 'draft', $draftitemid, $filepath, $filename);
  549. $source = unserialize($draftfile->get_source());
  550. $this->assertSame($ref, $source->original);
  551. $this->assertSame($sourcefield, $source->source);
  552. $draftfileref = $fs->get_file($usercontext->id, 'user', 'draft', $draftitemid, $filepath, $filerefrecord->filename);
  553. $this->assertInstanceOf('stored_file', $draftfileref);
  554. $this->assertTrue($draftfileref->is_external_file());
  555. // Change some information.
  556. $author = 'Dongsheng Cai';
  557. $draftfile->set_author($author);
  558. $newsourcefield = 'Get from Flickr';
  559. $license = 'GPLv3';
  560. $draftfile->set_license($license);
  561. // If you want to really just change source field, do this.
  562. $source = unserialize($draftfile->get_source());
  563. $newsourcefield = 'From flickr';
  564. $source->source = $newsourcefield;
  565. $draftfile->set_source(serialize($source));
  566. // Save changed file.
  567. file_save_draft_area_files($draftitemid, $syscontext->id, $component, $filearea, $itemid);
  568. $file = $fs->get_file($syscontext->id, $component, $filearea, $itemid, $filepath, $filename);
  569. // Make sure it's the original file id.
  570. $this->assertEquals($fileid, $file->get_id());
  571. $this->assertInstanceOf('stored_file', $file);
  572. $this->assertSame($author, $file->get_author());
  573. $this->assertSame($license, $file->get_license());
  574. $this->assertEquals($newsourcefield, $file->get_source());
  575. }
  576. /**
  577. * Testing deleting original files.
  578. *
  579. * @copyright 2012 Dongsheng Cai {@link http://dongsheng.org}
  580. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  581. */
  582. public function test_delete_original_file_from_draft() {
  583. global $USER, $DB;
  584. $this->resetAfterTest(true);
  585. $generator = $this->getDataGenerator();
  586. $user = $generator->create_user();
  587. $usercontext = context_user::instance($user->id);
  588. $USER = $DB->get_record('user', array('id'=>$user->id));
  589. $repositorypluginname = 'user';
  590. $args = array();
  591. $args['type'] = $repositorypluginname;
  592. $repos = repository::get_instances($args);
  593. $userrepository = reset($repos);
  594. $this->assertInstanceOf('repository', $userrepository);
  595. $fs = get_file_storage();
  596. $syscontext = context_system::instance();
  597. $filecontent = 'User file content';
  598. // Create a user private file.
  599. $userfilerecord = new stdClass;
  600. $userfilerecord->contextid = $usercontext->id;
  601. $userfilerecord->component = 'user';
  602. $userfilerecord->filearea = 'private';
  603. $userfilerecord->itemid = 0;
  604. $userfilerecord->filepath = '/';
  605. $userfilerecord->filename = 'userfile.txt';
  606. $userfilerecord->source = 'test';
  607. $userfile = $fs->create_file_from_string($userfilerecord, $filecontent);
  608. $userfileref = $fs->pack_reference($userfilerecord);
  609. $contenthash = $userfile->get_contenthash();
  610. $filerecord = array(
  611. 'contextid' => $syscontext->id,
  612. 'component' => 'core',
  613. 'filearea' => 'phpunit',
  614. 'itemid' => 0,
  615. 'filepath' => '/',
  616. 'filename' => 'test.txt',
  617. );
  618. // Create a file reference.
  619. $fileref = $fs->create_file_from_reference($filerecord, $userrepository->id, $userfileref);
  620. $this->assertInstanceOf('stored_file', $fileref);
  621. $this->assertEquals($userrepository->id, $fileref->get_repository_id());
  622. $this->assertSame($userfile->get_contenthash(), $fileref->get_contenthash());
  623. $this->assertEquals($userfile->get_filesize(), $fileref->get_filesize());
  624. $this->assertMatchesRegularExpression('#' . $userfile->get_filename(). '$#', $fileref->get_reference_details());
  625. $draftitemid = 0;
  626. file_prepare_draft_area($draftitemid, $usercontext->id, 'user', 'private', 0);
  627. $draftfiles = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftitemid);
  628. $this->assertCount(2, $draftfiles);
  629. $draftfile = $fs->get_file($usercontext->id, 'user', 'draft', $draftitemid, $userfilerecord->filepath, $userfilerecord->filename);
  630. $draftfile->delete();
  631. // Save changed file.
  632. file_save_draft_area_files($draftitemid, $usercontext->id, 'user', 'private', 0);
  633. // The file reference should be a regular moodle file now.
  634. $fileref = $fs->get_file($syscontext->id, 'core', 'phpunit', 0, '/', 'test.txt');
  635. $this->assertFalse($fileref->is_external_file());
  636. $this->assertSame($contenthash, $fileref->get_contenthash());
  637. $this->assertEquals($filecontent, $fileref->get_content());
  638. }
  639. /**
  640. * Test avoid file merging when working with draft areas.
  641. */
  642. public function test_ignore_file_merging_in_draft_area() {
  643. global $USER, $DB;
  644. $this->resetAfterTest(true);
  645. $generator = $this->getDataGenerator();
  646. $user = $generator->create_user();
  647. $usercontext = context_user::instance($user->id);
  648. $USER = $DB->get_record('user', array('id' => $user->id));
  649. $repositorypluginname = 'user';
  650. $args = array();
  651. $args['type'] = $repositorypluginname;
  652. $repos = repository::get_instances($args);
  653. $userrepository = reset($repos);
  654. $this->assertInstanceOf('repository', $userrepository);
  655. $fs = get_file_storage();
  656. $syscontext = context_system::instance();
  657. $filecontent = 'User file content';
  658. // Create a user private file.
  659. $userfilerecord = new stdClass;
  660. $userfilerecord->contextid = $usercontext->id;
  661. $userfilerecord->component = 'user';
  662. $userfilerecord->filearea = 'private';
  663. $userfilerecord->itemid = 0;
  664. $userfilerecord->filepath = '/';
  665. $userfilerecord->filename = 'userfile.txt';
  666. $userfilerecord->source = 'test';
  667. $userfile = $fs->create_file_from_string($userfilerecord, $filecontent);
  668. $userfileref = $fs->pack_reference($userfilerecord);
  669. $contenthash = $userfile->get_contenthash();
  670. $filerecord = array(
  671. 'contextid' => $syscontext->id,
  672. 'component' => 'core',
  673. 'filearea' => 'phpunit',
  674. 'itemid' => 0,
  675. 'filepath' => '/',
  676. 'filename' => 'test.txt',
  677. );
  678. // Create a file reference.
  679. $fileref = $fs->create_file_from_reference($filerecord, $userrepository->id, $userfileref);
  680. $this->assertCount(2, $fs->get_area_files($usercontext->id, 'user', 'private')); // 2 because includes the '.' file.
  681. // Save using empty draft item id, all files will be deleted.
  682. file_save_draft_area_files(0, $usercontext->id, 'user', 'private', 0);
  683. $this->assertCount(0, $fs->get_area_files($usercontext->id, 'user', 'private'));
  684. // Create a file again.
  685. $userfile = $fs->create_file_from_string($userfilerecord, $filecontent);
  686. $this->assertCount(2, $fs->get_area_files($usercontext->id, 'user', 'private'));
  687. // Save without merge.
  688. file_save_draft_area_files(IGNORE_FILE_MERGE, $usercontext->id, 'user', 'private', 0);
  689. $this->assertCount(2, $fs->get_area_files($usercontext->id, 'user', 'private'));
  690. // Save again, this time including some inline text.
  691. $inlinetext = 'Some text <img src="@@PLUGINFILE@@/file.png">';
  692. $text = file_save_draft_area_files(IGNORE_FILE_MERGE, $usercontext->id, 'user', 'private', 0, null, $inlinetext);
  693. $this->assertCount(2, $fs->get_area_files($usercontext->id, 'user', 'private'));
  694. $this->assertEquals($inlinetext, $text);
  695. }
  696. /**
  697. * Testing deleting file_save_draft_area_files won't accidentally wipe unintended files.
  698. */
  699. public function test_file_save_draft_area_files_itemid_cannot_be_false() {
  700. global $USER, $DB;
  701. $this->resetAfterTest();
  702. $generator = $this->getDataGenerator();
  703. $user = $generator->create_user();
  704. $usercontext = context_user::instance($user->id);
  705. $USER = $DB->get_record('user', ['id' => $user->id]);
  706. $draftitemid = 0;
  707. file_prepare_draft_area($draftitemid, $usercontext->id, 'user', 'private', 0);
  708. // Call file_save_draft_area_files with itemid false - which could only happen due to a bug.
  709. // This should throw an exception.
  710. $this->expectExceptionMessage('file_save_draft_area_files was called with $itemid false. ' .
  711. 'This suggests a bug, because it would wipe all (' . $usercontext->id . ', user, private) files.');
  712. file_save_draft_area_files($draftitemid, $usercontext->id, 'user', 'private', false);
  713. }
  714. /**
  715. * Tests the strip_double_headers function in the curl class.
  716. */
  717. public function test_curl_strip_double_headers() {
  718. // Example from issue tracker.
  719. $mdl30648example = <<<EOF
  720. HTTP/1.0 407 Proxy Authentication Required
  721. Server: squid/2.7.STABLE9
  722. Date: Thu, 08 Dec 2011 14:44:33 GMT
  723. Content-Type: text/html
  724. Content-Length: 1275
  725. X-Squid-Error: ERR_CACHE_ACCESS_DENIED 0
  726. Proxy-Authenticate: Basic realm="Squid proxy-caching web server"
  727. X-Cache: MISS from homer.lancs.ac.uk
  728. X-Cache-Lookup: NONE from homer.lancs.ac.uk:3128
  729. Via: 1.0 homer.lancs.ac.uk:3128 (squid/2.7.STABLE9)
  730. Connection: close
  731. HTTP/1.0 200 OK
  732. Server: Apache
  733. X-Lb-Nocache: true
  734. Cache-Control: private, max-age=15, no-transform
  735. ETag: "4d69af5d8ba873ea9192c489e151bd7b"
  736. Content-Type: text/html
  737. Date: Thu, 08 Dec 2011 14:44:53 GMT
  738. Set-Cookie: BBC-UID=c4de2e109c8df6a51de627cee11b214bd4fb6054a030222488317afb31b343360MoodleBot/1.0; expires=Mon, 07-Dec-15 14:44:53 GMT; path=/; domain=bbc.co.uk
  739. X-Cache-Action: MISS
  740. X-Cache-Age: 0
  741. Vary: Cookie,X-Country,X-Ip-is-uk-combined,X-Ip-is-advertise-combined,X-Ip_is_uk_combined,X-Ip_is_advertise_combined, X-GeoIP
  742. X-Cache: MISS from ww
  743. <html>...
  744. EOF;
  745. $mdl30648expected = <<<EOF
  746. HTTP/1.0 200 OK
  747. Server: Apache
  748. X-Lb-Nocache: true
  749. Cache-Control: private, max-age=15, no-transform
  750. ETag: "4d69af5d8ba873ea9192c489e151bd7b"
  751. Content-Type: text/html
  752. Date: Thu, 08 Dec 2011 14:44:53 GMT
  753. Set-Cookie: BBC-UID=c4de2e109c8df6a51de627cee11b214bd4fb6054a030222488317afb31b343360MoodleBot/1.0; expires=Mon, 07-Dec-15 14:44:53 GMT; path=/; domain=bbc.co.uk
  754. X-Cache-Action: MISS
  755. X-Cache-Age: 0
  756. Vary: Cookie,X-Country,X-Ip-is-uk-combined,X-Ip-is-advertise-combined,X-Ip_is_uk_combined,X-Ip_is_advertise_combined, X-GeoIP
  757. X-Cache: MISS from ww
  758. <html>...
  759. EOF;
  760. // For HTTP, replace the \n with \r\n.
  761. $mdl30648example = preg_replace("~(?!<\r)\n~", "\r\n", $mdl30648example);
  762. $mdl30648expected = preg_replace("~(?!<\r)\n~", "\r\n", $mdl30648expected);
  763. // Test stripping works OK.
  764. $this->assertSame($mdl30648expected, curl::strip_double_headers($mdl30648example));
  765. // Test it does nothing to the 'plain' data.
  766. $this->assertSame($mdl30648expected, curl::strip_double_headers($mdl30648expected));
  767. // Example from OU proxy.
  768. $httpsexample = <<<EOF
  769. HTTP/1.0 200 Connection established
  770. HTTP/1.1 200 OK
  771. Date: Fri, 22 Feb 2013 17:14:23 GMT
  772. Server: Apache/2
  773. X-Powered-By: PHP/5.3.3-7+squeeze14
  774. Content-Type: text/xml
  775. Connection: close
  776. Content-Encoding: gzip
  777. Transfer-Encoding: chunked
  778. <?xml version="1.0" encoding="ISO-8859-1" ?>
  779. <rss version="2.0">...
  780. EOF;
  781. $httpsexpected = <<<EOF
  782. HTTP/1.1 200 OK
  783. Date: Fri, 22 Feb 2013 17:14:23 GMT
  784. Server: Apache/2
  785. X-Powered-By: PHP/5.3.3-7+squeeze14
  786. Content-Type: text/xml
  787. Connection: close
  788. Content-Encoding: gzip
  789. Transfer-Encoding: chunked
  790. <?xml version="1.0" encoding="ISO-8859-1" ?>
  791. <rss version="2.0">...
  792. EOF;
  793. // For HTTP, replace the \n with \r\n.
  794. $httpsexample = preg_replace("~(?!<\r)\n~", "\r\n", $httpsexample);
  795. $httpsexpected = preg_replace("~(?!<\r)\n~", "\r\n", $httpsexpected);
  796. // Test stripping works OK.
  797. $this->assertSame($httpsexpected, curl::strip_double_headers($httpsexample));
  798. // Test it does nothing to the 'plain' data.
  799. $this->assertSame($httpsexpected, curl::strip_double_headers($httpsexpected));
  800. }
  801. /**
  802. * Tests the get_mimetype_description function.
  803. */
  804. public function test_get_mimetype_description() {
  805. $this->resetAfterTest();
  806. // Test example type (.doc).
  807. $this->assertEquals(get_string('application/msword', 'mimetypes'),
  808. get_mimetype_description(array('filename' => 'test.doc')));
  809. // Test an unknown file type.
  810. $this->assertEquals(get_string('document/unknown', 'mimetypes'),
  811. get_mimetype_description(array('filename' => 'test.frog')));
  812. // Test a custom filetype with no lang string specified.
  813. core_filetypes::add_type('frog', 'application/x-frog', 'document');
  814. $this->assertEquals('application/x-frog',
  815. get_mimetype_description(array('filename' => 'test.frog')));
  816. // Test custom description.
  817. core_filetypes::update_type('frog', 'frog', 'application/x-frog', 'document',
  818. array(), '', 'Froggy file');
  819. $this->assertEquals('Froggy file',
  820. get_mimetype_description(array('filename' => 'test.frog')));
  821. // Test custom description using multilang filter.
  822. filter_manager::reset_caches();
  823. filter_set_global_state('multilang', TEXTFILTER_ON);
  824. filter_set_applies_to_strings('multilang', true);
  825. core_filetypes::update_type('frog', 'frog', 'application/x-frog', 'document',
  826. array(), '', '<span lang="en" class="multilang">Green amphibian</span>' .
  827. '<span lang="fr" class="multilang">Amphibian vert</span>');
  828. $this->assertEquals('Green amphibian',
  829. get_mimetype_description(array('filename' => 'test.frog')));
  830. }
  831. /**
  832. * Tests the get_mimetypes_array function.
  833. */
  834. public function test_get_mimetypes_array() {
  835. $mimeinfo = get_mimetypes_array();
  836. // Test example MIME type (doc).
  837. $this->assertEquals('application/msword', $mimeinfo['doc']['type']);
  838. $this->assertEquals('document', $mimeinfo['doc']['icon']);
  839. $this->assertEquals(array('document'), $mimeinfo['doc']['groups']);
  840. $this->assertFalse(isset($mimeinfo['doc']['string']));
  841. $this->assertFalse(isset($mimeinfo['doc']['defaulticon']));
  842. $this->assertFalse(isset($mimeinfo['doc']['customdescription']));
  843. // Check the less common fields using other examples.
  844. $this->assertEquals('image', $mimeinfo['png']['string']);
  845. $this->assertEquals(true, $mimeinfo['txt']['defaulticon']);
  846. }
  847. /**
  848. * Tests for get_mimetype_for_sending function.
  849. */
  850. public function test_get_mimetype_for_sending() {
  851. // Without argument.
  852. $this->assertEquals('application/octet-stream', get_mimetype_for_sending());
  853. // Argument is null.
  854. $this->assertEquals('application/octet-stream', get_mimetype_for_sending(null));
  855. // Filename having no extension.
  856. $this->assertEquals('application/octet-stream', get_mimetype_for_sending('filenamewithoutextension'));
  857. // Test using the extensions listed from the get_mimetypes_array function.
  858. $mimetypes = get_mimetypes_array();
  859. foreach ($mimetypes as $ext => $info) {
  860. if ($ext === 'xxx') {
  861. $this->assertEquals('application/octet-stream', get_mimetype_for_sending('SampleFile.' . $ext));
  862. } else {
  863. $this->assertEquals($info['type'], get_mimetype_for_sending('SampleFile.' . $ext));
  864. }
  865. }
  866. }
  867. /**
  868. * Test curl agent settings.
  869. */
  870. public function test_curl_useragent() {
  871. $curl = new testable_curl();
  872. $options = $curl->get_options();
  873. $this->assertNotEmpty($options);
  874. $moodlebot = \core_useragent::get_moodlebot_useragent();
  875. $curl->call_apply_opt($options);
  876. $this->assertTrue(in_array("User-Agent: $moodlebot", $curl->header));
  877. $this->assertFalse(in_array('User-Agent: Test/1.0', $curl->header));
  878. $options['CURLOPT_USERAGENT'] = 'Test/1.0';
  879. $curl->call_apply_opt($options);
  880. $this->assertTrue(in_array('User-Agent: Test/1.0', $curl->header));
  881. $this->assertFalse(in_array("User-Agent: $moodlebot", $curl->header));
  882. $curl->set_option('CURLOPT_USERAGENT', 'AnotherUserAgent/1.0');
  883. $curl->call_apply_opt();
  884. $this->assertTrue(in_array('User-Agent: AnotherUserAgent/1.0', $curl->header));
  885. $this->assertFalse(in_array('User-Agent: Test/1.0', $curl->header));
  886. $curl->set_option('CURLOPT_USERAGENT', 'AnotherUserAgent/1.1');
  887. $options = $curl->get_options();
  888. $curl->call_apply_opt($options);
  889. $this->assertTrue(in_array('User-Agent: AnotherUserAgent/1.1', $curl->header));
  890. $this->assertFalse(in_array('User-Agent: AnotherUserAgent/1.0', $curl->header));
  891. $curl->unset_option('CURLOPT_USERAGENT');
  892. $curl->call_apply_opt();
  893. $this->assertTrue(in_array("User-Agent: $moodlebot", $curl->header));
  894. // Finally, test it via exttests, to ensure the agent is sent properly.
  895. // Matching.
  896. $testurl = $this->getExternalTestFileUrl('/test_agent.php');
  897. $extcurl = new curl();
  898. $contents = $extcurl->get($testurl, array(), array('CURLOPT_USERAGENT' => 'AnotherUserAgent/1.2'));
  899. $response = $extcurl->getResponse();
  900. $this->assertSame('200 OK', reset($response));
  901. $this->assertSame(0, $extcurl->get_errno());
  902. $this->assertSame('OK', $contents);
  903. // Not matching.
  904. $contents = $extcurl->get($testurl, array(), array('CURLOPT_USERAGENT' => 'NonMatchingUserAgent/1.2'));
  905. $response = $extcurl->getResponse();
  906. $this->assertSame('200 OK', reset($response));
  907. $this->assertSame(0, $extcurl->get_errno());
  908. $this->assertSame('', $contents);
  909. }
  910. /**
  911. * Test file_rewrite_pluginfile_urls.
  912. */
  913. public function test_file_rewrite_pluginfile_urls() {
  914. $syscontext = context_system::instance();
  915. $originaltext = 'Fake test with an image <img src="@@PLUGINFILE@@/image.png">';
  916. // Do the rewrite.
  917. $finaltext = file_rewrite_pluginfile_urls($originaltext, 'pluginfile.php', $syscontext->id, 'user', 'private', 0);
  918. $this->assertStringContainsString("pluginfile.php", $finaltext);
  919. // Now undo.
  920. $options = array('reverse' => true);
  921. $finaltext = file_rewrite_pluginfile_urls($finaltext, 'pluginfile.php', $syscontext->id, 'user', 'private', 0, $options);
  922. // Compare the final text is the same that the original.
  923. $this->assertEquals($originaltext, $finaltext);
  924. }
  925. /**
  926. * Test file_rewrite_pluginfile_urls with includetoken.
  927. */
  928. public function test_file_rewrite_pluginfile_urls_includetoken() {
  929. global $USER, $CFG;
  930. $CFG->slasharguments = true;
  931. $this->resetAfterTest();
  932. $syscontext = context_system::instance();
  933. $originaltext = 'Fake test with an image <img src="@@PLUGINFILE@@/image.png">';
  934. $options = ['includetoken' => true];
  935. // Rewrite the content. This will generate a new token.
  936. $finaltext = file_rewrite_pluginfile_urls(
  937. $originaltext, 'pluginfile.php', $syscontext->id, 'user', 'private', 0, $options);
  938. $token = get_user_key('core_files', $USER->id);
  939. $expectedurl = new \moodle_url("/tokenpluginfile.php/{$token}/{$syscontext->id}/user/private/0/image.png");
  940. $expectedtext = "Fake test with an image <img src=\"{$expectedurl}\">";
  941. $this->assertEquals($expectedtext, $finaltext);
  942. // Do it again - the second time will use an existing token.
  943. $finaltext = file_rewrite_pluginfile_urls(
  944. $originaltext, 'pluginfile.php', $syscontext->id, 'user', 'private', 0, $options);
  945. $this->assertEquals($expectedtext, $finaltext);
  946. // Now undo.
  947. $options['reverse'] = true;
  948. $finaltext = file_rewrite_pluginfile_urls($finaltext, 'pluginfile.php', $syscontext->id, 'user', 'private', 0, $options);
  949. // Compare the final text is the same that the original.
  950. $this->assertEquals($originaltext, $finaltext);
  951. // Now indicates a user different than $USER.
  952. $user = $this->getDataGenerator()->create_user();
  953. $options = ['includetoken' => $user->id];
  954. // Rewrite the content. This will generate a new token.
  955. $finaltext = file_rewrite_pluginfile_urls(
  956. $originaltext, 'pluginfile.php', $syscontext->id, 'user', 'private', 0, $options);
  957. $token = get_user_key('core_files', $user->id);
  958. $expectedurl = new \moodle_url("/tokenpluginfile.php/{$token}/{$syscontext->id}/user/private/0/image.png");
  959. $expectedtext = "Fake test with an image <img src=\"{$expectedurl}\">";
  960. $this->assertEquals($expectedtext, $finaltext);
  961. }
  962. /**
  963. * Test file_rewrite_pluginfile_urls with includetoken with slasharguments disabled..
  964. */
  965. public function test_file_rewrite_pluginfile_urls_includetoken_no_slashargs() {
  966. global $USER, $CFG;
  967. $CFG->slasharguments = false;
  968. $this->resetAfterTest();
  969. $syscontext = context_system::instance();
  970. $originaltext = 'Fake test with an image <img src="@@PLUGINFILE@@/image.png">';
  971. $options = ['includetoken' => true];
  972. // Rewrite the content. This will generate a new token.
  973. $finaltext = file_rewrite_pluginfile_urls(
  974. $originaltext, 'pluginfile.php', $syscontext->id, 'user', 'private', 0, $options);
  975. $token = get_user_key('core_files', $USER->id);
  976. $expectedurl = new \moodle_url("/tokenpluginfile.php");
  977. $expectedurl .= "?token={$token}&file=/{$syscontext->id}/user/private/0/image.png";
  978. $expectedtext = "Fake test with an image <img src=\"{$expectedurl}\">";
  979. $this->assertEquals($expectedtext, $finaltext);
  980. // Do it again - the second time will use an existing token.
  981. $finaltext = file_rewrite_pluginfile_urls(
  982. $originaltext, 'pluginfile.php', $syscontext->id, 'user', 'private', 0, $options);
  983. $this->assertEquals($expectedtext, $finaltext);
  984. // Now undo.
  985. $options['reverse'] = true;
  986. $finaltext = file_rewrite_pluginfile_urls($finaltext, 'pluginfile.php', $syscontext->id, 'user', 'private', 0, $options);
  987. // Compare the final text is the same that the original.
  988. $this->assertEquals($originaltext, $finaltext);
  989. }
  990. /**
  991. * Helpter function to create draft files
  992. *
  993. * @param array $filedata data for the file record (to not use defaults)
  994. * @return stored_file the stored file instance
  995. */
  996. public static function create_draft_file($filedata = array()) {
  997. global $USER;
  998. $fs = get_file_storage();
  999. $filerecord = array(
  1000. 'component' => 'user',
  1001. 'filearea' => 'draft',
  1002. 'itemid' => isset($filedata['itemid']) ? $file

Large files files are truncated, but you can click here to view the full file