PageRenderTime 84ms CodeModel.GetById 24ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/filelib.php

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