PageRenderTime 70ms CodeModel.GetById 27ms RepoModel.GetById 1ms app.codeStats 1ms

/lib/filelib.php

https://github.com/dongsheng/moodle
PHP | 5175 lines | 3252 code | 534 blank | 1389 comment | 885 complexity | 2ae9b18013aff8782c4384398f6b4271 MD5 | raw file
Possible License(s): BSD-3-Clause, MIT, GPL-3.0, Apache-2.0, LGPL-2.1

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. /**
  37. * Capacity of the draft area bucket when using the leaking bucket technique to limit the draft upload rate.
  38. */
  39. define('DRAFT_AREA_BUCKET_CAPACITY', 50);
  40. /**
  41. * Leaking rate of the draft area bucket when using the leaking bucket technique to limit the draft upload rate.
  42. */
  43. define('DRAFT_AREA_BUCKET_LEAK', 0.2);
  44. require_once("$CFG->libdir/filestorage/file_exceptions.php");
  45. require_once("$CFG->libdir/filestorage/file_storage.php");
  46. require_once("$CFG->libdir/filestorage/zip_packer.php");
  47. require_once("$CFG->libdir/filebrowser/file_browser.php");
  48. /**
  49. * Encodes file serving url
  50. *
  51. * @deprecated use moodle_url factory methods instead
  52. *
  53. * @todo MDL-31071 deprecate this function
  54. * @global stdClass $CFG
  55. * @param string $urlbase
  56. * @param string $path /filearea/itemid/dir/dir/file.exe
  57. * @param bool $forcedownload
  58. * @param bool $https https url required
  59. * @return string encoded file url
  60. */
  61. function file_encode_url($urlbase, $path, $forcedownload=false, $https=false) {
  62. global $CFG;
  63. //TODO: deprecate this
  64. if ($CFG->slasharguments) {
  65. $parts = explode('/', $path);
  66. $parts = array_map('rawurlencode', $parts);
  67. $path = implode('/', $parts);
  68. $return = $urlbase.$path;
  69. if ($forcedownload) {
  70. $return .= '?forcedownload=1';
  71. }
  72. } else {
  73. $path = rawurlencode($path);
  74. $return = $urlbase.'?file='.$path;
  75. if ($forcedownload) {
  76. $return .= '&amp;forcedownload=1';
  77. }
  78. }
  79. if ($https) {
  80. $return = str_replace('http://', 'https://', $return);
  81. }
  82. return $return;
  83. }
  84. /**
  85. * Detects if area contains subdirs,
  86. * this is intended for file areas that are attached to content
  87. * migrated from 1.x where subdirs were allowed everywhere.
  88. *
  89. * @param context $context
  90. * @param string $component
  91. * @param string $filearea
  92. * @param string $itemid
  93. * @return bool
  94. */
  95. function file_area_contains_subdirs(context $context, $component, $filearea, $itemid) {
  96. global $DB;
  97. if (!isset($itemid)) {
  98. // Not initialised yet.
  99. return false;
  100. }
  101. // Detect if any directories are already present, this is necessary for content upgraded from 1.x.
  102. $select = "contextid = :contextid AND component = :component AND filearea = :filearea AND itemid = :itemid AND filepath <> '/' AND filename = '.'";
  103. $params = array('contextid'=>$context->id, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid);
  104. return $DB->record_exists_select('files', $select, $params);
  105. }
  106. /**
  107. * Prepares 'editor' formslib element from data in database
  108. *
  109. * The passed $data record must contain field foobar, foobarformat and optionally foobartrust. This
  110. * function then copies the embedded files into draft area (assigning itemids automatically),
  111. * creates the form element foobar_editor and rewrites the URLs so the embedded images can be
  112. * displayed.
  113. * In your mform definition, you must have an 'editor' element called foobar_editor. Then you call
  114. * your mform's set_data() supplying the object returned by this function.
  115. *
  116. * @category files
  117. * @param stdClass $data database field that holds the html text with embedded media
  118. * @param string $field the name of the database field that holds the html text with embedded media
  119. * @param array $options editor options (like maxifiles, maxbytes etc.)
  120. * @param stdClass $context context of the editor
  121. * @param string $component
  122. * @param string $filearea file area name
  123. * @param int $itemid item id, required if item exists
  124. * @return stdClass modified data object
  125. */
  126. function file_prepare_standard_editor($data, $field, array $options, $context=null, $component=null, $filearea=null, $itemid=null) {
  127. $options = (array)$options;
  128. if (!isset($options['trusttext'])) {
  129. $options['trusttext'] = false;
  130. }
  131. if (!isset($options['forcehttps'])) {
  132. $options['forcehttps'] = false;
  133. }
  134. if (!isset($options['subdirs'])) {
  135. $options['subdirs'] = false;
  136. }
  137. if (!isset($options['maxfiles'])) {
  138. $options['maxfiles'] = 0; // no files by default
  139. }
  140. if (!isset($options['noclean'])) {
  141. $options['noclean'] = false;
  142. }
  143. //sanity check for passed context. This function doesn't expect $option['context'] to be set
  144. //But this function is called before creating editor hence, this is one of the best places to check
  145. //if context is used properly. This check notify developer that they missed passing context to editor.
  146. if (isset($context) && !isset($options['context'])) {
  147. //if $context is not null then make sure $option['context'] is also set.
  148. debugging('Context for editor is not set in editoroptions. Hence editor will not respect editor filters', DEBUG_DEVELOPER);
  149. } else if (isset($options['context']) && isset($context)) {
  150. //If both are passed then they should be equal.
  151. if ($options['context']->id != $context->id) {
  152. $exceptionmsg = 'Editor context ['.$options['context']->id.'] is not equal to passed context ['.$context->id.']';
  153. throw new coding_exception($exceptionmsg);
  154. }
  155. }
  156. if (is_null($itemid) or is_null($context)) {
  157. $contextid = null;
  158. $itemid = null;
  159. if (!isset($data)) {
  160. $data = new stdClass();
  161. }
  162. if (!isset($data->{$field})) {
  163. $data->{$field} = '';
  164. }
  165. if (!isset($data->{$field.'format'})) {
  166. $data->{$field.'format'} = editors_get_preferred_format();
  167. }
  168. if (!$options['noclean']) {
  169. $data->{$field} = clean_text($data->{$field}, $data->{$field.'format'});
  170. }
  171. } else {
  172. if ($options['trusttext']) {
  173. // noclean ignored if trusttext enabled
  174. if (!isset($data->{$field.'trust'})) {
  175. $data->{$field.'trust'} = 0;
  176. }
  177. $data = trusttext_pre_edit($data, $field, $context);
  178. } else {
  179. if (!$options['noclean']) {
  180. $data->{$field} = clean_text($data->{$field}, $data->{$field.'format'});
  181. }
  182. }
  183. $contextid = $context->id;
  184. }
  185. if ($options['maxfiles'] != 0) {
  186. $draftid_editor = file_get_submitted_draft_itemid($field);
  187. $currenttext = file_prepare_draft_area($draftid_editor, $contextid, $component, $filearea, $itemid, $options, $data->{$field});
  188. $data->{$field.'_editor'} = array('text'=>$currenttext, 'format'=>$data->{$field.'format'}, 'itemid'=>$draftid_editor);
  189. } else {
  190. $data->{$field.'_editor'} = array('text'=>$data->{$field}, 'format'=>$data->{$field.'format'}, 'itemid'=>0);
  191. }
  192. return $data;
  193. }
  194. /**
  195. * Prepares the content of the 'editor' form element with embedded media files to be saved in database
  196. *
  197. * This function moves files from draft area to the destination area and
  198. * encodes URLs to the draft files so they can be safely saved into DB. The
  199. * form has to contain the 'editor' element named foobar_editor, where 'foobar'
  200. * is the name of the database field to hold the wysiwyg editor content. The
  201. * editor data comes as an array with text, format and itemid properties. This
  202. * function automatically adds $data properties foobar, foobarformat and
  203. * foobartrust, where foobar has URL to embedded files encoded.
  204. *
  205. * @category files
  206. * @param stdClass $data raw data submitted by the form
  207. * @param string $field name of the database field containing the html with embedded media files
  208. * @param array $options editor options (trusttext, subdirs, maxfiles, maxbytes etc.)
  209. * @param stdClass $context context, required for existing data
  210. * @param string $component file component
  211. * @param string $filearea file area name
  212. * @param int $itemid item id, required if item exists
  213. * @return stdClass modified data object
  214. */
  215. function file_postupdate_standard_editor($data, $field, array $options, $context, $component=null, $filearea=null, $itemid=null) {
  216. $options = (array)$options;
  217. if (!isset($options['trusttext'])) {
  218. $options['trusttext'] = false;
  219. }
  220. if (!isset($options['forcehttps'])) {
  221. $options['forcehttps'] = false;
  222. }
  223. if (!isset($options['subdirs'])) {
  224. $options['subdirs'] = false;
  225. }
  226. if (!isset($options['maxfiles'])) {
  227. $options['maxfiles'] = 0; // no files by default
  228. }
  229. if (!isset($options['maxbytes'])) {
  230. $options['maxbytes'] = 0; // unlimited
  231. }
  232. if (!isset($options['removeorphaneddrafts'])) {
  233. $options['removeorphaneddrafts'] = false; // Don't remove orphaned draft files by default.
  234. }
  235. if ($options['trusttext']) {
  236. $data->{$field.'trust'} = trusttext_trusted($context);
  237. } else {
  238. $data->{$field.'trust'} = 0;
  239. }
  240. $editor = $data->{$field.'_editor'};
  241. if ($options['maxfiles'] == 0 or is_null($filearea) or is_null($itemid) or empty($editor['itemid'])) {
  242. $data->{$field} = $editor['text'];
  243. } else {
  244. // Clean the user drafts area of any files not referenced in the editor text.
  245. if ($options['removeorphaneddrafts']) {
  246. file_remove_editor_orphaned_files($editor);
  247. }
  248. $data->{$field} = file_save_draft_area_files($editor['itemid'], $context->id, $component, $filearea, $itemid, $options, $editor['text'], $options['forcehttps']);
  249. }
  250. $data->{$field.'format'} = $editor['format'];
  251. return $data;
  252. }
  253. /**
  254. * Saves text and files modified by Editor formslib element
  255. *
  256. * @category files
  257. * @param stdClass $data $database entry field
  258. * @param string $field name of data field
  259. * @param array $options various options
  260. * @param stdClass $context context - must already exist
  261. * @param string $component
  262. * @param string $filearea file area name
  263. * @param int $itemid must already exist, usually means data is in db
  264. * @return stdClass modified data obejct
  265. */
  266. function file_prepare_standard_filemanager($data, $field, array $options, $context=null, $component=null, $filearea=null, $itemid=null) {
  267. $options = (array)$options;
  268. if (!isset($options['subdirs'])) {
  269. $options['subdirs'] = false;
  270. }
  271. if (is_null($itemid) or is_null($context)) {
  272. $itemid = null;
  273. $contextid = null;
  274. } else {
  275. $contextid = $context->id;
  276. }
  277. $draftid_editor = file_get_submitted_draft_itemid($field.'_filemanager');
  278. file_prepare_draft_area($draftid_editor, $contextid, $component, $filearea, $itemid, $options);
  279. $data->{$field.'_filemanager'} = $draftid_editor;
  280. return $data;
  281. }
  282. /**
  283. * Saves files modified by File manager formslib element
  284. *
  285. * @todo MDL-31073 review this function
  286. * @category files
  287. * @param stdClass $data $database entry field
  288. * @param string $field name of data field
  289. * @param array $options various options
  290. * @param stdClass $context context - must already exist
  291. * @param string $component
  292. * @param string $filearea file area name
  293. * @param int $itemid must already exist, usually means data is in db
  294. * @return stdClass modified data obejct
  295. */
  296. function file_postupdate_standard_filemanager($data, $field, array $options, $context, $component, $filearea, $itemid) {
  297. $options = (array)$options;
  298. if (!isset($options['subdirs'])) {
  299. $options['subdirs'] = false;
  300. }
  301. if (!isset($options['maxfiles'])) {
  302. $options['maxfiles'] = -1; // unlimited
  303. }
  304. if (!isset($options['maxbytes'])) {
  305. $options['maxbytes'] = 0; // unlimited
  306. }
  307. if (empty($data->{$field.'_filemanager'})) {
  308. $data->$field = '';
  309. } else {
  310. file_save_draft_area_files($data->{$field.'_filemanager'}, $context->id, $component, $filearea, $itemid, $options);
  311. $fs = get_file_storage();
  312. if ($fs->get_area_files($context->id, $component, $filearea, $itemid)) {
  313. $data->$field = '1'; // TODO: this is an ugly hack (skodak)
  314. } else {
  315. $data->$field = '';
  316. }
  317. }
  318. return $data;
  319. }
  320. /**
  321. * Generate a draft itemid
  322. *
  323. * @category files
  324. * @global moodle_database $DB
  325. * @global stdClass $USER
  326. * @return int a random but available draft itemid that can be used to create a new draft
  327. * file area.
  328. */
  329. function file_get_unused_draft_itemid() {
  330. global $DB, $USER;
  331. if (isguestuser() or !isloggedin()) {
  332. // guests and not-logged-in users can not be allowed to upload anything!!!!!!
  333. print_error('noguest');
  334. }
  335. $contextid = context_user::instance($USER->id)->id;
  336. $fs = get_file_storage();
  337. $draftitemid = rand(1, 999999999);
  338. while ($files = $fs->get_area_files($contextid, 'user', 'draft', $draftitemid)) {
  339. $draftitemid = rand(1, 999999999);
  340. }
  341. return $draftitemid;
  342. }
  343. /**
  344. * Initialise a draft file area from a real one by copying the files. A draft
  345. * area will be created if one does not already exist. Normally you should
  346. * get $draftitemid by calling file_get_submitted_draft_itemid('elementname');
  347. *
  348. * @category files
  349. * @global stdClass $CFG
  350. * @global stdClass $USER
  351. * @param int $draftitemid the id of the draft area to use, or 0 to create a new one, in which case this parameter is updated.
  352. * @param int $contextid This parameter and the next two identify the file area to copy files from.
  353. * @param string $component
  354. * @param string $filearea helps indentify the file area.
  355. * @param int $itemid helps identify the file area. Can be null if there are no files yet.
  356. * @param array $options text and file options ('subdirs'=>false, 'forcehttps'=>false)
  357. * @param string $text some html content that needs to have embedded links rewritten to point to the draft area.
  358. * @return string|null returns string if $text was passed in, the rewritten $text is returned. Otherwise NULL.
  359. */
  360. function file_prepare_draft_area(&$draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null) {
  361. global $CFG, $USER;
  362. $options = (array)$options;
  363. if (!isset($options['subdirs'])) {
  364. $options['subdirs'] = false;
  365. }
  366. if (!isset($options['forcehttps'])) {
  367. $options['forcehttps'] = false;
  368. }
  369. $usercontext = context_user::instance($USER->id);
  370. $fs = get_file_storage();
  371. if (empty($draftitemid)) {
  372. // create a new area and copy existing files into
  373. $draftitemid = file_get_unused_draft_itemid();
  374. $file_record = array('contextid'=>$usercontext->id, 'component'=>'user', 'filearea'=>'draft', 'itemid'=>$draftitemid);
  375. if (!is_null($itemid) and $files = $fs->get_area_files($contextid, $component, $filearea, $itemid)) {
  376. foreach ($files as $file) {
  377. if ($file->is_directory() and $file->get_filepath() === '/') {
  378. // we need a way to mark the age of each draft area,
  379. // by not copying the root dir we force it to be created automatically with current timestamp
  380. continue;
  381. }
  382. if (!$options['subdirs'] and ($file->is_directory() or $file->get_filepath() !== '/')) {
  383. continue;
  384. }
  385. $draftfile = $fs->create_file_from_storedfile($file_record, $file);
  386. // XXX: This is a hack for file manager (MDL-28666)
  387. // File manager needs to know the original file information before copying
  388. // to draft area, so we append these information in mdl_files.source field
  389. // {@link file_storage::search_references()}
  390. // {@link file_storage::search_references_count()}
  391. $sourcefield = $file->get_source();
  392. $newsourcefield = new stdClass;
  393. $newsourcefield->source = $sourcefield;
  394. $original = new stdClass;
  395. $original->contextid = $contextid;
  396. $original->component = $component;
  397. $original->filearea = $filearea;
  398. $original->itemid = $itemid;
  399. $original->filename = $file->get_filename();
  400. $original->filepath = $file->get_filepath();
  401. $newsourcefield->original = file_storage::pack_reference($original);
  402. $draftfile->set_source(serialize($newsourcefield));
  403. // End of file manager hack
  404. }
  405. }
  406. if (!is_null($text)) {
  407. // at this point there should not be any draftfile links yet,
  408. // because this is a new text from database that should still contain the @@pluginfile@@ links
  409. // this happens when developers forget to post process the text
  410. $text = str_replace("\"$CFG->wwwroot/draftfile.php", "\"$CFG->wwwroot/brokenfile.php#", $text);
  411. }
  412. } else {
  413. // nothing to do
  414. }
  415. if (is_null($text)) {
  416. return null;
  417. }
  418. // relink embedded files - editor can not handle @@PLUGINFILE@@ !
  419. return file_rewrite_pluginfile_urls($text, 'draftfile.php', $usercontext->id, 'user', 'draft', $draftitemid, $options);
  420. }
  421. /**
  422. * Convert encoded URLs in $text from the @@PLUGINFILE@@/... form to an actual URL.
  423. * Passing a new option reverse = true in the $options var will make the function to convert actual URLs in $text to encoded URLs
  424. * in the @@PLUGINFILE@@ form.
  425. *
  426. * @param string $text The content that may contain ULRs in need of rewriting.
  427. * @param string $file The script that should be used to serve these files. pluginfile.php, draftfile.php, etc.
  428. * @param int $contextid This parameter and the next two identify the file area to use.
  429. * @param string $component
  430. * @param string $filearea helps identify the file area.
  431. * @param int $itemid helps identify the file area.
  432. * @param array $options
  433. * bool $options.forcehttps Force the user of https
  434. * bool $options.reverse Reverse the behaviour of the function
  435. * mixed $options.includetoken Use a token for authentication. True for current user, int value for other user id.
  436. * string The processed text.
  437. */
  438. function file_rewrite_pluginfile_urls($text, $file, $contextid, $component, $filearea, $itemid, array $options=null) {
  439. global $CFG, $USER;
  440. $options = (array)$options;
  441. if (!isset($options['forcehttps'])) {
  442. $options['forcehttps'] = false;
  443. }
  444. $baseurl = "{$CFG->wwwroot}/{$file}";
  445. if (!empty($options['includetoken'])) {
  446. $userid = $options['includetoken'] === true ? $USER->id : $options['includetoken'];
  447. $token = get_user_key('core_files', $userid);
  448. $finalfile = basename($file);
  449. $tokenfile = "token{$finalfile}";
  450. $file = substr($file, 0, strlen($file) - strlen($finalfile)) . $tokenfile;
  451. $baseurl = "{$CFG->wwwroot}/{$file}";
  452. if (!$CFG->slasharguments) {
  453. $baseurl .= "?token={$token}&file=";
  454. } else {
  455. $baseurl .= "/{$token}";
  456. }
  457. }
  458. $baseurl .= "/{$contextid}/{$component}/{$filearea}/";
  459. if ($itemid !== null) {
  460. $baseurl .= "$itemid/";
  461. }
  462. if ($options['forcehttps']) {
  463. $baseurl = str_replace('http://', 'https://', $baseurl);
  464. }
  465. if (!empty($options['reverse'])) {
  466. return str_replace($baseurl, '@@PLUGINFILE@@/', $text);
  467. } else {
  468. return str_replace('@@PLUGINFILE@@/', $baseurl, $text);
  469. }
  470. }
  471. /**
  472. * Returns information about files in a draft area.
  473. *
  474. * @global stdClass $CFG
  475. * @global stdClass $USER
  476. * @param int $draftitemid the draft area item id.
  477. * @param string $filepath path to the directory from which the information have to be retrieved.
  478. * @return array with the following entries:
  479. * 'filecount' => number of files in the draft area.
  480. * 'filesize' => total size of the files in the draft area.
  481. * 'foldercount' => number of folders in the draft area.
  482. * 'filesize_without_references' => total size of the area excluding file references.
  483. * (more information will be added as needed).
  484. */
  485. function file_get_draft_area_info($draftitemid, $filepath = '/') {
  486. global $USER;
  487. $usercontext = context_user::instance($USER->id);
  488. return file_get_file_area_info($usercontext->id, 'user', 'draft', $draftitemid, $filepath);
  489. }
  490. /**
  491. * Returns information about files in an area.
  492. *
  493. * @param int $contextid context id
  494. * @param string $component component
  495. * @param string $filearea file area name
  496. * @param int $itemid item id or all files if not specified
  497. * @param string $filepath path to the directory from which the information have to be retrieved.
  498. * @return array with the following entries:
  499. * 'filecount' => number of files in the area.
  500. * 'filesize' => total size of the files in the area.
  501. * 'foldercount' => number of folders in the area.
  502. * 'filesize_without_references' => total size of the area excluding file references.
  503. * @since Moodle 3.4
  504. */
  505. function file_get_file_area_info($contextid, $component, $filearea, $itemid = 0, $filepath = '/') {
  506. $fs = get_file_storage();
  507. $results = array(
  508. 'filecount' => 0,
  509. 'foldercount' => 0,
  510. 'filesize' => 0,
  511. 'filesize_without_references' => 0
  512. );
  513. $draftfiles = $fs->get_directory_files($contextid, $component, $filearea, $itemid, $filepath, true, true);
  514. foreach ($draftfiles as $file) {
  515. if ($file->is_directory()) {
  516. $results['foldercount'] += 1;
  517. } else {
  518. $results['filecount'] += 1;
  519. }
  520. $filesize = $file->get_filesize();
  521. $results['filesize'] += $filesize;
  522. if (!$file->is_external_file()) {
  523. $results['filesize_without_references'] += $filesize;
  524. }
  525. }
  526. return $results;
  527. }
  528. /**
  529. * Returns whether a draft area has exceeded/will exceed its size limit.
  530. *
  531. * Please note that the unlimited value for $areamaxbytes is -1 {@link FILE_AREA_MAX_BYTES_UNLIMITED}, not 0.
  532. *
  533. * @param int $draftitemid the draft area item id.
  534. * @param int $areamaxbytes the maximum size allowed in this draft area.
  535. * @param int $newfilesize the size that would be added to the current area.
  536. * @param bool $includereferences true to include the size of the references in the area size.
  537. * @return bool true if the area will/has exceeded its limit.
  538. * @since Moodle 2.4
  539. */
  540. function file_is_draft_area_limit_reached($draftitemid, $areamaxbytes, $newfilesize = 0, $includereferences = false) {
  541. if ($areamaxbytes != FILE_AREA_MAX_BYTES_UNLIMITED) {
  542. $draftinfo = file_get_draft_area_info($draftitemid);
  543. $areasize = $draftinfo['filesize_without_references'];
  544. if ($includereferences) {
  545. $areasize = $draftinfo['filesize'];
  546. }
  547. if ($areasize + $newfilesize > $areamaxbytes) {
  548. return true;
  549. }
  550. }
  551. return false;
  552. }
  553. /**
  554. * Returns whether a user has reached their draft area upload rate.
  555. *
  556. * @param int $userid The user id
  557. * @return bool
  558. */
  559. function file_is_draft_areas_limit_reached(int $userid): bool {
  560. global $CFG;
  561. $capacity = $CFG->draft_area_bucket_capacity ?? DRAFT_AREA_BUCKET_CAPACITY;
  562. $leak = $CFG->draft_area_bucket_leak ?? DRAFT_AREA_BUCKET_LEAK;
  563. $since = time() - floor($capacity / $leak); // The items that were in the bucket before this time are already leaked by now.
  564. // We are going to be a bit generous to the user when using the leaky bucket
  565. // algorithm below. We are going to assume that the bucket is empty at $since.
  566. // We have to do an assumption here unless we really want to get ALL user's draft
  567. // items without any limit and put all of them in the leaking bucket.
  568. // I decided to favour performance over accuracy here.
  569. $fs = get_file_storage();
  570. $items = $fs->get_user_draft_items($userid, $since);
  571. $items = array_reverse($items); // So that the items are sorted based on time in the ascending direction.
  572. // We only need to store the time that each element in the bucket is going to leak. So $bucket is array of leaking times.
  573. $bucket = [];
  574. foreach ($items as $item) {
  575. $now = $item->timemodified;
  576. // First let's see if items can be dropped from the bucket as a result of leakage.
  577. while (!empty($bucket) && ($now >= $bucket[0])) {
  578. array_shift($bucket);
  579. }
  580. // Calculate the time that the new item we put into the bucket will be leaked from it, and store it into the bucket.
  581. if ($bucket) {
  582. $bucket[] = max($bucket[count($bucket) - 1], $now) + (1 / $leak);
  583. } else {
  584. $bucket[] = $now + (1 / $leak);
  585. }
  586. }
  587. // Recalculate the bucket's content based on the leakage until now.
  588. $now = time();
  589. while (!empty($bucket) && ($now >= $bucket[0])) {
  590. array_shift($bucket);
  591. }
  592. return count($bucket) >= $capacity;
  593. }
  594. /**
  595. * Get used space of files
  596. * @global moodle_database $DB
  597. * @global stdClass $USER
  598. * @return int total bytes
  599. */
  600. function file_get_user_used_space() {
  601. global $DB, $USER;
  602. $usercontext = context_user::instance($USER->id);
  603. $sql = "SELECT SUM(files1.filesize) AS totalbytes FROM {files} files1
  604. JOIN (SELECT contenthash, filename, MAX(id) AS id
  605. FROM {files}
  606. WHERE contextid = ? AND component = ? AND filearea != ?
  607. GROUP BY contenthash, filename) files2 ON files1.id = files2.id";
  608. $params = array('contextid'=>$usercontext->id, 'component'=>'user', 'filearea'=>'draft');
  609. $record = $DB->get_record_sql($sql, $params);
  610. return (int)$record->totalbytes;
  611. }
  612. /**
  613. * Convert any string to a valid filepath
  614. * @todo review this function
  615. * @param string $str
  616. * @return string path
  617. */
  618. function file_correct_filepath($str) { //TODO: what is this? (skodak) - No idea (Fred)
  619. if ($str == '/' or empty($str)) {
  620. return '/';
  621. } else {
  622. return '/'.trim($str, '/').'/';
  623. }
  624. }
  625. /**
  626. * Generate a folder tree of draft area of current USER recursively
  627. *
  628. * @todo MDL-31073 use normal return value instead, this does not fit the rest of api here (skodak)
  629. * @param int $draftitemid
  630. * @param string $filepath
  631. * @param mixed $data
  632. */
  633. function file_get_drafarea_folders($draftitemid, $filepath, &$data) {
  634. global $USER, $OUTPUT, $CFG;
  635. $data->children = array();
  636. $context = context_user::instance($USER->id);
  637. $fs = get_file_storage();
  638. if ($files = $fs->get_directory_files($context->id, 'user', 'draft', $draftitemid, $filepath, false)) {
  639. foreach ($files as $file) {
  640. if ($file->is_directory()) {
  641. $item = new stdClass();
  642. $item->sortorder = $file->get_sortorder();
  643. $item->filepath = $file->get_filepath();
  644. $foldername = explode('/', trim($item->filepath, '/'));
  645. $item->fullname = trim(array_pop($foldername), '/');
  646. $item->id = uniqid();
  647. file_get_drafarea_folders($draftitemid, $item->filepath, $item);
  648. $data->children[] = $item;
  649. } else {
  650. continue;
  651. }
  652. }
  653. }
  654. }
  655. /**
  656. * Listing all files (including folders) in current path (draft area)
  657. * used by file manager
  658. * @param int $draftitemid
  659. * @param string $filepath
  660. * @return stdClass
  661. */
  662. function file_get_drafarea_files($draftitemid, $filepath = '/') {
  663. global $USER, $OUTPUT, $CFG;
  664. $context = context_user::instance($USER->id);
  665. $fs = get_file_storage();
  666. $data = new stdClass();
  667. $data->path = array();
  668. $data->path[] = array('name'=>get_string('files'), 'path'=>'/');
  669. // will be used to build breadcrumb
  670. $trail = '/';
  671. if ($filepath !== '/') {
  672. $filepath = file_correct_filepath($filepath);
  673. $parts = explode('/', $filepath);
  674. foreach ($parts as $part) {
  675. if ($part != '' && $part != null) {
  676. $trail .= ($part.'/');
  677. $data->path[] = array('name'=>$part, 'path'=>$trail);
  678. }
  679. }
  680. }
  681. $list = array();
  682. $maxlength = 12;
  683. if ($files = $fs->get_directory_files($context->id, 'user', 'draft', $draftitemid, $filepath, false)) {
  684. foreach ($files as $file) {
  685. $item = new stdClass();
  686. $item->filename = $file->get_filename();
  687. $item->filepath = $file->get_filepath();
  688. $item->fullname = trim($item->filename, '/');
  689. $filesize = $file->get_filesize();
  690. $item->size = $filesize ? $filesize : null;
  691. $item->filesize = $filesize ? display_size($filesize) : '';
  692. $item->sortorder = $file->get_sortorder();
  693. $item->author = $file->get_author();
  694. $item->license = $file->get_license();
  695. $item->datemodified = $file->get_timemodified();
  696. $item->datecreated = $file->get_timecreated();
  697. $item->isref = $file->is_external_file();
  698. if ($item->isref && $file->get_status() == 666) {
  699. $item->originalmissing = true;
  700. }
  701. // find the file this draft file was created from and count all references in local
  702. // system pointing to that file
  703. $source = @unserialize($file->get_source());
  704. if (isset($source->original)) {
  705. $item->refcount = $fs->search_references_count($source->original);
  706. }
  707. if ($file->is_directory()) {
  708. $item->filesize = 0;
  709. $item->icon = $OUTPUT->image_url(file_folder_icon(24))->out(false);
  710. $item->type = 'folder';
  711. $foldername = explode('/', trim($item->filepath, '/'));
  712. $item->fullname = trim(array_pop($foldername), '/');
  713. $item->thumbnail = $OUTPUT->image_url(file_folder_icon(90))->out(false);
  714. } else {
  715. // do NOT use file browser here!
  716. $item->mimetype = get_mimetype_description($file);
  717. if (file_extension_in_typegroup($file->get_filename(), 'archive')) {
  718. $item->type = 'zip';
  719. } else {
  720. $item->type = 'file';
  721. }
  722. $itemurl = moodle_url::make_draftfile_url($draftitemid, $item->filepath, $item->filename);
  723. $item->url = $itemurl->out();
  724. $item->icon = $OUTPUT->image_url(file_file_icon($file, 24))->out(false);
  725. $item->thumbnail = $OUTPUT->image_url(file_file_icon($file, 90))->out(false);
  726. // The call to $file->get_imageinfo() fails with an exception if the file can't be read on the file system.
  727. // We still want to add such files to the list, so the owner can view and delete them if needed. So, we only call
  728. // get_imageinfo() on files that can be read, and we also spoof the file status based on whether it was found.
  729. // We'll use the same status types used by stored_file->get_status(), where 0 = OK. 1 = problem, as these will be
  730. // used by the widget to display a warning about the problem files.
  731. // The value of stored_file->get_status(), and the file record are unaffected by this. It's only superficially set.
  732. $item->status = $fs->get_file_system()->is_file_readable_remotely_by_storedfile($file) ? 0 : 1;
  733. if ($item->status == 0) {
  734. if ($imageinfo = $file->get_imageinfo()) {
  735. $item->realthumbnail = $itemurl->out(false, array('preview' => 'thumb',
  736. 'oid' => $file->get_timemodified()));
  737. $item->realicon = $itemurl->out(false, array('preview' => 'tinyicon', 'oid' => $file->get_timemodified()));
  738. $item->image_width = $imageinfo['width'];
  739. $item->image_height = $imageinfo['height'];
  740. }
  741. }
  742. }
  743. $list[] = $item;
  744. }
  745. }
  746. $data->itemid = $draftitemid;
  747. $data->list = $list;
  748. return $data;
  749. }
  750. /**
  751. * Returns all of the files in the draftarea.
  752. *
  753. * @param int $draftitemid The draft item ID
  754. * @param string $filepath path for the uploaded files.
  755. * @return array An array of files associated with this draft item id.
  756. */
  757. function file_get_all_files_in_draftarea(int $draftitemid, string $filepath = '/') : array {
  758. $files = [];
  759. $draftfiles = file_get_drafarea_files($draftitemid, $filepath);
  760. file_get_drafarea_folders($draftitemid, $filepath, $draftfiles);
  761. if (!empty($draftfiles)) {
  762. foreach ($draftfiles->list as $draftfile) {
  763. if ($draftfile->type == 'file') {
  764. $files[] = $draftfile;
  765. }
  766. }
  767. if (isset($draftfiles->children)) {
  768. foreach ($draftfiles->children as $draftfile) {
  769. $files = array_merge($files, file_get_all_files_in_draftarea($draftitemid, $draftfile->filepath));
  770. }
  771. }
  772. }
  773. return $files;
  774. }
  775. /**
  776. * Returns draft area itemid for a given element.
  777. *
  778. * @category files
  779. * @param string $elname name of formlib editor element, or a hidden form field that stores the draft area item id, etc.
  780. * @return int the itemid, or 0 if there is not one yet.
  781. */
  782. function file_get_submitted_draft_itemid($elname) {
  783. // this is a nasty hack, ideally all new elements should use arrays here or there should be a new parameter
  784. if (!isset($_REQUEST[$elname])) {
  785. return 0;
  786. }
  787. if (is_array($_REQUEST[$elname])) {
  788. $param = optional_param_array($elname, 0, PARAM_INT);
  789. if (!empty($param['itemid'])) {
  790. $param = $param['itemid'];
  791. } else {
  792. debugging('Missing itemid, maybe caused by unset maxfiles option', DEBUG_DEVELOPER);
  793. return false;
  794. }
  795. } else {
  796. $param = optional_param($elname, 0, PARAM_INT);
  797. }
  798. if ($param) {
  799. require_sesskey();
  800. }
  801. return $param;
  802. }
  803. /**
  804. * Restore the original source field from draft files
  805. *
  806. * Do not use this function because it makes field files.source inconsistent
  807. * for draft area files. This function will be deprecated in 2.6
  808. *
  809. * @param stored_file $storedfile This only works with draft files
  810. * @return stored_file
  811. */
  812. function file_restore_source_field_from_draft_file($storedfile) {
  813. $source = @unserialize($storedfile->get_source());
  814. if (!empty($source)) {
  815. if (is_object($source)) {
  816. $restoredsource = $source->source;
  817. $storedfile->set_source($restoredsource);
  818. } else {
  819. throw new moodle_exception('invalidsourcefield', 'error');
  820. }
  821. }
  822. return $storedfile;
  823. }
  824. /**
  825. * Removes those files from the user drafts filearea which are not referenced in the editor text.
  826. *
  827. * @param stdClass $editor The online text editor element from the submitted form data.
  828. */
  829. function file_remove_editor_orphaned_files($editor) {
  830. global $CFG, $USER;
  831. // Find those draft files included in the text, and generate their hashes.
  832. $context = context_user::instance($USER->id);
  833. $baseurl = $CFG->wwwroot . '/draftfile.php/' . $context->id . '/user/draft/' . $editor['itemid'] . '/';
  834. $pattern = "/" . preg_quote($baseurl, '/') . "(.+?)[\?\"']/";
  835. preg_match_all($pattern, $editor['text'], $matches);
  836. $usedfilehashes = [];
  837. foreach ($matches[1] as $matchedfilename) {
  838. $matchedfilename = urldecode($matchedfilename);
  839. $usedfilehashes[] = \file_storage::get_pathname_hash($context->id, 'user', 'draft', $editor['itemid'], '/',
  840. $matchedfilename);
  841. }
  842. // Now, compare the hashes of all draft files, and remove those which don't match used files.
  843. $fs = get_file_storage();
  844. $files = $fs->get_area_files($context->id, 'user', 'draft', $editor['itemid'], 'id', false);
  845. foreach ($files as $file) {
  846. $tmphash = $file->get_pathnamehash();
  847. if (!in_array($tmphash, $usedfilehashes)) {
  848. $file->delete();
  849. }
  850. }
  851. }
  852. /**
  853. * Finds all draft areas used in a textarea and copies the files into the primary textarea. If a user copies and pastes
  854. * content from another draft area it's possible for a single textarea to reference multiple draft areas.
  855. *
  856. * @category files
  857. * @param int $draftitemid the id of the primary draft area.
  858. * When set to -1 (probably, by a WebService) it won't process file merging, keeping the original state of the file area.
  859. * @param int $usercontextid the user's context id.
  860. * @param string $text some html content that needs to have files copied to the correct draft area.
  861. * @param bool $forcehttps force https urls.
  862. *
  863. * @return string $text html content modified with new draft links
  864. */
  865. function file_merge_draft_areas($draftitemid, $usercontextid, $text, $forcehttps = false) {
  866. if (is_null($text)) {
  867. return null;
  868. }
  869. // Do not merge files, leave it as it was.
  870. if ($draftitemid === IGNORE_FILE_MERGE) {
  871. return null;
  872. }
  873. $urls = extract_draft_file_urls_from_text($text, $forcehttps, $usercontextid, 'user', 'draft');
  874. // No draft areas to rewrite.
  875. if (empty($urls)) {
  876. return $text;
  877. }
  878. foreach ($urls as $url) {
  879. // Do not process the "home" draft area.
  880. if ($url['itemid'] == $draftitemid) {
  881. continue;
  882. }
  883. // Decode the filename.
  884. $filename = urldecode($url['filename']);
  885. // Copy the file.
  886. file_copy_file_to_file_area($url, $filename, $draftitemid);
  887. // Rewrite draft area.
  888. $text = file_replace_file_area_in_text($url, $draftitemid, $text, $forcehttps);
  889. }
  890. return $text;
  891. }
  892. /**
  893. * Rewrites a file area in arbitrary text.
  894. *
  895. * @param array $file General information about the file.
  896. * @param int $newid The new file area itemid.
  897. * @param string $text The text to rewrite.
  898. * @param bool $forcehttps force https urls.
  899. * @return string The rewritten text.
  900. */
  901. function file_replace_file_area_in_text($file, $newid, $text, $forcehttps = false) {
  902. global $CFG;
  903. $wwwroot = $CFG->wwwroot;
  904. if ($forcehttps) {
  905. $wwwroot = str_replace('http://', 'https://', $wwwroot);
  906. }
  907. $search = [
  908. $wwwroot,
  909. $file['urlbase'],
  910. $file['contextid'],
  911. $file['component'],
  912. $file['filearea'],
  913. $file['itemid'],
  914. $file['filename']
  915. ];
  916. $replace = [
  917. $wwwroot,
  918. $file['urlbase'],
  919. $file['contextid'],
  920. $file['component'],
  921. $file['filearea'],
  922. $newid,
  923. $file['filename']
  924. ];
  925. $text = str_ireplace( implode('/', $search), implode('/', $replace), $text);
  926. return $text;
  927. }
  928. /**
  929. * Copies a file from one file area to another.
  930. *
  931. * @param array $file Information about the file to be copied.
  932. * @param string $filename The filename.
  933. * @param int $itemid The new file area.
  934. */
  935. function file_copy_file_to_file_area($file, $filename, $itemid) {
  936. $fs = get_file_storage();
  937. // Load the current file in the old draft area.
  938. $fileinfo = array(
  939. 'component' => $file['component'],
  940. 'filearea' => $file['filearea'],
  941. 'itemid' => $file['itemid'],
  942. 'contextid' => $file['contextid'],
  943. 'filepath' => '/',
  944. 'filename' => $filename
  945. );
  946. $oldfile = $fs->get_file($fileinfo['contextid'], $fileinfo['component'], $fileinfo['filearea'],
  947. $fileinfo['itemid'], $fileinfo['filepath'], $fileinfo['filename']);
  948. $newfileinfo = array(
  949. 'component' => $file['component'],
  950. 'filearea' => $file['filearea'],
  951. 'itemid' => $itemid,
  952. 'contextid' => $file['contextid'],
  953. 'filepath' => '/',
  954. 'filename' => $filename
  955. );
  956. $newcontextid = $newfileinfo['contextid'];
  957. $newcomponent = $newfileinfo['component'];
  958. $newfilearea = $newfileinfo['filearea'];
  959. $newitemid = $newfileinfo['itemid'];
  960. $newfilepath = $newfileinfo['filepath'];
  961. $newfilename = $newfileinfo['filename'];
  962. // Check if the file exists.
  963. if (!$fs->file_exists($newcontextid, $newcomponent, $newfilearea, $newitemid, $newfilepath, $newfilename)) {
  964. $fs->create_file_from_storedfile($newfileinfo, $oldfile);
  965. }
  966. }
  967. /**
  968. * Saves files from a draft file area to a real one (merging the list of files).
  969. * Can rewrite URLs in some content at the same time if desired.
  970. *
  971. * @category files
  972. * @global stdClass $USER
  973. * @param int $draftitemid the id of the draft area to use. Normally obtained
  974. * from file_get_submitted_draft_itemid('elementname') or similar.
  975. * When set to -1 (probably, by a WebService) it won't process file merging, keeping the original state of the file area.
  976. * @param int $contextid This parameter and the next two identify the file area to save to.
  977. * @param string $component
  978. * @param string $filearea indentifies the file area.
  979. * @param int $itemid helps identifies the file area.
  980. * @param array $options area options (subdirs=>false, maxfiles=-1, maxbytes=0)
  981. * @param string $text some html content that needs to have embedded links rewritten
  982. * to the @@PLUGINFILE@@ form for saving in the database.
  983. * @param bool $forcehttps force https urls.
  984. * @return string|null if $text was passed in, the rewritten $text is returned. Otherwise NULL.
  985. */
  986. function file_save_draft_area_files($draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null, $forcehttps=false) {
  987. global $USER;
  988. // Do not merge files, leave it as it was.
  989. if ($draftitemid === IGNORE_FILE_MERGE) {
  990. // Safely return $text, no need to rewrite pluginfile because this is mostly comming from an external client like the app.
  991. return $text;
  992. }
  993. if ($itemid === false) {
  994. // Catch a potentially dangerous coding error.
  995. throw new coding_exception('file_save_draft_area_files was called with $itemid false. ' .
  996. "This suggests a bug, because it would wipe all ($contextid, $component, $filearea) files.");
  997. }
  998. $usercontext = context_user::instance($USER->id);
  999. $fs = get_file_storage();
  1000. $options = (array)$options;
  1001. if (!isset($options['subdirs'])) {
  1002. $options['subdirs'] = false;
  1003. }
  1004. if (!isset($options['maxfiles'])) {
  1005. $options['maxfiles'] = -1; // unlimited
  1006. }
  1007. if (!isset($options['maxbytes']) || $options['maxbytes'] == USER_CAN_IGNORE_FILE_SIZE_LIMITS) {
  1008. $options['maxbytes'] = 0; // unlimited
  1009. }
  1010. if (!isset($options['areamaxbytes'])) {
  1011. $options['areamaxbytes'] = FILE_AREA_MAX_BYTES_UNLIMITED; // Unlimited.
  1012. }
  1013. $allowreferences = true;
  1014. if (isset($options['return_types']) && !($options['return_types'] & (FILE_REFERENCE | FILE_CONTROLLED_LINK))) {
  1015. // we assume that if $options['return_types'] is NOT specified, we DO allow references.
  1016. // this is not exactly right. BUT there are many places in code where filemanager options
  1017. // are not passed to file_save_draft_area_files()
  1018. $allowreferences = false;
  1019. }
  1020. // Check if the user has copy-pasted from other draft areas. Those files will be located in different draft
  1021. // areas and need to be copied into the current draft area.
  1022. $text = file_merge_draft_areas($draftitemid, $usercontext->id, $text, $forcehttps);
  1023. // Check if the draft area has exceeded the authorised limit. This should never happen as validation
  1024. // should have taken place before, unless the user is doing something nauthly. If so, let's just not save
  1025. // anything at all in the next area.
  1026. if (file_is_draft_area_limit_reached($draftitemid, $options['areamaxbytes'])) {
  1027. return null;
  1028. }
  1029. $draftfiles = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftitemid, 'id');
  1030. $oldfiles = $fs->get_area_files($contextid, $component, $filearea, $itemid, 'id');
  1031. // One file in filearea means it is empty (it has only top-level directory '.').
  1032. if (count($draftfiles) > 1 || count($oldfiles) > 1) {
  1033. // we have to merge old and new files - we want to keep file ids for files that were not changed
  1034. // we change time modified for all new and changed files, we keep time created as is
  1035. $newhashes = array();
  1036. $filecount = 0;
  1037. $context = context::instance_by_id($contextid, MUST_EXIST);
  1038. foreach ($draftfiles as $file) {
  1039. if (!$options['subdirs'] && $file->get_filepath() !== '/') {
  1040. continue;
  1041. }
  1042. if (!$allowreferences && $file->is_external_file()) {
  1043. continue;
  1044. }
  1045. if (!$file->is_directory()) {
  1046. // Check to see if this file was uploaded by someone who can ignore the file size limits.
  1047. $fileusermaxbytes = get_user_max_upload_file_size($context, $options['maxbytes'], 0, 0, $file->get_userid());
  1048. if ($fileusermaxbytes != USER_CAN_IGNORE_FILE_SIZE_LIMITS
  1049. && ($options['maxbytes'] and $options['maxbytes'] < $file->get_filesize())) {
  1050. // Oversized file.
  1051. continue;
  1052. }
  1053. if ($options['maxfiles'] != -1 and $options['maxfiles'] <= $filecount) {
  1054. // more files - should not get here at all
  1055. continue;
  1056. }
  1057. $filecount++;
  1058. }
  1059. $newhash = $fs->get_pathname_hash($contextid, $component, $filearea, $itemid, $file->get_filepath(), $file->get_filename());
  1060. $newhashes[$newhash] = $file;
  1061. }
  1062. // Loop through oldfiles and decide which we need to delete and which to update.
  1063. // After this cycle the array $newhashes will only contain the files that need to be added.
  1064. foreach ($oldfiles as $oldfile) {
  1065. $oldhash = $oldfile->get_pathnamehash();
  1066. if (!isset($newhashes[$oldhash])) {
  1067. // delete files not needed any more - deleted by user
  1068. $oldfile->delete();
  1069. continue;
  1070. }
  1071. $newfile = $newhashes[$oldhash];
  1072. // Now we know that we have $oldfile and $newfile for the same path.
  1073. // Let's check if we can update this file or we need to delete and create.
  1074. if ($newfile->is_directory()) {
  1075. // Directories are always ok to just update.
  1076. } else if (($source = @unserialize($newfile->get_source())) && isset($source->original)) {
  1077. // File has the 'original' - we need to update the file (it may even have not been changed at all).
  1078. $original = file_storage::unpack_reference($source->original);
  1079. if ($original['filename'] !== $oldfile->get_filename() || $original['filepath'] !== $oldfile->get_filepath()) {
  1080. // Very odd, original points to another file. Delete and create file.
  1081. $oldfile->delete();
  1082. continue;
  1083. }
  1084. } else {
  1085. // The same file name but absence of 'original' means that file was deteled and uploaded again.
  1086. // By deleting and creating new file we properly manage all existing references.
  1087. $oldfile->delete();
  1088. continue;
  1089. }
  1090. // status changed, we delete old file, and create a new one
  1091. if ($oldfile->get_status() != $newfile->get_status()) {
  1092. // file was changed, use updated with new timemodified data
  1093. $oldfile->delete();
  1094. // This file will be added later
  1095. continue;
  1096. }
  1097. // Updated author
  1098. if ($oldfile->get_author() != $newfile->get_author()) {
  1099. $oldfile->set_author($newfile->get_author());
  1100. }
  1101. // Updated license
  1102. if ($oldfile->get_license() != $newfile->get_license()) {
  1103. $oldfile->set_license($newfile->get_license());
  1104. }
  1105. // Updated file source
  1106. // Field files.source for draftarea files contains serialised object with source and original information.
  1107. // We only store the source part of it for non-draft file area.
  1108. $newsource = $newfile->get_source();
  1109. if ($source = @unserialize($newfile->get_source())) {
  1110. $newsource = $source->source;
  1111. }
  1112. if ($oldfile->get_source() !== $newsource) {
  1113. $oldfile->set_source($newsource);
  1114. }
  1115. // Updated sort order
  1116. if ($oldfile->get_sortorder() != $newfile->get_sortorder()) {
  1117. $oldfile->set_sortorder($newfile->get_sortorder());
  1118. }
  1119. // Update file timemodified
  1120. if ($oldfile->get_

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