PageRenderTime 81ms CodeModel.GetById 21ms 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

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

  1. <?php
  2. // This file is part of Moodle - http://moodle.org/
  3. //
  4. // Moodle is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // Moodle is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU General Public License
  15. // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
  16. /**
  17. * 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. }

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