PageRenderTime 90ms CodeModel.GetById 30ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/filelib.php

https://github.com/dongsheng/moodle
PHP | 5175 lines | 3252 code | 534 blank | 1389 comment | 885 complexity | 2ae9b18013aff8782c4384398f6b4271 MD5 | raw file
Possible License(s): BSD-3-Clause, MIT, GPL-3.0, Apache-2.0, LGPL-2.1
  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. * Functions for file handling.
  18. *
  19. * @package core_files
  20. * @copyright 1999 onwards Martin Dougiamas (http://dougiamas.com)
  21. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  22. */
  23. defined('MOODLE_INTERNAL') || die();
  24. /**
  25. * BYTESERVING_BOUNDARY - string unique string constant.
  26. */
  27. define('BYTESERVING_BOUNDARY', 's1k2o3d4a5k6s7');
  28. /**
  29. * Do not process file merging when working with draft area files.
  30. */
  31. define('IGNORE_FILE_MERGE', -1);
  32. /**
  33. * Unlimited area size constant
  34. */
  35. define('FILE_AREA_MAX_BYTES_UNLIMITED', -1);
  36. /**
  37. * Capacity of the draft area bucket when using the leaking bucket technique to limit the draft upload rate.
  38. */
  39. define('DRAFT_AREA_BUCKET_CAPACITY', 50);
  40. /**
  41. * Leaking rate of the draft area bucket when using the leaking bucket technique to limit the draft upload rate.
  42. */
  43. define('DRAFT_AREA_BUCKET_LEAK', 0.2);
  44. require_once("$CFG->libdir/filestorage/file_exceptions.php");
  45. require_once("$CFG->libdir/filestorage/file_storage.php");
  46. require_once("$CFG->libdir/filestorage/zip_packer.php");
  47. require_once("$CFG->libdir/filebrowser/file_browser.php");
  48. /**
  49. * Encodes file serving url
  50. *
  51. * @deprecated use moodle_url factory methods instead
  52. *
  53. * @todo MDL-31071 deprecate this function
  54. * @global stdClass $CFG
  55. * @param string $urlbase
  56. * @param string $path /filearea/itemid/dir/dir/file.exe
  57. * @param bool $forcedownload
  58. * @param bool $https https url required
  59. * @return string encoded file url
  60. */
  61. function file_encode_url($urlbase, $path, $forcedownload=false, $https=false) {
  62. global $CFG;
  63. //TODO: deprecate this
  64. if ($CFG->slasharguments) {
  65. $parts = explode('/', $path);
  66. $parts = array_map('rawurlencode', $parts);
  67. $path = implode('/', $parts);
  68. $return = $urlbase.$path;
  69. if ($forcedownload) {
  70. $return .= '?forcedownload=1';
  71. }
  72. } else {
  73. $path = rawurlencode($path);
  74. $return = $urlbase.'?file='.$path;
  75. if ($forcedownload) {
  76. $return .= '&amp;forcedownload=1';
  77. }
  78. }
  79. if ($https) {
  80. $return = str_replace('http://', 'https://', $return);
  81. }
  82. return $return;
  83. }
  84. /**
  85. * Detects if area contains subdirs,
  86. * this is intended for file areas that are attached to content
  87. * migrated from 1.x where subdirs were allowed everywhere.
  88. *
  89. * @param context $context
  90. * @param string $component
  91. * @param string $filearea
  92. * @param string $itemid
  93. * @return bool
  94. */
  95. function file_area_contains_subdirs(context $context, $component, $filearea, $itemid) {
  96. global $DB;
  97. if (!isset($itemid)) {
  98. // Not initialised yet.
  99. return false;
  100. }
  101. // Detect if any directories are already present, this is necessary for content upgraded from 1.x.
  102. $select = "contextid = :contextid AND component = :component AND filearea = :filearea AND itemid = :itemid AND filepath <> '/' AND filename = '.'";
  103. $params = array('contextid'=>$context->id, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid);
  104. return $DB->record_exists_select('files', $select, $params);
  105. }
  106. /**
  107. * Prepares 'editor' formslib element from data in database
  108. *
  109. * The passed $data record must contain field foobar, foobarformat and optionally foobartrust. This
  110. * function then copies the embedded files into draft area (assigning itemids automatically),
  111. * creates the form element foobar_editor and rewrites the URLs so the embedded images can be
  112. * displayed.
  113. * In your mform definition, you must have an 'editor' element called foobar_editor. Then you call
  114. * your mform's set_data() supplying the object returned by this function.
  115. *
  116. * @category files
  117. * @param stdClass $data database field that holds the html text with embedded media
  118. * @param string $field the name of the database field that holds the html text with embedded media
  119. * @param array $options editor options (like maxifiles, maxbytes etc.)
  120. * @param stdClass $context context of the editor
  121. * @param string $component
  122. * @param string $filearea file area name
  123. * @param int $itemid item id, required if item exists
  124. * @return stdClass modified data object
  125. */
  126. function file_prepare_standard_editor($data, $field, array $options, $context=null, $component=null, $filearea=null, $itemid=null) {
  127. $options = (array)$options;
  128. if (!isset($options['trusttext'])) {
  129. $options['trusttext'] = false;
  130. }
  131. if (!isset($options['forcehttps'])) {
  132. $options['forcehttps'] = false;
  133. }
  134. if (!isset($options['subdirs'])) {
  135. $options['subdirs'] = false;
  136. }
  137. if (!isset($options['maxfiles'])) {
  138. $options['maxfiles'] = 0; // no files by default
  139. }
  140. if (!isset($options['noclean'])) {
  141. $options['noclean'] = false;
  142. }
  143. //sanity check for passed context. This function doesn't expect $option['context'] to be set
  144. //But this function is called before creating editor hence, this is one of the best places to check
  145. //if context is used properly. This check notify developer that they missed passing context to editor.
  146. if (isset($context) && !isset($options['context'])) {
  147. //if $context is not null then make sure $option['context'] is also set.
  148. debugging('Context for editor is not set in editoroptions. Hence editor will not respect editor filters', DEBUG_DEVELOPER);
  149. } else if (isset($options['context']) && isset($context)) {
  150. //If both are passed then they should be equal.
  151. if ($options['context']->id != $context->id) {
  152. $exceptionmsg = 'Editor context ['.$options['context']->id.'] is not equal to passed context ['.$context->id.']';
  153. throw new coding_exception($exceptionmsg);
  154. }
  155. }
  156. if (is_null($itemid) or is_null($context)) {
  157. $contextid = null;
  158. $itemid = null;
  159. if (!isset($data)) {
  160. $data = new stdClass();
  161. }
  162. if (!isset($data->{$field})) {
  163. $data->{$field} = '';
  164. }
  165. if (!isset($data->{$field.'format'})) {
  166. $data->{$field.'format'} = editors_get_preferred_format();
  167. }
  168. if (!$options['noclean']) {
  169. $data->{$field} = clean_text($data->{$field}, $data->{$field.'format'});
  170. }
  171. } else {
  172. if ($options['trusttext']) {
  173. // noclean ignored if trusttext enabled
  174. if (!isset($data->{$field.'trust'})) {
  175. $data->{$field.'trust'} = 0;
  176. }
  177. $data = trusttext_pre_edit($data, $field, $context);
  178. } else {
  179. if (!$options['noclean']) {
  180. $data->{$field} = clean_text($data->{$field}, $data->{$field.'format'});
  181. }
  182. }
  183. $contextid = $context->id;
  184. }
  185. if ($options['maxfiles'] != 0) {
  186. $draftid_editor = file_get_submitted_draft_itemid($field);
  187. $currenttext = file_prepare_draft_area($draftid_editor, $contextid, $component, $filearea, $itemid, $options, $data->{$field});
  188. $data->{$field.'_editor'} = array('text'=>$currenttext, 'format'=>$data->{$field.'format'}, 'itemid'=>$draftid_editor);
  189. } else {
  190. $data->{$field.'_editor'} = array('text'=>$data->{$field}, 'format'=>$data->{$field.'format'}, 'itemid'=>0);
  191. }
  192. return $data;
  193. }
  194. /**
  195. * Prepares the content of the 'editor' form element with embedded media files to be saved in database
  196. *
  197. * This function moves files from draft area to the destination area and
  198. * encodes URLs to the draft files so they can be safely saved into DB. The
  199. * form has to contain the 'editor' element named foobar_editor, where 'foobar'
  200. * is the name of the database field to hold the wysiwyg editor content. The
  201. * editor data comes as an array with text, format and itemid properties. This
  202. * function automatically adds $data properties foobar, foobarformat and
  203. * foobartrust, where foobar has URL to embedded files encoded.
  204. *
  205. * @category files
  206. * @param stdClass $data raw data submitted by the form
  207. * @param string $field name of the database field containing the html with embedded media files
  208. * @param array $options editor options (trusttext, subdirs, maxfiles, maxbytes etc.)
  209. * @param stdClass $context context, required for existing data
  210. * @param string $component file component
  211. * @param string $filearea file area name
  212. * @param int $itemid item id, required if item exists
  213. * @return stdClass modified data object
  214. */
  215. function file_postupdate_standard_editor($data, $field, array $options, $context, $component=null, $filearea=null, $itemid=null) {
  216. $options = (array)$options;
  217. if (!isset($options['trusttext'])) {
  218. $options['trusttext'] = false;
  219. }
  220. if (!isset($options['forcehttps'])) {
  221. $options['forcehttps'] = false;
  222. }
  223. if (!isset($options['subdirs'])) {
  224. $options['subdirs'] = false;
  225. }
  226. if (!isset($options['maxfiles'])) {
  227. $options['maxfiles'] = 0; // no files by default
  228. }
  229. if (!isset($options['maxbytes'])) {
  230. $options['maxbytes'] = 0; // unlimited
  231. }
  232. if (!isset($options['removeorphaneddrafts'])) {
  233. $options['removeorphaneddrafts'] = false; // Don't remove orphaned draft files by default.
  234. }
  235. if ($options['trusttext']) {
  236. $data->{$field.'trust'} = trusttext_trusted($context);
  237. } else {
  238. $data->{$field.'trust'} = 0;
  239. }
  240. $editor = $data->{$field.'_editor'};
  241. if ($options['maxfiles'] == 0 or is_null($filearea) or is_null($itemid) or empty($editor['itemid'])) {
  242. $data->{$field} = $editor['text'];
  243. } else {
  244. // Clean the user drafts area of any files not referenced in the editor text.
  245. if ($options['removeorphaneddrafts']) {
  246. file_remove_editor_orphaned_files($editor);
  247. }
  248. $data->{$field} = file_save_draft_area_files($editor['itemid'], $context->id, $component, $filearea, $itemid, $options, $editor['text'], $options['forcehttps']);
  249. }
  250. $data->{$field.'format'} = $editor['format'];
  251. return $data;
  252. }
  253. /**
  254. * Saves text and files modified by Editor formslib element
  255. *
  256. * @category files
  257. * @param stdClass $data $database entry field
  258. * @param string $field name of data field
  259. * @param array $options various options
  260. * @param stdClass $context context - must already exist
  261. * @param string $component
  262. * @param string $filearea file area name
  263. * @param int $itemid must already exist, usually means data is in db
  264. * @return stdClass modified data obejct
  265. */
  266. function file_prepare_standard_filemanager($data, $field, array $options, $context=null, $component=null, $filearea=null, $itemid=null) {
  267. $options = (array)$options;
  268. if (!isset($options['subdirs'])) {
  269. $options['subdirs'] = false;
  270. }
  271. if (is_null($itemid) or is_null($context)) {
  272. $itemid = null;
  273. $contextid = null;
  274. } else {
  275. $contextid = $context->id;
  276. }
  277. $draftid_editor = file_get_submitted_draft_itemid($field.'_filemanager');
  278. file_prepare_draft_area($draftid_editor, $contextid, $component, $filearea, $itemid, $options);
  279. $data->{$field.'_filemanager'} = $draftid_editor;
  280. return $data;
  281. }
  282. /**
  283. * Saves files modified by File manager formslib element
  284. *
  285. * @todo MDL-31073 review this function
  286. * @category files
  287. * @param stdClass $data $database entry field
  288. * @param string $field name of data field
  289. * @param array $options various options
  290. * @param stdClass $context context - must already exist
  291. * @param string $component
  292. * @param string $filearea file area name
  293. * @param int $itemid must already exist, usually means data is in db
  294. * @return stdClass modified data obejct
  295. */
  296. function file_postupdate_standard_filemanager($data, $field, array $options, $context, $component, $filearea, $itemid) {
  297. $options = (array)$options;
  298. if (!isset($options['subdirs'])) {
  299. $options['subdirs'] = false;
  300. }
  301. if (!isset($options['maxfiles'])) {
  302. $options['maxfiles'] = -1; // unlimited
  303. }
  304. if (!isset($options['maxbytes'])) {
  305. $options['maxbytes'] = 0; // unlimited
  306. }
  307. if (empty($data->{$field.'_filemanager'})) {
  308. $data->$field = '';
  309. } else {
  310. file_save_draft_area_files($data->{$field.'_filemanager'}, $context->id, $component, $filearea, $itemid, $options);
  311. $fs = get_file_storage();
  312. if ($fs->get_area_files($context->id, $component, $filearea, $itemid)) {
  313. $data->$field = '1'; // TODO: this is an ugly hack (skodak)
  314. } else {
  315. $data->$field = '';
  316. }
  317. }
  318. return $data;
  319. }
  320. /**
  321. * Generate a draft itemid
  322. *
  323. * @category files
  324. * @global moodle_database $DB
  325. * @global stdClass $USER
  326. * @return int a random but available draft itemid that can be used to create a new draft
  327. * file area.
  328. */
  329. function file_get_unused_draft_itemid() {
  330. global $DB, $USER;
  331. if (isguestuser() or !isloggedin()) {
  332. // guests and not-logged-in users can not be allowed to upload anything!!!!!!
  333. print_error('noguest');
  334. }
  335. $contextid = context_user::instance($USER->id)->id;
  336. $fs = get_file_storage();
  337. $draftitemid = rand(1, 999999999);
  338. while ($files = $fs->get_area_files($contextid, 'user', 'draft', $draftitemid)) {
  339. $draftitemid = rand(1, 999999999);
  340. }
  341. return $draftitemid;
  342. }
  343. /**
  344. * Initialise a draft file area from a real one by copying the files. A draft
  345. * area will be created if one does not already exist. Normally you should
  346. * get $draftitemid by calling file_get_submitted_draft_itemid('elementname');
  347. *
  348. * @category files
  349. * @global stdClass $CFG
  350. * @global stdClass $USER
  351. * @param int $draftitemid the id of the draft area to use, or 0 to create a new one, in which case this parameter is updated.
  352. * @param int $contextid This parameter and the next two identify the file area to copy files from.
  353. * @param string $component
  354. * @param string $filearea helps indentify the file area.
  355. * @param int $itemid helps identify the file area. Can be null if there are no files yet.
  356. * @param array $options text and file options ('subdirs'=>false, 'forcehttps'=>false)
  357. * @param string $text some html content that needs to have embedded links rewritten to point to the draft area.
  358. * @return string|null returns string if $text was passed in, the rewritten $text is returned. Otherwise NULL.
  359. */
  360. function file_prepare_draft_area(&$draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null) {
  361. global $CFG, $USER;
  362. $options = (array)$options;
  363. if (!isset($options['subdirs'])) {
  364. $options['subdirs'] = false;
  365. }
  366. if (!isset($options['forcehttps'])) {
  367. $options['forcehttps'] = false;
  368. }
  369. $usercontext = context_user::instance($USER->id);
  370. $fs = get_file_storage();
  371. if (empty($draftitemid)) {
  372. // create a new area and copy existing files into
  373. $draftitemid = file_get_unused_draft_itemid();
  374. $file_record = array('contextid'=>$usercontext->id, 'component'=>'user', 'filearea'=>'draft', 'itemid'=>$draftitemid);
  375. if (!is_null($itemid) and $files = $fs->get_area_files($contextid, $component, $filearea, $itemid)) {
  376. foreach ($files as $file) {
  377. if ($file->is_directory() and $file->get_filepath() === '/') {
  378. // we need a way to mark the age of each draft area,
  379. // by not copying the root dir we force it to be created automatically with current timestamp
  380. continue;
  381. }
  382. if (!$options['subdirs'] and ($file->is_directory() or $file->get_filepath() !== '/')) {
  383. continue;
  384. }
  385. $draftfile = $fs->create_file_from_storedfile($file_record, $file);
  386. // XXX: This is a hack for file manager (MDL-28666)
  387. // File manager needs to know the original file information before copying
  388. // to draft area, so we append these information in mdl_files.source field
  389. // {@link file_storage::search_references()}
  390. // {@link file_storage::search_references_count()}
  391. $sourcefield = $file->get_source();
  392. $newsourcefield = new stdClass;
  393. $newsourcefield->source = $sourcefield;
  394. $original = new stdClass;
  395. $original->contextid = $contextid;
  396. $original->component = $component;
  397. $original->filearea = $filearea;
  398. $original->itemid = $itemid;
  399. $original->filename = $file->get_filename();
  400. $original->filepath = $file->get_filepath();
  401. $newsourcefield->original = file_storage::pack_reference($original);
  402. $draftfile->set_source(serialize($newsourcefield));
  403. // End of file manager hack
  404. }
  405. }
  406. if (!is_null($text)) {
  407. // at this point there should not be any draftfile links yet,
  408. // because this is a new text from database that should still contain the @@pluginfile@@ links
  409. // this happens when developers forget to post process the text
  410. $text = str_replace("\"$CFG->wwwroot/draftfile.php", "\"$CFG->wwwroot/brokenfile.php#", $text);
  411. }
  412. } else {
  413. // nothing to do
  414. }
  415. if (is_null($text)) {
  416. return null;
  417. }
  418. // relink embedded files - editor can not handle @@PLUGINFILE@@ !
  419. return file_rewrite_pluginfile_urls($text, 'draftfile.php', $usercontext->id, 'user', 'draft', $draftitemid, $options);
  420. }
  421. /**
  422. * Convert encoded URLs in $text from the @@PLUGINFILE@@/... form to an actual URL.
  423. * Passing a new option reverse = true in the $options var will make the function to convert actual URLs in $text to encoded URLs
  424. * in the @@PLUGINFILE@@ form.
  425. *
  426. * @param string $text The content that may contain ULRs in need of rewriting.
  427. * @param string $file The script that should be used to serve these files. pluginfile.php, draftfile.php, etc.
  428. * @param int $contextid This parameter and the next two identify the file area to use.
  429. * @param string $component
  430. * @param string $filearea helps identify the file area.
  431. * @param int $itemid helps identify the file area.
  432. * @param array $options
  433. * bool $options.forcehttps Force the user of https
  434. * bool $options.reverse Reverse the behaviour of the function
  435. * mixed $options.includetoken Use a token for authentication. True for current user, int value for other user id.
  436. * string The processed text.
  437. */
  438. function file_rewrite_pluginfile_urls($text, $file, $contextid, $component, $filearea, $itemid, array $options=null) {
  439. global $CFG, $USER;
  440. $options = (array)$options;
  441. if (!isset($options['forcehttps'])) {
  442. $options['forcehttps'] = false;
  443. }
  444. $baseurl = "{$CFG->wwwroot}/{$file}";
  445. if (!empty($options['includetoken'])) {
  446. $userid = $options['includetoken'] === true ? $USER->id : $options['includetoken'];
  447. $token = get_user_key('core_files', $userid);
  448. $finalfile = basename($file);
  449. $tokenfile = "token{$finalfile}";
  450. $file = substr($file, 0, strlen($file) - strlen($finalfile)) . $tokenfile;
  451. $baseurl = "{$CFG->wwwroot}/{$file}";
  452. if (!$CFG->slasharguments) {
  453. $baseurl .= "?token={$token}&file=";
  454. } else {
  455. $baseurl .= "/{$token}";
  456. }
  457. }
  458. $baseurl .= "/{$contextid}/{$component}/{$filearea}/";
  459. if ($itemid !== null) {
  460. $baseurl .= "$itemid/";
  461. }
  462. if ($options['forcehttps']) {
  463. $baseurl = str_replace('http://', 'https://', $baseurl);
  464. }
  465. if (!empty($options['reverse'])) {
  466. return str_replace($baseurl, '@@PLUGINFILE@@/', $text);
  467. } else {
  468. return str_replace('@@PLUGINFILE@@/', $baseurl, $text);
  469. }
  470. }
  471. /**
  472. * Returns information about files in a draft area.
  473. *
  474. * @global stdClass $CFG
  475. * @global stdClass $USER
  476. * @param int $draftitemid the draft area item id.
  477. * @param string $filepath path to the directory from which the information have to be retrieved.
  478. * @return array with the following entries:
  479. * 'filecount' => number of files in the draft area.
  480. * 'filesize' => total size of the files in the draft area.
  481. * 'foldercount' => number of folders in the draft area.
  482. * 'filesize_without_references' => total size of the area excluding file references.
  483. * (more information will be added as needed).
  484. */
  485. function file_get_draft_area_info($draftitemid, $filepath = '/') {
  486. global $USER;
  487. $usercontext = context_user::instance($USER->id);
  488. return file_get_file_area_info($usercontext->id, 'user', 'draft', $draftitemid, $filepath);
  489. }
  490. /**
  491. * Returns information about files in an area.
  492. *
  493. * @param int $contextid context id
  494. * @param string $component component
  495. * @param string $filearea file area name
  496. * @param int $itemid item id or all files if not specified
  497. * @param string $filepath path to the directory from which the information have to be retrieved.
  498. * @return array with the following entries:
  499. * 'filecount' => number of files in the area.
  500. * 'filesize' => total size of the files in the area.
  501. * 'foldercount' => number of folders in the area.
  502. * 'filesize_without_references' => total size of the area excluding file references.
  503. * @since Moodle 3.4
  504. */
  505. function file_get_file_area_info($contextid, $component, $filearea, $itemid = 0, $filepath = '/') {
  506. $fs = get_file_storage();
  507. $results = array(
  508. 'filecount' => 0,
  509. 'foldercount' => 0,
  510. 'filesize' => 0,
  511. 'filesize_without_references' => 0
  512. );
  513. $draftfiles = $fs->get_directory_files($contextid, $component, $filearea, $itemid, $filepath, true, true);
  514. foreach ($draftfiles as $file) {
  515. if ($file->is_directory()) {
  516. $results['foldercount'] += 1;
  517. } else {
  518. $results['filecount'] += 1;
  519. }
  520. $filesize = $file->get_filesize();
  521. $results['filesize'] += $filesize;
  522. if (!$file->is_external_file()) {
  523. $results['filesize_without_references'] += $filesize;
  524. }
  525. }
  526. return $results;
  527. }
  528. /**
  529. * Returns whether a draft area has exceeded/will exceed its size limit.
  530. *
  531. * Please note that the unlimited value for $areamaxbytes is -1 {@link FILE_AREA_MAX_BYTES_UNLIMITED}, not 0.
  532. *
  533. * @param int $draftitemid the draft area item id.
  534. * @param int $areamaxbytes the maximum size allowed in this draft area.
  535. * @param int $newfilesize the size that would be added to the current area.
  536. * @param bool $includereferences true to include the size of the references in the area size.
  537. * @return bool true if the area will/has exceeded its limit.
  538. * @since Moodle 2.4
  539. */
  540. function file_is_draft_area_limit_reached($draftitemid, $areamaxbytes, $newfilesize = 0, $includereferences = false) {
  541. if ($areamaxbytes != FILE_AREA_MAX_BYTES_UNLIMITED) {
  542. $draftinfo = file_get_draft_area_info($draftitemid);
  543. $areasize = $draftinfo['filesize_without_references'];
  544. if ($includereferences) {
  545. $areasize = $draftinfo['filesize'];
  546. }
  547. if ($areasize + $newfilesize > $areamaxbytes) {
  548. return true;
  549. }
  550. }
  551. return false;
  552. }
  553. /**
  554. * Returns whether a user has reached their draft area upload rate.
  555. *
  556. * @param int $userid The user id
  557. * @return bool
  558. */
  559. function file_is_draft_areas_limit_reached(int $userid): bool {
  560. global $CFG;
  561. $capacity = $CFG->draft_area_bucket_capacity ?? DRAFT_AREA_BUCKET_CAPACITY;
  562. $leak = $CFG->draft_area_bucket_leak ?? DRAFT_AREA_BUCKET_LEAK;
  563. $since = time() - floor($capacity / $leak); // The items that were in the bucket before this time are already leaked by now.
  564. // We are going to be a bit generous to the user when using the leaky bucket
  565. // algorithm below. We are going to assume that the bucket is empty at $since.
  566. // We have to do an assumption here unless we really want to get ALL user's draft
  567. // items without any limit and put all of them in the leaking bucket.
  568. // I decided to favour performance over accuracy here.
  569. $fs = get_file_storage();
  570. $items = $fs->get_user_draft_items($userid, $since);
  571. $items = array_reverse($items); // So that the items are sorted based on time in the ascending direction.
  572. // We only need to store the time that each element in the bucket is going to leak. So $bucket is array of leaking times.
  573. $bucket = [];
  574. foreach ($items as $item) {
  575. $now = $item->timemodified;
  576. // First let's see if items can be dropped from the bucket as a result of leakage.
  577. while (!empty($bucket) && ($now >= $bucket[0])) {
  578. array_shift($bucket);
  579. }
  580. // Calculate the time that the new item we put into the bucket will be leaked from it, and store it into the bucket.
  581. if ($bucket) {
  582. $bucket[] = max($bucket[count($bucket) - 1], $now) + (1 / $leak);
  583. } else {
  584. $bucket[] = $now + (1 / $leak);
  585. }
  586. }
  587. // Recalculate the bucket's content based on the leakage until now.
  588. $now = time();
  589. while (!empty($bucket) && ($now >= $bucket[0])) {
  590. array_shift($bucket);
  591. }
  592. return count($bucket) >= $capacity;
  593. }
  594. /**
  595. * Get used space of files
  596. * @global moodle_database $DB
  597. * @global stdClass $USER
  598. * @return int total bytes
  599. */
  600. function file_get_user_used_space() {
  601. global $DB, $USER;
  602. $usercontext = context_user::instance($USER->id);
  603. $sql = "SELECT SUM(files1.filesize) AS totalbytes FROM {files} files1
  604. JOIN (SELECT contenthash, filename, MAX(id) AS id
  605. FROM {files}
  606. WHERE contextid = ? AND component = ? AND filearea != ?
  607. GROUP BY contenthash, filename) files2 ON files1.id = files2.id";
  608. $params = array('contextid'=>$usercontext->id, 'component'=>'user', 'filearea'=>'draft');
  609. $record = $DB->get_record_sql($sql, $params);
  610. return (int)$record->totalbytes;
  611. }
  612. /**
  613. * Convert any string to a valid filepath
  614. * @todo review this function
  615. * @param string $str
  616. * @return string path
  617. */
  618. function file_correct_filepath($str) { //TODO: what is this? (skodak) - No idea (Fred)
  619. if ($str == '/' or empty($str)) {
  620. return '/';
  621. } else {
  622. return '/'.trim($str, '/').'/';
  623. }
  624. }
  625. /**
  626. * Generate a folder tree of draft area of current USER recursively
  627. *
  628. * @todo MDL-31073 use normal return value instead, this does not fit the rest of api here (skodak)
  629. * @param int $draftitemid
  630. * @param string $filepath
  631. * @param mixed $data
  632. */
  633. function file_get_drafarea_folders($draftitemid, $filepath, &$data) {
  634. global $USER, $OUTPUT, $CFG;
  635. $data->children = array();
  636. $context = context_user::instance($USER->id);
  637. $fs = get_file_storage();
  638. if ($files = $fs->get_directory_files($context->id, 'user', 'draft', $draftitemid, $filepath, false)) {
  639. foreach ($files as $file) {
  640. if ($file->is_directory()) {
  641. $item = new stdClass();
  642. $item->sortorder = $file->get_sortorder();
  643. $item->filepath = $file->get_filepath();
  644. $foldername = explode('/', trim($item->filepath, '/'));
  645. $item->fullname = trim(array_pop($foldername), '/');
  646. $item->id = uniqid();
  647. file_get_drafarea_folders($draftitemid, $item->filepath, $item);
  648. $data->children[] = $item;
  649. } else {
  650. continue;
  651. }
  652. }
  653. }
  654. }
  655. /**
  656. * Listing all files (including folders) in current path (draft area)
  657. * used by file manager
  658. * @param int $draftitemid
  659. * @param string $filepath
  660. * @return stdClass
  661. */
  662. function file_get_drafarea_files($draftitemid, $filepath = '/') {
  663. global $USER, $OUTPUT, $CFG;
  664. $context = context_user::instance($USER->id);
  665. $fs = get_file_storage();
  666. $data = new stdClass();
  667. $data->path = array();
  668. $data->path[] = array('name'=>get_string('files'), 'path'=>'/');
  669. // will be used to build breadcrumb
  670. $trail = '/';
  671. if ($filepath !== '/') {
  672. $filepath = file_correct_filepath($filepath);
  673. $parts = explode('/', $filepath);
  674. foreach ($parts as $part) {
  675. if ($part != '' && $part != null) {
  676. $trail .= ($part.'/');
  677. $data->path[] = array('name'=>$part, 'path'=>$trail);
  678. }
  679. }
  680. }
  681. $list = array();
  682. $maxlength = 12;
  683. if ($files = $fs->get_directory_files($context->id, 'user', 'draft', $draftitemid, $filepath, false)) {
  684. foreach ($files as $file) {
  685. $item = new stdClass();
  686. $item->filename = $file->get_filename();
  687. $item->filepath = $file->get_filepath();
  688. $item->fullname = trim($item->filename, '/');
  689. $filesize = $file->get_filesize();
  690. $item->size = $filesize ? $filesize : null;
  691. $item->filesize = $filesize ? display_size($filesize) : '';
  692. $item->sortorder = $file->get_sortorder();
  693. $item->author = $file->get_author();
  694. $item->license = $file->get_license();
  695. $item->datemodified = $file->get_timemodified();
  696. $item->datecreated = $file->get_timecreated();
  697. $item->isref = $file->is_external_file();
  698. if ($item->isref && $file->get_status() == 666) {
  699. $item->originalmissing = true;
  700. }
  701. // find the file this draft file was created from and count all references in local
  702. // system pointing to that file
  703. $source = @unserialize($file->get_source());
  704. if (isset($source->original)) {
  705. $item->refcount = $fs->search_references_count($source->original);
  706. }
  707. if ($file->is_directory()) {
  708. $item->filesize = 0;
  709. $item->icon = $OUTPUT->image_url(file_folder_icon(24))->out(false);
  710. $item->type = 'folder';
  711. $foldername = explode('/', trim($item->filepath, '/'));
  712. $item->fullname = trim(array_pop($foldername), '/');
  713. $item->thumbnail = $OUTPUT->image_url(file_folder_icon(90))->out(false);
  714. } else {
  715. // do NOT use file browser here!
  716. $item->mimetype = get_mimetype_description($file);
  717. if (file_extension_in_typegroup($file->get_filename(), 'archive')) {
  718. $item->type = 'zip';
  719. } else {
  720. $item->type = 'file';
  721. }
  722. $itemurl = moodle_url::make_draftfile_url($draftitemid, $item->filepath, $item->filename);
  723. $item->url = $itemurl->out();
  724. $item->icon = $OUTPUT->image_url(file_file_icon($file, 24))->out(false);
  725. $item->thumbnail = $OUTPUT->image_url(file_file_icon($file, 90))->out(false);
  726. // The call to $file->get_imageinfo() fails with an exception if the file can't be read on the file system.
  727. // We still want to add such files to the list, so the owner can view and delete them if needed. So, we only call
  728. // get_imageinfo() on files that can be read, and we also spoof the file status based on whether it was found.
  729. // We'll use the same status types used by stored_file->get_status(), where 0 = OK. 1 = problem, as these will be
  730. // used by the widget to display a warning about the problem files.
  731. // The value of stored_file->get_status(), and the file record are unaffected by this. It's only superficially set.
  732. $item->status = $fs->get_file_system()->is_file_readable_remotely_by_storedfile($file) ? 0 : 1;
  733. if ($item->status == 0) {
  734. if ($imageinfo = $file->get_imageinfo()) {
  735. $item->realthumbnail = $itemurl->out(false, array('preview' => 'thumb',
  736. 'oid' => $file->get_timemodified()));
  737. $item->realicon = $itemurl->out(false, array('preview' => 'tinyicon', 'oid' => $file->get_timemodified()));
  738. $item->image_width = $imageinfo['width'];
  739. $item->image_height = $imageinfo['height'];
  740. }
  741. }
  742. }
  743. $list[] = $item;
  744. }
  745. }
  746. $data->itemid = $draftitemid;
  747. $data->list = $list;
  748. return $data;
  749. }
  750. /**
  751. * Returns all of the files in the draftarea.
  752. *
  753. * @param int $draftitemid The draft item ID
  754. * @param string $filepath path for the uploaded files.
  755. * @return array An array of files associated with this draft item id.
  756. */
  757. function file_get_all_files_in_draftarea(int $draftitemid, string $filepath = '/') : array {
  758. $files = [];
  759. $draftfiles = file_get_drafarea_files($draftitemid, $filepath);
  760. file_get_drafarea_folders($draftitemid, $filepath, $draftfiles);
  761. if (!empty($draftfiles)) {
  762. foreach ($draftfiles->list as $draftfile) {
  763. if ($draftfile->type == 'file') {
  764. $files[] = $draftfile;
  765. }
  766. }
  767. if (isset($draftfiles->children)) {
  768. foreach ($draftfiles->children as $draftfile) {
  769. $files = array_merge($files, file_get_all_files_in_draftarea($draftitemid, $draftfile->filepath));
  770. }
  771. }
  772. }
  773. return $files;
  774. }
  775. /**
  776. * Returns draft area itemid for a given element.
  777. *
  778. * @category files
  779. * @param string $elname name of formlib editor element, or a hidden form field that stores the draft area item id, etc.
  780. * @return int the itemid, or 0 if there is not one yet.
  781. */
  782. function file_get_submitted_draft_itemid($elname) {
  783. // this is a nasty hack, ideally all new elements should use arrays here or there should be a new parameter
  784. if (!isset($_REQUEST[$elname])) {
  785. return 0;
  786. }
  787. if (is_array($_REQUEST[$elname])) {
  788. $param = optional_param_array($elname, 0, PARAM_INT);
  789. if (!empty($param['itemid'])) {
  790. $param = $param['itemid'];
  791. } else {
  792. debugging('Missing itemid, maybe caused by unset maxfiles option', DEBUG_DEVELOPER);
  793. return false;
  794. }
  795. } else {
  796. $param = optional_param($elname, 0, PARAM_INT);
  797. }
  798. if ($param) {
  799. require_sesskey();
  800. }
  801. return $param;
  802. }
  803. /**
  804. * Restore the original source field from draft files
  805. *
  806. * Do not use this function because it makes field files.source inconsistent
  807. * for draft area files. This function will be deprecated in 2.6
  808. *
  809. * @param stored_file $storedfile This only works with draft files
  810. * @return stored_file
  811. */
  812. function file_restore_source_field_from_draft_file($storedfile) {
  813. $source = @unserialize($storedfile->get_source());
  814. if (!empty($source)) {
  815. if (is_object($source)) {
  816. $restoredsource = $source->source;
  817. $storedfile->set_source($restoredsource);
  818. } else {
  819. throw new moodle_exception('invalidsourcefield', 'error');
  820. }
  821. }
  822. return $storedfile;
  823. }
  824. /**
  825. * Removes those files from the user drafts filearea which are not referenced in the editor text.
  826. *
  827. * @param stdClass $editor The online text editor element from the submitted form data.
  828. */
  829. function file_remove_editor_orphaned_files($editor) {
  830. global $CFG, $USER;
  831. // Find those draft files included in the text, and generate their hashes.
  832. $context = context_user::instance($USER->id);
  833. $baseurl = $CFG->wwwroot . '/draftfile.php/' . $context->id . '/user/draft/' . $editor['itemid'] . '/';
  834. $pattern = "/" . preg_quote($baseurl, '/') . "(.+?)[\?\"']/";
  835. preg_match_all($pattern, $editor['text'], $matches);
  836. $usedfilehashes = [];
  837. foreach ($matches[1] as $matchedfilename) {
  838. $matchedfilename = urldecode($matchedfilename);
  839. $usedfilehashes[] = \file_storage::get_pathname_hash($context->id, 'user', 'draft', $editor['itemid'], '/',
  840. $matchedfilename);
  841. }
  842. // Now, compare the hashes of all draft files, and remove those which don't match used files.
  843. $fs = get_file_storage();
  844. $files = $fs->get_area_files($context->id, 'user', 'draft', $editor['itemid'], 'id', false);
  845. foreach ($files as $file) {
  846. $tmphash = $file->get_pathnamehash();
  847. if (!in_array($tmphash, $usedfilehashes)) {
  848. $file->delete();
  849. }
  850. }
  851. }
  852. /**
  853. * Finds all draft areas used in a textarea and copies the files into the primary textarea. If a user copies and pastes
  854. * content from another draft area it's possible for a single textarea to reference multiple draft areas.
  855. *
  856. * @category files
  857. * @param int $draftitemid the id of the primary draft area.
  858. * When set to -1 (probably, by a WebService) it won't process file merging, keeping the original state of the file area.
  859. * @param int $usercontextid the user's context id.
  860. * @param string $text some html content that needs to have files copied to the correct draft area.
  861. * @param bool $forcehttps force https urls.
  862. *
  863. * @return string $text html content modified with new draft links
  864. */
  865. function file_merge_draft_areas($draftitemid, $usercontextid, $text, $forcehttps = false) {
  866. if (is_null($text)) {
  867. return null;
  868. }
  869. // Do not merge files, leave it as it was.
  870. if ($draftitemid === IGNORE_FILE_MERGE) {
  871. return null;
  872. }
  873. $urls = extract_draft_file_urls_from_text($text, $forcehttps, $usercontextid, 'user', 'draft');
  874. // No draft areas to rewrite.
  875. if (empty($urls)) {
  876. return $text;
  877. }
  878. foreach ($urls as $url) {
  879. // Do not process the "home" draft area.
  880. if ($url['itemid'] == $draftitemid) {
  881. continue;
  882. }
  883. // Decode the filename.
  884. $filename = urldecode($url['filename']);
  885. // Copy the file.
  886. file_copy_file_to_file_area($url, $filename, $draftitemid);
  887. // Rewrite draft area.
  888. $text = file_replace_file_area_in_text($url, $draftitemid, $text, $forcehttps);
  889. }
  890. return $text;
  891. }
  892. /**
  893. * Rewrites a file area in arbitrary text.
  894. *
  895. * @param array $file General information about the file.
  896. * @param int $newid The new file area itemid.
  897. * @param string $text The text to rewrite.
  898. * @param bool $forcehttps force https urls.
  899. * @return string The rewritten text.
  900. */
  901. function file_replace_file_area_in_text($file, $newid, $text, $forcehttps = false) {
  902. global $CFG;
  903. $wwwroot = $CFG->wwwroot;
  904. if ($forcehttps) {
  905. $wwwroot = str_replace('http://', 'https://', $wwwroot);
  906. }
  907. $search = [
  908. $wwwroot,
  909. $file['urlbase'],
  910. $file['contextid'],
  911. $file['component'],
  912. $file['filearea'],
  913. $file['itemid'],
  914. $file['filename']
  915. ];
  916. $replace = [
  917. $wwwroot,
  918. $file['urlbase'],
  919. $file['contextid'],
  920. $file['component'],
  921. $file['filearea'],
  922. $newid,
  923. $file['filename']
  924. ];
  925. $text = str_ireplace( implode('/', $search), implode('/', $replace), $text);
  926. return $text;
  927. }
  928. /**
  929. * Copies a file from one file area to another.
  930. *
  931. * @param array $file Information about the file to be copied.
  932. * @param string $filename The filename.
  933. * @param int $itemid The new file area.
  934. */
  935. function file_copy_file_to_file_area($file, $filename, $itemid) {
  936. $fs = get_file_storage();
  937. // Load the current file in the old draft area.
  938. $fileinfo = array(
  939. 'component' => $file['component'],
  940. 'filearea' => $file['filearea'],
  941. 'itemid' => $file['itemid'],
  942. 'contextid' => $file['contextid'],
  943. 'filepath' => '/',
  944. 'filename' => $filename
  945. );
  946. $oldfile = $fs->get_file($fileinfo['contextid'], $fileinfo['component'], $fileinfo['filearea'],
  947. $fileinfo['itemid'], $fileinfo['filepath'], $fileinfo['filename']);
  948. $newfileinfo = array(
  949. 'component' => $file['component'],
  950. 'filearea' => $file['filearea'],
  951. 'itemid' => $itemid,
  952. 'contextid' => $file['contextid'],
  953. 'filepath' => '/',
  954. 'filename' => $filename
  955. );
  956. $newcontextid = $newfileinfo['contextid'];
  957. $newcomponent = $newfileinfo['component'];
  958. $newfilearea = $newfileinfo['filearea'];
  959. $newitemid = $newfileinfo['itemid'];
  960. $newfilepath = $newfileinfo['filepath'];
  961. $newfilename = $newfileinfo['filename'];
  962. // Check if the file exists.
  963. if (!$fs->file_exists($newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
  964. $fs->create_file_from_storedfile($newfileinfo, $oldfile);
  965. }
  966. }
  967. /**
  968. * Saves files from a draft file area to a real one (merging the list of files).
  969. * Can rewrite URLs in some content at the same time if desired.
  970. *
  971. * @category files
  972. * @global stdClass $USER
  973. * @param int $draftitemid the id of the draft area to use. Normally obtained
  974. * from file_get_submitted_draft_itemid('elementname') or similar.
  975. * When set to -1 (probably, by a WebService) it won't process file merging, keeping the original state of the file area.
  976. * @param int $contextid This parameter and the next two identify the file area to save to.
  977. * @param string $component
  978. * @param string $filearea indentifies the file area.
  979. * @param int $itemid helps identifies the file area.
  980. * @param array $options area options (subdirs=>false, maxfiles=-1, maxbytes=0)
  981. * @param string $text some html content that needs to have embedded links rewritten
  982. * to the @@PLUGINFILE@@ form for saving in the database.
  983. * @param bool $forcehttps force https urls.
  984. * @return string|null if $text was passed in, the rewritten $text is returned. Otherwise NULL.
  985. */
  986. function file_save_draft_area_files($draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null, $forcehttps=false) {
  987. global $USER;
  988. // Do not merge files, leave it as it was.
  989. if ($draftitemid === IGNORE_FILE_MERGE) {
  990. // Safely return $text, no need to rewrite pluginfile because this is mostly comming from an external client like the app.
  991. return $text;
  992. }
  993. if ($itemid === false) {
  994. // Catch a potentially dangerous coding error.
  995. throw new coding_exception('file_save_draft_area_files was called with $itemid false. ' .
  996. "This suggests a bug, because it would wipe all ($contextid, $component, $filearea) files.");
  997. }
  998. $usercontext = context_user::instance($USER->id);
  999. $fs = get_file_storage();
  1000. $options = (array)$options;
  1001. if (!isset($options['subdirs'])) {
  1002. $options['subdirs'] = false;
  1003. }
  1004. if (!isset($options['maxfiles'])) {
  1005. $options['maxfiles'] = -1; // unlimited
  1006. }
  1007. if (!isset($options['maxbytes']) || $options['maxbytes'] == USER_CAN_IGNORE_FILE_SIZE_LIMITS) {
  1008. $options['maxbytes'] = 0; // unlimited
  1009. }
  1010. if (!isset($options['areamaxbytes'])) {
  1011. $options['areamaxbytes'] = FILE_AREA_MAX_BYTES_UNLIMITED; // Unlimited.
  1012. }
  1013. $allowreferences = true;
  1014. if (isset($options['return_types']) && !($options['return_types'] & (FILE_REFERENCE | FILE_CONTROLLED_LINK))) {
  1015. // we assume that if $options['return_types'] is NOT specified, we DO allow references.
  1016. // this is not exactly right. BUT there are many places in code where filemanager options
  1017. // are not passed to file_save_draft_area_files()
  1018. $allowreferences = false;
  1019. }
  1020. // Check if the user has copy-pasted from other draft areas. Those files will be located in different draft
  1021. // areas and need to be copied into the current draft area.
  1022. $text = file_merge_draft_areas($draftitemid, $usercontext->id, $text, $forcehttps);
  1023. // Check if the draft area has exceeded the authorised limit. This should never happen as validation
  1024. // should have taken place before, unless the user is doing something nauthly. If so, let's just not save
  1025. // anything at all in the next area.
  1026. if (file_is_draft_area_limit_reached($draftitemid, $options['areamaxbytes'])) {
  1027. return null;
  1028. }
  1029. $draftfiles = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftitemid, 'id');
  1030. $oldfiles = $fs->get_area_files($contextid, $component, $filearea, $itemid, 'id');
  1031. // One file in filearea means it is empty (it has only top-level directory '.').
  1032. if (count($draftfiles) > 1 || count($oldfiles) > 1) {
  1033. // we have to merge old and new files - we want to keep file ids for files that were not changed
  1034. // we change time modified for all new and changed files, we keep time created as is
  1035. $newhashes = array();
  1036. $filecount = 0;
  1037. $context = context::instance_by_id($contextid, MUST_EXIST);
  1038. foreach ($draftfiles as $file) {
  1039. if (!$options['subdirs'] && $file->get_filepath() !== '/') {
  1040. continue;
  1041. }
  1042. if (!$allowreferences && $file->is_external_file()) {
  1043. continue;
  1044. }
  1045. if (!$file->is_directory()) {
  1046. // Check to see if this file was uploaded by someone who can ignore the file size limits.
  1047. $fileusermaxbytes = get_user_max_upload_file_size($context, $options['maxbytes'], 0, 0, $file->get_userid());
  1048. if ($fileusermaxbytes != USER_CAN_IGNORE_FILE_SIZE_LIMITS
  1049. && ($options['maxbytes'] and $options['maxbytes'] < $file->get_filesize())) {
  1050. // Oversized file.
  1051. continue;
  1052. }
  1053. if ($options['maxfiles'] != -1 and $options['maxfiles'] <= $filecount) {
  1054. // more files - should not get here at all
  1055. continue;
  1056. }
  1057. $filecount++;
  1058. }
  1059. $newhash = $fs->get_pathname_hash($contextid, $component, $filearea, $itemid, $file->get_filepath(), $file->get_filename());
  1060. $newhashes[$newhash] = $file;
  1061. }
  1062. // Loop through oldfiles and decide which we need to delete and which to update.
  1063. // After this cycle the array $newhashes will only contain the files that need to be added.
  1064. foreach ($oldfiles as $oldfile) {
  1065. $oldhash = $oldfile->get_pathnamehash();
  1066. if (!isset($newhashes[$oldhash])) {
  1067. // delete files not needed any more - deleted by user
  1068. $oldfile->delete();
  1069. continue;
  1070. }
  1071. $newfile = $newhashes[$oldhash];
  1072. // Now we know that we have $oldfile and $newfile for the same path.
  1073. // Let's check if we can update this file or we need to delete and create.
  1074. if ($newfile->is_directory()) {
  1075. // Directories are always ok to just update.
  1076. } else if (($source = @unserialize($newfile->get_source())) && isset($source->original)) {
  1077. // File has the 'original' - we need to update the file (it may even have not been changed at all).
  1078. $original = file_storage::unpack_reference($source->original);
  1079. if ($original['filename'] !== $oldfile->get_filename() || $original['filepath'] !== $oldfile->get_filepath()) {
  1080. // Very odd, original points to another file. Delete and create file.
  1081. $oldfile->delete();
  1082. continue;
  1083. }
  1084. } else {
  1085. // The same file name but absence of 'original' means that file was deteled and uploaded again.
  1086. // By deleting and creating new file we properly manage all existing references.
  1087. $oldfile->delete();
  1088. continue;
  1089. }
  1090. // status changed, we delete old file, and create a new one
  1091. if ($oldfile->get_status() != $newfile->get_status()) {
  1092. // file was changed, use updated with new timemodified data
  1093. $oldfile->delete();
  1094. // This file will be added later
  1095. continue;
  1096. }
  1097. // Updated author
  1098. if ($oldfile->get_author() != $newfile->get_author()) {
  1099. $oldfile->set_author($newfile->get_author());
  1100. }
  1101. // Updated license
  1102. if ($oldfile->get_license() != $newfile->get_license()) {
  1103. $oldfile->set_license($newfile->get_license());
  1104. }
  1105. // Updated file source
  1106. // Field files.source for draftarea files contains serialised object with source and original information.
  1107. // We only store the source part of it for non-draft file area.
  1108. $newsource = $newfile->get_source();
  1109. if ($source = @unserialize($newfile->get_source())) {
  1110. $newsource = $source->source;
  1111. }
  1112. if ($oldfile->get_source() !== $newsource) {
  1113. $oldfile->set_source($newsource);
  1114. }
  1115. // Updated sort order
  1116. if ($oldfile->get_sortorder() != $newfile->get_sortorder()) {
  1117. $oldfile->set_sortorder($newfile->get_sortorder());
  1118. }
  1119. // Update file timemodified
  1120. if ($oldfile->get_timemodified() != $newfile->get_timemodified()) {
  1121. $oldfile->set_timemodified($newfile->get_timemodified());
  1122. }
  1123. // Replaced file content
  1124. if (!$oldfile->is_directory() &&
  1125. ($oldfile->get_contenthash() != $newfile->get_contenthash() ||
  1126. $oldfile->get_filesize() != $newfile->get_filesize() ||
  1127. $oldfile->get_referencefileid() != $newfile->get_referencefileid() ||
  1128. $oldfile->get_userid() != $newfile->get_userid())) {
  1129. $oldfile->replace_file_with($newfile);
  1130. }
  1131. // unchanged file or directory - we keep it as is
  1132. unset($newhashes[$oldhash]);
  1133. }
  1134. // Add fresh file or the file which has changed status
  1135. // the size and subdirectory tests are extra safety only, the UI should prevent it
  1136. foreach ($newhashes as $file) {
  1137. $file_record = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'timemodified'=>time());
  1138. if ($source = @unserialize($file->get_source())) {
  1139. // Field files.source for draftarea files contains serialised object with source and original information.
  1140. // We only store the source part of it for non-draft file area.
  1141. $file_record['source'] = $source->source;
  1142. }
  1143. if ($file->is_external_file()) {
  1144. $repoid = $file->get_repository_id();
  1145. if (!empty($repoid)) {
  1146. $context = context::instance_by_id($contextid, MUST_EXIST);
  1147. $repo = repository::get_repository_by_id($repoid, $context);
  1148. if (!empty($options)) {
  1149. $repo->options = $options;
  1150. }
  1151. $file_record['repositoryid'] = $repoid;
  1152. // This hook gives the repo a place to do some house cleaning, and update the $reference before it's saved
  1153. // to the file store. E.g. transfer ownership of the file to a system account etc.
  1154. $reference = $repo->reference_file_selected($file->get_reference(), $context, $component, $filearea, $itemid);
  1155. $file_record['reference'] = $reference;
  1156. }
  1157. }
  1158. $fs->create_file_from_storedfile($file_record, $file);
  1159. }
  1160. }
  1161. // note: do not purge the draft area - we clean up areas later in cron,
  1162. // the reason is that user might press submit twice and they would loose the files,
  1163. // also sometimes we might want to use hacks that save files into two different areas
  1164. if (is_null($text)) {
  1165. return null;
  1166. } else {
  1167. return file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps);
  1168. }
  1169. }
  1170. /**
  1171. * Convert the draft file area URLs in some content to @@PLUGINFILE@@ tokens
  1172. * ready to be saved in the database. Normally, this is done automatically by
  1173. * {@link file_save_draft_area_files()}.
  1174. *
  1175. * @category files
  1176. * @param string $text the content to process.
  1177. * @param int $draftitemid the draft file area the content was using.
  1178. * @param bool $forcehttps whether the content contains https URLs. Default false.
  1179. * @return string the processed content.
  1180. */
  1181. function file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps = false) {
  1182. global $CFG, $USER;
  1183. $usercontext = context_user::instance($USER->id);
  1184. $wwwroot = $CFG->wwwroot;
  1185. if ($forcehttps) {
  1186. $wwwroot = str_replace('http://', 'https://', $wwwroot);
  1187. }
  1188. // relink embedded files if text submitted - no absolute links allowed in database!
  1189. $text = str_ireplace("$wwwroot/draftfile.php/$usercontext->id/user/draft/$draftitemid/", '@@PLUGINFILE@@/', $text);
  1190. if (strpos($text, 'draftfile.php?file=') !== false) {
  1191. $matches = array();
  1192. preg_match_all("!$wwwroot/draftfile.php\?file=%2F{$usercontext->id}%2Fuser%2Fdraft%2F{$draftitemid}%2F[^'\",&<>|`\s:\\\\]+!iu", $text, $matches);
  1193. if ($matches) {
  1194. foreach ($matches[0] as $match) {
  1195. $replace = str_ireplace('%2F', '/', $match);
  1196. $text = str_replace($match, $replace, $text);
  1197. }
  1198. }
  1199. $text = str_ireplace("$wwwroot/draftfile.php?file=/$usercontext->id/user/draft/$draftitemid/", '@@PLUGINFILE@@/', $text);
  1200. }
  1201. return $text;
  1202. }
  1203. /**
  1204. * Set file sort order
  1205. *
  1206. * @global moodle_database $DB
  1207. * @param int $contextid the context id
  1208. * @param string $component file component
  1209. * @param string $filearea file area.
  1210. * @param int $itemid itemid.
  1211. * @param string $filepath file path.
  1212. * @param string $filename file name.
  1213. * @param int $sortorder the sort order of file.
  1214. * @return bool
  1215. */
  1216. function file_set_sortorder($contextid, $component, $filearea, $itemid, $filepath, $filename, $sortorder) {
  1217. global $DB;
  1218. $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'filepath'=>$filepath, 'filename'=>$filename);
  1219. if ($file_record = $DB->get_record('files', $conditions)) {
  1220. $sortorder = (int)$sortorder;
  1221. $file_record->sortorder = $sortorder;
  1222. $DB->update_record('files', $file_record);
  1223. return true;
  1224. }
  1225. return false;
  1226. }
  1227. /**
  1228. * reset file sort order number to 0
  1229. * @global moodle_database $DB
  1230. * @param int $contextid the context id
  1231. * @param string $component
  1232. * @param string $filearea file area.
  1233. * @param int|bool $itemid itemid.
  1234. * @return bool
  1235. */
  1236. function file_reset_sortorder($contextid, $component, $filearea, $itemid=false) {
  1237. global $DB;
  1238. $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea);
  1239. if ($itemid !== false) {
  1240. $conditions['itemid'] = $itemid;
  1241. }
  1242. $file_records = $DB->get_records('files', $conditions);
  1243. foreach ($file_records as $file_record) {
  1244. $file_record->sortorder = 0;
  1245. $DB->update_record('files', $file_record);
  1246. }
  1247. return true;
  1248. }
  1249. /**
  1250. * Returns description of upload error
  1251. *
  1252. * @param int $errorcode found in $_FILES['filename.ext']['error']
  1253. * @return string error description string, '' if ok
  1254. */
  1255. function file_get_upload_error($errorcode) {
  1256. switch ($errorcode) {
  1257. case 0: // UPLOAD_ERR_OK - no error
  1258. $errmessage = '';
  1259. break;
  1260. case 1: // UPLOAD_ERR_INI_SIZE
  1261. $errmessage = get_string('uploadserverlimit');
  1262. break;
  1263. case 2: // UPLOAD_ERR_FORM_SIZE
  1264. $errmessage = get_string('uploadformlimit');
  1265. break;
  1266. case 3: // UPLOAD_ERR_PARTIAL
  1267. $errmessage = get_string('uploadpartialfile');
  1268. break;
  1269. case 4: // UPLOAD_ERR_NO_FILE
  1270. $errmessage = get_string('uploadnofilefound');
  1271. break;
  1272. // Note: there is no error with a value of 5
  1273. case 6: // UPLOAD_ERR_NO_TMP_DIR
  1274. $errmessage = get_string('uploadnotempdir');
  1275. break;
  1276. case 7: // UPLOAD_ERR_CANT_WRITE
  1277. $errmessage = get_string('uploadcantwrite');
  1278. break;
  1279. case 8: // UPLOAD_ERR_EXTENSION
  1280. $errmessage = get_string('uploadextension');
  1281. break;
  1282. default:
  1283. $errmessage = get_string('uploadproblem');
  1284. }
  1285. return $errmessage;
  1286. }
  1287. /**
  1288. * Recursive function formating an array in POST parameter
  1289. * @param array $arraydata - the array that we are going to format and add into &$data array
  1290. * @param string $currentdata - a row of the final postdata array at instant T
  1291. * when finish, it's assign to $data under this format: name[keyname][][]...[]='value'
  1292. * @param array $data - the final data array containing all POST parameters : 1 row = 1 parameter
  1293. */
  1294. function format_array_postdata_for_curlcall($arraydata, $currentdata, &$data) {
  1295. foreach ($arraydata as $k=>$v) {
  1296. $newcurrentdata = $currentdata;
  1297. if (is_array($v)) { //the value is an array, call the function recursively
  1298. $newcurrentdata = $newcurrentdata.'['.urlencode($k).']';
  1299. format_array_postdata_for_curlcall($v, $newcurrentdata, $data);
  1300. } else { //add the POST parameter to the $data array
  1301. $data[] = $newcurrentdata.'['.urlencode($k).']='.urlencode($v);
  1302. }
  1303. }
  1304. }
  1305. /**
  1306. * Transform a PHP array into POST parameter
  1307. * (see the recursive function format_array_postdata_for_curlcall)
  1308. * @param array $postdata
  1309. * @return array containing all POST parameters (1 row = 1 POST parameter)
  1310. */
  1311. function format_postdata_for_curlcall($postdata) {
  1312. $data = array();
  1313. foreach ($postdata as $k=>$v) {
  1314. if (is_array($v)) {
  1315. $currentdata = urlencode($k);
  1316. format_array_postdata_for_curlcall($v, $currentdata, $data);
  1317. } else {
  1318. $data[] = urlencode($k).'='.urlencode($v);
  1319. }
  1320. }
  1321. $convertedpostdata = implode('&', $data);
  1322. return $convertedpostdata;
  1323. }
  1324. /**
  1325. * Fetches content of file from Internet (using proxy if defined). Uses cURL extension if present.
  1326. * Due to security concerns only downloads from http(s) sources are supported.
  1327. *
  1328. * @category files
  1329. * @param string $url file url starting with http(s)://
  1330. * @param array $headers http headers, null if none. If set, should be an
  1331. * associative array of header name => value pairs.
  1332. * @param array $postdata array means use POST request with given parameters
  1333. * @param bool $fullresponse return headers, responses, etc in a similar way snoopy does
  1334. * (if false, just returns content)
  1335. * @param int $timeout timeout for complete download process including all file transfer
  1336. * (default 5 minutes)
  1337. * @param int $connecttimeout timeout for connection to server; this is the timeout that
  1338. * usually happens if the remote server is completely down (default 20 seconds);
  1339. * may not work when using proxy
  1340. * @param bool $skipcertverify If true, the peer's SSL certificate will not be checked.
  1341. * Only use this when already in a trusted location.
  1342. * @param string $tofile store the downloaded content to file instead of returning it.
  1343. * @param bool $calctimeout false by default, true enables an extra head request to try and determine
  1344. * filesize and appropriately larger timeout based on $CFG->curltimeoutkbitrate
  1345. * @return stdClass|string|bool stdClass object if $fullresponse is true, false if request failed, true
  1346. * if file downloaded into $tofile successfully or the file content as a string.
  1347. */
  1348. function download_file_content($url, $headers=null, $postdata=null, $fullresponse=false, $timeout=300, $connecttimeout=20, $skipcertverify=false, $tofile=NULL, $calctimeout=false) {
  1349. global $CFG;
  1350. // Only http and https links supported.
  1351. if (!preg_match('|^https?://|i', $url)) {
  1352. if ($fullresponse) {
  1353. $response = new stdClass();
  1354. $response->status = 0;
  1355. $response->headers = array();
  1356. $response->response_code = 'Invalid protocol specified in url';
  1357. $response->results = '';
  1358. $response->error = 'Invalid protocol specified in url';
  1359. return $response;
  1360. } else {
  1361. return false;
  1362. }
  1363. }
  1364. $options = array();
  1365. $headers2 = array();
  1366. if (is_array($headers)) {
  1367. foreach ($headers as $key => $value) {
  1368. if (is_numeric($key)) {
  1369. $headers2[] = $value;
  1370. } else {
  1371. $headers2[] = "$key: $value";
  1372. }
  1373. }
  1374. }
  1375. if ($skipcertverify) {
  1376. $options['CURLOPT_SSL_VERIFYPEER'] = false;
  1377. } else {
  1378. $options['CURLOPT_SSL_VERIFYPEER'] = true;
  1379. }
  1380. $options['CURLOPT_CONNECTTIMEOUT'] = $connecttimeout;
  1381. $options['CURLOPT_FOLLOWLOCATION'] = 1;
  1382. $options['CURLOPT_MAXREDIRS'] = 5;
  1383. // Use POST if requested.
  1384. if (is_array($postdata)) {
  1385. $postdata = format_postdata_for_curlcall($postdata);
  1386. } else if (empty($postdata)) {
  1387. $postdata = null;
  1388. }
  1389. // Optionally attempt to get more correct timeout by fetching the file size.
  1390. if (!isset($CFG->curltimeoutkbitrate)) {
  1391. // Use very slow rate of 56kbps as a timeout speed when not set.
  1392. $bitrate = 56;
  1393. } else {
  1394. $bitrate = $CFG->curltimeoutkbitrate;
  1395. }
  1396. if ($calctimeout and !isset($postdata)) {
  1397. $curl = new curl();
  1398. $curl->setHeader($headers2);
  1399. $curl->head($url, $postdata, $options);
  1400. $info = $curl->get_info();
  1401. $error_no = $curl->get_errno();
  1402. if (!$error_no && $info['download_content_length'] > 0) {
  1403. // No curl errors - adjust for large files only - take max timeout.
  1404. $timeout = max($timeout, ceil($info['download_content_length'] * 8 / ($bitrate * 1024)));
  1405. }
  1406. }
  1407. $curl = new curl();
  1408. $curl->setHeader($headers2);
  1409. $options['CURLOPT_RETURNTRANSFER'] = true;
  1410. $options['CURLOPT_NOBODY'] = false;
  1411. $options['CURLOPT_TIMEOUT'] = $timeout;
  1412. if ($tofile) {
  1413. $fh = fopen($tofile, 'w');
  1414. if (!$fh) {
  1415. if ($fullresponse) {
  1416. $response = new stdClass();
  1417. $response->status = 0;
  1418. $response->headers = array();
  1419. $response->response_code = 'Can not write to file';
  1420. $response->results = false;
  1421. $response->error = 'Can not write to file';
  1422. return $response;
  1423. } else {
  1424. return false;
  1425. }
  1426. }
  1427. $options['CURLOPT_FILE'] = $fh;
  1428. }
  1429. if (isset($postdata)) {
  1430. $content = $curl->post($url, $postdata, $options);
  1431. } else {
  1432. $content = $curl->get($url, null, $options);
  1433. }
  1434. if ($tofile) {
  1435. fclose($fh);
  1436. @chmod($tofile, $CFG->filepermissions);
  1437. }
  1438. /*
  1439. // Try to detect encoding problems.
  1440. if ((curl_errno($ch) == 23 or curl_errno($ch) == 61) and defined('CURLOPT_ENCODING')) {
  1441. curl_setopt($ch, CURLOPT_ENCODING, 'none');
  1442. $result = curl_exec($ch);
  1443. }
  1444. */
  1445. $info = $curl->get_info();
  1446. $error_no = $curl->get_errno();
  1447. $rawheaders = $curl->get_raw_response();
  1448. if ($error_no) {
  1449. $error = $content;
  1450. if (!$fullresponse) {
  1451. debugging("cURL request for \"$url\" failed with: $error ($error_no)", DEBUG_ALL);
  1452. return false;
  1453. }
  1454. $response = new stdClass();
  1455. if ($error_no == 28) {
  1456. $response->status = '-100'; // Mimic snoopy.
  1457. } else {
  1458. $response->status = '0';
  1459. }
  1460. $response->headers = array();
  1461. $response->response_code = $error;
  1462. $response->results = false;
  1463. $response->error = $error;
  1464. return $response;
  1465. }
  1466. if ($tofile) {
  1467. $content = true;
  1468. }
  1469. if (empty($info['http_code'])) {
  1470. // For security reasons we support only true http connections (Location: file:// exploit prevention).
  1471. $response = new stdClass();
  1472. $response->status = '0';
  1473. $response->headers = array();
  1474. $response->response_code = 'Unknown cURL error';
  1475. $response->results = false; // do NOT change this, we really want to ignore the result!
  1476. $response->error = 'Unknown cURL error';
  1477. } else {
  1478. $response = new stdClass();
  1479. $response->status = (string)$info['http_code'];
  1480. $response->headers = $rawheaders;
  1481. $response->results = $content;
  1482. $response->error = '';
  1483. // There might be multiple headers on redirect, find the status of the last one.
  1484. $firstline = true;
  1485. foreach ($rawheaders as $line) {
  1486. if ($firstline) {
  1487. $response->response_code = $line;
  1488. $firstline = false;
  1489. }
  1490. if (trim($line, "\r\n") === '') {
  1491. $firstline = true;
  1492. }
  1493. }
  1494. }
  1495. if ($fullresponse) {
  1496. return $response;
  1497. }
  1498. if ($info['http_code'] != 200) {
  1499. debugging("cURL request for \"$url\" failed, HTTP response code: ".$response->response_code, DEBUG_ALL);
  1500. return false;
  1501. }
  1502. return $response->results;
  1503. }
  1504. /**
  1505. * Returns a list of information about file types based on extensions.
  1506. *
  1507. * The following elements expected in value array for each extension:
  1508. * 'type' - mimetype
  1509. * 'icon' - location of the icon file. If value is FILENAME, then either pix/f/FILENAME.gif
  1510. * or pix/f/FILENAME.png must be present in moodle and contain 16x16 filetype icon;
  1511. * also files with bigger sizes under names
  1512. * FILENAME-24, FILENAME-32, FILENAME-64, FILENAME-128, FILENAME-256 are recommended.
  1513. * 'groups' (optional) - array of filetype groups this filetype extension is part of;
  1514. * commonly used in moodle the following groups:
  1515. * - web_image - image that can be included as <img> in HTML
  1516. * - image - image that we can parse using GD to find it's dimensions, also used for portfolio format
  1517. * - optimised_image - image that will be processed and optimised
  1518. * - video - file that can be imported as video in text editor
  1519. * - audio - file that can be imported as audio in text editor
  1520. * - archive - we can extract files from this archive
  1521. * - spreadsheet - used for portfolio format
  1522. * - document - used for portfolio format
  1523. * - presentation - used for portfolio format
  1524. * 'string' (optional) - the name of the string from lang/en/mimetypes.php that displays
  1525. * human-readable description for this filetype;
  1526. * Function {@link get_mimetype_description()} first looks at the presence of string for
  1527. * particular mimetype (value of 'type'), if not found looks for string specified in 'string'
  1528. * attribute, if not found returns the value of 'type';
  1529. * 'defaulticon' (boolean, optional) - used by function {@link file_mimetype_icon()} to find
  1530. * an icon for mimetype. If an entry with 'defaulticon' is not found for a particular mimetype,
  1531. * this function will return first found icon; Especially usefull for types such as 'text/plain'
  1532. *
  1533. * @category files
  1534. * @return array List of information about file types based on extensions.
  1535. * Associative array of extension (lower-case) to associative array
  1536. * from 'element name' to data. Current element names are 'type' and 'icon'.
  1537. * Unknown types should use the 'xxx' entry which includes defaults.
  1538. */
  1539. function &get_mimetypes_array() {
  1540. // Get types from the core_filetypes function, which includes caching.
  1541. return core_filetypes::get_types();
  1542. }
  1543. /**
  1544. * Determine a file's MIME type based on the given filename using the function mimeinfo.
  1545. *
  1546. * This function retrieves a file's MIME type for a file that will be sent to the user.
  1547. * This should only be used for file-sending purposes just like in send_stored_file, send_file, and send_temp_file.
  1548. * Should the file's MIME type cannot be determined by mimeinfo, it will return 'application/octet-stream' as a default
  1549. * MIME type which should tell the browser "I don't know what type of file this is, so just download it.".
  1550. *
  1551. * @param string $filename The file's filename.
  1552. * @return string The file's MIME type or 'application/octet-stream' if it cannot be determined.
  1553. */
  1554. function get_mimetype_for_sending($filename = '') {
  1555. // Guess the file's MIME type using mimeinfo.
  1556. $mimetype = mimeinfo('type', $filename);
  1557. // Use octet-stream as fallback if MIME type cannot be determined by mimeinfo.
  1558. if (!$mimetype || $mimetype === 'document/unknown') {
  1559. $mimetype = 'application/octet-stream';
  1560. }
  1561. return $mimetype;
  1562. }
  1563. /**
  1564. * Obtains information about a filetype based on its extension. Will
  1565. * use a default if no information is present about that particular
  1566. * extension.
  1567. *
  1568. * @category files
  1569. * @param string $element Desired information (usually 'icon'
  1570. * for icon filename or 'type' for MIME type. Can also be
  1571. * 'icon24', ...32, 48, 64, 72, 80, 96, 128, 256)
  1572. * @param string $filename Filename we're looking up
  1573. * @return string Requested piece of information from array
  1574. */
  1575. function mimeinfo($element, $filename) {
  1576. global $CFG;
  1577. $mimeinfo = & get_mimetypes_array();
  1578. static $iconpostfixes = array(256=>'-256', 128=>'-128', 96=>'-96', 80=>'-80', 72=>'-72', 64=>'-64', 48=>'-48', 32=>'-32', 24=>'-24', 16=>'');
  1579. $filetype = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
  1580. if (empty($filetype)) {
  1581. $filetype = 'xxx'; // file without extension
  1582. }
  1583. if (preg_match('/^icon(\d*)$/', $element, $iconsizematch)) {
  1584. $iconsize = max(array(16, (int)$iconsizematch[1]));
  1585. $filenames = array($mimeinfo['xxx']['icon']);
  1586. if ($filetype != 'xxx' && isset($mimeinfo[$filetype]['icon'])) {
  1587. array_unshift($filenames, $mimeinfo[$filetype]['icon']);
  1588. }
  1589. // find the file with the closest size, first search for specific icon then for default icon
  1590. foreach ($filenames as $filename) {
  1591. foreach ($iconpostfixes as $size => $postfix) {
  1592. $fullname = $CFG->dirroot.'/pix/f/'.$filename.$postfix;
  1593. if ($iconsize >= $size &&
  1594. (file_exists($fullname.'.svg') || file_exists($fullname.'.png') || file_exists($fullname.'.gif'))) {
  1595. return $filename.$postfix;
  1596. }
  1597. }
  1598. }
  1599. } else if (isset($mimeinfo[$filetype][$element])) {
  1600. return $mimeinfo[$filetype][$element];
  1601. } else if (isset($mimeinfo['xxx'][$element])) {
  1602. return $mimeinfo['xxx'][$element]; // By default
  1603. } else {
  1604. return null;
  1605. }
  1606. }
  1607. /**
  1608. * Obtains information about a filetype based on the MIME type rather than
  1609. * the other way around.
  1610. *
  1611. * @category files
  1612. * @param string $element Desired information ('extension', 'icon', 'icon-24', etc.)
  1613. * @param string $mimetype MIME type we're looking up
  1614. * @return string Requested piece of information from array
  1615. */
  1616. function mimeinfo_from_type($element, $mimetype) {
  1617. /* array of cached mimetype->extension associations */
  1618. static $cached = array();
  1619. $mimeinfo = & get_mimetypes_array();
  1620. if (!array_key_exists($mimetype, $cached)) {
  1621. $cached[$mimetype] = null;
  1622. foreach($mimeinfo as $filetype => $values) {
  1623. if ($values['type'] == $mimetype) {
  1624. if ($cached[$mimetype] === null) {
  1625. $cached[$mimetype] = '.'.$filetype;
  1626. }
  1627. if (!empty($values['defaulticon'])) {
  1628. $cached[$mimetype] = '.'.$filetype;
  1629. break;
  1630. }
  1631. }
  1632. }
  1633. if (empty($cached[$mimetype])) {
  1634. $cached[$mimetype] = '.xxx';
  1635. }
  1636. }
  1637. if ($element === 'extension') {
  1638. return $cached[$mimetype];
  1639. } else {
  1640. return mimeinfo($element, $cached[$mimetype]);
  1641. }
  1642. }
  1643. /**
  1644. * Return the relative icon path for a given file
  1645. *
  1646. * Usage:
  1647. * <code>
  1648. * // $file - instance of stored_file or file_info
  1649. * $icon = $OUTPUT->image_url(file_file_icon($file))->out();
  1650. * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => get_mimetype_description($file)));
  1651. * </code>
  1652. * or
  1653. * <code>
  1654. * echo $OUTPUT->pix_icon(file_file_icon($file), get_mimetype_description($file));
  1655. * </code>
  1656. *
  1657. * @param stored_file|file_info|stdClass|array $file (in case of object attributes $file->filename
  1658. * and $file->mimetype are expected)
  1659. * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
  1660. * @return string
  1661. */
  1662. function file_file_icon($file, $size = null) {
  1663. if (!is_object($file)) {
  1664. $file = (object)$file;
  1665. }
  1666. if (isset($file->filename)) {
  1667. $filename = $file->filename;
  1668. } else if (method_exists($file, 'get_filename')) {
  1669. $filename = $file->get_filename();
  1670. } else if (method_exists($file, 'get_visible_name')) {
  1671. $filename = $file->get_visible_name();
  1672. } else {
  1673. $filename = '';
  1674. }
  1675. if (isset($file->mimetype)) {
  1676. $mimetype = $file->mimetype;
  1677. } else if (method_exists($file, 'get_mimetype')) {
  1678. $mimetype = $file->get_mimetype();
  1679. } else {
  1680. $mimetype = '';
  1681. }
  1682. $mimetypes = &get_mimetypes_array();
  1683. if ($filename) {
  1684. $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
  1685. if ($extension && !empty($mimetypes[$extension])) {
  1686. // if file name has known extension, return icon for this extension
  1687. return file_extension_icon($filename, $size);
  1688. }
  1689. }
  1690. return file_mimetype_icon($mimetype, $size);
  1691. }
  1692. /**
  1693. * Return the relative icon path for a folder image
  1694. *
  1695. * Usage:
  1696. * <code>
  1697. * $icon = $OUTPUT->image_url(file_folder_icon())->out();
  1698. * echo html_writer::empty_tag('img', array('src' => $icon));
  1699. * </code>
  1700. * or
  1701. * <code>
  1702. * echo $OUTPUT->pix_icon(file_folder_icon(32), '');
  1703. * </code>
  1704. *
  1705. * @param int $iconsize The size of the icon. Defaults to 16 can also be 24, 32, 48, 64, 72, 80, 96, 128, 256
  1706. * @return string
  1707. */
  1708. function file_folder_icon($iconsize = null) {
  1709. global $CFG;
  1710. static $iconpostfixes = array(256=>'-256', 128=>'-128', 96=>'-96', 80=>'-80', 72=>'-72', 64=>'-64', 48=>'-48', 32=>'-32', 24=>'-24', 16=>'');
  1711. static $cached = array();
  1712. $iconsize = max(array(16, (int)$iconsize));
  1713. if (!array_key_exists($iconsize, $cached)) {
  1714. foreach ($iconpostfixes as $size => $postfix) {
  1715. $fullname = $CFG->dirroot.'/pix/f/folder'.$postfix;
  1716. if ($iconsize >= $size &&
  1717. (file_exists($fullname.'.svg') || file_exists($fullname.'.png') || file_exists($fullname.'.gif'))) {
  1718. $cached[$iconsize] = 'f/folder'.$postfix;
  1719. break;
  1720. }
  1721. }
  1722. }
  1723. return $cached[$iconsize];
  1724. }
  1725. /**
  1726. * Returns the relative icon path for a given mime type
  1727. *
  1728. * This function should be used in conjunction with $OUTPUT->image_url to produce
  1729. * a return the full path to an icon.
  1730. *
  1731. * <code>
  1732. * $mimetype = 'image/jpg';
  1733. * $icon = $OUTPUT->image_url(file_mimetype_icon($mimetype))->out();
  1734. * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => get_mimetype_description($mimetype)));
  1735. * </code>
  1736. *
  1737. * @category files
  1738. * @todo MDL-31074 When an $OUTPUT->icon method is available this function should be altered
  1739. * to conform with that.
  1740. * @param string $mimetype The mimetype to fetch an icon for
  1741. * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
  1742. * @return string The relative path to the icon
  1743. */
  1744. function file_mimetype_icon($mimetype, $size = NULL) {
  1745. return 'f/'.mimeinfo_from_type('icon'.$size, $mimetype);
  1746. }
  1747. /**
  1748. * Returns the relative icon path for a given file name
  1749. *
  1750. * This function should be used in conjunction with $OUTPUT->image_url to produce
  1751. * a return the full path to an icon.
  1752. *
  1753. * <code>
  1754. * $filename = '.jpg';
  1755. * $icon = $OUTPUT->image_url(file_extension_icon($filename))->out();
  1756. * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => '...'));
  1757. * </code>
  1758. *
  1759. * @todo MDL-31074 When an $OUTPUT->icon method is available this function should be altered
  1760. * to conform with that.
  1761. * @todo MDL-31074 Implement $size
  1762. * @category files
  1763. * @param string $filename The filename to get the icon for
  1764. * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
  1765. * @return string
  1766. */
  1767. function file_extension_icon($filename, $size = NULL) {
  1768. return 'f/'.mimeinfo('icon'.$size, $filename);
  1769. }
  1770. /**
  1771. * Obtains descriptions for file types (e.g. 'Microsoft Word document') from the
  1772. * mimetypes.php language file.
  1773. *
  1774. * @param mixed $obj - instance of stored_file or file_info or array/stdClass with field
  1775. * 'filename' and 'mimetype', or just a string with mimetype (though it is recommended to
  1776. * have filename); In case of array/stdClass the field 'mimetype' is optional.
  1777. * @param bool $capitalise If true, capitalises first character of result
  1778. * @return string Text description
  1779. */
  1780. function get_mimetype_description($obj, $capitalise=false) {
  1781. $filename = $mimetype = '';
  1782. if (is_object($obj) && method_exists($obj, 'get_filename') && method_exists($obj, 'get_mimetype')) {
  1783. // this is an instance of stored_file
  1784. $mimetype = $obj->get_mimetype();
  1785. $filename = $obj->get_filename();
  1786. } else if (is_object($obj) && method_exists($obj, 'get_visible_name') && method_exists($obj, 'get_mimetype')) {
  1787. // this is an instance of file_info
  1788. $mimetype = $obj->get_mimetype();
  1789. $filename = $obj->get_visible_name();
  1790. } else if (is_array($obj) || is_object ($obj)) {
  1791. $obj = (array)$obj;
  1792. if (!empty($obj['filename'])) {
  1793. $filename = $obj['filename'];
  1794. }
  1795. if (!empty($obj['mimetype'])) {
  1796. $mimetype = $obj['mimetype'];
  1797. }
  1798. } else {
  1799. $mimetype = $obj;
  1800. }
  1801. $mimetypefromext = mimeinfo('type', $filename);
  1802. if (empty($mimetype) || $mimetypefromext !== 'document/unknown') {
  1803. // if file has a known extension, overwrite the specified mimetype
  1804. $mimetype = $mimetypefromext;
  1805. }
  1806. $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
  1807. if (empty($extension)) {
  1808. $mimetypestr = mimeinfo_from_type('string', $mimetype);
  1809. $extension = str_replace('.', '', mimeinfo_from_type('extension', $mimetype));
  1810. } else {
  1811. $mimetypestr = mimeinfo('string', $filename);
  1812. }
  1813. $chunks = explode('/', $mimetype, 2);
  1814. $chunks[] = '';
  1815. $attr = array(
  1816. 'mimetype' => $mimetype,
  1817. 'ext' => $extension,
  1818. 'mimetype1' => $chunks[0],
  1819. 'mimetype2' => $chunks[1],
  1820. );
  1821. $a = array();
  1822. foreach ($attr as $key => $value) {
  1823. $a[$key] = $value;
  1824. $a[strtoupper($key)] = strtoupper($value);
  1825. $a[ucfirst($key)] = ucfirst($value);
  1826. }
  1827. // MIME types may include + symbol but this is not permitted in string ids.
  1828. $safemimetype = str_replace('+', '_', $mimetype);
  1829. $safemimetypestr = str_replace('+', '_', $mimetypestr);
  1830. $customdescription = mimeinfo('customdescription', $filename);
  1831. if ($customdescription) {
  1832. // Call format_string on the custom description so that multilang
  1833. // filter can be used (if enabled on system context). We use system
  1834. // context because it is possible that the page context might not have
  1835. // been defined yet.
  1836. $result = format_string($customdescription, true,
  1837. array('context' => context_system::instance()));
  1838. } else if (get_string_manager()->string_exists($safemimetype, 'mimetypes')) {
  1839. $result = get_string($safemimetype, 'mimetypes', (object)$a);
  1840. } else if (get_string_manager()->string_exists($safemimetypestr, 'mimetypes')) {
  1841. $result = get_string($safemimetypestr, 'mimetypes', (object)$a);
  1842. } else if (get_string_manager()->string_exists('default', 'mimetypes')) {
  1843. $result = get_string('default', 'mimetypes', (object)$a);
  1844. } else {
  1845. $result = $mimetype;
  1846. }
  1847. if ($capitalise) {
  1848. $result=ucfirst($result);
  1849. }
  1850. return $result;
  1851. }
  1852. /**
  1853. * Returns array of elements of type $element in type group(s)
  1854. *
  1855. * @param string $element name of the element we are interested in, usually 'type' or 'extension'
  1856. * @param string|array $groups one group or array of groups/extensions/mimetypes
  1857. * @return array
  1858. */
  1859. function file_get_typegroup($element, $groups) {
  1860. static $cached = array();
  1861. if (!is_array($groups)) {
  1862. $groups = array($groups);
  1863. }
  1864. if (!array_key_exists($element, $cached)) {
  1865. $cached[$element] = array();
  1866. }
  1867. $result = array();
  1868. foreach ($groups as $group) {
  1869. if (!array_key_exists($group, $cached[$element])) {
  1870. // retrieive and cache all elements of type $element for group $group
  1871. $mimeinfo = & get_mimetypes_array();
  1872. $cached[$element][$group] = array();
  1873. foreach ($mimeinfo as $extension => $value) {
  1874. $value['extension'] = '.'.$extension;
  1875. if (empty($value[$element])) {
  1876. continue;
  1877. }
  1878. if (($group === '.'.$extension || $group === $value['type'] ||
  1879. (!empty($value['groups']) && in_array($group, $value['groups']))) &&
  1880. !in_array($value[$element], $cached[$element][$group])) {
  1881. $cached[$element][$group][] = $value[$element];
  1882. }
  1883. }
  1884. }
  1885. $result = array_merge($result, $cached[$element][$group]);
  1886. }
  1887. return array_values(array_unique($result));
  1888. }
  1889. /**
  1890. * Checks if file with name $filename has one of the extensions in groups $groups
  1891. *
  1892. * @see get_mimetypes_array()
  1893. * @param string $filename name of the file to check
  1894. * @param string|array $groups one group or array of groups to check
  1895. * @param bool $checktype if true and extension check fails, find the mimetype and check if
  1896. * file mimetype is in mimetypes in groups $groups
  1897. * @return bool
  1898. */
  1899. function file_extension_in_typegroup($filename, $groups, $checktype = false) {
  1900. $extension = pathinfo($filename, PATHINFO_EXTENSION);
  1901. if (!empty($extension) && in_array('.'.strtolower($extension), file_get_typegroup('extension', $groups))) {
  1902. return true;
  1903. }
  1904. return $checktype && file_mimetype_in_typegroup(mimeinfo('type', $filename), $groups);
  1905. }
  1906. /**
  1907. * Checks if mimetype $mimetype belongs to one of the groups $groups
  1908. *
  1909. * @see get_mimetypes_array()
  1910. * @param string $mimetype
  1911. * @param string|array $groups one group or array of groups to check
  1912. * @return bool
  1913. */
  1914. function file_mimetype_in_typegroup($mimetype, $groups) {
  1915. return !empty($mimetype) && in_array($mimetype, file_get_typegroup('type', $groups));
  1916. }
  1917. /**
  1918. * Requested file is not found or not accessible, does not return, terminates script
  1919. *
  1920. * @global stdClass $CFG
  1921. * @global stdClass $COURSE
  1922. */
  1923. function send_file_not_found() {
  1924. global $CFG, $COURSE;
  1925. // Allow cross-origin requests only for Web Services.
  1926. // This allow to receive requests done by Web Workers or webapps in different domains.
  1927. if (WS_SERVER) {
  1928. header('Access-Control-Allow-Origin: *');
  1929. }
  1930. send_header_404();
  1931. print_error('filenotfound', 'error', $CFG->wwwroot.'/course/view.php?id='.$COURSE->id); //this is not displayed on IIS??
  1932. }
  1933. /**
  1934. * Helper function to send correct 404 for server.
  1935. */
  1936. function send_header_404() {
  1937. if (substr(php_sapi_name(), 0, 3) == 'cgi') {
  1938. header("Status: 404 Not Found");
  1939. } else {
  1940. header('HTTP/1.0 404 not found');
  1941. }
  1942. }
  1943. /**
  1944. * The readfile function can fail when files are larger than 2GB (even on 64-bit
  1945. * platforms). This wrapper uses readfile for small files and custom code for
  1946. * large ones.
  1947. *
  1948. * @param string $path Path to file
  1949. * @param int $filesize Size of file (if left out, will get it automatically)
  1950. * @return int|bool Size read (will always be $filesize) or false if failed
  1951. */
  1952. function readfile_allow_large($path, $filesize = -1) {
  1953. // Automatically get size if not specified.
  1954. if ($filesize === -1) {
  1955. $filesize = filesize($path);
  1956. }
  1957. if ($filesize <= 2147483647) {
  1958. // If the file is up to 2^31 - 1, send it normally using readfile.
  1959. return readfile($path);
  1960. } else {
  1961. // For large files, read and output in 64KB chunks.
  1962. $handle = fopen($path, 'r');
  1963. if ($handle === false) {
  1964. return false;
  1965. }
  1966. $left = $filesize;
  1967. while ($left > 0) {
  1968. $size = min($left, 65536);
  1969. $buffer = fread($handle, $size);
  1970. if ($buffer === false) {
  1971. return false;
  1972. }
  1973. echo $buffer;
  1974. $left -= $size;
  1975. }
  1976. return $filesize;
  1977. }
  1978. }
  1979. /**
  1980. * Enhanced readfile() with optional acceleration.
  1981. * @param string|stored_file $file
  1982. * @param string $mimetype
  1983. * @param bool $accelerate
  1984. * @return void
  1985. */
  1986. function readfile_accel($file, $mimetype, $accelerate) {
  1987. global $CFG;
  1988. if ($mimetype === 'text/plain') {
  1989. // there is no encoding specified in text files, we need something consistent
  1990. header('Content-Type: text/plain; charset=utf-8');
  1991. } else {
  1992. header('Content-Type: '.$mimetype);
  1993. }
  1994. $lastmodified = is_object($file) ? $file->get_timemodified() : filemtime($file);
  1995. header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
  1996. if (is_object($file)) {
  1997. header('Etag: "' . $file->get_contenthash() . '"');
  1998. if (isset($_SERVER['HTTP_IF_NONE_MATCH']) and trim($_SERVER['HTTP_IF_NONE_MATCH'], '"') === $file->get_contenthash()) {
  1999. header('HTTP/1.1 304 Not Modified');
  2000. return;
  2001. }
  2002. }
  2003. // if etag present for stored file rely on it exclusively
  2004. if (!empty($_SERVER['HTTP_IF_MODIFIED_SINCE']) and (empty($_SERVER['HTTP_IF_NONE_MATCH']) or !is_object($file))) {
  2005. // get unixtime of request header; clip extra junk off first
  2006. $since = strtotime(preg_replace('/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"]));
  2007. if ($since && $since >= $lastmodified) {
  2008. header('HTTP/1.1 304 Not Modified');
  2009. return;
  2010. }
  2011. }
  2012. if ($accelerate and empty($CFG->disablebyteserving) and $mimetype !== 'text/plain') {
  2013. header('Accept-Ranges: bytes');
  2014. } else {
  2015. header('Accept-Ranges: none');
  2016. }
  2017. if ($accelerate) {
  2018. if (is_object($file)) {
  2019. $fs = get_file_storage();
  2020. if ($fs->supports_xsendfile()) {
  2021. if ($fs->xsendfile_file($file)) {
  2022. return;
  2023. }
  2024. }
  2025. } else {
  2026. if (!empty($CFG->xsendfile)) {
  2027. require_once("$CFG->libdir/xsendfilelib.php");
  2028. if (xsendfile($file)) {
  2029. return;
  2030. }
  2031. }
  2032. }
  2033. }
  2034. $filesize = is_object($file) ? $file->get_filesize() : filesize($file);
  2035. header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
  2036. if ($accelerate and empty($CFG->disablebyteserving) and $mimetype !== 'text/plain') {
  2037. if (!empty($_SERVER['HTTP_RANGE']) and strpos($_SERVER['HTTP_RANGE'],'bytes=') !== FALSE) {
  2038. // byteserving stuff - for acrobat reader and download accelerators
  2039. // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
  2040. // inspired by: http://www.coneural.org/florian/papers/04_byteserving.php
  2041. $ranges = false;
  2042. if (preg_match_all('/(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER)) {
  2043. foreach ($ranges as $key=>$value) {
  2044. if ($ranges[$key][1] == '') {
  2045. //suffix case
  2046. $ranges[$key][1] = $filesize - $ranges[$key][2];
  2047. $ranges[$key][2] = $filesize - 1;
  2048. } else if ($ranges[$key][2] == '' || $ranges[$key][2] > $filesize - 1) {
  2049. //fix range length
  2050. $ranges[$key][2] = $filesize - 1;
  2051. }
  2052. if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
  2053. //invalid byte-range ==> ignore header
  2054. $ranges = false;
  2055. break;
  2056. }
  2057. //prepare multipart header
  2058. $ranges[$key][0] = "\r\n--".BYTESERVING_BOUNDARY."\r\nContent-Type: $mimetype\r\n";
  2059. $ranges[$key][0] .= "Content-Range: bytes {$ranges[$key][1]}-{$ranges[$key][2]}/$filesize\r\n\r\n";
  2060. }
  2061. } else {
  2062. $ranges = false;
  2063. }
  2064. if ($ranges) {
  2065. if (is_object($file)) {
  2066. $handle = $file->get_content_file_handle();
  2067. if ($handle === false) {
  2068. throw new file_exception('storedfilecannotreadfile', $file->get_filename());
  2069. }
  2070. } else {
  2071. $handle = fopen($file, 'rb');
  2072. if ($handle === false) {
  2073. throw new file_exception('cannotopenfile', $file);
  2074. }
  2075. }
  2076. byteserving_send_file($handle, $mimetype, $ranges, $filesize);
  2077. }
  2078. }
  2079. }
  2080. header('Content-Length: ' . $filesize);
  2081. if (!empty($_SERVER['REQUEST_METHOD']) and $_SERVER['REQUEST_METHOD'] === 'HEAD') {
  2082. exit;
  2083. }
  2084. while (ob_get_level()) {
  2085. $handlerstack = ob_list_handlers();
  2086. $activehandler = array_pop($handlerstack);
  2087. if ($activehandler === 'default output handler') {
  2088. // We do not expect any content in the buffer when we are serving files.
  2089. $buffercontents = ob_get_clean();
  2090. if ($buffercontents !== '') {
  2091. error_log('Non-empty default output handler buffer detected while serving the file ' . $file);
  2092. }
  2093. } else {
  2094. // Some handlers such as zlib output compression may have file signature buffered - flush it.
  2095. ob_end_flush();
  2096. }
  2097. }
  2098. // send the whole file content
  2099. if (is_object($file)) {
  2100. $file->readfile();
  2101. } else {
  2102. if (readfile_allow_large($file, $filesize) === false) {
  2103. throw new file_exception('cannotopenfile', $file);
  2104. }
  2105. }
  2106. }
  2107. /**
  2108. * Similar to readfile_accel() but designed for strings.
  2109. * @param string $string
  2110. * @param string $mimetype
  2111. * @param bool $accelerate Ignored
  2112. * @return void
  2113. */
  2114. function readstring_accel($string, $mimetype, $accelerate = false) {
  2115. global $CFG;
  2116. if ($mimetype === 'text/plain') {
  2117. // there is no encoding specified in text files, we need something consistent
  2118. header('Content-Type: text/plain; charset=utf-8');
  2119. } else {
  2120. header('Content-Type: '.$mimetype);
  2121. }
  2122. header('Last-Modified: '. gmdate('D, d M Y H:i:s', time()) .' GMT');
  2123. header('Accept-Ranges: none');
  2124. header('Content-Length: '.strlen($string));
  2125. echo $string;
  2126. }
  2127. /**
  2128. * Handles the sending of temporary file to user, download is forced.
  2129. * File is deleted after abort or successful sending, does not return, script terminated
  2130. *
  2131. * @param string $path path to file, preferably from moodledata/temp/something; or content of file itself
  2132. * @param string $filename proposed file name when saving file
  2133. * @param bool $pathisstring If the path is string
  2134. */
  2135. function send_temp_file($path, $filename, $pathisstring=false) {
  2136. global $CFG;
  2137. // Guess the file's MIME type.
  2138. $mimetype = get_mimetype_for_sending($filename);
  2139. // close session - not needed anymore
  2140. \core\session\manager::write_close();
  2141. if (!$pathisstring) {
  2142. if (!file_exists($path)) {
  2143. send_header_404();
  2144. print_error('filenotfound', 'error', $CFG->wwwroot.'/');
  2145. }
  2146. // executed after normal finish or abort
  2147. core_shutdown_manager::register_function('send_temp_file_finished', array($path));
  2148. }
  2149. // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
  2150. if (core_useragent::is_ie() || core_useragent::is_edge()) {
  2151. $filename = urlencode($filename);
  2152. }
  2153. // If this file was requested from a form, then mark download as complete.
  2154. \core_form\util::form_download_complete();
  2155. header('Content-Disposition: attachment; filename="'.$filename.'"');
  2156. if (is_https()) { // HTTPS sites - watch out for IE! KB812935 and KB316431.
  2157. header('Cache-Control: private, max-age=10, no-transform');
  2158. header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
  2159. header('Pragma: ');
  2160. } else { //normal http - prevent caching at all cost
  2161. header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0, no-transform');
  2162. header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
  2163. header('Pragma: no-cache');
  2164. }
  2165. // send the contents - we can not accelerate this because the file will be deleted asap
  2166. if ($pathisstring) {
  2167. readstring_accel($path, $mimetype);
  2168. } else {
  2169. readfile_accel($path, $mimetype, false);
  2170. @unlink($path);
  2171. }
  2172. die; //no more chars to output
  2173. }
  2174. /**
  2175. * Internal callback function used by send_temp_file()
  2176. *
  2177. * @param string $path
  2178. */
  2179. function send_temp_file_finished($path) {
  2180. if (file_exists($path)) {
  2181. @unlink($path);
  2182. }
  2183. }
  2184. /**
  2185. * Serve content which is not meant to be cached.
  2186. *
  2187. * This is only intended to be used for volatile public files, for instance
  2188. * when development is enabled, or when caching is not required on a public resource.
  2189. *
  2190. * @param string $content Raw content.
  2191. * @param string $filename The file name.
  2192. * @return void
  2193. */
  2194. function send_content_uncached($content, $filename) {
  2195. $mimetype = mimeinfo('type', $filename);
  2196. $charset = strpos($mimetype, 'text/') === 0 ? '; charset=utf-8' : '';
  2197. header('Content-Disposition: inline; filename="' . $filename . '"');
  2198. header('Last-Modified: ' . gmdate('D, d M Y H:i:s', time()) . ' GMT');
  2199. header('Expires: ' . gmdate('D, d M Y H:i:s', time() + 2) . ' GMT');
  2200. header('Pragma: ');
  2201. header('Accept-Ranges: none');
  2202. header('Content-Type: ' . $mimetype . $charset);
  2203. header('Content-Length: ' . strlen($content));
  2204. echo $content;
  2205. die();
  2206. }
  2207. /**
  2208. * Safely save content to a certain path.
  2209. *
  2210. * This function tries hard to be atomic by first copying the content
  2211. * to a separate file, and then moving the file across. It also prevents
  2212. * the user to abort a request to prevent half-safed files.
  2213. *
  2214. * This function is intended to be used when saving some content to cache like
  2215. * $CFG->localcachedir. If you're not caching a file you should use the File API.
  2216. *
  2217. * @param string $content The file content.
  2218. * @param string $destination The absolute path of the final file.
  2219. * @return void
  2220. */
  2221. function file_safe_save_content($content, $destination) {
  2222. global $CFG;
  2223. clearstatcache();
  2224. if (!file_exists(dirname($destination))) {
  2225. @mkdir(dirname($destination), $CFG->directorypermissions, true);
  2226. }
  2227. // Prevent serving of incomplete file from concurrent request,
  2228. // the rename() should be more atomic than fwrite().
  2229. ignore_user_abort(true);
  2230. if ($fp = fopen($destination . '.tmp', 'xb')) {
  2231. fwrite($fp, $content);
  2232. fclose($fp);
  2233. rename($destination . '.tmp', $destination);
  2234. @chmod($destination, $CFG->filepermissions);
  2235. @unlink($destination . '.tmp'); // Just in case anything fails.
  2236. }
  2237. ignore_user_abort(false);
  2238. if (connection_aborted()) {
  2239. die();
  2240. }
  2241. }
  2242. /**
  2243. * Handles the sending of file data to the user's browser, including support for
  2244. * byteranges etc.
  2245. *
  2246. * @category files
  2247. * @param string|stored_file $path Path of file on disk (including real filename),
  2248. * or actual content of file as string,
  2249. * or stored_file object
  2250. * @param string $filename Filename to send
  2251. * @param int $lifetime Number of seconds before the file should expire from caches (null means $CFG->filelifetime)
  2252. * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
  2253. * @param bool $pathisstring If true (default false), $path is the content to send and not the pathname.
  2254. * Forced to false when $path is a stored_file object.
  2255. * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
  2256. * @param string $mimetype Include to specify the MIME type; leave blank to have it guess the type from $filename
  2257. * @param bool $dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
  2258. * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
  2259. * you must detect this case when control is returned using connection_aborted. Please not that session is closed
  2260. * and should not be reopened.
  2261. * @param array $options An array of options, currently accepts:
  2262. * - (string) cacheability: public, or private.
  2263. * - (string|null) immutable
  2264. * - (bool) dontforcesvgdownload: true if force download should be disabled on SVGs.
  2265. * Note: This overrides a security feature, so should only be applied to "trusted" content
  2266. * (eg module content that is created using an XSS risk flagged capability, such as SCORM).
  2267. * @return null script execution stopped unless $dontdie is true
  2268. */
  2269. function send_file($path, $filename, $lifetime = null , $filter=0, $pathisstring=false, $forcedownload=false, $mimetype='',
  2270. $dontdie=false, array $options = array()) {
  2271. global $CFG, $COURSE;
  2272. if ($dontdie) {
  2273. ignore_user_abort(true);
  2274. }
  2275. if ($lifetime === 'default' or is_null($lifetime)) {
  2276. $lifetime = $CFG->filelifetime;
  2277. }
  2278. if (is_object($path)) {
  2279. $pathisstring = false;
  2280. }
  2281. \core\session\manager::write_close(); // Unlock session during file serving.
  2282. // Use given MIME type if specified, otherwise guess it.
  2283. if (!$mimetype || $mimetype === 'document/unknown') {
  2284. $mimetype = get_mimetype_for_sending($filename);
  2285. }
  2286. // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
  2287. if (core_useragent::is_ie() || core_useragent::is_edge()) {
  2288. $filename = rawurlencode($filename);
  2289. }
  2290. // Make sure we force download of SVG files, unless the module explicitly allows them (eg within SCORM content).
  2291. // This is for security reasons (https://digi.ninja/blog/svg_xss.php).
  2292. if (file_is_svg_image_from_mimetype($mimetype) && empty($options['dontforcesvgdownload'])) {
  2293. $forcedownload = true;
  2294. }
  2295. if ($forcedownload) {
  2296. header('Content-Disposition: attachment; filename="'.$filename.'"');
  2297. // If this file was requested from a form, then mark download as complete.
  2298. \core_form\util::form_download_complete();
  2299. } else if ($mimetype !== 'application/x-shockwave-flash') {
  2300. // If this is an swf don't pass content-disposition with filename as this makes the flash player treat the file
  2301. // as an upload and enforces security that may prevent the file from being loaded.
  2302. header('Content-Disposition: inline; filename="'.$filename.'"');
  2303. }
  2304. if ($lifetime > 0) {
  2305. $immutable = '';
  2306. if (!empty($options['immutable'])) {
  2307. $immutable = ', immutable';
  2308. // Overwrite lifetime accordingly:
  2309. // 90 days only - based on Moodle point release cadence being every 3 months.
  2310. $lifetimemin = 60 * 60 * 24 * 90;
  2311. $lifetime = max($lifetime, $lifetimemin);
  2312. }
  2313. $cacheability = ' public,';
  2314. if (!empty($options['cacheability']) && ($options['cacheability'] === 'public')) {
  2315. // This file must be cache-able by both browsers and proxies.
  2316. $cacheability = ' public,';
  2317. } else if (!empty($options['cacheability']) && ($options['cacheability'] === 'private')) {
  2318. // This file must be cache-able only by browsers.
  2319. $cacheability = ' private,';
  2320. } else if (isloggedin() and !isguestuser()) {
  2321. // By default, under the conditions above, this file must be cache-able only by browsers.
  2322. $cacheability = ' private,';
  2323. }
  2324. $nobyteserving = false;
  2325. header('Cache-Control:'.$cacheability.' max-age='.$lifetime.', no-transform'.$immutable);
  2326. header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
  2327. header('Pragma: ');
  2328. } else { // Do not cache files in proxies and browsers
  2329. $nobyteserving = true;
  2330. if (is_https()) { // HTTPS sites - watch out for IE! KB812935 and KB316431.
  2331. header('Cache-Control: private, max-age=10, no-transform');
  2332. header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
  2333. header('Pragma: ');
  2334. } else { //normal http - prevent caching at all cost
  2335. header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0, no-transform');
  2336. header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
  2337. header('Pragma: no-cache');
  2338. }
  2339. }
  2340. if (empty($filter)) {
  2341. // send the contents
  2342. if ($pathisstring) {
  2343. readstring_accel($path, $mimetype);
  2344. } else {
  2345. readfile_accel($path, $mimetype, !$dontdie);
  2346. }
  2347. } else {
  2348. // Try to put the file through filters
  2349. if ($mimetype == 'text/html' || $mimetype == 'application/xhtml+xml' || file_is_svg_image_from_mimetype($mimetype)) {
  2350. $options = new stdClass();
  2351. $options->noclean = true;
  2352. $options->nocache = true; // temporary workaround for MDL-5136
  2353. if (is_object($path)) {
  2354. $text = $path->get_content();
  2355. } else if ($pathisstring) {
  2356. $text = $path;
  2357. } else {
  2358. $text = implode('', file($path));
  2359. }
  2360. $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
  2361. readstring_accel($output, $mimetype);
  2362. } else if (($mimetype == 'text/plain') and ($filter == 1)) {
  2363. // only filter text if filter all files is selected
  2364. $options = new stdClass();
  2365. $options->newlines = false;
  2366. $options->noclean = true;
  2367. if (is_object($path)) {
  2368. $text = htmlentities($path->get_content(), ENT_QUOTES, 'UTF-8');
  2369. } else if ($pathisstring) {
  2370. $text = htmlentities($path, ENT_QUOTES, 'UTF-8');
  2371. } else {
  2372. $text = htmlentities(implode('', file($path)), ENT_QUOTES, 'UTF-8');
  2373. }
  2374. $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
  2375. readstring_accel($output, $mimetype);
  2376. } else {
  2377. // send the contents
  2378. if ($pathisstring) {
  2379. readstring_accel($path, $mimetype);
  2380. } else {
  2381. readfile_accel($path, $mimetype, !$dontdie);
  2382. }
  2383. }
  2384. }
  2385. if ($dontdie) {
  2386. return;
  2387. }
  2388. die; //no more chars to output!!!
  2389. }
  2390. /**
  2391. * Handles the sending of file data to the user's browser, including support for
  2392. * byteranges etc.
  2393. *
  2394. * The $options parameter supports the following keys:
  2395. * (string|null) preview - send the preview of the file (e.g. "thumb" for a thumbnail)
  2396. * (string|null) filename - overrides the implicit filename
  2397. * (bool) dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
  2398. * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
  2399. * you must detect this case when control is returned using connection_aborted. Please not that session is closed
  2400. * and should not be reopened
  2401. * (string|null) cacheability - force the cacheability setting of the HTTP response, "private" or "public",
  2402. * when $lifetime is greater than 0. Cacheability defaults to "private" when logged in as other than guest; otherwise,
  2403. * defaults to "public".
  2404. * (string|null) immutable - set the immutable cache setting in the HTTP response, when served under HTTPS.
  2405. * Note: it's up to the consumer to set it properly i.e. when serving a "versioned" URL.
  2406. *
  2407. * @category files
  2408. * @param stored_file $stored_file local file object
  2409. * @param int $lifetime Number of seconds before the file should expire from caches (null means $CFG->filelifetime)
  2410. * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
  2411. * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
  2412. * @param array $options additional options affecting the file serving
  2413. * @return null script execution stopped unless $options['dontdie'] is true
  2414. */
  2415. function send_stored_file($stored_file, $lifetime=null, $filter=0, $forcedownload=false, array $options=array()) {
  2416. global $CFG, $COURSE;
  2417. if (empty($options['filename'])) {
  2418. $filename = null;
  2419. } else {
  2420. $filename = $options['filename'];
  2421. }
  2422. if (empty($options['dontdie'])) {
  2423. $dontdie = false;
  2424. } else {
  2425. $dontdie = true;
  2426. }
  2427. if ($lifetime === 'default' or is_null($lifetime)) {
  2428. $lifetime = $CFG->filelifetime;
  2429. }
  2430. if (!empty($options['preview'])) {
  2431. // replace the file with its preview
  2432. $fs = get_file_storage();
  2433. $preview_file = $fs->get_file_preview($stored_file, $options['preview']);
  2434. if (!$preview_file) {
  2435. // unable to create a preview of the file, send its default mime icon instead
  2436. if ($options['preview'] === 'tinyicon') {
  2437. $size = 24;
  2438. } else if ($options['preview'] === 'thumb') {
  2439. $size = 90;
  2440. } else {
  2441. $size = 256;
  2442. }
  2443. $fileicon = file_file_icon($stored_file, $size);
  2444. send_file($CFG->dirroot.'/pix/'.$fileicon.'.png', basename($fileicon).'.png');
  2445. } else {
  2446. // preview images have fixed cache lifetime and they ignore forced download
  2447. // (they are generated by GD and therefore they are considered reasonably safe).
  2448. $stored_file = $preview_file;
  2449. $lifetime = DAYSECS;
  2450. $filter = 0;
  2451. $forcedownload = false;
  2452. }
  2453. }
  2454. // handle external resource
  2455. if ($stored_file && $stored_file->is_external_file() && !isset($options['sendcachedexternalfile'])) {
  2456. $stored_file->send_file($lifetime, $filter, $forcedownload, $options);
  2457. die;
  2458. }
  2459. if (!$stored_file or $stored_file->is_directory()) {
  2460. // nothing to serve
  2461. if ($dontdie) {
  2462. return;
  2463. }
  2464. die;
  2465. }
  2466. $filename = is_null($filename) ? $stored_file->get_filename() : $filename;
  2467. // Use given MIME type if specified.
  2468. $mimetype = $stored_file->get_mimetype();
  2469. // Allow cross-origin requests only for Web Services.
  2470. // This allow to receive requests done by Web Workers or webapps in different domains.
  2471. if (WS_SERVER) {
  2472. header('Access-Control-Allow-Origin: *');
  2473. }
  2474. send_file($stored_file, $filename, $lifetime, $filter, false, $forcedownload, $mimetype, $dontdie, $options);
  2475. }
  2476. /**
  2477. * Recursively delete the file or folder with path $location. That is,
  2478. * if it is a file delete it. If it is a folder, delete all its content
  2479. * then delete it. If $location does not exist to start, that is not
  2480. * considered an error.
  2481. *
  2482. * @param string $location the path to remove.
  2483. * @return bool
  2484. */
  2485. function fulldelete($location) {
  2486. if (empty($location)) {
  2487. // extra safety against wrong param
  2488. return false;
  2489. }
  2490. if (is_dir($location)) {
  2491. if (!$currdir = opendir($location)) {
  2492. return false;
  2493. }
  2494. while (false !== ($file = readdir($currdir))) {
  2495. if ($file <> ".." && $file <> ".") {
  2496. $fullfile = $location."/".$file;
  2497. if (is_dir($fullfile)) {
  2498. if (!fulldelete($fullfile)) {
  2499. return false;
  2500. }
  2501. } else {
  2502. if (!unlink($fullfile)) {
  2503. return false;
  2504. }
  2505. }
  2506. }
  2507. }
  2508. closedir($currdir);
  2509. if (! rmdir($location)) {
  2510. return false;
  2511. }
  2512. } else if (file_exists($location)) {
  2513. if (!unlink($location)) {
  2514. return false;
  2515. }
  2516. }
  2517. return true;
  2518. }
  2519. /**
  2520. * Send requested byterange of file.
  2521. *
  2522. * @param resource $handle A file handle
  2523. * @param string $mimetype The mimetype for the output
  2524. * @param array $ranges An array of ranges to send
  2525. * @param string $filesize The size of the content if only one range is used
  2526. */
  2527. function byteserving_send_file($handle, $mimetype, $ranges, $filesize) {
  2528. // better turn off any kind of compression and buffering
  2529. ini_set('zlib.output_compression', 'Off');
  2530. $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
  2531. if ($handle === false) {
  2532. die;
  2533. }
  2534. if (count($ranges) == 1) { //only one range requested
  2535. $length = $ranges[0][2] - $ranges[0][1] + 1;
  2536. header('HTTP/1.1 206 Partial content');
  2537. header('Content-Length: '.$length);
  2538. header('Content-Range: bytes '.$ranges[0][1].'-'.$ranges[0][2].'/'.$filesize);
  2539. header('Content-Type: '.$mimetype);
  2540. while(@ob_get_level()) {
  2541. if (!@ob_end_flush()) {
  2542. break;
  2543. }
  2544. }
  2545. fseek($handle, $ranges[0][1]);
  2546. while (!feof($handle) && $length > 0) {
  2547. core_php_time_limit::raise(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
  2548. $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
  2549. echo $buffer;
  2550. flush();
  2551. $length -= strlen($buffer);
  2552. }
  2553. fclose($handle);
  2554. die;
  2555. } else { // multiple ranges requested - not tested much
  2556. $totallength = 0;
  2557. foreach($ranges as $range) {
  2558. $totallength += strlen($range[0]) + $range[2] - $range[1] + 1;
  2559. }
  2560. $totallength += strlen("\r\n--".BYTESERVING_BOUNDARY."--\r\n");
  2561. header('HTTP/1.1 206 Partial content');
  2562. header('Content-Length: '.$totallength);
  2563. header('Content-Type: multipart/byteranges; boundary='.BYTESERVING_BOUNDARY);
  2564. while(@ob_get_level()) {
  2565. if (!@ob_end_flush()) {
  2566. break;
  2567. }
  2568. }
  2569. foreach($ranges as $range) {
  2570. $length = $range[2] - $range[1] + 1;
  2571. echo $range[0];
  2572. fseek($handle, $range[1]);
  2573. while (!feof($handle) && $length > 0) {
  2574. core_php_time_limit::raise(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
  2575. $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
  2576. echo $buffer;
  2577. flush();
  2578. $length -= strlen($buffer);
  2579. }
  2580. }
  2581. echo "\r\n--".BYTESERVING_BOUNDARY."--\r\n";
  2582. fclose($handle);
  2583. die;
  2584. }
  2585. }
  2586. /**
  2587. * Tells whether the filename is executable.
  2588. *
  2589. * @link http://php.net/manual/en/function.is-executable.php
  2590. * @link https://bugs.php.net/bug.php?id=41062
  2591. * @param string $filename Path to the file.
  2592. * @return bool True if the filename exists and is executable; otherwise, false.
  2593. */
  2594. function file_is_executable($filename) {
  2595. if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
  2596. if (is_executable($filename)) {
  2597. return true;
  2598. } else {
  2599. $fileext = strrchr($filename, '.');
  2600. // If we have an extension we can check if it is listed as executable.
  2601. if ($fileext && file_exists($filename) && !is_dir($filename)) {
  2602. $winpathext = strtolower(getenv('PATHEXT'));
  2603. $winpathexts = explode(';', $winpathext);
  2604. return in_array(strtolower($fileext), $winpathexts);
  2605. }
  2606. return false;
  2607. }
  2608. } else {
  2609. return is_executable($filename);
  2610. }
  2611. }
  2612. /**
  2613. * Overwrite an existing file in a draft area.
  2614. *
  2615. * @param stored_file $newfile the new file with the new content and meta-data
  2616. * @param stored_file $existingfile the file that will be overwritten
  2617. * @throws moodle_exception
  2618. * @since Moodle 3.2
  2619. */
  2620. function file_overwrite_existing_draftfile(stored_file $newfile, stored_file $existingfile) {
  2621. if ($existingfile->get_component() != 'user' or $existingfile->get_filearea() != 'draft') {
  2622. throw new coding_exception('The file to overwrite is not in a draft area.');
  2623. }
  2624. $fs = get_file_storage();
  2625. // Remember original file source field.
  2626. $source = @unserialize($existingfile->get_source());
  2627. // Remember the original sortorder.
  2628. $sortorder = $existingfile->get_sortorder();
  2629. if ($newfile->is_external_file()) {
  2630. // New file is a reference. Check that existing file does not have any other files referencing to it
  2631. if (isset($source->original) && $fs->search_references_count($source->original)) {
  2632. throw new moodle_exception('errordoublereference', 'repository');
  2633. }
  2634. }
  2635. // Delete existing file to release filename.
  2636. $newfilerecord = array(
  2637. 'contextid' => $existingfile->get_contextid(),
  2638. 'component' => 'user',
  2639. 'filearea' => 'draft',
  2640. 'itemid' => $existingfile->get_itemid(),
  2641. 'timemodified' => time()
  2642. );
  2643. $existingfile->delete();
  2644. // Create new file.
  2645. $newfile = $fs->create_file_from_storedfile($newfilerecord, $newfile);
  2646. // Preserve original file location (stored in source field) for handling references.
  2647. if (isset($source->original)) {
  2648. if (!($newfilesource = @unserialize($newfile->get_source()))) {
  2649. $newfilesource = new stdClass();
  2650. }
  2651. $newfilesource->original = $source->original;
  2652. $newfile->set_source(serialize($newfilesource));
  2653. }
  2654. $newfile->set_sortorder($sortorder);
  2655. }
  2656. /**
  2657. * Add files from a draft area into a final area.
  2658. *
  2659. * Most of the time you do not want to use this. It is intended to be used
  2660. * by asynchronous services which cannot direcly manipulate a final
  2661. * area through a draft area. Instead they add files to a new draft
  2662. * area and merge that new draft into the final area when ready.
  2663. *
  2664. * @param int $draftitemid the id of the draft area to use.
  2665. * @param int $contextid this parameter and the next two identify the file area to save to.
  2666. * @param string $component component name
  2667. * @param string $filearea indentifies the file area
  2668. * @param int $itemid identifies the item id or false for all items in the file area
  2669. * @param array $options area options (subdirs=false, maxfiles=-1, maxbytes=0, areamaxbytes=FILE_AREA_MAX_BYTES_UNLIMITED)
  2670. * @see file_save_draft_area_files
  2671. * @since Moodle 3.2
  2672. */
  2673. function file_merge_files_from_draft_area_into_filearea($draftitemid, $contextid, $component, $filearea, $itemid,
  2674. array $options = null) {
  2675. // We use 0 here so file_prepare_draft_area creates a new one, finaldraftid will be updated with the new draft id.
  2676. $finaldraftid = 0;
  2677. file_prepare_draft_area($finaldraftid, $contextid, $component, $filearea, $itemid, $options);
  2678. file_merge_draft_area_into_draft_area($draftitemid, $finaldraftid);
  2679. file_save_draft_area_files($finaldraftid, $contextid, $component, $filearea, $itemid, $options);
  2680. }
  2681. /**
  2682. * Merge files from two draftarea areas.
  2683. *
  2684. * This does not handle conflict resolution, files in the destination area which appear
  2685. * to be more recent will be kept disregarding the intended ones.
  2686. *
  2687. * @param int $getfromdraftid the id of the draft area where are the files to merge.
  2688. * @param int $mergeintodraftid the id of the draft area where new files will be merged.
  2689. * @throws coding_exception
  2690. * @since Moodle 3.2
  2691. */
  2692. function file_merge_draft_area_into_draft_area($getfromdraftid, $mergeintodraftid) {
  2693. global $USER;
  2694. $fs = get_file_storage();
  2695. $contextid = context_user::instance($USER->id)->id;
  2696. if (!$filestomerge = $fs->get_area_files($contextid, 'user', 'draft', $getfromdraftid)) {
  2697. throw new coding_exception('Nothing to merge or area does not belong to current user');
  2698. }
  2699. $currentfiles = $fs->get_area_files($contextid, 'user', 'draft', $mergeintodraftid);
  2700. // Get hashes of the files to merge.
  2701. $newhashes = array();
  2702. foreach ($filestomerge as $filetomerge) {
  2703. $filepath = $filetomerge->get_filepath();
  2704. $filename = $filetomerge->get_filename();
  2705. $newhash = $fs->get_pathname_hash($contextid, 'user', 'draft', $mergeintodraftid, $filepath, $filename);
  2706. $newhashes[$newhash] = $filetomerge;
  2707. }
  2708. // Calculate wich files must be added.
  2709. foreach ($currentfiles as $file) {
  2710. $filehash = $file->get_pathnamehash();
  2711. // One file to be merged already exists.
  2712. if (isset($newhashes[$filehash])) {
  2713. $updatedfile = $newhashes[$filehash];
  2714. // Avoid race conditions.
  2715. if ($file->get_timemodified() > $updatedfile->get_timemodified()) {
  2716. // The existing file is more recent, do not copy the suposedly "new" one.
  2717. unset($newhashes[$filehash]);
  2718. continue;
  2719. }
  2720. // Update existing file (not only content, meta-data too).
  2721. file_overwrite_existing_draftfile($updatedfile, $file);
  2722. unset($newhashes[$filehash]);
  2723. }
  2724. }
  2725. foreach ($newhashes as $newfile) {
  2726. $newfilerecord = array(
  2727. 'contextid' => $contextid,
  2728. 'component' => 'user',
  2729. 'filearea' => 'draft',
  2730. 'itemid' => $mergeintodraftid,
  2731. 'timemodified' => time()
  2732. );
  2733. $fs->create_file_from_storedfile($newfilerecord, $newfile);
  2734. }
  2735. }
  2736. /**
  2737. * Attempt to determine whether the specified mime-type is an SVG image or not.
  2738. *
  2739. * @param string $mimetype Mime-type
  2740. * @return bool True if it is an SVG file
  2741. */
  2742. function file_is_svg_image_from_mimetype(string $mimetype): bool {
  2743. return preg_match('|^image/svg|', $mimetype);
  2744. }
  2745. /**
  2746. * RESTful cURL class
  2747. *
  2748. * This is a wrapper class for curl, it is quite easy to use:
  2749. * <code>
  2750. * $c = new curl;
  2751. * // enable cache
  2752. * $c = new curl(array('cache'=>true));
  2753. * // enable cookie
  2754. * $c = new curl(array('cookie'=>true));
  2755. * // enable proxy
  2756. * $c = new curl(array('proxy'=>true));
  2757. *
  2758. * // HTTP GET Method
  2759. * $html = $c->get('http://example.com');
  2760. * // HTTP POST Method
  2761. * $html = $c->post('http://example.com/', array('q'=>'words', 'name'=>'moodle'));
  2762. * // HTTP PUT Method
  2763. * $html = $c->put('http://example.com/', array('file'=>'/var/www/test.txt');
  2764. * </code>
  2765. *
  2766. * @package core_files
  2767. * @category files
  2768. * @copyright Dongsheng Cai <dongsheng@moodle.com>
  2769. * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
  2770. */
  2771. class curl {
  2772. /** @var bool Caches http request contents */
  2773. public $cache = false;
  2774. /** @var bool Uses proxy, null means automatic based on URL */
  2775. public $proxy = null;
  2776. /** @var string library version */
  2777. public $version = '0.4 dev';
  2778. /** @var array http's response */
  2779. public $response = array();
  2780. /** @var array Raw response headers, needed for BC in download_file_content(). */
  2781. public $rawresponse = array();
  2782. /** @var array http header */
  2783. public $header = array();
  2784. /** @var string cURL information */
  2785. public $info;
  2786. /** @var string error */
  2787. public $error;
  2788. /** @var int error code */
  2789. public $errno;
  2790. /** @var bool Perform redirects at PHP level instead of relying on native cURL functionality. Always true now. */
  2791. public $emulateredirects = null;
  2792. /** @var array cURL options */
  2793. private $options;
  2794. /** @var string Proxy host */
  2795. private $proxy_host = '';
  2796. /** @var string Proxy auth */
  2797. private $proxy_auth = '';
  2798. /** @var string Proxy type */
  2799. private $proxy_type = '';
  2800. /** @var bool Debug mode on */
  2801. private $debug = false;
  2802. /** @var bool|string Path to cookie file */
  2803. private $cookie = false;
  2804. /** @var bool tracks multiple headers in response - redirect detection */
  2805. private $responsefinished = false;
  2806. /** @var security helper class, responsible for checking host/ports against allowed/blocked entries.*/
  2807. private $securityhelper;
  2808. /** @var bool ignoresecurity a flag which can be supplied to the constructor, allowing security to be bypassed. */
  2809. private $ignoresecurity;
  2810. /** @var array $mockresponses For unit testing only - return the head of this list instead of making the next request. */
  2811. private static $mockresponses = [];
  2812. /**
  2813. * Curl constructor.
  2814. *
  2815. * Allowed settings are:
  2816. * proxy: (bool) use proxy server, null means autodetect non-local from url
  2817. * debug: (bool) use debug output
  2818. * cookie: (string) path to cookie file, false if none
  2819. * cache: (bool) use cache
  2820. * module_cache: (string) type of cache
  2821. * securityhelper: (\core\files\curl_security_helper_base) helper object providing URL checking for requests.
  2822. * ignoresecurity: (bool) set true to override and ignore the security helper when making requests.
  2823. *
  2824. * @param array $settings
  2825. */
  2826. public function __construct($settings = array()) {
  2827. global $CFG;
  2828. if (!function_exists('curl_init')) {
  2829. $this->error = 'cURL module must be enabled!';
  2830. trigger_error($this->error, E_USER_ERROR);
  2831. return false;
  2832. }
  2833. // All settings of this class should be init here.
  2834. $this->resetopt();
  2835. if (!empty($settings['debug'])) {
  2836. $this->debug = true;
  2837. }
  2838. if (!empty($settings['cookie'])) {
  2839. if($settings['cookie'] === true) {
  2840. $this->cookie = $CFG->dataroot.'/curl_cookie.txt';
  2841. } else {
  2842. $this->cookie = $settings['cookie'];
  2843. }
  2844. }
  2845. if (!empty($settings['cache'])) {
  2846. if (class_exists('curl_cache')) {
  2847. if (!empty($settings['module_cache'])) {
  2848. $this->cache = new curl_cache($settings['module_cache']);
  2849. } else {
  2850. $this->cache = new curl_cache('misc');
  2851. }
  2852. }
  2853. }
  2854. if (!empty($CFG->proxyhost)) {
  2855. if (empty($CFG->proxyport)) {
  2856. $this->proxy_host = $CFG->proxyhost;
  2857. } else {
  2858. $this->proxy_host = $CFG->proxyhost.':'.$CFG->proxyport;
  2859. }
  2860. if (!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) {
  2861. $this->proxy_auth = $CFG->proxyuser.':'.$CFG->proxypassword;
  2862. $this->setopt(array(
  2863. 'proxyauth'=> CURLAUTH_BASIC | CURLAUTH_NTLM,
  2864. 'proxyuserpwd'=>$this->proxy_auth));
  2865. }
  2866. if (!empty($CFG->proxytype)) {
  2867. if ($CFG->proxytype == 'SOCKS5') {
  2868. $this->proxy_type = CURLPROXY_SOCKS5;
  2869. } else {
  2870. $this->proxy_type = CURLPROXY_HTTP;
  2871. $this->setopt(array('httpproxytunnel'=>false));
  2872. }
  2873. $this->setopt(array('proxytype'=>$this->proxy_type));
  2874. }
  2875. if (isset($settings['proxy'])) {
  2876. $this->proxy = $settings['proxy'];
  2877. }
  2878. } else {
  2879. $this->proxy = false;
  2880. }
  2881. // All redirects are performed at PHP level now and each one is checked against blocked URLs rules. We do not
  2882. // want to let cURL naively follow the redirect chain and visit every URL for security reasons. Even when the
  2883. // caller explicitly wants to ignore the security checks, we would need to fall back to the original
  2884. // implementation and use emulated redirects if open_basedir is in effect to avoid the PHP warning
  2885. // "CURLOPT_FOLLOWLOCATION cannot be activated when in safe_mode or an open_basedir". So it is better to simply
  2886. // ignore this property and always handle redirects at this PHP wrapper level and not inside the native cURL.
  2887. $this->emulateredirects = true;
  2888. // Curl security setup. Allow injection of a security helper, but if not found, default to the core helper.
  2889. if (isset($settings['securityhelper']) && $settings['securityhelper'] instanceof \core\files\curl_security_helper_base) {
  2890. $this->set_security($settings['securityhelper']);
  2891. } else {
  2892. $this->set_security(new \core\files\curl_security_helper());
  2893. }
  2894. $this->ignoresecurity = isset($settings['ignoresecurity']) ? $settings['ignoresecurity'] : false;
  2895. }
  2896. /**
  2897. * Resets the CURL options that have already been set
  2898. */
  2899. public function resetopt() {
  2900. $this->options = array();
  2901. $this->options['CURLOPT_USERAGENT'] = \core_useragent::get_moodlebot_useragent();
  2902. // True to include the header in the output
  2903. $this->options['CURLOPT_HEADER'] = 0;
  2904. // True to Exclude the body from the output
  2905. $this->options['CURLOPT_NOBODY'] = 0;
  2906. // Redirect ny default.
  2907. $this->options['CURLOPT_FOLLOWLOCATION'] = 1;
  2908. $this->options['CURLOPT_MAXREDIRS'] = 10;
  2909. $this->options['CURLOPT_ENCODING'] = '';
  2910. // TRUE to return the transfer as a string of the return
  2911. // value of curl_exec() instead of outputting it out directly.
  2912. $this->options['CURLOPT_RETURNTRANSFER'] = 1;
  2913. $this->options['CURLOPT_SSL_VERIFYPEER'] = 0;
  2914. $this->options['CURLOPT_SSL_VERIFYHOST'] = 2;
  2915. $this->options['CURLOPT_CONNECTTIMEOUT'] = 30;
  2916. if ($cacert = self::get_cacert()) {
  2917. $this->options['CURLOPT_CAINFO'] = $cacert;
  2918. }
  2919. }
  2920. /**
  2921. * Get the location of ca certificates.
  2922. * @return string absolute file path or empty if default used
  2923. */
  2924. public static function get_cacert() {
  2925. global $CFG;
  2926. // Bundle in dataroot always wins.
  2927. if (is_readable("$CFG->dataroot/moodleorgca.crt")) {
  2928. return realpath("$CFG->dataroot/moodleorgca.crt");
  2929. }
  2930. // Next comes the default from php.ini
  2931. $cacert = ini_get('curl.cainfo');
  2932. if (!empty($cacert) and is_readable($cacert)) {
  2933. return realpath($cacert);
  2934. }
  2935. // Windows PHP does not have any certs, we need to use something.
  2936. if ($CFG->ostype === 'WINDOWS') {
  2937. if (is_readable("$CFG->libdir/cacert.pem")) {
  2938. return realpath("$CFG->libdir/cacert.pem");
  2939. }
  2940. }
  2941. // Use default, this should work fine on all properly configured *nix systems.
  2942. return null;
  2943. }
  2944. /**
  2945. * Reset Cookie
  2946. */
  2947. public function resetcookie() {
  2948. if (!empty($this->cookie)) {
  2949. if (is_file($this->cookie)) {
  2950. $fp = fopen($this->cookie, 'w');
  2951. if (!empty($fp)) {
  2952. fwrite($fp, '');
  2953. fclose($fp);
  2954. }
  2955. }
  2956. }
  2957. }
  2958. /**
  2959. * Set curl options.
  2960. *
  2961. * Do not use the curl constants to define the options, pass a string
  2962. * corresponding to that constant. Ie. to set CURLOPT_MAXREDIRS, pass
  2963. * array('CURLOPT_MAXREDIRS' => 10) or array('maxredirs' => 10) to this method.
  2964. *
  2965. * @param array $options If array is null, this function will reset the options to default value.
  2966. * @return void
  2967. * @throws coding_exception If an option uses constant value instead of option name.
  2968. */
  2969. public function setopt($options = array()) {
  2970. if (is_array($options)) {
  2971. foreach ($options as $name => $val) {
  2972. if (!is_string($name)) {
  2973. throw new coding_exception('Curl options should be defined using strings, not constant values.');
  2974. }
  2975. if (stripos($name, 'CURLOPT_') === false) {
  2976. $name = strtoupper('CURLOPT_'.$name);
  2977. } else {
  2978. $name = strtoupper($name);
  2979. }
  2980. $this->options[$name] = $val;
  2981. }
  2982. }
  2983. }
  2984. /**
  2985. * Reset http method
  2986. */
  2987. public function cleanopt() {
  2988. unset($this->options['CURLOPT_HTTPGET']);
  2989. unset($this->options['CURLOPT_POST']);
  2990. unset($this->options['CURLOPT_POSTFIELDS']);
  2991. unset($this->options['CURLOPT_PUT']);
  2992. unset($this->options['CURLOPT_INFILE']);
  2993. unset($this->options['CURLOPT_INFILESIZE']);
  2994. unset($this->options['CURLOPT_CUSTOMREQUEST']);
  2995. unset($this->options['CURLOPT_FILE']);
  2996. }
  2997. /**
  2998. * Resets the HTTP Request headers (to prepare for the new request)
  2999. */
  3000. public function resetHeader() {
  3001. $this->header = array();
  3002. }
  3003. /**
  3004. * Set HTTP Request Header
  3005. *
  3006. * @param array $header
  3007. */
  3008. public function setHeader($header) {
  3009. if (is_array($header)) {
  3010. foreach ($header as $v) {
  3011. $this->setHeader($v);
  3012. }
  3013. } else {
  3014. // Remove newlines, they are not allowed in headers.
  3015. $newvalue = preg_replace('/[\r\n]/', '', $header);
  3016. if (!in_array($newvalue, $this->header)) {
  3017. $this->header[] = $newvalue;
  3018. }
  3019. }
  3020. }
  3021. /**
  3022. * Get HTTP Response Headers
  3023. * @return array of arrays
  3024. */
  3025. public function getResponse() {
  3026. return $this->response;
  3027. }
  3028. /**
  3029. * Get raw HTTP Response Headers
  3030. * @return array of strings
  3031. */
  3032. public function get_raw_response() {
  3033. return $this->rawresponse;
  3034. }
  3035. /**
  3036. * private callback function
  3037. * Formatting HTTP Response Header
  3038. *
  3039. * We only keep the last headers returned. For example during a redirect the
  3040. * redirect headers will not appear in {@link self::getResponse()}, if you need
  3041. * to use those headers, refer to {@link self::get_raw_response()}.
  3042. *
  3043. * @param resource $ch Apparently not used
  3044. * @param string $header
  3045. * @return int The strlen of the header
  3046. */
  3047. private function formatHeader($ch, $header) {
  3048. $this->rawresponse[] = $header;
  3049. if (trim($header, "\r\n") === '') {
  3050. // This must be the last header.
  3051. $this->responsefinished = true;
  3052. }
  3053. if (strlen($header) > 2) {
  3054. if ($this->responsefinished) {
  3055. // We still have headers after the supposedly last header, we must be
  3056. // in a redirect so let's empty the response to keep the last headers.
  3057. $this->responsefinished = false;
  3058. $this->response = array();
  3059. }
  3060. $parts = explode(" ", rtrim($header, "\r\n"), 2);
  3061. $key = rtrim($parts[0], ':');
  3062. $value = isset($parts[1]) ? $parts[1] : null;
  3063. if (!empty($this->response[$key])) {
  3064. if (is_array($this->response[$key])) {
  3065. $this->response[$key][] = $value;
  3066. } else {
  3067. $tmp = $this->response[$key];
  3068. $this->response[$key] = array();
  3069. $this->response[$key][] = $tmp;
  3070. $this->response[$key][] = $value;
  3071. }
  3072. } else {
  3073. $this->response[$key] = $value;
  3074. }
  3075. }
  3076. return strlen($header);
  3077. }
  3078. /**
  3079. * Set options for individual curl instance
  3080. *
  3081. * @param resource $curl A curl handle
  3082. * @param array $options
  3083. * @return resource The curl handle
  3084. */
  3085. private function apply_opt($curl, $options) {
  3086. // Clean up
  3087. $this->cleanopt();
  3088. // set cookie
  3089. if (!empty($this->cookie) || !empty($options['cookie'])) {
  3090. $this->setopt(array('cookiejar'=>$this->cookie,
  3091. 'cookiefile'=>$this->cookie
  3092. ));
  3093. }
  3094. // Bypass proxy if required.
  3095. if ($this->proxy === null) {
  3096. if (!empty($this->options['CURLOPT_URL']) and is_proxybypass($this->options['CURLOPT_URL'])) {
  3097. $proxy = false;
  3098. } else {
  3099. $proxy = true;
  3100. }
  3101. } else {
  3102. $proxy = (bool)$this->proxy;
  3103. }
  3104. // Set proxy.
  3105. if ($proxy) {
  3106. $options['CURLOPT_PROXY'] = $this->proxy_host;
  3107. } else {
  3108. unset($this->options['CURLOPT_PROXY']);
  3109. }
  3110. $this->setopt($options);
  3111. // Reset before set options.
  3112. curl_setopt($curl, CURLOPT_HEADERFUNCTION, array(&$this,'formatHeader'));
  3113. // Setting the User-Agent based on options provided.
  3114. $useragent = '';
  3115. if (!empty($options['CURLOPT_USERAGENT'])) {
  3116. $useragent = $options['CURLOPT_USERAGENT'];
  3117. } else if (!empty($this->options['CURLOPT_USERAGENT'])) {
  3118. $useragent = $this->options['CURLOPT_USERAGENT'];
  3119. } else {
  3120. $useragent = \core_useragent::get_moodlebot_useragent();
  3121. }
  3122. // Set headers.
  3123. if (empty($this->header)) {
  3124. $this->setHeader(array(
  3125. 'User-Agent: ' . $useragent,
  3126. 'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7',
  3127. 'Connection: keep-alive'
  3128. ));
  3129. } else if (!in_array('User-Agent: ' . $useragent, $this->header)) {
  3130. // Remove old User-Agent if one existed.
  3131. // We have to partial search since we don't know what the original User-Agent is.
  3132. if ($match = preg_grep('/User-Agent.*/', $this->header)) {
  3133. $key = array_keys($match)[0];
  3134. unset($this->header[$key]);
  3135. }
  3136. $this->setHeader(array('User-Agent: ' . $useragent));
  3137. }
  3138. curl_setopt($curl, CURLOPT_HTTPHEADER, $this->header);
  3139. if ($this->debug) {
  3140. echo '<h1>Options</h1>';
  3141. var_dump($this->options);
  3142. echo '<h1>Header</h1>';
  3143. var_dump($this->header);
  3144. }
  3145. // Do not allow infinite redirects.
  3146. if (!isset($this->options['CURLOPT_MAXREDIRS'])) {
  3147. $this->options['CURLOPT_MAXREDIRS'] = 0;
  3148. } else if ($this->options['CURLOPT_MAXREDIRS'] > 100) {
  3149. $this->options['CURLOPT_MAXREDIRS'] = 100;
  3150. } else {
  3151. $this->options['CURLOPT_MAXREDIRS'] = (int)$this->options['CURLOPT_MAXREDIRS'];
  3152. }
  3153. // Make sure we always know if redirects expected.
  3154. if (!isset($this->options['CURLOPT_FOLLOWLOCATION'])) {
  3155. $this->options['CURLOPT_FOLLOWLOCATION'] = 0;
  3156. }
  3157. // Limit the protocols to HTTP and HTTPS.
  3158. if (defined('CURLOPT_PROTOCOLS')) {
  3159. $this->options['CURLOPT_PROTOCOLS'] = (CURLPROTO_HTTP | CURLPROTO_HTTPS);
  3160. $this->options['CURLOPT_REDIR_PROTOCOLS'] = (CURLPROTO_HTTP | CURLPROTO_HTTPS);
  3161. }
  3162. // Set options.
  3163. foreach($this->options as $name => $val) {
  3164. if ($name === 'CURLOPT_FOLLOWLOCATION') {
  3165. // All the redirects are emulated at PHP level.
  3166. curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 0);
  3167. continue;
  3168. }
  3169. $name = constant($name);
  3170. curl_setopt($curl, $name, $val);
  3171. }
  3172. return $curl;
  3173. }
  3174. /**
  3175. * Download multiple files in parallel
  3176. *
  3177. * Calls {@link multi()} with specific download headers
  3178. *
  3179. * <code>
  3180. * $c = new curl();
  3181. * $file1 = fopen('a', 'wb');
  3182. * $file2 = fopen('b', 'wb');
  3183. * $c->download(array(
  3184. * array('url'=>'http://localhost/', 'file'=>$file1),
  3185. * array('url'=>'http://localhost/20/', 'file'=>$file2)
  3186. * ));
  3187. * fclose($file1);
  3188. * fclose($file2);
  3189. * </code>
  3190. *
  3191. * or
  3192. *
  3193. * <code>
  3194. * $c = new curl();
  3195. * $c->download(array(
  3196. * array('url'=>'http://localhost/', 'filepath'=>'/tmp/file1.tmp'),
  3197. * array('url'=>'http://localhost/20/', 'filepath'=>'/tmp/file2.tmp')
  3198. * ));
  3199. * </code>
  3200. *
  3201. * @param array $requests An array of files to request {
  3202. * url => url to download the file [required]
  3203. * file => file handler, or
  3204. * filepath => file path
  3205. * }
  3206. * If 'file' and 'filepath' parameters are both specified in one request, the
  3207. * open file handle in the 'file' parameter will take precedence and 'filepath'
  3208. * will be ignored.
  3209. *
  3210. * @param array $options An array of options to set
  3211. * @return array An array of results
  3212. */
  3213. public function download($requests, $options = array()) {
  3214. $options['RETURNTRANSFER'] = false;
  3215. return $this->multi($requests, $options);
  3216. }
  3217. /**
  3218. * Returns the current curl security helper.
  3219. *
  3220. * @return \core\files\curl_security_helper instance.
  3221. */
  3222. public function get_security() {
  3223. return $this->securityhelper;
  3224. }
  3225. /**
  3226. * Sets the curl security helper.
  3227. *
  3228. * @param \core\files\curl_security_helper $securityobject instance/subclass of the base curl_security_helper class.
  3229. * @return bool true if the security helper could be set, false otherwise.
  3230. */
  3231. public function set_security($securityobject) {
  3232. if ($securityobject instanceof \core\files\curl_security_helper) {
  3233. $this->securityhelper = $securityobject;
  3234. return true;
  3235. }
  3236. return false;
  3237. }
  3238. /**
  3239. * Multi HTTP Requests
  3240. * This function could run multi-requests in parallel.
  3241. *
  3242. * @param array $requests An array of files to request
  3243. * @param array $options An array of options to set
  3244. * @return array An array of results
  3245. */
  3246. protected function multi($requests, $options = array()) {
  3247. $count = count($requests);
  3248. $handles = array();
  3249. $results = array();
  3250. $main = curl_multi_init();
  3251. for ($i = 0; $i < $count; $i++) {
  3252. if (!empty($requests[$i]['filepath']) and empty($requests[$i]['file'])) {
  3253. // open file
  3254. $requests[$i]['file'] = fopen($requests[$i]['filepath'], 'w');
  3255. $requests[$i]['auto-handle'] = true;
  3256. }
  3257. foreach($requests[$i] as $n=>$v) {
  3258. $options[$n] = $v;
  3259. }
  3260. $handles[$i] = curl_init($requests[$i]['url']);
  3261. $this->apply_opt($handles[$i], $options);
  3262. curl_multi_add_handle($main, $handles[$i]);
  3263. }
  3264. $running = 0;
  3265. do {
  3266. curl_multi_exec($main, $running);
  3267. } while($running > 0);
  3268. for ($i = 0; $i < $count; $i++) {
  3269. if (!empty($options['CURLOPT_RETURNTRANSFER'])) {
  3270. $results[] = true;
  3271. } else {
  3272. $results[] = curl_multi_getcontent($handles[$i]);
  3273. }
  3274. curl_multi_remove_handle($main, $handles[$i]);
  3275. }
  3276. curl_multi_close($main);
  3277. for ($i = 0; $i < $count; $i++) {
  3278. if (!empty($requests[$i]['filepath']) and !empty($requests[$i]['auto-handle'])) {
  3279. // close file handler if file is opened in this function
  3280. fclose($requests[$i]['file']);
  3281. }
  3282. }
  3283. return $results;
  3284. }
  3285. /**
  3286. * Helper function to reset the request state vars.
  3287. *
  3288. * @return void.
  3289. */
  3290. protected function reset_request_state_vars() {
  3291. $this->info = array();
  3292. $this->error = '';
  3293. $this->errno = 0;
  3294. $this->response = array();
  3295. $this->rawresponse = array();
  3296. $this->responsefinished = false;
  3297. }
  3298. /**
  3299. * For use only in unit tests - we can pre-set the next curl response.
  3300. * This is useful for unit testing APIs that call external systems.
  3301. * @param string $response
  3302. */
  3303. public static function mock_response($response) {
  3304. if ((defined('PHPUNIT_TEST') && PHPUNIT_TEST)) {
  3305. array_push(self::$mockresponses, $response);
  3306. } else {
  3307. throw new coding_exception('mock_response function is only available for unit tests.');
  3308. }
  3309. }
  3310. /**
  3311. * check_securityhelper_blocklist.
  3312. * Checks whether the given URL is blocked by checking both plugin's security helpers
  3313. * and core curl security helper or any curl security helper that passed to curl class constructor.
  3314. * If ignoresecurity is set to true, skip checking and consider the url is not blocked.
  3315. * This augments all installed plugin's security helpers if there is any.
  3316. *
  3317. * @param string $url the url to check.
  3318. * @return string - an error message if URL is blocked or null if URL is not blocked.
  3319. */
  3320. protected function check_securityhelper_blocklist(string $url): ?string {
  3321. // If curl security is not enabled, do not proceed.
  3322. if ($this->ignoresecurity) {
  3323. return null;
  3324. }
  3325. // Augment all installed plugin's security helpers if there is any.
  3326. // The plugin's function has to be defined as plugintype_pluginname_curl_security_helper in pluginname/lib.php.
  3327. $plugintypes = get_plugins_with_function('curl_security_helper');
  3328. // If any of the security helper's function returns true, treat as URL is blocked.
  3329. foreach ($plugintypes as $plugins) {
  3330. foreach ($plugins as $pluginfunction) {
  3331. // Get curl security helper object from plugin lib.php.
  3332. $pluginsecurityhelper = $pluginfunction();
  3333. if ($pluginsecurityhelper instanceof \core\files\curl_security_helper_base) {
  3334. if ($pluginsecurityhelper->url_is_blocked($url)) {
  3335. $this->error = $pluginsecurityhelper->get_blocked_url_string();
  3336. return $this->error;
  3337. }
  3338. }
  3339. }
  3340. }
  3341. // Check if the URL is blocked in core curl_security_helper or
  3342. // curl security helper that passed to curl class constructor.
  3343. if ($this->securityhelper->url_is_blocked($url)) {
  3344. $this->error = $this->securityhelper->get_blocked_url_string();
  3345. return $this->error;
  3346. }
  3347. return null;
  3348. }
  3349. /**
  3350. * Single HTTP Request
  3351. *
  3352. * @param string $url The URL to request
  3353. * @param array $options
  3354. * @return bool
  3355. */
  3356. protected function request($url, $options = array()) {
  3357. // Reset here so that the data is valid when result returned from cache, or if we return due to a blocked URL hit.
  3358. $this->reset_request_state_vars();
  3359. if ((defined('PHPUNIT_TEST') && PHPUNIT_TEST)) {
  3360. if ($mockresponse = array_pop(self::$mockresponses)) {
  3361. $this->info = [ 'http_code' => 200 ];
  3362. return $mockresponse;
  3363. }
  3364. }
  3365. if (empty($this->emulateredirects)) {
  3366. // Just in case someone had tried to explicitly disable emulated redirects in legacy code.
  3367. debugging('Attempting to disable emulated redirects has no effect any more!', DEBUG_DEVELOPER);
  3368. }
  3369. $urlisblocked = $this->check_securityhelper_blocklist($url);
  3370. if (!is_null($urlisblocked)) {
  3371. return $urlisblocked;
  3372. }
  3373. // Set the URL as a curl option.
  3374. $this->setopt(array('CURLOPT_URL' => $url));
  3375. // Create curl instance.
  3376. $curl = curl_init();
  3377. $this->apply_opt($curl, $options);
  3378. if ($this->cache && $ret = $this->cache->get($this->options)) {
  3379. return $ret;
  3380. }
  3381. $ret = curl_exec($curl);
  3382. $this->info = curl_getinfo($curl);
  3383. $this->error = curl_error($curl);
  3384. $this->errno = curl_errno($curl);
  3385. // Note: $this->response and $this->rawresponse are filled by $hits->formatHeader callback.
  3386. if (intval($this->info['redirect_count']) > 0) {
  3387. // For security reasons we do not allow the cURL handle to follow redirects on its own.
  3388. // See setting CURLOPT_FOLLOWLOCATION in {@see self::apply_opt()} method.
  3389. throw new coding_exception('Internal cURL handle should never follow redirects on its own!',
  3390. 'Reported number of redirects: ' . $this->info['redirect_count']);
  3391. }
  3392. if ($this->options['CURLOPT_FOLLOWLOCATION'] && $this->info['http_code'] != 200) {
  3393. $redirects = 0;
  3394. while($redirects <= $this->options['CURLOPT_MAXREDIRS']) {
  3395. if ($this->info['http_code'] == 301) {
  3396. // Moved Permanently - repeat the same request on new URL.
  3397. } else if ($this->info['http_code'] == 302) {
  3398. // Found - the standard redirect - repeat the same request on new URL.
  3399. } else if ($this->info['http_code'] == 303) {
  3400. // 303 See Other - repeat only if GET, do not bother with POSTs.
  3401. if (empty($this->options['CURLOPT_HTTPGET'])) {
  3402. break;
  3403. }
  3404. } else if ($this->info['http_code'] == 307) {
  3405. // Temporary Redirect - must repeat using the same request type.
  3406. } else if ($this->info['http_code'] == 308) {
  3407. // Permanent Redirect - must repeat using the same request type.
  3408. } else {
  3409. // Some other http code means do not retry!
  3410. break;
  3411. }
  3412. $redirects++;
  3413. $redirecturl = null;
  3414. if (isset($this->info['redirect_url'])) {
  3415. if (preg_match('|^https?://|i', $this->info['redirect_url'])) {
  3416. $redirecturl = $this->info['redirect_url'];
  3417. } else {
  3418. // Emulate CURLOPT_REDIR_PROTOCOLS behaviour which we have set to (CURLPROTO_HTTP | CURLPROTO_HTTPS) only.
  3419. $this->errno = CURLE_UNSUPPORTED_PROTOCOL;
  3420. $this->error = 'Redirect to a URL with unsuported protocol: ' . $this->info['redirect_url'];
  3421. curl_close($curl);
  3422. return $this->error;
  3423. }
  3424. }
  3425. if (!$redirecturl) {
  3426. foreach ($this->response as $k => $v) {
  3427. if (strtolower($k) === 'location') {
  3428. $redirecturl = $v;
  3429. break;
  3430. }
  3431. }
  3432. if (preg_match('|^https?://|i', $redirecturl)) {
  3433. // Great, this is the correct location format!
  3434. } else if ($redirecturl) {
  3435. $current = curl_getinfo($curl, CURLINFO_EFFECTIVE_URL);
  3436. if (strpos($redirecturl, '/') === 0) {
  3437. // Relative to server root - just guess.
  3438. $pos = strpos('/', $current, 8);
  3439. if ($pos === false) {
  3440. $redirecturl = $current.$redirecturl;
  3441. } else {
  3442. $redirecturl = substr($current, 0, $pos).$redirecturl;
  3443. }
  3444. } else {
  3445. // Relative to current script.
  3446. $redirecturl = dirname($current).'/'.$redirecturl;
  3447. }
  3448. }
  3449. }
  3450. $urlisblocked = $this->check_securityhelper_blocklist($redirecturl);
  3451. if (!is_null($urlisblocked)) {
  3452. $this->reset_request_state_vars();
  3453. curl_close($curl);
  3454. return $urlisblocked;
  3455. }
  3456. curl_setopt($curl, CURLOPT_URL, $redirecturl);
  3457. $ret = curl_exec($curl);
  3458. $this->info = curl_getinfo($curl);
  3459. $this->error = curl_error($curl);
  3460. $this->errno = curl_errno($curl);
  3461. $this->info['redirect_count'] = $redirects;
  3462. if ($this->info['http_code'] === 200) {
  3463. // Finally this is what we wanted.
  3464. break;
  3465. }
  3466. if ($this->errno != CURLE_OK) {
  3467. // Something wrong is going on.
  3468. break;
  3469. }
  3470. }
  3471. if ($redirects > $this->options['CURLOPT_MAXREDIRS']) {
  3472. $this->errno = CURLE_TOO_MANY_REDIRECTS;
  3473. $this->error = 'Maximum ('.$this->options['CURLOPT_MAXREDIRS'].') redirects followed';
  3474. }
  3475. }
  3476. if ($this->cache) {
  3477. $this->cache->set($this->options, $ret);
  3478. }
  3479. if ($this->debug) {
  3480. echo '<h1>Return Data</h1>';
  3481. var_dump($ret);
  3482. echo '<h1>Info</h1>';
  3483. var_dump($this->info);
  3484. echo '<h1>Error</h1>';
  3485. var_dump($this->error);
  3486. }
  3487. curl_close($curl);
  3488. if (empty($this->error)) {
  3489. return $ret;
  3490. } else {
  3491. return $this->error;
  3492. // exception is not ajax friendly
  3493. //throw new moodle_exception($this->error, 'curl');
  3494. }
  3495. }
  3496. /**
  3497. * HTTP HEAD method
  3498. *
  3499. * @see request()
  3500. *
  3501. * @param string $url
  3502. * @param array $options
  3503. * @return bool
  3504. */
  3505. public function head($url, $options = array()) {
  3506. $options['CURLOPT_HTTPGET'] = 0;
  3507. $options['CURLOPT_HEADER'] = 1;
  3508. $options['CURLOPT_NOBODY'] = 1;
  3509. return $this->request($url, $options);
  3510. }
  3511. /**
  3512. * HTTP PATCH method
  3513. *
  3514. * @param string $url
  3515. * @param array|string $params
  3516. * @param array $options
  3517. * @return bool
  3518. */
  3519. public function patch($url, $params = '', $options = array()) {
  3520. $options['CURLOPT_CUSTOMREQUEST'] = 'PATCH';
  3521. if (is_array($params)) {
  3522. $this->_tmp_file_post_params = array();
  3523. foreach ($params as $key => $value) {
  3524. if ($value instanceof stored_file) {
  3525. $value->add_to_curl_request($this, $key);
  3526. } else {
  3527. $this->_tmp_file_post_params[$key] = $value;
  3528. }
  3529. }
  3530. $options['CURLOPT_POSTFIELDS'] = $this->_tmp_file_post_params;
  3531. unset($this->_tmp_file_post_params);
  3532. } else {
  3533. // The variable $params is the raw post data.
  3534. $options['CURLOPT_POSTFIELDS'] = $params;
  3535. }
  3536. return $this->request($url, $options);
  3537. }
  3538. /**
  3539. * HTTP POST method
  3540. *
  3541. * @param string $url
  3542. * @param array|string $params
  3543. * @param array $options
  3544. * @return bool
  3545. */
  3546. public function post($url, $params = '', $options = array()) {
  3547. $options['CURLOPT_POST'] = 1;
  3548. if (is_array($params)) {
  3549. $this->_tmp_file_post_params = array();
  3550. foreach ($params as $key => $value) {
  3551. if ($value instanceof stored_file) {
  3552. $value->add_to_curl_request($this, $key);
  3553. } else {
  3554. $this->_tmp_file_post_params[$key] = $value;
  3555. }
  3556. }
  3557. $options['CURLOPT_POSTFIELDS'] = $this->_tmp_file_post_params;
  3558. unset($this->_tmp_file_post_params);
  3559. } else {
  3560. // $params is the raw post data
  3561. $options['CURLOPT_POSTFIELDS'] = $params;
  3562. }
  3563. return $this->request($url, $options);
  3564. }
  3565. /**
  3566. * HTTP GET method
  3567. *
  3568. * @param string $url
  3569. * @param array $params
  3570. * @param array $options
  3571. * @return bool
  3572. */
  3573. public function get($url, $params = array(), $options = array()) {
  3574. $options['CURLOPT_HTTPGET'] = 1;
  3575. if (!empty($params)) {
  3576. $url .= (stripos($url, '?') !== false) ? '&' : '?';
  3577. $url .= http_build_query($params, '', '&');
  3578. }
  3579. return $this->request($url, $options);
  3580. }
  3581. /**
  3582. * Downloads one file and writes it to the specified file handler
  3583. *
  3584. * <code>
  3585. * $c = new curl();
  3586. * $file = fopen('savepath', 'w');
  3587. * $result = $c->download_one('http://localhost/', null,
  3588. * array('file' => $file, 'timeout' => 5, 'followlocation' => true, 'maxredirs' => 3));
  3589. * fclose($file);
  3590. * $download_info = $c->get_info();
  3591. * if ($result === true) {
  3592. * // file downloaded successfully
  3593. * } else {
  3594. * $error_text = $result;
  3595. * $error_code = $c->get_errno();
  3596. * }
  3597. * </code>
  3598. *
  3599. * <code>
  3600. * $c = new curl();
  3601. * $result = $c->download_one('http://localhost/', null,
  3602. * array('filepath' => 'savepath', 'timeout' => 5, 'followlocation' => true, 'maxredirs' => 3));
  3603. * // ... see above, no need to close handle and remove file if unsuccessful
  3604. * </code>
  3605. *
  3606. * @param string $url
  3607. * @param array|null $params key-value pairs to be added to $url as query string
  3608. * @param array $options request options. Must include either 'file' or 'filepath'
  3609. * @return bool|string true on success or error string on failure
  3610. */
  3611. public function download_one($url, $params, $options = array()) {
  3612. $options['CURLOPT_HTTPGET'] = 1;
  3613. if (!empty($params)) {
  3614. $url .= (stripos($url, '?') !== false) ? '&' : '?';
  3615. $url .= http_build_query($params, '', '&');
  3616. }
  3617. if (!empty($options['filepath']) && empty($options['file'])) {
  3618. // open file
  3619. if (!($options['file'] = fopen($options['filepath'], 'w'))) {
  3620. $this->errno = 100;
  3621. return get_string('cannotwritefile', 'error', $options['filepath']);
  3622. }
  3623. $filepath = $options['filepath'];
  3624. }
  3625. unset($options['filepath']);
  3626. $result = $this->request($url, $options);
  3627. if (isset($filepath)) {
  3628. fclose($options['file']);
  3629. if ($result !== true) {
  3630. unlink($filepath);
  3631. }
  3632. }
  3633. return $result;
  3634. }
  3635. /**
  3636. * HTTP PUT method
  3637. *
  3638. * @param string $url
  3639. * @param array $params
  3640. * @param array $options
  3641. * @return bool
  3642. */
  3643. public function put($url, $params = array(), $options = array()) {
  3644. $file = '';
  3645. $fp = false;
  3646. if (isset($params['file'])) {
  3647. $file = $params['file'];
  3648. if (is_file($file)) {
  3649. $fp = fopen($file, 'r');
  3650. $size = filesize($file);
  3651. $options['CURLOPT_PUT'] = 1;
  3652. $options['CURLOPT_INFILESIZE'] = $size;
  3653. $options['CURLOPT_INFILE'] = $fp;
  3654. } else {
  3655. return null;
  3656. }
  3657. if (!isset($this->options['CURLOPT_USERPWD'])) {
  3658. $this->setopt(array('CURLOPT_USERPWD' => 'anonymous: noreply@moodle.org'));
  3659. }
  3660. } else {
  3661. $options['CURLOPT_CUSTOMREQUEST'] = 'PUT';
  3662. $options['CURLOPT_POSTFIELDS'] = $params;
  3663. }
  3664. $ret = $this->request($url, $options);
  3665. if ($fp !== false) {
  3666. fclose($fp);
  3667. }
  3668. return $ret;
  3669. }
  3670. /**
  3671. * HTTP DELETE method
  3672. *
  3673. * @param string $url
  3674. * @param array $param
  3675. * @param array $options
  3676. * @return bool
  3677. */
  3678. public function delete($url, $param = array(), $options = array()) {
  3679. $options['CURLOPT_CUSTOMREQUEST'] = 'DELETE';
  3680. if (!isset($options['CURLOPT_USERPWD'])) {
  3681. $options['CURLOPT_USERPWD'] = 'anonymous: noreply@moodle.org';
  3682. }
  3683. $ret = $this->request($url, $options);
  3684. return $ret;
  3685. }
  3686. /**
  3687. * HTTP TRACE method
  3688. *
  3689. * @param string $url
  3690. * @param array $options
  3691. * @return bool
  3692. */
  3693. public function trace($url, $options = array()) {
  3694. $options['CURLOPT_CUSTOMREQUEST'] = 'TRACE';
  3695. $ret = $this->request($url, $options);
  3696. return $ret;
  3697. }
  3698. /**
  3699. * HTTP OPTIONS method
  3700. *
  3701. * @param string $url
  3702. * @param array $options
  3703. * @return bool
  3704. */
  3705. public function options($url, $options = array()) {
  3706. $options['CURLOPT_CUSTOMREQUEST'] = 'OPTIONS';
  3707. $ret = $this->request($url, $options);
  3708. return $ret;
  3709. }
  3710. /**
  3711. * Get curl information
  3712. *
  3713. * @return string
  3714. */
  3715. public function get_info() {
  3716. return $this->info;
  3717. }
  3718. /**
  3719. * Get curl error code
  3720. *
  3721. * @return int
  3722. */
  3723. public function get_errno() {
  3724. return $this->errno;
  3725. }
  3726. /**
  3727. * When using a proxy, an additional HTTP response code may appear at
  3728. * the start of the header. For example, when using https over a proxy
  3729. * there may be 'HTTP/1.0 200 Connection Established'. Other codes are
  3730. * also possible and some may come with their own headers.
  3731. *
  3732. * If using the return value containing all headers, this function can be
  3733. * called to remove unwanted doubles.
  3734. *
  3735. * Note that it is not possible to distinguish this situation from valid
  3736. * data unless you know the actual response part (below the headers)
  3737. * will not be included in this string, or else will not 'look like' HTTP
  3738. * headers. As a result it is not safe to call this function for general
  3739. * data.
  3740. *
  3741. * @param string $input Input HTTP response
  3742. * @return string HTTP response with additional headers stripped if any
  3743. */
  3744. public static function strip_double_headers($input) {
  3745. // I have tried to make this regular expression as specific as possible
  3746. // to avoid any case where it does weird stuff if you happen to put
  3747. // HTTP/1.1 200 at the start of any line in your RSS file. This should
  3748. // also make it faster because it can abandon regex processing as soon
  3749. // as it hits something that doesn't look like an http header. The
  3750. // header definition is taken from RFC 822, except I didn't support
  3751. // folding which is never used in practice.
  3752. $crlf = "\r\n";
  3753. return preg_replace(
  3754. // HTTP version and status code (ignore value of code).
  3755. '~^HTTP/1\..*' . $crlf .
  3756. // Header name: character between 33 and 126 decimal, except colon.
  3757. // Colon. Header value: any character except \r and \n. CRLF.
  3758. '(?:[\x21-\x39\x3b-\x7e]+:[^' . $crlf . ']+' . $crlf . ')*' .
  3759. // Headers are terminated by another CRLF (blank line).
  3760. $crlf .
  3761. // Second HTTP status code, this time must be 200.
  3762. '(HTTP/1.[01] 200 )~', '$1', $input);
  3763. }
  3764. }
  3765. /**
  3766. * This class is used by cURL class, use case:
  3767. *
  3768. * <code>
  3769. * $CFG->repositorycacheexpire = 120;
  3770. * $CFG->curlcache = 120;
  3771. *
  3772. * $c = new curl(array('cache'=>true), 'module_cache'=>'repository');
  3773. * $ret = $c->get('http://www.google.com');
  3774. * </code>
  3775. *
  3776. * @package core_files
  3777. * @copyright Dongsheng Cai <dongsheng@moodle.com>
  3778. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  3779. */
  3780. class curl_cache {
  3781. /** @var string Path to cache directory */
  3782. public $dir = '';
  3783. /**
  3784. * Constructor
  3785. *
  3786. * @global stdClass $CFG
  3787. * @param string $module which module is using curl_cache
  3788. */
  3789. public function __construct($module = 'repository') {
  3790. global $CFG;
  3791. if (!empty($module)) {
  3792. $this->dir = $CFG->cachedir.'/'.$module.'/';
  3793. } else {
  3794. $this->dir = $CFG->cachedir.'/misc/';
  3795. }
  3796. if (!file_exists($this->dir)) {
  3797. mkdir($this->dir, $CFG->directorypermissions, true);
  3798. }
  3799. if ($module == 'repository') {
  3800. if (empty($CFG->repositorycacheexpire)) {
  3801. $CFG->repositorycacheexpire = 120;
  3802. }
  3803. $this->ttl = $CFG->repositorycacheexpire;
  3804. } else {
  3805. if (empty($CFG->curlcache)) {
  3806. $CFG->curlcache = 120;
  3807. }
  3808. $this->ttl = $CFG->curlcache;
  3809. }
  3810. }
  3811. /**
  3812. * Get cached value
  3813. *
  3814. * @global stdClass $CFG
  3815. * @global stdClass $USER
  3816. * @param mixed $param
  3817. * @return bool|string
  3818. */
  3819. public function get($param) {
  3820. global $CFG, $USER;
  3821. $this->cleanup($this->ttl);
  3822. $filename = 'u'.$USER->id.'_'.md5(serialize($param));
  3823. if(file_exists($this->dir.$filename)) {
  3824. $lasttime = filemtime($this->dir.$filename);
  3825. if (time()-$lasttime > $this->ttl) {
  3826. return false;
  3827. } else {
  3828. $fp = fopen($this->dir.$filename, 'r');
  3829. $size = filesize($this->dir.$filename);
  3830. $content = fread($fp, $size);
  3831. return unserialize($content);
  3832. }
  3833. }
  3834. return false;
  3835. }
  3836. /**
  3837. * Set cache value
  3838. *
  3839. * @global object $CFG
  3840. * @global object $USER
  3841. * @param mixed $param
  3842. * @param mixed $val
  3843. */
  3844. public function set($param, $val) {
  3845. global $CFG, $USER;
  3846. $filename = 'u'.$USER->id.'_'.md5(serialize($param));
  3847. $fp = fopen($this->dir.$filename, 'w');
  3848. fwrite($fp, serialize($val));
  3849. fclose($fp);
  3850. @chmod($this->dir.$filename, $CFG->filepermissions);
  3851. }
  3852. /**
  3853. * Remove cache files
  3854. *
  3855. * @param int $expire The number of seconds before expiry
  3856. */
  3857. public function cleanup($expire) {
  3858. if ($dir = opendir($this->dir)) {
  3859. while (false !== ($file = readdir($dir))) {
  3860. if(!is_dir($file) && $file != '.' && $file != '..') {
  3861. $lasttime = @filemtime($this->dir.$file);
  3862. if (time() - $lasttime > $expire) {
  3863. @unlink($this->dir.$file);
  3864. }
  3865. }
  3866. }
  3867. closedir($dir);
  3868. }
  3869. }
  3870. /**
  3871. * delete current user's cache file
  3872. *
  3873. * @global object $CFG
  3874. * @global object $USER
  3875. */
  3876. public function refresh() {
  3877. global $CFG, $USER;
  3878. if ($dir = opendir($this->dir)) {
  3879. while (false !== ($file = readdir($dir))) {
  3880. if (!is_dir($file) && $file != '.' && $file != '..') {
  3881. if (strpos($file, 'u'.$USER->id.'_') !== false) {
  3882. @unlink($this->dir.$file);
  3883. }
  3884. }
  3885. }
  3886. }
  3887. }
  3888. }
  3889. /**
  3890. * This function delegates file serving to individual plugins
  3891. *
  3892. * @param string $relativepath
  3893. * @param bool $forcedownload
  3894. * @param null|string $preview the preview mode, defaults to serving the original file
  3895. * @param boolean $offline If offline is requested - don't serve a redirect to an external file, return a file suitable for viewing
  3896. * offline (e.g. mobile app).
  3897. * @param bool $embed Whether this file will be served embed into an iframe.
  3898. * @todo MDL-31088 file serving improments
  3899. */
  3900. function file_pluginfile($relativepath, $forcedownload, $preview = null, $offline = false, $embed = false) {
  3901. global $DB, $CFG, $USER;
  3902. // relative path must start with '/'
  3903. if (!$relativepath) {
  3904. print_error('invalidargorconf');
  3905. } else if ($relativepath[0] != '/') {
  3906. print_error('pathdoesnotstartslash');
  3907. }
  3908. // extract relative path components
  3909. $args = explode('/', ltrim($relativepath, '/'));
  3910. if (count($args) < 3) { // always at least context, component and filearea
  3911. print_error('invalidarguments');
  3912. }
  3913. $contextid = (int)array_shift($args);
  3914. $component = clean_param(array_shift($args), PARAM_COMPONENT);
  3915. $filearea = clean_param(array_shift($args), PARAM_AREA);
  3916. list($context, $course, $cm) = get_context_info_array($contextid);
  3917. $fs = get_file_storage();
  3918. $sendfileoptions = ['preview' => $preview, 'offline' => $offline, 'embed' => $embed];
  3919. // ========================================================================================================================
  3920. if ($component === 'blog') {
  3921. // Blog file serving
  3922. if ($context->contextlevel != CONTEXT_SYSTEM) {
  3923. send_file_not_found();
  3924. }
  3925. if ($filearea !== 'attachment' and $filearea !== 'post') {
  3926. send_file_not_found();
  3927. }
  3928. if (empty($CFG->enableblogs)) {
  3929. print_error('siteblogdisable', 'blog');
  3930. }
  3931. $entryid = (int)array_shift($args);
  3932. if (!$entry = $DB->get_record('post', array('module'=>'blog', 'id'=>$entryid))) {
  3933. send_file_not_found();
  3934. }
  3935. if ($CFG->bloglevel < BLOG_GLOBAL_LEVEL) {
  3936. require_login();
  3937. if (isguestuser()) {
  3938. print_error('noguest');
  3939. }
  3940. if ($CFG->bloglevel == BLOG_USER_LEVEL) {
  3941. if ($USER->id != $entry->userid) {
  3942. send_file_not_found();
  3943. }
  3944. }
  3945. }
  3946. if ($entry->publishstate === 'public') {
  3947. if ($CFG->forcelogin) {
  3948. require_login();
  3949. }
  3950. } else if ($entry->publishstate === 'site') {
  3951. require_login();
  3952. //ok
  3953. } else if ($entry->publishstate === 'draft') {
  3954. require_login();
  3955. if ($USER->id != $entry->userid) {
  3956. send_file_not_found();
  3957. }
  3958. }
  3959. $filename = array_pop($args);
  3960. $filepath = $args ? '/'.implode('/', $args).'/' : '/';
  3961. if (!$file = $fs->get_file($context->id, $component, $filearea, $entryid, $filepath, $filename) or $file->is_directory()) {
  3962. send_file_not_found();
  3963. }
  3964. send_stored_file($file, 10*60, 0, true, $sendfileoptions); // download MUST be forced - security!
  3965. // ========================================================================================================================
  3966. } else if ($component === 'grade') {
  3967. require_once($CFG->libdir . '/grade/constants.php');
  3968. if (($filearea === 'outcome' or $filearea === 'scale') and $context->contextlevel == CONTEXT_SYSTEM) {
  3969. // Global gradebook files
  3970. if ($CFG->forcelogin) {
  3971. require_login();
  3972. }
  3973. $fullpath = "/$context->id/$component/$filearea/".implode('/', $args);
  3974. if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
  3975. send_file_not_found();
  3976. }
  3977. \core\session\manager::write_close(); // Unlock session during file serving.
  3978. send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
  3979. } else if ($filearea == GRADE_FEEDBACK_FILEAREA || $filearea == GRADE_HISTORY_FEEDBACK_FILEAREA) {
  3980. if ($context->contextlevel != CONTEXT_MODULE) {
  3981. send_file_not_found();
  3982. }
  3983. require_login($course, false);
  3984. $gradeid = (int) array_shift($args);
  3985. $filename = array_pop($args);
  3986. if ($filearea == GRADE_HISTORY_FEEDBACK_FILEAREA) {
  3987. $grade = $DB->get_record('grade_grades_history', ['id' => $gradeid]);
  3988. } else {
  3989. $grade = $DB->get_record('grade_grades', ['id' => $gradeid]);
  3990. }
  3991. if (!$grade) {
  3992. send_file_not_found();
  3993. }
  3994. $iscurrentuser = $USER->id == $grade->userid;
  3995. if (!$iscurrentuser) {
  3996. $coursecontext = context_course::instance($course->id);
  3997. if (!has_capability('moodle/grade:viewall', $coursecontext)) {
  3998. send_file_not_found();
  3999. }
  4000. }
  4001. $fullpath = "/$context->id/$component/$filearea/$gradeid/$filename";
  4002. if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
  4003. send_file_not_found();
  4004. }
  4005. \core\session\manager::write_close(); // Unlock session during file serving.
  4006. send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
  4007. } else {
  4008. send_file_not_found();
  4009. }
  4010. // ========================================================================================================================
  4011. } else if ($component === 'tag') {
  4012. if ($filearea === 'description' and $context->contextlevel == CONTEXT_SYSTEM) {
  4013. // All tag descriptions are going to be public but we still need to respect forcelogin
  4014. if ($CFG->forcelogin) {
  4015. require_login();
  4016. }
  4017. $fullpath = "/$context->id/tag/description/".implode('/', $args);
  4018. if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
  4019. send_file_not_found();
  4020. }
  4021. \core\session\manager::write_close(); // Unlock session during file serving.
  4022. send_stored_file($file, 60*60, 0, true, $sendfileoptions);
  4023. } else {
  4024. send_file_not_found();
  4025. }
  4026. // ========================================================================================================================
  4027. } else if ($component === 'badges') {
  4028. require_once($CFG->libdir . '/badgeslib.php');
  4029. $badgeid = (int)array_shift($args);
  4030. $badge = new badge($badgeid);
  4031. $filename = array_pop($args);
  4032. if ($filearea === 'badgeimage') {
  4033. if ($filename !== 'f1' && $filename !== 'f2' && $filename !== 'f3') {
  4034. send_file_not_found();
  4035. }
  4036. if (!$file = $fs->get_file($context->id, 'badges', 'badgeimage', $badge->id, '/', $filename.'.png')) {
  4037. send_file_not_found();
  4038. }
  4039. \core\session\manager::write_close();
  4040. send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
  4041. } else if ($filearea === 'userbadge' and $context->contextlevel == CONTEXT_USER) {
  4042. if (!$file = $fs->get_file($context->id, 'badges', 'userbadge', $badge->id, '/', $filename.'.png')) {
  4043. send_file_not_found();
  4044. }
  4045. \core\session\manager::write_close();
  4046. send_stored_file($file, 60*60, 0, true, $sendfileoptions);
  4047. }
  4048. // ========================================================================================================================
  4049. } else if ($component === 'calendar') {
  4050. if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_SYSTEM) {
  4051. // All events here are public the one requirement is that we respect forcelogin
  4052. if ($CFG->forcelogin) {
  4053. require_login();
  4054. }
  4055. // Get the event if from the args array
  4056. $eventid = array_shift($args);
  4057. // Load the event from the database
  4058. if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'eventtype'=>'site'))) {
  4059. send_file_not_found();
  4060. }
  4061. // Get the file and serve if successful
  4062. $filename = array_pop($args);
  4063. $filepath = $args ? '/'.implode('/', $args).'/' : '/';
  4064. if (!$file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
  4065. send_file_not_found();
  4066. }
  4067. \core\session\manager::write_close(); // Unlock session during file serving.
  4068. send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
  4069. } else if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_USER) {
  4070. // Must be logged in, if they are not then they obviously can't be this user
  4071. require_login();
  4072. // Don't want guests here, potentially saves a DB call
  4073. if (isguestuser()) {
  4074. send_file_not_found();
  4075. }
  4076. // Get the event if from the args array
  4077. $eventid = array_shift($args);
  4078. // Load the event from the database - user id must match
  4079. if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'userid'=>$USER->id, 'eventtype'=>'user'))) {
  4080. send_file_not_found();
  4081. }
  4082. // Get the file and serve if successful
  4083. $filename = array_pop($args);
  4084. $filepath = $args ? '/'.implode('/', $args).'/' : '/';
  4085. if (!$file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
  4086. send_file_not_found();
  4087. }
  4088. \core\session\manager::write_close(); // Unlock session during file serving.
  4089. send_stored_file($file, 0, 0, true, $sendfileoptions);
  4090. } else if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_COURSE) {
  4091. // Respect forcelogin and require login unless this is the site.... it probably
  4092. // should NEVER be the site
  4093. if ($CFG->forcelogin || $course->id != SITEID) {
  4094. require_login($course);
  4095. }
  4096. // Must be able to at least view the course. This does not apply to the front page.
  4097. if ($course->id != SITEID && (!is_enrolled($context)) && (!is_viewing($context))) {
  4098. //TODO: hmm, do we really want to block guests here?
  4099. send_file_not_found();
  4100. }
  4101. // Get the event id
  4102. $eventid = array_shift($args);
  4103. // Load the event from the database we need to check whether it is
  4104. // a) valid course event
  4105. // b) a group event
  4106. // Group events use the course context (there is no group context)
  4107. if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'courseid'=>$course->id))) {
  4108. send_file_not_found();
  4109. }
  4110. // If its a group event require either membership of view all groups capability
  4111. if ($event->eventtype === 'group') {
  4112. if (!has_capability('moodle/site:accessallgroups', $context) && !groups_is_member($event->groupid, $USER->id)) {
  4113. send_file_not_found();
  4114. }
  4115. } else if ($event->eventtype === 'course' || $event->eventtype === 'site') {
  4116. // Ok. Please note that the event type 'site' still uses a course context.
  4117. } else {
  4118. // Some other type.
  4119. send_file_not_found();
  4120. }
  4121. // If we get this far we can serve the file
  4122. $filename = array_pop($args);
  4123. $filepath = $args ? '/'.implode('/', $args).'/' : '/';
  4124. if (!$file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
  4125. send_file_not_found();
  4126. }
  4127. \core\session\manager::write_close(); // Unlock session during file serving.
  4128. send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
  4129. } else {
  4130. send_file_not_found();
  4131. }
  4132. // ========================================================================================================================
  4133. } else if ($component === 'user') {
  4134. if ($filearea === 'icon' and $context->contextlevel == CONTEXT_USER) {
  4135. if (count($args) == 1) {
  4136. $themename = theme_config::DEFAULT_THEME;
  4137. $filename = array_shift($args);
  4138. } else {
  4139. $themename = array_shift($args);
  4140. $filename = array_shift($args);
  4141. }
  4142. // fix file name automatically
  4143. if ($filename !== 'f1' and $filename !== 'f2' and $filename !== 'f3') {
  4144. $filename = 'f1';
  4145. }
  4146. if ((!empty($CFG->forcelogin) and !isloggedin()) ||
  4147. (!empty($CFG->forceloginforprofileimage) && (!isloggedin() || isguestuser()))) {
  4148. // protect images if login required and not logged in;
  4149. // also if login is required for profile images and is not logged in or guest
  4150. // do not use require_login() because it is expensive and not suitable here anyway
  4151. $theme = theme_config::load($themename);
  4152. redirect($theme->image_url('u/'.$filename, 'moodle')); // intentionally not cached
  4153. }
  4154. if (!$file = $fs->get_file($context->id, 'user', 'icon', 0, '/', $filename.'.png')) {
  4155. if (!$file = $fs->get_file($context->id, 'user', 'icon', 0, '/', $filename.'.jpg')) {
  4156. if ($filename === 'f3') {
  4157. // f3 512x512px was introduced in 2.3, there might be only the smaller version.
  4158. if (!$file = $fs->get_file($context->id, 'user', 'icon', 0, '/', 'f1.png')) {
  4159. $file = $fs->get_file($context->id, 'user', 'icon', 0, '/', 'f1.jpg');
  4160. }
  4161. }
  4162. }
  4163. }
  4164. if (!$file) {
  4165. // bad reference - try to prevent future retries as hard as possible!
  4166. if ($user = $DB->get_record('user', array('id'=>$context->instanceid), 'id, picture')) {
  4167. if ($user->picture > 0) {
  4168. $DB->set_field('user', 'picture', 0, array('id'=>$user->id));
  4169. }
  4170. }
  4171. // no redirect here because it is not cached
  4172. $theme = theme_config::load($themename);
  4173. $imagefile = $theme->resolve_image_location('u/'.$filename, 'moodle', null);
  4174. send_file($imagefile, basename($imagefile), 60*60*24*14);
  4175. }
  4176. $options = $sendfileoptions;
  4177. if (empty($CFG->forcelogin) && empty($CFG->forceloginforprofileimage)) {
  4178. // Profile images should be cache-able by both browsers and proxies according
  4179. // to $CFG->forcelogin and $CFG->forceloginforprofileimage.
  4180. $options['cacheability'] = 'public';
  4181. }
  4182. send_stored_file($file, 60*60*24*365, 0, false, $options); // enable long caching, there are many images on each page
  4183. } else if ($filearea === 'private' and $context->contextlevel == CONTEXT_USER) {
  4184. require_login();
  4185. if (isguestuser()) {
  4186. send_file_not_found();
  4187. }
  4188. if ($USER->id !== $context->instanceid) {
  4189. send_file_not_found();
  4190. }
  4191. $filename = array_pop($args);
  4192. $filepath = $args ? '/'.implode('/', $args).'/' : '/';
  4193. if (!$file = $fs->get_file($context->id, $component, $filearea, 0, $filepath, $filename) or $file->is_directory()) {
  4194. send_file_not_found();
  4195. }
  4196. \core\session\manager::write_close(); // Unlock session during file serving.
  4197. send_stored_file($file, 0, 0, true, $sendfileoptions); // must force download - security!
  4198. } else if ($filearea === 'profile' and $context->contextlevel == CONTEXT_USER) {
  4199. if ($CFG->forcelogin) {
  4200. require_login();
  4201. }
  4202. $userid = $context->instanceid;
  4203. if (!empty($CFG->forceloginforprofiles)) {
  4204. require_once("{$CFG->dirroot}/user/lib.php");
  4205. require_login();
  4206. // Verify the current user is able to view the profile of the supplied user anywhere.
  4207. $user = core_user::get_user($userid);
  4208. if (!user_can_view_profile($user, null, $context)) {
  4209. send_file_not_found();
  4210. }
  4211. }
  4212. $filename = array_pop($args);
  4213. $filepath = $args ? '/'.implode('/', $args).'/' : '/';
  4214. if (!$file = $fs->get_file($context->id, $component, $filearea, 0, $filepath, $filename) or $file->is_directory()) {
  4215. send_file_not_found();
  4216. }
  4217. \core\session\manager::write_close(); // Unlock session during file serving.
  4218. send_stored_file($file, 0, 0, true, $sendfileoptions); // must force download - security!
  4219. } else if ($filearea === 'profile' and $context->contextlevel == CONTEXT_COURSE) {
  4220. $userid = (int)array_shift($args);
  4221. $usercontext = context_user::instance($userid);
  4222. if ($CFG->forcelogin) {
  4223. require_login();
  4224. }
  4225. if (!empty($CFG->forceloginforprofiles)) {
  4226. require_once("{$CFG->dirroot}/user/lib.php");
  4227. require_login();
  4228. // Verify the current user is able to view the profile of the supplied user in current course.
  4229. $user = core_user::get_user($userid);
  4230. if (!user_can_view_profile($user, $course, $usercontext)) {
  4231. send_file_not_found();
  4232. }
  4233. }
  4234. $filename = array_pop($args);
  4235. $filepath = $args ? '/'.implode('/', $args).'/' : '/';
  4236. if (!$file = $fs->get_file($usercontext->id, 'user', 'profile', 0, $filepath, $filename) or $file->is_directory()) {
  4237. send_file_not_found();
  4238. }
  4239. \core\session\manager::write_close(); // Unlock session during file serving.
  4240. send_stored_file($file, 0, 0, true, $sendfileoptions); // must force download - security!
  4241. } else if ($filearea === 'backup' and $context->contextlevel == CONTEXT_USER) {
  4242. require_login();
  4243. if (isguestuser()) {
  4244. send_file_not_found();
  4245. }
  4246. $userid = $context->instanceid;
  4247. if ($USER->id != $userid) {
  4248. send_file_not_found();
  4249. }
  4250. $filename = array_pop($args);
  4251. $filepath = $args ? '/'.implode('/', $args).'/' : '/';
  4252. if (!$file = $fs->get_file($context->id, 'user', 'backup', 0, $filepath, $filename) or $file->is_directory()) {
  4253. send_file_not_found();
  4254. }
  4255. \core\session\manager::write_close(); // Unlock session during file serving.
  4256. send_stored_file($file, 0, 0, true, $sendfileoptions); // must force download - security!
  4257. } else {
  4258. send_file_not_found();
  4259. }
  4260. // ========================================================================================================================
  4261. } else if ($component === 'coursecat') {
  4262. if ($context->contextlevel != CONTEXT_COURSECAT) {
  4263. send_file_not_found();
  4264. }
  4265. if ($filearea === 'description') {
  4266. if ($CFG->forcelogin) {
  4267. // no login necessary - unless login forced everywhere
  4268. require_login();
  4269. }
  4270. // Check if user can view this category.
  4271. if (!core_course_category::get($context->instanceid, IGNORE_MISSING)) {
  4272. send_file_not_found();
  4273. }
  4274. $filename = array_pop($args);
  4275. $filepath = $args ? '/'.implode('/', $args).'/' : '/';
  4276. if (!$file = $fs->get_file($context->id, 'coursecat', 'description', 0, $filepath, $filename) or $file->is_directory()) {
  4277. send_file_not_found();
  4278. }
  4279. \core\session\manager::write_close(); // Unlock session during file serving.
  4280. send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
  4281. } else {
  4282. send_file_not_found();
  4283. }
  4284. // ========================================================================================================================
  4285. } else if ($component === 'course') {
  4286. if ($context->contextlevel != CONTEXT_COURSE) {
  4287. send_file_not_found();
  4288. }
  4289. if ($filearea === 'summary' || $filearea === 'overviewfiles') {
  4290. if ($CFG->forcelogin) {
  4291. require_login();
  4292. }
  4293. $filename = array_pop($args);
  4294. $filepath = $args ? '/'.implode('/', $args).'/' : '/';
  4295. if (!$file = $fs->get_file($context->id, 'course', $filearea, 0, $filepath, $filename) or $file->is_directory()) {
  4296. send_file_not_found();
  4297. }
  4298. \core\session\manager::write_close(); // Unlock session during file serving.
  4299. send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
  4300. } else if ($filearea === 'section') {
  4301. if ($CFG->forcelogin) {
  4302. require_login($course);
  4303. } else if ($course->id != SITEID) {
  4304. require_login($course);
  4305. }
  4306. $sectionid = (int)array_shift($args);
  4307. if (!$section = $DB->get_record('course_sections', array('id'=>$sectionid, 'course'=>$course->id))) {
  4308. send_file_not_found();
  4309. }
  4310. $filename = array_pop($args);
  4311. $filepath = $args ? '/'.implode('/', $args).'/' : '/';
  4312. if (!$file = $fs->get_file($context->id, 'course', 'section', $sectionid, $filepath, $filename) or $file->is_directory()) {
  4313. send_file_not_found();
  4314. }
  4315. \core\session\manager::write_close(); // Unlock session during file serving.
  4316. send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
  4317. } else {
  4318. send_file_not_found();
  4319. }
  4320. } else if ($component === 'cohort') {
  4321. $cohortid = (int)array_shift($args);
  4322. $cohort = $DB->get_record('cohort', array('id' => $cohortid), '*', MUST_EXIST);
  4323. $cohortcontext = context::instance_by_id($cohort->contextid);
  4324. // The context in the file URL must be either cohort context or context of the course underneath the cohort's context.
  4325. if ($context->id != $cohort->contextid &&
  4326. ($context->contextlevel != CONTEXT_COURSE || !in_array($cohort->contextid, $context->get_parent_context_ids()))) {
  4327. send_file_not_found();
  4328. }
  4329. // User is able to access cohort if they have view cap on cohort level or
  4330. // the cohort is visible and they have view cap on course level.
  4331. $canview = has_capability('moodle/cohort:view', $cohortcontext) ||
  4332. ($cohort->visible && has_capability('moodle/cohort:view', $context));
  4333. if ($filearea === 'description' && $canview) {
  4334. $filename = array_pop($args);
  4335. $filepath = $args ? '/'.implode('/', $args).'/' : '/';
  4336. if (($file = $fs->get_file($cohortcontext->id, 'cohort', 'description', $cohort->id, $filepath, $filename))
  4337. && !$file->is_directory()) {
  4338. \core\session\manager::write_close(); // Unlock session during file serving.
  4339. send_stored_file($file, 60 * 60, 0, $forcedownload, $sendfileoptions);
  4340. }
  4341. }
  4342. send_file_not_found();
  4343. } else if ($component === 'group') {
  4344. if ($context->contextlevel != CONTEXT_COURSE) {
  4345. send_file_not_found();
  4346. }
  4347. require_course_login($course, true, null, false);
  4348. $groupid = (int)array_shift($args);
  4349. $group = $DB->get_record('groups', array('id'=>$groupid, 'courseid'=>$course->id), '*', MUST_EXIST);
  4350. if (($course->groupmodeforce and $course->groupmode == SEPARATEGROUPS) and !has_capability('moodle/site:accessallgroups', $context) and !groups_is_member($group->id, $USER->id)) {
  4351. // do not allow access to separate group info if not member or teacher
  4352. send_file_not_found();
  4353. }
  4354. if ($filearea === 'description') {
  4355. require_login($course);
  4356. $filename = array_pop($args);
  4357. $filepath = $args ? '/'.implode('/', $args).'/' : '/';
  4358. if (!$file = $fs->get_file($context->id, 'group', 'description', $group->id, $filepath, $filename) or $file->is_directory()) {
  4359. send_file_not_found();
  4360. }
  4361. \core\session\manager::write_close(); // Unlock session during file serving.
  4362. send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
  4363. } else if ($filearea === 'icon') {
  4364. $filename = array_pop($args);
  4365. if ($filename !== 'f1' and $filename !== 'f2') {
  4366. send_file_not_found();
  4367. }
  4368. if (!$file = $fs->get_file($context->id, 'group', 'icon', $group->id, '/', $filename.'.png')) {
  4369. if (!$file = $fs->get_file($context->id, 'group', 'icon', $group->id, '/', $filename.'.jpg')) {
  4370. send_file_not_found();
  4371. }
  4372. }
  4373. \core\session\manager::write_close(); // Unlock session during file serving.
  4374. send_stored_file($file, 60*60, 0, false, $sendfileoptions);
  4375. } else {
  4376. send_file_not_found();
  4377. }
  4378. } else if ($component === 'grouping') {
  4379. if ($context->contextlevel != CONTEXT_COURSE) {
  4380. send_file_not_found();
  4381. }
  4382. require_login($course);
  4383. $groupingid = (int)array_shift($args);
  4384. // note: everybody has access to grouping desc images for now
  4385. if ($filearea === 'description') {
  4386. $filename = array_pop($args);
  4387. $filepath = $args ? '/'.implode('/', $args).'/' : '/';
  4388. if (!$file = $fs->get_file($context->id, 'grouping', 'description', $groupingid, $filepath, $filename) or $file->is_directory()) {
  4389. send_file_not_found();
  4390. }
  4391. \core\session\manager::write_close(); // Unlock session during file serving.
  4392. send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
  4393. } else {
  4394. send_file_not_found();
  4395. }
  4396. // ========================================================================================================================
  4397. } else if ($component === 'backup') {
  4398. if ($filearea === 'course' and $context->contextlevel == CONTEXT_COURSE) {
  4399. require_login($course);
  4400. require_capability('moodle/backup:downloadfile', $context);
  4401. $filename = array_pop($args);
  4402. $filepath = $args ? '/'.implode('/', $args).'/' : '/';
  4403. if (!$file = $fs->get_file($context->id, 'backup', 'course', 0, $filepath, $filename) or $file->is_directory()) {
  4404. send_file_not_found();
  4405. }
  4406. \core\session\manager::write_close(); // Unlock session during file serving.
  4407. send_stored_file($file, 0, 0, $forcedownload, $sendfileoptions);
  4408. } else if ($filearea === 'section' and $context->contextlevel == CONTEXT_COURSE) {
  4409. require_login($course);
  4410. require_capability('moodle/backup:downloadfile', $context);
  4411. $sectionid = (int)array_shift($args);
  4412. $filename = array_pop($args);
  4413. $filepath = $args ? '/'.implode('/', $args).'/' : '/';
  4414. if (!$file = $fs->get_file($context->id, 'backup', 'section', $sectionid, $filepath, $filename) or $file->is_directory()) {
  4415. send_file_not_found();
  4416. }
  4417. \core\session\manager::write_close();
  4418. send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
  4419. } else if ($filearea === 'activity' and $context->contextlevel == CONTEXT_MODULE) {
  4420. require_login($course, false, $cm);
  4421. require_capability('moodle/backup:downloadfile', $context);
  4422. $filename = array_pop($args);
  4423. $filepath = $args ? '/'.implode('/', $args).'/' : '/';
  4424. if (!$file = $fs->get_file($context->id, 'backup', 'activity', 0, $filepath, $filename) or $file->is_directory()) {
  4425. send_file_not_found();
  4426. }
  4427. \core\session\manager::write_close();
  4428. send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
  4429. } else if ($filearea === 'automated' and $context->contextlevel == CONTEXT_COURSE) {
  4430. // Backup files that were generated by the automated backup systems.
  4431. require_login($course);
  4432. require_capability('moodle/backup:downloadfile', $context);
  4433. require_capability('moodle/restore:userinfo', $context);
  4434. $filename = array_pop($args);
  4435. $filepath = $args ? '/'.implode('/', $args).'/' : '/';
  4436. if (!$file = $fs->get_file($context->id, 'backup', 'automated', 0, $filepath, $filename) or $file->is_directory()) {
  4437. send_file_not_found();
  4438. }
  4439. \core\session\manager::write_close(); // Unlock session during file serving.
  4440. send_stored_file($file, 0, 0, $forcedownload, $sendfileoptions);
  4441. } else {
  4442. send_file_not_found();
  4443. }
  4444. // ========================================================================================================================
  4445. } else if ($component === 'question') {
  4446. require_once($CFG->libdir . '/questionlib.php');
  4447. question_pluginfile($course, $context, 'question', $filearea, $args, $forcedownload, $sendfileoptions);
  4448. send_file_not_found();
  4449. // ========================================================================================================================
  4450. } else if ($component === 'grading') {
  4451. if ($filearea === 'description') {
  4452. // files embedded into the form definition description
  4453. if ($context->contextlevel == CONTEXT_SYSTEM) {
  4454. require_login();
  4455. } else if ($context->contextlevel >= CONTEXT_COURSE) {
  4456. require_login($course, false, $cm);
  4457. } else {
  4458. send_file_not_found();
  4459. }
  4460. $formid = (int)array_shift($args);
  4461. $sql = "SELECT ga.id
  4462. FROM {grading_areas} ga
  4463. JOIN {grading_definitions} gd ON (gd.areaid = ga.id)
  4464. WHERE gd.id = ? AND ga.contextid = ?";
  4465. $areaid = $DB->get_field_sql($sql, array($formid, $context->id), IGNORE_MISSING);
  4466. if (!$areaid) {
  4467. send_file_not_found();
  4468. }
  4469. $fullpath = "/$context->id/$component/$filearea/$formid/".implode('/', $args);
  4470. if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
  4471. send_file_not_found();
  4472. }
  4473. \core\session\manager::write_close(); // Unlock session during file serving.
  4474. send_stored_file($file, 60*60, 0, $forcedownload, $sendfileoptions);
  4475. }
  4476. } else if ($component === 'contentbank') {
  4477. if ($filearea != 'public' || isguestuser()) {
  4478. send_file_not_found();
  4479. }
  4480. if ($context->contextlevel == CONTEXT_SYSTEM || $context->contextlevel == CONTEXT_COURSECAT) {
  4481. require_login();
  4482. } else if ($context->contextlevel == CONTEXT_COURSE) {
  4483. require_login($course);
  4484. } else {
  4485. send_file_not_found();
  4486. }
  4487. $itemid = (int)array_shift($args);
  4488. $filename = array_pop($args);
  4489. $filepath = $args ? '/'.implode('/', $args).'/' : '/';
  4490. if (!$file = $fs->get_file($context->id, $component, $filearea, $itemid, $filepath, $filename) or
  4491. $file->is_directory()) {
  4492. send_file_not_found();
  4493. }
  4494. \core\session\manager::write_close(); // Unlock session during file serving.
  4495. send_stored_file($file, 0, 0, true, $sendfileoptions); // must force download - security!
  4496. } else if (strpos($component, 'mod_') === 0) {
  4497. $modname = substr($component, 4);
  4498. if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
  4499. send_file_not_found();
  4500. }
  4501. require_once("$CFG->dirroot/mod/$modname/lib.php");
  4502. if ($context->contextlevel == CONTEXT_MODULE) {
  4503. if ($cm->modname !== $modname) {
  4504. // somebody tries to gain illegal access, cm type must match the component!
  4505. send_file_not_found();
  4506. }
  4507. }
  4508. if ($filearea === 'intro') {
  4509. if (!plugin_supports('mod', $modname, FEATURE_MOD_INTRO, true)) {
  4510. send_file_not_found();
  4511. }
  4512. // Require login to the course first (without login to the module).
  4513. require_course_login($course, true);
  4514. // Now check if module is available OR it is restricted but the intro is shown on the course page.
  4515. $cminfo = cm_info::create($cm);
  4516. if (!$cminfo->uservisible) {
  4517. if (!$cm->showdescription || !$cminfo->is_visible_on_course_page()) {
  4518. // Module intro is not visible on the course page and module is not available, show access error.
  4519. require_course_login($course, true, $cminfo);
  4520. }
  4521. }
  4522. // all users may access it
  4523. $filename = array_pop($args);
  4524. $filepath = $args ? '/'.implode('/', $args).'/' : '/';
  4525. if (!$file = $fs->get_file($context->id, 'mod_'.$modname, 'intro', 0, $filepath, $filename) or $file->is_directory()) {
  4526. send_file_not_found();
  4527. }
  4528. // finally send the file
  4529. send_stored_file($file, null, 0, false, $sendfileoptions);
  4530. }
  4531. $filefunction = $component.'_pluginfile';
  4532. $filefunctionold = $modname.'_pluginfile';
  4533. if (function_exists($filefunction)) {
  4534. // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
  4535. $filefunction($course, $cm, $context, $filearea, $args, $forcedownload, $sendfileoptions);
  4536. } else if (function_exists($filefunctionold)) {
  4537. // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
  4538. $filefunctionold($course, $cm, $context, $filearea, $args, $forcedownload, $sendfileoptions);
  4539. }
  4540. send_file_not_found();
  4541. // ========================================================================================================================
  4542. } else if (strpos($component, 'block_') === 0) {
  4543. $blockname = substr($component, 6);
  4544. // note: no more class methods in blocks please, that is ....
  4545. if (!file_exists("$CFG->dirroot/blocks/$blockname/lib.php")) {
  4546. send_file_not_found();
  4547. }
  4548. require_once("$CFG->dirroot/blocks/$blockname/lib.php");
  4549. if ($context->contextlevel == CONTEXT_BLOCK) {
  4550. $birecord = $DB->get_record('block_instances', array('id'=>$context->instanceid), '*',MUST_EXIST);
  4551. if ($birecord->blockname !== $blockname) {
  4552. // somebody tries to gain illegal access, cm type must match the component!
  4553. send_file_not_found();
  4554. }
  4555. if ($context->get_course_context(false)) {
  4556. // If block is in course context, then check if user has capability to access course.
  4557. require_course_login($course);
  4558. } else if ($CFG->forcelogin) {
  4559. // If user is logged out, bp record will not be visible, even if the user would have access if logged in.
  4560. require_login();
  4561. }
  4562. $bprecord = $DB->get_record('block_positions', array('contextid' => $context->id, 'blockinstanceid' => $context->instanceid));
  4563. // User can't access file, if block is hidden or doesn't have block:view capability
  4564. if (($bprecord && !$bprecord->visible) || !has_capability('moodle/block:view', $context)) {
  4565. send_file_not_found();
  4566. }
  4567. } else {
  4568. $birecord = null;
  4569. }
  4570. $filefunction = $component.'_pluginfile';
  4571. if (function_exists($filefunction)) {
  4572. // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
  4573. $filefunction($course, $birecord, $context, $filearea, $args, $forcedownload, $sendfileoptions);
  4574. }
  4575. send_file_not_found();
  4576. // ========================================================================================================================
  4577. } else if (strpos($component, '_') === false) {
  4578. // all core subsystems have to be specified above, no more guessing here!
  4579. send_file_not_found();
  4580. } else {
  4581. // try to serve general plugin file in arbitrary context
  4582. $dir = core_component::get_component_directory($component);
  4583. if (!file_exists("$dir/lib.php")) {
  4584. send_file_not_found();
  4585. }
  4586. include_once("$dir/lib.php");
  4587. $filefunction = $component.'_pluginfile';
  4588. if (function_exists($filefunction)) {
  4589. // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
  4590. $filefunction($course, $cm, $context, $filearea, $args, $forcedownload, $sendfileoptions);
  4591. }
  4592. send_file_not_found();
  4593. }
  4594. }