PageRenderTime 60ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/lib/filelib.php

https://github.com/nfreear/moodle
PHP | 3096 lines | 1979 code | 274 blank | 843 comment | 450 complexity | 2f1d16160006e497f69909fd98b6c9c5 MD5 | raw file
Possible License(s): GPL-3.0, LGPL-2.1, BSD-3-Clause
  1. <?php
  2. // This file is part of Moodle - http://moodle.org/
  3. //
  4. // Moodle is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // Moodle is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU General Public License
  15. // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
  16. /**
  17. * Functions for file handling.
  18. *
  19. * @package core
  20. * @subpackage file
  21. * @copyright 1999 onwards Martin Dougiamas (http://dougiamas.com)
  22. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  23. */
  24. defined('MOODLE_INTERNAL') || die();
  25. /** @var string unique string constant. */
  26. define('BYTESERVING_BOUNDARY', 's1k2o3d4a5k6s7');
  27. require_once("$CFG->libdir/filestorage/file_exceptions.php");
  28. require_once("$CFG->libdir/filestorage/file_storage.php");
  29. require_once("$CFG->libdir/filestorage/zip_packer.php");
  30. require_once("$CFG->libdir/filebrowser/file_browser.php");
  31. /**
  32. * Encodes file serving url
  33. *
  34. * @deprecated use moodle_url factory methods instead
  35. *
  36. * @global object
  37. * @param string $urlbase
  38. * @param string $path /filearea/itemid/dir/dir/file.exe
  39. * @param bool $forcedownload
  40. * @param bool $https https url required
  41. * @return string encoded file url
  42. */
  43. function file_encode_url($urlbase, $path, $forcedownload=false, $https=false) {
  44. global $CFG;
  45. //TODO: deprecate this
  46. if ($CFG->slasharguments) {
  47. $parts = explode('/', $path);
  48. $parts = array_map('rawurlencode', $parts);
  49. $path = implode('/', $parts);
  50. $return = $urlbase.$path;
  51. if ($forcedownload) {
  52. $return .= '?forcedownload=1';
  53. }
  54. } else {
  55. $path = rawurlencode($path);
  56. $return = $urlbase.'?file='.$path;
  57. if ($forcedownload) {
  58. $return .= '&amp;forcedownload=1';
  59. }
  60. }
  61. if ($https) {
  62. $return = str_replace('http://', 'https://', $return);
  63. }
  64. return $return;
  65. }
  66. /**
  67. * Prepares 'editor' formslib element from data in database
  68. *
  69. * The passed $data record must contain field foobar, foobarformat and optionally foobartrust. This
  70. * function then copies the embedded files into draft area (assigning itemids automatically),
  71. * creates the form element foobar_editor and rewrites the URLs so the embedded images can be
  72. * displayed.
  73. * In your mform definition, you must have an 'editor' element called foobar_editor. Then you call
  74. * your mform's set_data() supplying the object returned by this function.
  75. *
  76. * @param object $data database field that holds the html text with embedded media
  77. * @param string $field the name of the database field that holds the html text with embedded media
  78. * @param array $options editor options (like maxifiles, maxbytes etc.)
  79. * @param object $context context of the editor
  80. * @param string $component
  81. * @param string $filearea file area name
  82. * @param int $itemid item id, required if item exists
  83. * @return object modified data object
  84. */
  85. function file_prepare_standard_editor($data, $field, array $options, $context=null, $component=null, $filearea=null, $itemid=null) {
  86. $options = (array)$options;
  87. if (!isset($options['trusttext'])) {
  88. $options['trusttext'] = false;
  89. }
  90. if (!isset($options['forcehttps'])) {
  91. $options['forcehttps'] = false;
  92. }
  93. if (!isset($options['subdirs'])) {
  94. $options['subdirs'] = false;
  95. }
  96. if (!isset($options['maxfiles'])) {
  97. $options['maxfiles'] = 0; // no files by default
  98. }
  99. if (!isset($options['noclean'])) {
  100. $options['noclean'] = false;
  101. }
  102. if (is_null($itemid) or is_null($context)) {
  103. $contextid = null;
  104. $itemid = null;
  105. if (!isset($data->{$field})) {
  106. $data->{$field} = '';
  107. }
  108. if (!isset($data->{$field.'format'})) {
  109. $data->{$field.'format'} = editors_get_preferred_format();
  110. }
  111. if (!$options['noclean']) {
  112. $data->{$field} = clean_text($data->{$field}, $data->{$field.'format'});
  113. }
  114. } else {
  115. if ($options['trusttext']) {
  116. // noclean ignored if trusttext enabled
  117. if (!isset($data->{$field.'trust'})) {
  118. $data->{$field.'trust'} = 0;
  119. }
  120. $data = trusttext_pre_edit($data, $field, $context);
  121. } else {
  122. if (!$options['noclean']) {
  123. $data->{$field} = clean_text($data->{$field}, $data->{$field.'format'});
  124. }
  125. }
  126. $contextid = $context->id;
  127. }
  128. if ($options['maxfiles'] != 0) {
  129. $draftid_editor = file_get_submitted_draft_itemid($field);
  130. $currenttext = file_prepare_draft_area($draftid_editor, $contextid, $component, $filearea, $itemid, $options, $data->{$field});
  131. $data->{$field.'_editor'} = array('text'=>$currenttext, 'format'=>$data->{$field.'format'}, 'itemid'=>$draftid_editor);
  132. } else {
  133. $data->{$field.'_editor'} = array('text'=>$data->{$field}, 'format'=>$data->{$field.'format'}, 'itemid'=>0);
  134. }
  135. return $data;
  136. }
  137. /**
  138. * Prepares the content of the 'editor' form element with embedded media files to be saved in database
  139. *
  140. * This function moves files from draft area to the destination area and
  141. * encodes URLs to the draft files so they can be safely saved into DB. The
  142. * form has to contain the 'editor' element named foobar_editor, where 'foobar'
  143. * is the name of the database field to hold the wysiwyg editor content. The
  144. * editor data comes as an array with text, format and itemid properties. This
  145. * function automatically adds $data properties foobar, foobarformat and
  146. * foobartrust, where foobar has URL to embedded files encoded.
  147. *
  148. * @param object $data raw data submitted by the form
  149. * @param string $field name of the database field containing the html with embedded media files
  150. * @param array $options editor options (trusttext, subdirs, maxfiles, maxbytes etc.)
  151. * @param object $context context, required for existing data
  152. * @param string component
  153. * @param string $filearea file area name
  154. * @param int $itemid item id, required if item exists
  155. * @return object modified data object
  156. */
  157. function file_postupdate_standard_editor($data, $field, array $options, $context, $component=null, $filearea=null, $itemid=null) {
  158. $options = (array)$options;
  159. if (!isset($options['trusttext'])) {
  160. $options['trusttext'] = false;
  161. }
  162. if (!isset($options['forcehttps'])) {
  163. $options['forcehttps'] = false;
  164. }
  165. if (!isset($options['subdirs'])) {
  166. $options['subdirs'] = false;
  167. }
  168. if (!isset($options['maxfiles'])) {
  169. $options['maxfiles'] = 0; // no files by default
  170. }
  171. if (!isset($options['maxbytes'])) {
  172. $options['maxbytes'] = 0; // unlimited
  173. }
  174. if ($options['trusttext']) {
  175. $data->{$field.'trust'} = trusttext_trusted($context);
  176. } else {
  177. $data->{$field.'trust'} = 0;
  178. }
  179. $editor = $data->{$field.'_editor'};
  180. if ($options['maxfiles'] == 0 or is_null($filearea) or is_null($itemid) or empty($editor['itemid'])) {
  181. $data->{$field} = $editor['text'];
  182. } else {
  183. $data->{$field} = file_save_draft_area_files($editor['itemid'], $context->id, $component, $filearea, $itemid, $options, $editor['text'], $options['forcehttps']);
  184. }
  185. $data->{$field.'format'} = $editor['format'];
  186. return $data;
  187. }
  188. /**
  189. * Saves text and files modified by Editor formslib element
  190. *
  191. * @param object $data $database entry field
  192. * @param string $field name of data field
  193. * @param array $options various options
  194. * @param object $context context - must already exist
  195. * @param string $component
  196. * @param string $filearea file area name
  197. * @param int $itemid must already exist, usually means data is in db
  198. * @return object modified data obejct
  199. */
  200. function file_prepare_standard_filemanager($data, $field, array $options, $context=null, $component=null, $filearea=null, $itemid=null) {
  201. $options = (array)$options;
  202. if (!isset($options['subdirs'])) {
  203. $options['subdirs'] = false;
  204. }
  205. if (is_null($itemid) or is_null($context)) {
  206. $itemid = null;
  207. $contextid = null;
  208. } else {
  209. $contextid = $context->id;
  210. }
  211. $draftid_editor = file_get_submitted_draft_itemid($field.'_filemanager');
  212. file_prepare_draft_area($draftid_editor, $contextid, $component, $filearea, $itemid, $options);
  213. $data->{$field.'_filemanager'} = $draftid_editor;
  214. return $data;
  215. }
  216. /**
  217. * Saves files modified by File manager formslib element
  218. *
  219. * @param object $data $database entry field
  220. * @param string $field name of data field
  221. * @param array $options various options
  222. * @param object $context context - must already exist
  223. * @param string $component
  224. * @param string $filearea file area name
  225. * @param int $itemid must already exist, usually means data is in db
  226. * @return object modified data obejct
  227. */
  228. function file_postupdate_standard_filemanager($data, $field, array $options, $context, $component, $filearea, $itemid) {
  229. $options = (array)$options;
  230. if (!isset($options['subdirs'])) {
  231. $options['subdirs'] = false;
  232. }
  233. if (!isset($options['maxfiles'])) {
  234. $options['maxfiles'] = -1; // unlimited
  235. }
  236. if (!isset($options['maxbytes'])) {
  237. $options['maxbytes'] = 0; // unlimited
  238. }
  239. if (empty($data->{$field.'_filemanager'})) {
  240. $data->$field = '';
  241. } else {
  242. file_save_draft_area_files($data->{$field.'_filemanager'}, $context->id, $component, $filearea, $itemid, $options);
  243. $fs = get_file_storage();
  244. if ($fs->get_area_files($context->id, $component, $filearea, $itemid)) {
  245. $data->$field = '1'; // TODO: this is an ugly hack (skodak)
  246. } else {
  247. $data->$field = '';
  248. }
  249. }
  250. return $data;
  251. }
  252. /**
  253. *
  254. * @global object
  255. * @global object
  256. * @return int a random but available draft itemid that can be used to create a new draft
  257. * file area.
  258. */
  259. function file_get_unused_draft_itemid() {
  260. global $DB, $USER;
  261. if (isguestuser() or !isloggedin()) {
  262. // guests and not-logged-in users can not be allowed to upload anything!!!!!!
  263. print_error('noguest');
  264. }
  265. $contextid = get_context_instance(CONTEXT_USER, $USER->id)->id;
  266. $fs = get_file_storage();
  267. $draftitemid = rand(1, 999999999);
  268. while ($files = $fs->get_area_files($contextid, 'user', 'draft', $draftitemid)) {
  269. $draftitemid = rand(1, 999999999);
  270. }
  271. return $draftitemid;
  272. }
  273. /**
  274. * Initialise a draft file area from a real one by copying the files. A draft
  275. * area will be created if one does not already exist. Normally you should
  276. * get $draftitemid by calling file_get_submitted_draft_itemid('elementname');
  277. *
  278. * @global object
  279. * @global object
  280. * @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.
  281. * @param integer $contextid This parameter and the next two identify the file area to copy files from.
  282. * @param string $component
  283. * @param string $filearea helps indentify the file area.
  284. * @param integer $itemid helps identify the file area. Can be null if there are no files yet.
  285. * @param array $options text and file options ('subdirs'=>false, 'forcehttps'=>false)
  286. * @param string $text some html content that needs to have embedded links rewritten to point to the draft area.
  287. * @return string if $text was passed in, the rewritten $text is returned. Otherwise NULL.
  288. */
  289. function file_prepare_draft_area(&$draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null) {
  290. global $CFG, $USER, $CFG;
  291. $options = (array)$options;
  292. if (!isset($options['subdirs'])) {
  293. $options['subdirs'] = false;
  294. }
  295. if (!isset($options['forcehttps'])) {
  296. $options['forcehttps'] = false;
  297. }
  298. $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
  299. $fs = get_file_storage();
  300. if (empty($draftitemid)) {
  301. // create a new area and copy existing files into
  302. $draftitemid = file_get_unused_draft_itemid();
  303. $file_record = array('contextid'=>$usercontext->id, 'component'=>'user', 'filearea'=>'draft', 'itemid'=>$draftitemid);
  304. if (!is_null($itemid) and $files = $fs->get_area_files($contextid, $component, $filearea, $itemid)) {
  305. foreach ($files as $file) {
  306. if ($file->is_directory() and $file->get_filepath() === '/') {
  307. // we need a way to mark the age of each draft area,
  308. // by not copying the root dir we force it to be created automatically with current timestamp
  309. continue;
  310. }
  311. if (!$options['subdirs'] and ($file->is_directory() or $file->get_filepath() !== '/')) {
  312. continue;
  313. }
  314. $fs->create_file_from_storedfile($file_record, $file);
  315. }
  316. }
  317. if (!is_null($text)) {
  318. // at this point there should not be any draftfile links yet,
  319. // because this is a new text from database that should still contain the @@pluginfile@@ links
  320. // this happens when developers forget to post process the text
  321. $text = str_replace("\"$CFG->httpswwwroot/draftfile.php", "\"$CFG->httpswwwroot/brokenfile.php#", $text);
  322. }
  323. } else {
  324. // nothing to do
  325. }
  326. if (is_null($text)) {
  327. return null;
  328. }
  329. // relink embedded files - editor can not handle @@PLUGINFILE@@ !
  330. return file_rewrite_pluginfile_urls($text, 'draftfile.php', $usercontext->id, 'user', 'draft', $draftitemid, $options);
  331. }
  332. /**
  333. * Convert encoded URLs in $text from the @@PLUGINFILE@@/... form to an actual URL.
  334. *
  335. * @global object
  336. * @param string $text The content that may contain ULRs in need of rewriting.
  337. * @param string $file The script that should be used to serve these files. pluginfile.php, draftfile.php, etc.
  338. * @param integer $contextid This parameter and the next two identify the file area to use.
  339. * @param string $component
  340. * @param string $filearea helps identify the file area.
  341. * @param integer $itemid helps identify the file area.
  342. * @param array $options text and file options ('forcehttps'=>false)
  343. * @return string the processed text.
  344. */
  345. function file_rewrite_pluginfile_urls($text, $file, $contextid, $component, $filearea, $itemid, array $options=null) {
  346. global $CFG;
  347. $options = (array)$options;
  348. if (!isset($options['forcehttps'])) {
  349. $options['forcehttps'] = false;
  350. }
  351. if (!$CFG->slasharguments) {
  352. $file = $file . '?file=';
  353. }
  354. $baseurl = "$CFG->wwwroot/$file/$contextid/$component/$filearea/";
  355. if ($itemid !== null) {
  356. $baseurl .= "$itemid/";
  357. }
  358. if ($options['forcehttps']) {
  359. $baseurl = str_replace('http://', 'https://', $baseurl);
  360. }
  361. return str_replace('@@PLUGINFILE@@/', $baseurl, $text);
  362. }
  363. /**
  364. * Returns information about files in a draft area.
  365. *
  366. * @global object
  367. * @global object
  368. * @param integer $draftitemid the draft area item id.
  369. * @return array with the following entries:
  370. * 'filecount' => number of files in the draft area.
  371. * (more information will be added as needed).
  372. */
  373. function file_get_draft_area_info($draftitemid) {
  374. global $CFG, $USER;
  375. $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
  376. $fs = get_file_storage();
  377. $results = array();
  378. // The number of files
  379. $draftfiles = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftitemid, 'id', false);
  380. $results['filecount'] = count($draftfiles);
  381. $results['filesize'] = 0;
  382. foreach ($draftfiles as $file) {
  383. $results['filesize'] += $file->get_filesize();
  384. }
  385. return $results;
  386. }
  387. /**
  388. * Get used space of files
  389. * @return int total bytes
  390. */
  391. function file_get_user_used_space() {
  392. global $DB, $USER;
  393. $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
  394. $sql = "SELECT SUM(files1.filesize) AS totalbytes FROM {files} files1
  395. JOIN (SELECT contenthash, filename, MAX(id) AS id
  396. FROM {files}
  397. WHERE contextid = ? AND component = ? AND filearea != ?
  398. GROUP BY contenthash, filename) files2 ON files1.id = files2.id";
  399. $params = array('contextid'=>$usercontext->id, 'component'=>'user', 'filearea'=>'draft');
  400. $record = $DB->get_record_sql($sql, $params);
  401. return (int)$record->totalbytes;
  402. }
  403. /**
  404. * Convert any string to a valid filepath
  405. * @param string $str
  406. * @return string path
  407. */
  408. function file_correct_filepath($str) { //TODO: what is this? (skodak)
  409. if ($str == '/' or empty($str)) {
  410. return '/';
  411. } else {
  412. return '/'.trim($str, './@#$ ').'/';
  413. }
  414. }
  415. /**
  416. * Generate a folder tree of draft area of current USER recursively
  417. * @param int $itemid
  418. * @param string $filepath
  419. * @param mixed $data //TODO: use normal return value instead, this does not fit the rest of api here (skodak)
  420. */
  421. function file_get_drafarea_folders($draftitemid, $filepath, &$data) {
  422. global $USER, $OUTPUT, $CFG;
  423. $data->children = array();
  424. $context = get_context_instance(CONTEXT_USER, $USER->id);
  425. $fs = get_file_storage();
  426. if ($files = $fs->get_directory_files($context->id, 'user', 'draft', $draftitemid, $filepath, false)) {
  427. foreach ($files as $file) {
  428. if ($file->is_directory()) {
  429. $item = new stdClass();
  430. $item->sortorder = $file->get_sortorder();
  431. $item->filepath = $file->get_filepath();
  432. $foldername = explode('/', trim($item->filepath, '/'));
  433. $item->fullname = trim(array_pop($foldername), '/');
  434. $item->id = uniqid();
  435. file_get_drafarea_folders($draftitemid, $item->filepath, $item);
  436. $data->children[] = $item;
  437. } else {
  438. continue;
  439. }
  440. }
  441. }
  442. }
  443. /**
  444. * Listing all files (including folders) in current path (draft area)
  445. * used by file manager
  446. * @param int $draftitemid
  447. * @param string $filepath
  448. * @return mixed
  449. */
  450. function file_get_drafarea_files($draftitemid, $filepath = '/') {
  451. global $USER, $OUTPUT, $CFG;
  452. $context = get_context_instance(CONTEXT_USER, $USER->id);
  453. $fs = get_file_storage();
  454. $data = new stdClass();
  455. $data->path = array();
  456. $data->path[] = array('name'=>get_string('files'), 'path'=>'/');
  457. // will be used to build breadcrumb
  458. $trail = '';
  459. if ($filepath !== '/') {
  460. $filepath = file_correct_filepath($filepath);
  461. $parts = explode('/', $filepath);
  462. foreach ($parts as $part) {
  463. if ($part != '' && $part != null) {
  464. $trail .= ('/'.$part.'/');
  465. $data->path[] = array('name'=>$part, 'path'=>$trail);
  466. }
  467. }
  468. }
  469. $list = array();
  470. $maxlength = 12;
  471. if ($files = $fs->get_directory_files($context->id, 'user', 'draft', $draftitemid, $filepath, false)) {
  472. foreach ($files as $file) {
  473. $item = new stdClass();
  474. $item->filename = $file->get_filename();
  475. $item->filepath = $file->get_filepath();
  476. $item->fullname = trim($item->filename, '/');
  477. $filesize = $file->get_filesize();
  478. $item->filesize = $filesize ? display_size($filesize) : '';
  479. $icon = mimeinfo_from_type('icon', $file->get_mimetype());
  480. $item->icon = $OUTPUT->pix_url('f/' . $icon)->out();
  481. $item->sortorder = $file->get_sortorder();
  482. if ($icon == 'zip') {
  483. $item->type = 'zip';
  484. } else {
  485. $item->type = 'file';
  486. }
  487. if ($file->is_directory()) {
  488. $item->filesize = 0;
  489. $item->icon = $OUTPUT->pix_url('f/folder')->out();
  490. $item->type = 'folder';
  491. $foldername = explode('/', trim($item->filepath, '/'));
  492. $item->fullname = trim(array_pop($foldername), '/');
  493. } else {
  494. // do NOT use file browser here!
  495. $item->url = moodle_url::make_draftfile_url($draftitemid, $item->filepath, $item->filename)->out();
  496. }
  497. $list[] = $item;
  498. }
  499. }
  500. $data->itemid = $draftitemid;
  501. $data->list = $list;
  502. return $data;
  503. }
  504. /**
  505. * Returns draft area itemid for a given element.
  506. *
  507. * @param string $elname name of formlib editor element, or a hidden form field that stores the draft area item id, etc.
  508. * @return integer the itemid, or 0 if there is not one yet.
  509. */
  510. function file_get_submitted_draft_itemid($elname) {
  511. $param = optional_param($elname, 0, PARAM_INT);
  512. if ($param) {
  513. require_sesskey();
  514. }
  515. if (is_array($param)) {
  516. if (!empty($param['itemid'])) {
  517. $param = $param['itemid'];
  518. } else {
  519. debugging('Missing itemid, maybe caused by unset maxfiles option', DEBUG_DEVELOPER);
  520. return false;
  521. }
  522. }
  523. return $param;
  524. }
  525. /**
  526. * Saves files from a draft file area to a real one (merging the list of files).
  527. * Can rewrite URLs in some content at the same time if desired.
  528. *
  529. * @global object
  530. * @global object
  531. * @param integer $draftitemid the id of the draft area to use. Normally obtained
  532. * from file_get_submitted_draft_itemid('elementname') or similar.
  533. * @param integer $contextid This parameter and the next two identify the file area to save to.
  534. * @param string $component
  535. * @param string $filearea indentifies the file area.
  536. * @param integer $itemid helps identifies the file area.
  537. * @param array $options area options (subdirs=>false, maxfiles=-1, maxbytes=0)
  538. * @param string $text some html content that needs to have embedded links rewritten
  539. * to the @@PLUGINFILE@@ form for saving in the database.
  540. * @param boolean $forcehttps force https urls.
  541. * @return string if $text was passed in, the rewritten $text is returned. Otherwise NULL.
  542. */
  543. function file_save_draft_area_files($draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null, $forcehttps=false) {
  544. global $USER;
  545. $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
  546. $fs = get_file_storage();
  547. $options = (array)$options;
  548. if (!isset($options['subdirs'])) {
  549. $options['subdirs'] = false;
  550. }
  551. if (!isset($options['maxfiles'])) {
  552. $options['maxfiles'] = -1; // unlimited
  553. }
  554. if (!isset($options['maxbytes'])) {
  555. $options['maxbytes'] = 0; // unlimited
  556. }
  557. $draftfiles = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftitemid, 'id');
  558. $oldfiles = $fs->get_area_files($contextid, $component, $filearea, $itemid, 'id');
  559. if (count($draftfiles) < 2) {
  560. // means there are no files - one file means root dir only ;-)
  561. $fs->delete_area_files($contextid, $component, $filearea, $itemid);
  562. } else if (count($oldfiles) < 2) {
  563. $filecount = 0;
  564. // there were no files before - one file means root dir only ;-)
  565. $file_record = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid);
  566. foreach ($draftfiles as $file) {
  567. if (!$options['subdirs']) {
  568. if ($file->get_filepath() !== '/' or $file->is_directory()) {
  569. continue;
  570. }
  571. }
  572. if ($options['maxbytes'] and $options['maxbytes'] < $file->get_filesize()) {
  573. // oversized file - should not get here at all
  574. continue;
  575. }
  576. if ($options['maxfiles'] != -1 and $options['maxfiles'] <= $filecount) {
  577. // more files - should not get here at all
  578. break;
  579. }
  580. if (!$file->is_directory()) {
  581. $filecount++;
  582. }
  583. $fs->create_file_from_storedfile($file_record, $file);
  584. }
  585. } else {
  586. // we have to merge old and new files - we want to keep file ids for files that were not changed
  587. // we change time modified for all new and changed files, we keep time created as is
  588. $file_record = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'timemodified'=>time());
  589. $newhashes = array();
  590. foreach ($draftfiles as $file) {
  591. $newhash = $fs->get_pathname_hash($contextid, $component, $filearea, $itemid, $file->get_filepath(), $file->get_filename());
  592. $newhashes[$newhash] = $file;
  593. }
  594. $filecount = 0;
  595. foreach ($oldfiles as $oldfile) {
  596. $oldhash = $oldfile->get_pathnamehash();
  597. if (!isset($newhashes[$oldhash])) {
  598. // delete files not needed any more - deleted by user
  599. $oldfile->delete();
  600. continue;
  601. }
  602. $newfile = $newhashes[$oldhash];
  603. if ($oldfile->get_contenthash() != $newfile->get_contenthash() or $oldfile->get_sortorder() != $newfile->get_sortorder()
  604. or $oldfile->get_status() != $newfile->get_status() or $oldfile->get_license() != $newfile->get_license()
  605. or $oldfile->get_author() != $newfile->get_author() or $oldfile->get_source() != $newfile->get_source()) {
  606. // file was changed, use updated with new timemodified data
  607. $oldfile->delete();
  608. continue;
  609. }
  610. // unchanged file or directory - we keep it as is
  611. unset($newhashes[$oldhash]);
  612. if (!$oldfile->is_directory()) {
  613. $filecount++;
  614. }
  615. }
  616. // now add new/changed files
  617. // the size and subdirectory tests are extra safety only, the UI should prevent it
  618. foreach ($newhashes as $file) {
  619. if (!$options['subdirs']) {
  620. if ($file->get_filepath() !== '/' or $file->is_directory()) {
  621. continue;
  622. }
  623. }
  624. if ($options['maxbytes'] and $options['maxbytes'] < $file->get_filesize()) {
  625. // oversized file - should not get here at all
  626. continue;
  627. }
  628. if ($options['maxfiles'] != -1 and $options['maxfiles'] <= $filecount) {
  629. // more files - should not get here at all
  630. break;
  631. }
  632. if (!$file->is_directory()) {
  633. $filecount++;
  634. }
  635. $fs->create_file_from_storedfile($file_record, $file);
  636. }
  637. }
  638. // note: do not purge the draft area - we clean up areas later in cron,
  639. // the reason is that user might press submit twice and they would loose the files,
  640. // also sometimes we might want to use hacks that save files into two different areas
  641. if (is_null($text)) {
  642. return null;
  643. } else {
  644. return file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps);
  645. }
  646. }
  647. /**
  648. * Convert the draft file area URLs in some content to @@PLUGINFILE@@ tokens
  649. * ready to be saved in the database. Normally, this is done automatically by
  650. * {@link file_save_draft_area_files()}.
  651. * @param string $text the content to process.
  652. * @param int $draftitemid the draft file area the content was using.
  653. * @param bool $forcehttps whether the content contains https URLs. Default false.
  654. * @return string the processed content.
  655. */
  656. function file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps = false) {
  657. global $CFG, $USER;
  658. $usercontext = get_context_instance(CONTEXT_USER, $USER->id);
  659. $wwwroot = $CFG->wwwroot;
  660. if ($forcehttps) {
  661. $wwwroot = str_replace('http://', 'https://', $wwwroot);
  662. }
  663. // relink embedded files if text submitted - no absolute links allowed in database!
  664. $text = str_ireplace("$wwwroot/draftfile.php/$usercontext->id/user/draft/$draftitemid/", '@@PLUGINFILE@@/', $text);
  665. if (strpos($text, 'draftfile.php?file=') !== false) {
  666. $matches = array();
  667. preg_match_all("!$wwwroot/draftfile.php\?file=%2F{$usercontext->id}%2Fuser%2Fdraft%2F{$draftitemid}%2F[^'\",&<>|`\s:\\\\]+!iu", $text, $matches);
  668. if ($matches) {
  669. foreach ($matches[0] as $match) {
  670. $replace = str_ireplace('%2F', '/', $match);
  671. $text = str_replace($match, $replace, $text);
  672. }
  673. }
  674. $text = str_ireplace("$wwwroot/draftfile.php?file=/$usercontext->id/user/draft/$draftitemid/", '@@PLUGINFILE@@/', $text);
  675. }
  676. return $text;
  677. }
  678. /**
  679. * Set file sort order
  680. * @global object $DB
  681. * @param integer $contextid the context id
  682. * @param string $component
  683. * @param string $filearea file area.
  684. * @param integer $itemid itemid.
  685. * @param string $filepath file path.
  686. * @param string $filename file name.
  687. * @param integer $sortorer the sort order of file.
  688. * @return boolean
  689. */
  690. function file_set_sortorder($contextid, $component, $filearea, $itemid, $filepath, $filename, $sortorder) {
  691. global $DB;
  692. $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'filepath'=>$filepath, 'filename'=>$filename);
  693. if ($file_record = $DB->get_record('files', $conditions)) {
  694. $sortorder = (int)$sortorder;
  695. $file_record->sortorder = $sortorder;
  696. $DB->update_record('files', $file_record);
  697. return true;
  698. }
  699. return false;
  700. }
  701. /**
  702. * reset file sort order number to 0
  703. * @global object $DB
  704. * @param integer $contextid the context id
  705. * @param string $component
  706. * @param string $filearea file area.
  707. * @param integer $itemid itemid.
  708. * @return boolean
  709. */
  710. function file_reset_sortorder($contextid, $component, $filearea, $itemid=false) {
  711. global $DB;
  712. $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea);
  713. if ($itemid !== false) {
  714. $conditions['itemid'] = $itemid;
  715. }
  716. $file_records = $DB->get_records('files', $conditions);
  717. foreach ($file_records as $file_record) {
  718. $file_record->sortorder = 0;
  719. $DB->update_record('files', $file_record);
  720. }
  721. return true;
  722. }
  723. /**
  724. * Returns description of upload error
  725. *
  726. * @param int $errorcode found in $_FILES['filename.ext']['error']
  727. * @return string error description string, '' if ok
  728. */
  729. function file_get_upload_error($errorcode) {
  730. switch ($errorcode) {
  731. case 0: // UPLOAD_ERR_OK - no error
  732. $errmessage = '';
  733. break;
  734. case 1: // UPLOAD_ERR_INI_SIZE
  735. $errmessage = get_string('uploadserverlimit');
  736. break;
  737. case 2: // UPLOAD_ERR_FORM_SIZE
  738. $errmessage = get_string('uploadformlimit');
  739. break;
  740. case 3: // UPLOAD_ERR_PARTIAL
  741. $errmessage = get_string('uploadpartialfile');
  742. break;
  743. case 4: // UPLOAD_ERR_NO_FILE
  744. $errmessage = get_string('uploadnofilefound');
  745. break;
  746. // Note: there is no error with a value of 5
  747. case 6: // UPLOAD_ERR_NO_TMP_DIR
  748. $errmessage = get_string('uploadnotempdir');
  749. break;
  750. case 7: // UPLOAD_ERR_CANT_WRITE
  751. $errmessage = get_string('uploadcantwrite');
  752. break;
  753. case 8: // UPLOAD_ERR_EXTENSION
  754. $errmessage = get_string('uploadextension');
  755. break;
  756. default:
  757. $errmessage = get_string('uploadproblem');
  758. }
  759. return $errmessage;
  760. }
  761. /**
  762. * Recursive function formating an array in POST parameter
  763. * @param array $arraydata - the array that we are going to format and add into &$data array
  764. * @param string $currentdata - a row of the final postdata array at instant T
  765. * when finish, it's assign to $data under this format: name[keyname][][]...[]='value'
  766. * @param array $data - the final data array containing all POST parameters : 1 row = 1 parameter
  767. */
  768. function format_array_postdata_for_curlcall($arraydata, $currentdata, &$data) {
  769. foreach ($arraydata as $k=>$v) {
  770. $newcurrentdata = $currentdata;
  771. if (is_array($v)) { //the value is an array, call the function recursively
  772. $newcurrentdata = $newcurrentdata.'['.urlencode($k).']';
  773. format_array_postdata_for_curlcall($v, $newcurrentdata, $data);
  774. } else { //add the POST parameter to the $data array
  775. $data[] = $newcurrentdata.'['.urlencode($k).']='.urlencode($v);
  776. }
  777. }
  778. }
  779. /**
  780. * Transform a PHP array into POST parameter
  781. * (see the recursive function format_array_postdata_for_curlcall)
  782. * @param array $postdata
  783. * @return array containing all POST parameters (1 row = 1 POST parameter)
  784. */
  785. function format_postdata_for_curlcall($postdata) {
  786. $data = array();
  787. foreach ($postdata as $k=>$v) {
  788. if (is_array($v)) {
  789. $currentdata = urlencode($k);
  790. format_array_postdata_for_curlcall($v, $currentdata, $data);
  791. } else {
  792. $data[] = urlencode($k).'='.urlencode($v);
  793. }
  794. }
  795. $convertedpostdata = implode('&', $data);
  796. return $convertedpostdata;
  797. }
  798. /**
  799. * Fetches content of file from Internet (using proxy if defined). Uses cURL extension if present.
  800. * Due to security concerns only downloads from http(s) sources are supported.
  801. *
  802. * @global object
  803. * @param string $url file url starting with http(s)://
  804. * @param array $headers http headers, null if none. If set, should be an
  805. * associative array of header name => value pairs.
  806. * @param array $postdata array means use POST request with given parameters
  807. * @param bool $fullresponse return headers, responses, etc in a similar way snoopy does
  808. * (if false, just returns content)
  809. * @param int $timeout timeout for complete download process including all file transfer
  810. * (default 5 minutes)
  811. * @param int $connecttimeout timeout for connection to server; this is the timeout that
  812. * usually happens if the remote server is completely down (default 20 seconds);
  813. * may not work when using proxy
  814. * @param bool $skipcertverify If true, the peer's SSL certificate will not be checked. Only use this when already in a trusted location.
  815. * @param string $tofile store the downloaded content to file instead of returning it
  816. * @return mixed false if request failed or content of the file as string if ok. true if file downloaded into $tofile successfully.
  817. */
  818. function download_file_content($url, $headers=null, $postdata=null, $fullresponse=false, $timeout=300, $connecttimeout=20, $skipcertverify=false, $tofile=NULL) {
  819. global $CFG;
  820. // some extra security
  821. $newlines = array("\r", "\n");
  822. if (is_array($headers) ) {
  823. foreach ($headers as $key => $value) {
  824. $headers[$key] = str_replace($newlines, '', $value);
  825. }
  826. }
  827. $url = str_replace($newlines, '', $url);
  828. if (!preg_match('|^https?://|i', $url)) {
  829. if ($fullresponse) {
  830. $response = new stdClass();
  831. $response->status = 0;
  832. $response->headers = array();
  833. $response->response_code = 'Invalid protocol specified in url';
  834. $response->results = '';
  835. $response->error = 'Invalid protocol specified in url';
  836. return $response;
  837. } else {
  838. return false;
  839. }
  840. }
  841. // check if proxy (if used) should be bypassed for this url
  842. $proxybypass = is_proxybypass($url);
  843. if (!$ch = curl_init($url)) {
  844. debugging('Can not init curl.');
  845. return false;
  846. }
  847. // set extra headers
  848. if (is_array($headers) ) {
  849. $headers2 = array();
  850. foreach ($headers as $key => $value) {
  851. $headers2[] = "$key: $value";
  852. }
  853. curl_setopt($ch, CURLOPT_HTTPHEADER, $headers2);
  854. }
  855. if ($skipcertverify) {
  856. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  857. }
  858. // use POST if requested
  859. if (is_array($postdata)) {
  860. $postdata = format_postdata_for_curlcall($postdata);
  861. curl_setopt($ch, CURLOPT_POST, true);
  862. curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
  863. }
  864. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  865. curl_setopt($ch, CURLOPT_HEADER, false);
  866. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $connecttimeout);
  867. curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
  868. if (!ini_get('open_basedir') and !ini_get('safe_mode')) {
  869. // TODO: add version test for '7.10.5'
  870. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
  871. curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
  872. }
  873. if (!empty($CFG->proxyhost) and !$proxybypass) {
  874. // SOCKS supported in PHP5 only
  875. if (!empty($CFG->proxytype) and ($CFG->proxytype == 'SOCKS5')) {
  876. if (defined('CURLPROXY_SOCKS5')) {
  877. curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
  878. } else {
  879. curl_close($ch);
  880. if ($fullresponse) {
  881. $response = new stdClass();
  882. $response->status = '0';
  883. $response->headers = array();
  884. $response->response_code = 'SOCKS5 proxy is not supported in PHP4';
  885. $response->results = '';
  886. $response->error = 'SOCKS5 proxy is not supported in PHP4';
  887. return $response;
  888. } else {
  889. debugging("SOCKS5 proxy is not supported in PHP4.", DEBUG_ALL);
  890. return false;
  891. }
  892. }
  893. }
  894. curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, false);
  895. if (empty($CFG->proxyport)) {
  896. curl_setopt($ch, CURLOPT_PROXY, $CFG->proxyhost);
  897. } else {
  898. curl_setopt($ch, CURLOPT_PROXY, $CFG->proxyhost.':'.$CFG->proxyport);
  899. }
  900. if (!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) {
  901. curl_setopt($ch, CURLOPT_PROXYUSERPWD, $CFG->proxyuser.':'.$CFG->proxypassword);
  902. if (defined('CURLOPT_PROXYAUTH')) {
  903. // any proxy authentication if PHP 5.1
  904. curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_BASIC | CURLAUTH_NTLM);
  905. }
  906. }
  907. }
  908. // set up header and content handlers
  909. $received = new stdClass();
  910. $received->headers = array(); // received headers array
  911. $received->tofile = $tofile;
  912. $received->fh = null;
  913. curl_setopt($ch, CURLOPT_HEADERFUNCTION, partial('download_file_content_header_handler', $received));
  914. if ($tofile) {
  915. curl_setopt($ch, CURLOPT_WRITEFUNCTION, partial('download_file_content_write_handler', $received));
  916. }
  917. $result = curl_exec($ch);
  918. // try to detect encoding problems
  919. if ((curl_errno($ch) == 23 or curl_errno($ch) == 61) and defined('CURLOPT_ENCODING')) {
  920. curl_setopt($ch, CURLOPT_ENCODING, 'none');
  921. $result = curl_exec($ch);
  922. }
  923. if ($received->fh) {
  924. fclose($received->fh);
  925. }
  926. if (curl_errno($ch)) {
  927. $error = curl_error($ch);
  928. $error_no = curl_errno($ch);
  929. curl_close($ch);
  930. if ($fullresponse) {
  931. $response = new stdClass();
  932. if ($error_no == 28) {
  933. $response->status = '-100'; // mimic snoopy
  934. } else {
  935. $response->status = '0';
  936. }
  937. $response->headers = array();
  938. $response->response_code = $error;
  939. $response->results = false;
  940. $response->error = $error;
  941. return $response;
  942. } else {
  943. debugging("cURL request for \"$url\" failed with: $error ($error_no)", DEBUG_ALL);
  944. return false;
  945. }
  946. } else {
  947. $info = curl_getinfo($ch);
  948. curl_close($ch);
  949. if (empty($info['http_code'])) {
  950. // for security reasons we support only true http connections (Location: file:// exploit prevention)
  951. $response = new stdClass();
  952. $response->status = '0';
  953. $response->headers = array();
  954. $response->response_code = 'Unknown cURL error';
  955. $response->results = false; // do NOT change this, we really want to ignore the result!
  956. $response->error = 'Unknown cURL error';
  957. } else {
  958. $response = new stdClass();;
  959. $response->status = (string)$info['http_code'];
  960. $response->headers = $received->headers;
  961. $response->response_code = $received->headers[0];
  962. $response->results = $result;
  963. $response->error = '';
  964. }
  965. if ($fullresponse) {
  966. return $response;
  967. } else if ($info['http_code'] != 200) {
  968. debugging("cURL request for \"$url\" failed, HTTP response code: ".$response->response_code, DEBUG_ALL);
  969. return false;
  970. } else {
  971. return $response->results;
  972. }
  973. }
  974. }
  975. /**
  976. * internal implementation
  977. */
  978. function download_file_content_header_handler($received, $ch, $header) {
  979. $received->headers[] = $header;
  980. return strlen($header);
  981. }
  982. /**
  983. * internal implementation
  984. */
  985. function download_file_content_write_handler($received, $ch, $data) {
  986. if (!$received->fh) {
  987. $received->fh = fopen($received->tofile, 'w');
  988. if ($received->fh === false) {
  989. // bad luck, file creation or overriding failed
  990. return 0;
  991. }
  992. }
  993. if (fwrite($received->fh, $data) === false) {
  994. // bad luck, write failed, let's abort completely
  995. return 0;
  996. }
  997. return strlen($data);
  998. }
  999. /**
  1000. * @return array List of information about file types based on extensions.
  1001. * Associative array of extension (lower-case) to associative array
  1002. * from 'element name' to data. Current element names are 'type' and 'icon'.
  1003. * Unknown types should use the 'xxx' entry which includes defaults.
  1004. */
  1005. function get_mimetypes_array() {
  1006. static $mimearray = array (
  1007. 'xxx' => array ('type'=>'document/unknown', 'icon'=>'unknown'),
  1008. '3gp' => array ('type'=>'video/quicktime', 'icon'=>'video'),
  1009. 'aac' => array ('type'=>'audio/aac', 'icon'=>'audio'),
  1010. 'ai' => array ('type'=>'application/postscript', 'icon'=>'image'),
  1011. 'aif' => array ('type'=>'audio/x-aiff', 'icon'=>'audio'),
  1012. 'aiff' => array ('type'=>'audio/x-aiff', 'icon'=>'audio'),
  1013. 'aifc' => array ('type'=>'audio/x-aiff', 'icon'=>'audio'),
  1014. 'applescript' => array ('type'=>'text/plain', 'icon'=>'text'),
  1015. 'asc' => array ('type'=>'text/plain', 'icon'=>'text'),
  1016. 'asm' => array ('type'=>'text/plain', 'icon'=>'text'),
  1017. 'au' => array ('type'=>'audio/au', 'icon'=>'audio'),
  1018. 'avi' => array ('type'=>'video/x-ms-wm', 'icon'=>'avi'),
  1019. 'bmp' => array ('type'=>'image/bmp', 'icon'=>'image'),
  1020. 'c' => array ('type'=>'text/plain', 'icon'=>'text'),
  1021. 'cct' => array ('type'=>'shockwave/director', 'icon'=>'flash'),
  1022. 'cpp' => array ('type'=>'text/plain', 'icon'=>'text'),
  1023. 'cs' => array ('type'=>'application/x-csh', 'icon'=>'text'),
  1024. 'css' => array ('type'=>'text/css', 'icon'=>'text'),
  1025. 'csv' => array ('type'=>'text/csv', 'icon'=>'excel'),
  1026. 'dv' => array ('type'=>'video/x-dv', 'icon'=>'video'),
  1027. 'dmg' => array ('type'=>'application/octet-stream', 'icon'=>'dmg'),
  1028. 'doc' => array ('type'=>'application/msword', 'icon'=>'word'),
  1029. 'docx' => array ('type'=>'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'icon'=>'docx'),
  1030. 'docm' => array ('type'=>'application/vnd.ms-word.document.macroEnabled.12', 'icon'=>'docm'),
  1031. 'dotx' => array ('type'=>'application/vnd.openxmlformats-officedocument.wordprocessingml.template', 'icon'=>'dotx'),
  1032. 'dotm' => array ('type'=>'application/vnd.ms-word.template.macroEnabled.12', 'icon'=>'dotm'),
  1033. 'dcr' => array ('type'=>'application/x-director', 'icon'=>'flash'),
  1034. 'dif' => array ('type'=>'video/x-dv', 'icon'=>'video'),
  1035. 'dir' => array ('type'=>'application/x-director', 'icon'=>'flash'),
  1036. 'dxr' => array ('type'=>'application/x-director', 'icon'=>'flash'),
  1037. 'eps' => array ('type'=>'application/postscript', 'icon'=>'pdf'),
  1038. 'fdf' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
  1039. 'flv' => array ('type'=>'video/x-flv', 'icon'=>'video'),
  1040. 'f4v' => array ('type'=>'video/mp4', 'icon'=>'video'),
  1041. 'gif' => array ('type'=>'image/gif', 'icon'=>'image'),
  1042. 'gtar' => array ('type'=>'application/x-gtar', 'icon'=>'zip'),
  1043. 'tgz' => array ('type'=>'application/g-zip', 'icon'=>'zip'),
  1044. 'gz' => array ('type'=>'application/g-zip', 'icon'=>'zip'),
  1045. 'gzip' => array ('type'=>'application/g-zip', 'icon'=>'zip'),
  1046. 'h' => array ('type'=>'text/plain', 'icon'=>'text'),
  1047. 'hpp' => array ('type'=>'text/plain', 'icon'=>'text'),
  1048. 'hqx' => array ('type'=>'application/mac-binhex40', 'icon'=>'zip'),
  1049. 'htc' => array ('type'=>'text/x-component', 'icon'=>'text'),
  1050. 'html' => array ('type'=>'text/html', 'icon'=>'html'),
  1051. 'xhtml'=> array ('type'=>'application/xhtml+xml', 'icon'=>'html'),
  1052. 'htm' => array ('type'=>'text/html', 'icon'=>'html'),
  1053. 'ico' => array ('type'=>'image/vnd.microsoft.icon', 'icon'=>'image'),
  1054. 'ics' => array ('type'=>'text/calendar', 'icon'=>'text'),
  1055. 'isf' => array ('type'=>'application/inspiration', 'icon'=>'isf'),
  1056. 'ist' => array ('type'=>'application/inspiration.template', 'icon'=>'isf'),
  1057. 'java' => array ('type'=>'text/plain', 'icon'=>'text'),
  1058. 'jcb' => array ('type'=>'text/xml', 'icon'=>'jcb'),
  1059. 'jcl' => array ('type'=>'text/xml', 'icon'=>'jcl'),
  1060. 'jcw' => array ('type'=>'text/xml', 'icon'=>'jcw'),
  1061. 'jmt' => array ('type'=>'text/xml', 'icon'=>'jmt'),
  1062. 'jmx' => array ('type'=>'text/xml', 'icon'=>'jmx'),
  1063. 'jpe' => array ('type'=>'image/jpeg', 'icon'=>'image'),
  1064. 'jpeg' => array ('type'=>'image/jpeg', 'icon'=>'image'),
  1065. 'jpg' => array ('type'=>'image/jpeg', 'icon'=>'image'),
  1066. 'jqz' => array ('type'=>'text/xml', 'icon'=>'jqz'),
  1067. 'js' => array ('type'=>'application/x-javascript', 'icon'=>'text'),
  1068. 'latex'=> array ('type'=>'application/x-latex', 'icon'=>'text'),
  1069. 'm' => array ('type'=>'text/plain', 'icon'=>'text'),
  1070. 'mbz' => array ('type'=>'application/vnd.moodle.backup', 'icon'=>'moodle'),
  1071. 'mov' => array ('type'=>'video/quicktime', 'icon'=>'video'),
  1072. 'movie'=> array ('type'=>'video/x-sgi-movie', 'icon'=>'video'),
  1073. 'm3u' => array ('type'=>'audio/x-mpegurl', 'icon'=>'audio'),
  1074. 'mp3' => array ('type'=>'audio/mp3', 'icon'=>'audio'),
  1075. 'mp4' => array ('type'=>'video/mp4', 'icon'=>'video'),
  1076. 'm4v' => array ('type'=>'video/mp4', 'icon'=>'video'),
  1077. 'm4a' => array ('type'=>'audio/mp4', 'icon'=>'audio'),
  1078. 'mpeg' => array ('type'=>'video/mpeg', 'icon'=>'video'),
  1079. 'mpe' => array ('type'=>'video/mpeg', 'icon'=>'video'),
  1080. 'mpg' => array ('type'=>'video/mpeg', 'icon'=>'video'),
  1081. 'odt' => array ('type'=>'application/vnd.oasis.opendocument.text', 'icon'=>'odt'),
  1082. 'ott' => array ('type'=>'application/vnd.oasis.opendocument.text-template', 'icon'=>'odt'),
  1083. 'oth' => array ('type'=>'application/vnd.oasis.opendocument.text-web', 'icon'=>'odt'),
  1084. 'odm' => array ('type'=>'application/vnd.oasis.opendocument.text-master', 'icon'=>'odm'),
  1085. 'odg' => array ('type'=>'application/vnd.oasis.opendocument.graphics', 'icon'=>'odg'),
  1086. 'otg' => array ('type'=>'application/vnd.oasis.opendocument.graphics-template', 'icon'=>'odg'),
  1087. 'odp' => array ('type'=>'application/vnd.oasis.opendocument.presentation', 'icon'=>'odp'),
  1088. 'otp' => array ('type'=>'application/vnd.oasis.opendocument.presentation-template', 'icon'=>'odp'),
  1089. 'ods' => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet', 'icon'=>'ods'),
  1090. 'ots' => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet-template', 'icon'=>'ods'),
  1091. 'odc' => array ('type'=>'application/vnd.oasis.opendocument.chart', 'icon'=>'odc'),
  1092. 'odf' => array ('type'=>'application/vnd.oasis.opendocument.formula', 'icon'=>'odf'),
  1093. 'odb' => array ('type'=>'application/vnd.oasis.opendocument.database', 'icon'=>'odb'),
  1094. 'odi' => array ('type'=>'application/vnd.oasis.opendocument.image', 'icon'=>'odi'),
  1095. 'oga' => array ('type'=>'audio/ogg', 'icon'=>'audio'),
  1096. 'ogg' => array ('type'=>'audio/ogg', 'icon'=>'audio'),
  1097. 'ogv' => array ('type'=>'video/ogg', 'icon'=>'video'),
  1098. 'pct' => array ('type'=>'image/pict', 'icon'=>'image'),
  1099. 'pdf' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
  1100. 'php' => array ('type'=>'text/plain', 'icon'=>'text'),
  1101. 'pic' => array ('type'=>'image/pict', 'icon'=>'image'),
  1102. 'pict' => array ('type'=>'image/pict', 'icon'=>'image'),
  1103. 'png' => array ('type'=>'image/png', 'icon'=>'image'),
  1104. 'pps' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'powerpoint'),
  1105. 'ppt' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'powerpoint'),
  1106. 'pptx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'icon'=>'pptx'),
  1107. 'pptm' => array ('type'=>'application/vnd.ms-powerpoint.presentation.macroEnabled.12', 'icon'=>'pptm'),
  1108. 'potx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.template', 'icon'=>'potx'),
  1109. 'potm' => array ('type'=>'application/vnd.ms-powerpoint.template.macroEnabled.12', 'icon'=>'potm'),
  1110. 'ppam' => array ('type'=>'application/vnd.ms-powerpoint.addin.macroEnabled.12', 'icon'=>'ppam'),
  1111. 'ppsx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.slideshow', 'icon'=>'ppsx'),
  1112. 'ppsm' => array ('type'=>'application/vnd.ms-powerpoint.slideshow.macroEnabled.12', 'icon'=>'ppsm'),
  1113. 'ps' => array ('type'=>'application/postscript', 'icon'=>'pdf'),
  1114. 'qt' => array ('type'=>'video/quicktime', 'icon'=>'video'),
  1115. 'ra' => array ('type'=>'audio/x-realaudio-plugin', 'icon'=>'audio'),
  1116. 'ram' => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'audio'),
  1117. 'rhb' => array ('type'=>'text/xml', 'icon'=>'xml'),
  1118. 'rm' => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'audio'),
  1119. 'rmvb' => array ('type'=>'application/vnd.rn-realmedia-vbr', 'icon'=>'video'),
  1120. 'rtf' => array ('type'=>'text/rtf', 'icon'=>'text'),
  1121. 'rtx' => array ('type'=>'text/richtext', 'icon'=>'text'),
  1122. 'rv' => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'video'),
  1123. 'sh' => array ('type'=>'application/x-sh', 'icon'=>'text'),
  1124. 'sit' => array ('type'=>'application/x-stuffit', 'icon'=>'zip'),
  1125. 'smi' => array ('type'=>'application/smil', 'icon'=>'text'),
  1126. 'smil' => array ('type'=>'application/smil', 'icon'=>'text'),
  1127. 'sqt' => array ('type'=>'text/xml', 'icon'=>'xml'),
  1128. 'svg' => array ('type'=>'image/svg+xml', 'icon'=>'image'),
  1129. 'svgz' => array ('type'=>'image/svg+xml', 'icon'=>'image'),
  1130. 'swa' => array ('type'=>'application/x-director', 'icon'=>'flash'),
  1131. 'swf' => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash'),
  1132. 'swfl' => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash'),
  1133. 'sxw' => array ('type'=>'application/vnd.sun.xml.writer', 'icon'=>'odt'),
  1134. 'stw' => array ('type'=>'application/vnd.sun.xml.writer.template', 'icon'=>'odt'),
  1135. 'sxc' => array ('type'=>'application/vnd.sun.xml.calc', 'icon'=>'odt'),
  1136. 'stc' => array ('type'=>'application/vnd.sun.xml.calc.template', 'icon'=>'odt'),
  1137. 'sxd' => array ('type'=>'application/vnd.sun.xml.draw', 'icon'=>'odt'),
  1138. 'std' => array ('type'=>'application/vnd.sun.xml.draw.template', 'icon'=>'odt'),
  1139. 'sxi' => array ('type'=>'application/vnd.sun.xml.impress', 'icon'=>'odt'),
  1140. 'sti' => array ('type'=>'application/vnd.sun.xml.impress.template', 'icon'=>'odt'),
  1141. 'sxg' => array ('type'=>'application/vnd.sun.xml.writer.global', 'icon'=>'odt'),
  1142. 'sxm' => array ('type'=>'application/vnd.sun.xml.math', 'icon'=>'odt'),
  1143. 'tar' => array ('type'=>'application/x-tar', 'icon'=>'zip'),
  1144. 'tif' => array ('type'=>'image/tiff', 'icon'=>'image'),
  1145. 'tiff' => array ('type'=>'image/tiff', 'icon'=>'image'),
  1146. 'tex' => array ('type'=>'application/x-tex', 'icon'=>'text'),
  1147. 'texi' => array ('type'=>'application/x-texinfo', 'icon'=>'text'),
  1148. 'texinfo' => array ('type'=>'application/x-texinfo', 'icon'=>'text'),
  1149. 'tsv' => array ('type'=>'text/tab-separated-values', 'icon'=>'text'),
  1150. 'txt' => array ('type'=>'text/plain', 'icon'=>'text'),
  1151. 'wav' => array ('type'=>'audio/wav', 'icon'=>'audio'),
  1152. 'webm' => array ('type'=>'video/webm', 'icon'=>'video'),
  1153. 'wmv' => array ('type'=>'video/x-ms-wmv', 'icon'=>'avi'),
  1154. 'asf' => array ('type'=>'video/x-ms-asf', 'icon'=>'avi'),
  1155. 'xdp' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
  1156. 'xfd' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
  1157. 'xfdf' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
  1158. 'xls' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'excel'),
  1159. 'xlsx' => array ('type'=>'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'icon'=>'xlsx'),
  1160. 'xlsm' => array ('type'=>'application/vnd.ms-excel.sheet.macroEnabled.12', 'icon'=>'xlsm'),
  1161. 'xltx' => array ('type'=>'application/vnd.openxmlformats-officedocument.spreadsheetml.template', 'icon'=>'xltx'),
  1162. 'xltm' => array ('type'=>'application/vnd.ms-excel.template.macroEnabled.12', 'icon'=>'xltm'),
  1163. 'xlsb' => array ('type'=>'application/vnd.ms-excel.sheet.binary.macroEnabled.12', 'icon'=>'xlsb'),
  1164. 'xlam' => array ('type'=>'application/vnd.ms-excel.addin.macroEnabled.12', 'icon'=>'xlam'),
  1165. 'xml' => array ('type'=>'application/xml', 'icon'=>'xml'),
  1166. 'xsl' => array ('type'=>'text/xml', 'icon'=>'xml'),
  1167. 'zip' => array ('type'=>'application/zip', 'icon'=>'zip')
  1168. );
  1169. return $mimearray;
  1170. }
  1171. /**
  1172. * Obtains information about a filetype based on its extension. Will
  1173. * use a default if no information is present about that particular
  1174. * extension.
  1175. *
  1176. * @param string $element Desired information (usually 'icon'
  1177. * for icon filename or 'type' for MIME type)
  1178. * @param string $filename Filename we're looking up
  1179. * @return string Requested piece of information from array
  1180. */
  1181. function mimeinfo($element, $filename) {
  1182. global $CFG;
  1183. $mimeinfo = get_mimetypes_array();
  1184. if (preg_match('/\.([a-z0-9]+)$/i', $filename, $match)) {
  1185. if (isset($mimeinfo[strtolower($match[1])][$element])) {
  1186. return $mimeinfo[strtolower($match[1])][$element];
  1187. } else {
  1188. if ($element == 'icon32') {
  1189. if (isset($mimeinfo[strtolower($match[1])]['icon'])) {
  1190. $filename = $mimeinfo[strtolower($match[1])]['icon'];
  1191. } else {
  1192. $filename = 'unknown';
  1193. }
  1194. $filename .= '-32';
  1195. if (file_exists($CFG->dirroot.'/pix/f/'.$filename.'.png') or file_exists($CFG->dirroot.'/pix/f/'.$filename.'.gif')) {
  1196. return $filename;
  1197. } else {
  1198. return 'unknown-32';
  1199. }
  1200. } else {
  1201. return $mimeinfo['xxx'][$element]; // By default
  1202. }
  1203. }
  1204. } else {
  1205. if ($element == 'icon32') {
  1206. return 'unknown-32';
  1207. }
  1208. return $mimeinfo['xxx'][$element]; // By default
  1209. }
  1210. }
  1211. /**
  1212. * Obtains information about a filetype based on the MIME type rather than
  1213. * the other way around.
  1214. *
  1215. * @param string $element Desired information (usually 'icon')
  1216. * @param string $mimetype MIME type we're looking up
  1217. * @return string Requested piece of information from array
  1218. */
  1219. function mimeinfo_from_type($element, $mimetype) {
  1220. $mimeinfo = get_mimetypes_array();
  1221. foreach($mimeinfo as $values) {
  1222. if ($values['type']==$mimetype) {
  1223. if (isset($values[$element])) {
  1224. return $values[$element];
  1225. }
  1226. break;
  1227. }
  1228. }
  1229. return $mimeinfo['xxx'][$element]; // Default
  1230. }
  1231. /**
  1232. * Get information about a filetype based on the icon file.
  1233. *
  1234. * @param string $element Desired information (usually 'icon')
  1235. * @param string $icon Icon file name without extension
  1236. * @param boolean $all return all matching entries (defaults to false - best (by ext)/last match)
  1237. * @return string Requested piece of information from array
  1238. */
  1239. function mimeinfo_from_icon($element, $icon, $all=false) {
  1240. $mimeinfo = get_mimetypes_array();
  1241. if (preg_match("/\/(.*)/", $icon, $matches)) {
  1242. $icon = $matches[1];
  1243. }
  1244. // Try to get the extension
  1245. $extension = '';
  1246. if (($cutat = strrpos($icon, '.')) !== false && $cutat < strlen($icon)-1) {
  1247. $extension = substr($icon, $cutat + 1);
  1248. }
  1249. $info = array($mimeinfo['xxx'][$element]); // Default
  1250. foreach($mimeinfo as $key => $values) {
  1251. if ($values['icon']==$icon) {
  1252. if (isset($values[$element])) {
  1253. $info[$key] = $values[$element];
  1254. }
  1255. //No break, for example for 'excel' we don't want 'csv'!
  1256. }
  1257. }
  1258. if ($all) {
  1259. if (count($info) > 1) {
  1260. array_shift($info); // take off document/unknown if we have better options
  1261. }
  1262. return array_values($info); // Keep keys out when requesting all
  1263. }
  1264. // Requested only one, try to get the best by extension coincidence, else return the last
  1265. if ($extension && isset($info[$extension])) {
  1266. return $info[$extension];
  1267. }
  1268. return array_pop($info); // Return last match (mimicking behaviour/comment inside foreach loop)
  1269. }
  1270. /**
  1271. * Returns the relative icon path for a given mime type
  1272. *
  1273. * This function should be used in conjunction with $OUTPUT->pix_url to produce
  1274. * a return the full path to an icon.
  1275. *
  1276. * <code>
  1277. * $mimetype = 'image/jpg';
  1278. * $icon = $OUTPUT->pix_url(file_mimetype_icon($mimetype));
  1279. * echo '<img src="'.$icon.'" alt="'.$mimetype.'" />';
  1280. * </code>
  1281. *
  1282. * @todo When an $OUTPUT->icon method is available this function should be altered
  1283. * to conform with that.
  1284. *
  1285. * @param string $mimetype The mimetype to fetch an icon for
  1286. * @param int $size The size of the icon. Not yet implemented
  1287. * @return string The relative path to the icon
  1288. */
  1289. function file_mimetype_icon($mimetype, $size = NULL) {
  1290. global $CFG;
  1291. $icon = mimeinfo_from_type('icon', $mimetype);
  1292. if ($size) {
  1293. if (file_exists("$CFG->dirroot/pix/f/$icon-$size.png") or file_exists("$CFG->dirroot/pix/f/$icon-$size.gif")) {
  1294. $icon = "$icon-$size";
  1295. }
  1296. }
  1297. return 'f/'.$icon;
  1298. }
  1299. /**
  1300. * Returns the relative icon path for a given file name
  1301. *
  1302. * This function should be used in conjunction with $OUTPUT->pix_url to produce
  1303. * a return the full path to an icon.
  1304. *
  1305. * <code>
  1306. * $filename = 'jpg';
  1307. * $icon = $OUTPUT->pix_url(file_extension_icon($filename));
  1308. * echo '<img src="'.$icon.'" alt="blah" />';
  1309. * </code>
  1310. *
  1311. * @todo When an $OUTPUT->icon method is available this function should be altered
  1312. * to conform with that.
  1313. * @todo Implement $size
  1314. *
  1315. * @param string filename The filename to get the icon for
  1316. * @param int $size The size of the icon. Defaults to null can also be 32
  1317. * @return string
  1318. */
  1319. function file_extension_icon($filename, $size = NULL) {
  1320. global $CFG;
  1321. $icon = mimeinfo('icon', $filename);
  1322. if ($size) {
  1323. if (file_exists("$CFG->dirroot/pix/f/$icon-$size.png") or file_exists("$CFG->dirroot/pix/f/$icon-$size.gif")) {
  1324. $icon = "$icon-$size";
  1325. }
  1326. }
  1327. return 'f/'.$icon;
  1328. }
  1329. /**
  1330. * Obtains descriptions for file types (e.g. 'Microsoft Word document') from the
  1331. * mimetypes.php language file.
  1332. *
  1333. * @param string $mimetype MIME type (can be obtained using the mimeinfo function)
  1334. * @param bool $capitalise If true, capitalises first character of result
  1335. * @return string Text description
  1336. */
  1337. function get_mimetype_description($mimetype, $capitalise=false) {
  1338. if (get_string_manager()->string_exists($mimetype, 'mimetypes')) {
  1339. $result = get_string($mimetype, 'mimetypes');
  1340. } else {
  1341. $result = get_string('document/unknown','mimetypes');
  1342. }
  1343. if ($capitalise) {
  1344. $result=ucfirst($result);
  1345. }
  1346. return $result;
  1347. }
  1348. /**
  1349. * Requested file is not found or not accessible
  1350. *
  1351. * @return does not return, terminates script
  1352. */
  1353. function send_file_not_found() {
  1354. global $CFG, $COURSE;
  1355. header('HTTP/1.0 404 not found');
  1356. print_error('filenotfound', 'error', $CFG->wwwroot.'/course/view.php?id='.$COURSE->id); //this is not displayed on IIS??
  1357. }
  1358. /**
  1359. * Check output buffering settings before sending file.
  1360. * Please note you should not send any other headers after calling this function.
  1361. *
  1362. * @private to be called only from lib/filelib.php !
  1363. * @return void
  1364. */
  1365. function prepare_file_content_sending() {
  1366. // We needed to be able to send headers up until now
  1367. if (headers_sent()) {
  1368. throw new file_serving_exception('Headers already sent, can not serve file.');
  1369. }
  1370. $olddebug = error_reporting(0);
  1371. // IE compatibility HACK - it does not like zlib compression much
  1372. // there is also a problem with the length header in older PHP versions
  1373. if (ini_get_bool('zlib.output_compression')) {
  1374. ini_set('zlib.output_compression', 'Off');
  1375. }
  1376. // flush and close all buffers if possible
  1377. while(ob_get_level()) {
  1378. if (!ob_end_flush()) {
  1379. // prevent infinite loop when buffer can not be closed
  1380. break;
  1381. }
  1382. }
  1383. error_reporting($olddebug);
  1384. //NOTE: we can not reliable test headers_sent() here because
  1385. // the headers might be sent which trying to close the buffers,
  1386. // this happens especially if browser does not support gzip or deflate
  1387. }
  1388. /**
  1389. * Handles the sending of temporary file to user, download is forced.
  1390. * File is deleted after abort or successful sending.
  1391. *
  1392. * @param string $path path to file, preferably from moodledata/temp/something; or content of file itself
  1393. * @param string $filename proposed file name when saving file
  1394. * @param bool $path is content of file
  1395. * @return does not return, script terminated
  1396. */
  1397. function send_temp_file($path, $filename, $pathisstring=false) {
  1398. global $CFG;
  1399. // close session - not needed anymore
  1400. @session_get_instance()->write_close();
  1401. if (!$pathisstring) {
  1402. if (!file_exists($path)) {
  1403. header('HTTP/1.0 404 not found');
  1404. print_error('filenotfound', 'error', $CFG->wwwroot.'/');
  1405. }
  1406. // executed after normal finish or abort
  1407. @register_shutdown_function('send_temp_file_finished', $path);
  1408. }
  1409. // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
  1410. if (check_browser_version('MSIE')) {
  1411. $filename = urlencode($filename);
  1412. }
  1413. $filesize = $pathisstring ? strlen($path) : filesize($path);
  1414. header('Content-Disposition: attachment; filename='.$filename);
  1415. header('Content-Length: '.$filesize);
  1416. if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
  1417. header('Cache-Control: max-age=10');
  1418. header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
  1419. header('Pragma: ');
  1420. } else { //normal http - prevent caching at all cost
  1421. header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
  1422. header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
  1423. header('Pragma: no-cache');
  1424. }
  1425. header('Accept-Ranges: none'); // Do not allow byteserving
  1426. //flush the buffers - save memory and disable sid rewrite
  1427. // this also disables zlib compression
  1428. prepare_file_content_sending();
  1429. // send the contents
  1430. if ($pathisstring) {
  1431. echo $path;
  1432. } else {
  1433. @readfile($path);
  1434. }
  1435. die; //no more chars to output
  1436. }
  1437. /**
  1438. * Internal callback function used by send_temp_file()
  1439. */
  1440. function send_temp_file_finished($path) {
  1441. if (file_exists($path)) {
  1442. @unlink($path);
  1443. }
  1444. }
  1445. /**
  1446. * Handles the sending of file data to the user's browser, including support for
  1447. * byteranges etc.
  1448. *
  1449. * @global object
  1450. * @global object
  1451. * @global object
  1452. * @param string $path Path of file on disk (including real filename), or actual content of file as string
  1453. * @param string $filename Filename to send
  1454. * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
  1455. * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
  1456. * @param bool $pathisstring If true (default false), $path is the content to send and not the pathname
  1457. * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
  1458. * @param string $mimetype Include to specify the MIME type; leave blank to have it guess the type from $filename
  1459. * @param bool $dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
  1460. * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
  1461. * you must detect this case when control is returned using connection_aborted. Please not that session is closed
  1462. * and should not be reopened.
  1463. * @return no return or void, script execution stopped unless $dontdie is true
  1464. */
  1465. function send_file($path, $filename, $lifetime = 'default' , $filter=0, $pathisstring=false, $forcedownload=false, $mimetype='', $dontdie=false) {
  1466. global $CFG, $COURSE, $SESSION;
  1467. if ($dontdie) {
  1468. ignore_user_abort(true);
  1469. }
  1470. // MDL-11789, apply $CFG->filelifetime here
  1471. if ($lifetime === 'default') {
  1472. if (!empty($CFG->filelifetime)) {
  1473. $lifetime = $CFG->filelifetime;
  1474. } else {
  1475. $lifetime = 86400;
  1476. }
  1477. }
  1478. session_get_instance()->write_close(); // unlock session during fileserving
  1479. // Use given MIME type if specified, otherwise guess it using mimeinfo.
  1480. // IE, Konqueror and Opera open html file directly in browser from web even when directed to save it to disk :-O
  1481. // only Firefox saves all files locally before opening when content-disposition: attachment stated
  1482. $isFF = check_browser_version('Firefox', '1.5'); // only FF > 1.5 properly tested
  1483. $mimetype = ($forcedownload and !$isFF) ? 'application/x-forcedownload' :
  1484. ($mimetype ? $mimetype : mimeinfo('type', $filename));
  1485. $lastmodified = $pathisstring ? time() : filemtime($path);
  1486. $filesize = $pathisstring ? strlen($path) : filesize($path);
  1487. /* - MDL-13949
  1488. //Adobe Acrobat Reader XSS prevention
  1489. if ($mimetype=='application/pdf' or mimeinfo('type', $filename)=='application/pdf') {
  1490. //please note that it prevents opening of pdfs in browser when http referer disabled
  1491. //or file linked from another site; browser caching of pdfs is now disabled too
  1492. if (!empty($_SERVER['HTTP_RANGE'])) {
  1493. //already byteserving
  1494. $lifetime = 1; // >0 needed for byteserving
  1495. } else if (empty($_SERVER['HTTP_REFERER']) or strpos($_SERVER['HTTP_REFERER'], $CFG->wwwroot)!==0) {
  1496. $mimetype = 'application/x-forcedownload';
  1497. $forcedownload = true;
  1498. $lifetime = 0;
  1499. } else {
  1500. $lifetime = 1; // >0 needed for byteserving
  1501. }
  1502. }
  1503. */
  1504. //try to disable automatic sid rewrite in cookieless mode
  1505. @ini_set("session.use_trans_sid", "false");
  1506. //do not put '@' before the next header to detect incorrect moodle configurations,
  1507. //error should be better than "weird" empty lines for admins/users
  1508. header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
  1509. // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
  1510. if (check_browser_version('MSIE')) {
  1511. $filename = rawurlencode($filename);
  1512. }
  1513. if ($forcedownload) {
  1514. header('Content-Disposition: attachment; filename="'.$filename.'"');
  1515. } else {
  1516. header('Content-Disposition: inline; filename="'.$filename.'"');
  1517. }
  1518. if ($lifetime > 0) {
  1519. header('Cache-Control: max-age='.$lifetime);
  1520. header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
  1521. header('Pragma: ');
  1522. if (empty($CFG->disablebyteserving) && !$pathisstring && $mimetype != 'text/plain' && $mimetype != 'text/html') {
  1523. header('Accept-Ranges: bytes');
  1524. if (!empty($_SERVER['HTTP_RANGE']) && strpos($_SERVER['HTTP_RANGE'],'bytes=') !== FALSE) {
  1525. // byteserving stuff - for acrobat reader and download accelerators
  1526. // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
  1527. // inspired by: http://www.coneural.org/florian/papers/04_byteserving.php
  1528. $ranges = false;
  1529. if (preg_match_all('/(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER)) {
  1530. foreach ($ranges as $key=>$value) {
  1531. if ($ranges[$key][1] == '') {
  1532. //suffix case
  1533. $ranges[$key][1] = $filesize - $ranges[$key][2];
  1534. $ranges[$key][2] = $filesize - 1;
  1535. } else if ($ranges[$key][2] == '' || $ranges[$key][2] > $filesize - 1) {
  1536. //fix range length
  1537. $ranges[$key][2] = $filesize - 1;
  1538. }
  1539. if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
  1540. //invalid byte-range ==> ignore header
  1541. $ranges = false;
  1542. break;
  1543. }
  1544. //prepare multipart header
  1545. $ranges[$key][0] = "\r\n--".BYTESERVING_BOUNDARY."\r\nContent-Type: $mimetype\r\n";
  1546. $ranges[$key][0] .= "Content-Range: bytes {$ranges[$key][1]}-{$ranges[$key][2]}/$filesize\r\n\r\n";
  1547. }
  1548. } else {
  1549. $ranges = false;
  1550. }
  1551. if ($ranges) {
  1552. $handle = fopen($path, 'rb');
  1553. byteserving_send_file($handle, $mimetype, $ranges, $filesize);
  1554. }
  1555. }
  1556. } else {
  1557. /// Do not byteserve (disabled, strings, text and html files).
  1558. header('Accept-Ranges: none');
  1559. }
  1560. } else { // Do not cache files in proxies and browsers
  1561. if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
  1562. header('Cache-Control: max-age=10');
  1563. header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
  1564. header('Pragma: ');
  1565. } else { //normal http - prevent caching at all cost
  1566. header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
  1567. header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
  1568. header('Pragma: no-cache');
  1569. }
  1570. header('Accept-Ranges: none'); // Do not allow byteserving when caching disabled
  1571. }
  1572. if (empty($filter)) {
  1573. if ($mimetype == 'text/html' && !empty($CFG->usesid)) {
  1574. //cookieless mode - rewrite links
  1575. header('Content-Type: text/html');
  1576. $path = $pathisstring ? $path : implode('', file($path));
  1577. $path = sid_ob_rewrite($path);
  1578. $filesize = strlen($path);
  1579. $pathisstring = true;
  1580. } else if ($mimetype == 'text/plain') {
  1581. header('Content-Type: Text/plain; charset=utf-8'); //add encoding
  1582. } else {
  1583. header('Content-Type: '.$mimetype);
  1584. }
  1585. header('Content-Length: '.$filesize);
  1586. //flush the buffers - save memory and disable sid rewrite
  1587. //this also disables zlib compression
  1588. prepare_file_content_sending();
  1589. // send the contents
  1590. if ($pathisstring) {
  1591. echo $path;
  1592. } else {
  1593. @readfile($path);
  1594. }
  1595. } else { // Try to put the file through filters
  1596. if ($mimetype == 'text/html') {
  1597. $options = new stdClass();
  1598. $options->noclean = true;
  1599. $options->nocache = true; // temporary workaround for MDL-5136
  1600. $text = $pathisstring ? $path : implode('', file($path));
  1601. $text = file_modify_html_header($text);
  1602. $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
  1603. if (!empty($CFG->usesid)) {
  1604. //cookieless mode - rewrite links
  1605. $output = sid_ob_rewrite($output);
  1606. }
  1607. header('Content-Length: '.strlen($output));
  1608. header('Content-Type: text/html');
  1609. //flush the buffers - save memory and disable sid rewrite
  1610. //this also disables zlib compression
  1611. prepare_file_content_sending();
  1612. // send the contents
  1613. echo $output;
  1614. // only filter text if filter all files is selected
  1615. } else if (($mimetype == 'text/plain') and ($filter == 1)) {
  1616. $options = new stdClass();
  1617. $options->newlines = false;
  1618. $options->noclean = true;
  1619. $text = htmlentities($pathisstring ? $path : implode('', file($path)));
  1620. $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
  1621. if (!empty($CFG->usesid)) {
  1622. //cookieless mode - rewrite links
  1623. $output = sid_ob_rewrite($output);
  1624. }
  1625. header('Content-Length: '.strlen($output));
  1626. header('Content-Type: text/html; charset=utf-8'); //add encoding
  1627. //flush the buffers - save memory and disable sid rewrite
  1628. //this also disables zlib compression
  1629. prepare_file_content_sending();
  1630. // send the contents
  1631. echo $output;
  1632. } else { // Just send it out raw
  1633. header('Content-Length: '.$filesize);
  1634. header('Content-Type: '.$mimetype);
  1635. //flush the buffers - save memory and disable sid rewrite
  1636. //this also disables zlib compression
  1637. prepare_file_content_sending();
  1638. // send the contents
  1639. if ($pathisstring) {
  1640. echo $path;
  1641. }else {
  1642. @readfile($path);
  1643. }
  1644. }
  1645. }
  1646. if ($dontdie) {
  1647. return;
  1648. }
  1649. die; //no more chars to output!!!
  1650. }
  1651. /**
  1652. * Handles the sending of file data to the user's browser, including support for
  1653. * byteranges etc.
  1654. *
  1655. * @global object
  1656. * @global object
  1657. * @global object
  1658. * @param object $stored_file local file object
  1659. * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
  1660. * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
  1661. * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
  1662. * @param string $filename Override filename
  1663. * @param bool $dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
  1664. * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
  1665. * you must detect this case when control is returned using connection_aborted. Please not that session is closed
  1666. * and should not be reopened.
  1667. * @return void no return or void, script execution stopped unless $dontdie is true
  1668. */
  1669. function send_stored_file($stored_file, $lifetime=86400 , $filter=0, $forcedownload=false, $filename=null, $dontdie=false) {
  1670. global $CFG, $COURSE, $SESSION;
  1671. if (!$stored_file or $stored_file->is_directory()) {
  1672. // nothing to serve
  1673. if ($dontdie) {
  1674. return;
  1675. }
  1676. die;
  1677. }
  1678. if ($dontdie) {
  1679. ignore_user_abort(true);
  1680. }
  1681. session_get_instance()->write_close(); // unlock session during fileserving
  1682. // Use given MIME type if specified, otherwise guess it using mimeinfo.
  1683. // IE, Konqueror and Opera open html file directly in browser from web even when directed to save it to disk :-O
  1684. // only Firefox saves all files locally before opening when content-disposition: attachment stated
  1685. $filename = is_null($filename) ? $stored_file->get_filename() : $filename;
  1686. $isFF = check_browser_version('Firefox', '1.5'); // only FF > 1.5 properly tested
  1687. $mimetype = ($forcedownload and !$isFF) ? 'application/x-forcedownload' :
  1688. ($stored_file->get_mimetype() ? $stored_file->get_mimetype() : mimeinfo('type', $filename));
  1689. $lastmodified = $stored_file->get_timemodified();
  1690. $filesize = $stored_file->get_filesize();
  1691. //try to disable automatic sid rewrite in cookieless mode
  1692. @ini_set("session.use_trans_sid", "false");
  1693. //do not put '@' before the next header to detect incorrect moodle configurations,
  1694. //error should be better than "weird" empty lines for admins/users
  1695. //TODO: should we remove all those @ before the header()? Are all of the values supported on all servers?
  1696. header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
  1697. // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
  1698. if (check_browser_version('MSIE')) {
  1699. $filename = rawurlencode($filename);
  1700. }
  1701. if ($forcedownload) {
  1702. header('Content-Disposition: attachment; filename="'.$filename.'"');
  1703. } else {
  1704. header('Content-Disposition: inline; filename="'.$filename.'"');
  1705. }
  1706. if ($lifetime > 0) {
  1707. header('Cache-Control: max-age='.$lifetime);
  1708. header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
  1709. header('Pragma: ');
  1710. if (empty($CFG->disablebyteserving) && $mimetype != 'text/plain' && $mimetype != 'text/html') {
  1711. header('Accept-Ranges: bytes');
  1712. if (!empty($_SERVER['HTTP_RANGE']) && strpos($_SERVER['HTTP_RANGE'],'bytes=') !== FALSE) {
  1713. // byteserving stuff - for acrobat reader and download accelerators
  1714. // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
  1715. // inspired by: http://www.coneural.org/florian/papers/04_byteserving.php
  1716. $ranges = false;
  1717. if (preg_match_all('/(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER)) {
  1718. foreach ($ranges as $key=>$value) {
  1719. if ($ranges[$key][1] == '') {
  1720. //suffix case
  1721. $ranges[$key][1] = $filesize - $ranges[$key][2];
  1722. $ranges[$key][2] = $filesize - 1;
  1723. } else if ($ranges[$key][2] == '' || $ranges[$key][2] > $filesize - 1) {
  1724. //fix range length
  1725. $ranges[$key][2] = $filesize - 1;
  1726. }
  1727. if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
  1728. //invalid byte-range ==> ignore header
  1729. $ranges = false;
  1730. break;
  1731. }
  1732. //prepare multipart header
  1733. $ranges[$key][0] = "\r\n--".BYTESERVING_BOUNDARY."\r\nContent-Type: $mimetype\r\n";
  1734. $ranges[$key][0] .= "Content-Range: bytes {$ranges[$key][1]}-{$ranges[$key][2]}/$filesize\r\n\r\n";
  1735. }
  1736. } else {
  1737. $ranges = false;
  1738. }
  1739. if ($ranges) {
  1740. byteserving_send_file($stored_file->get_content_file_handle(), $mimetype, $ranges, $filesize);
  1741. }
  1742. }
  1743. } else {
  1744. /// Do not byteserve (disabled, strings, text and html files).
  1745. header('Accept-Ranges: none');
  1746. }
  1747. } else { // Do not cache files in proxies and browsers
  1748. if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
  1749. header('Cache-Control: max-age=10');
  1750. header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
  1751. header('Pragma: ');
  1752. } else { //normal http - prevent caching at all cost
  1753. header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
  1754. header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
  1755. header('Pragma: no-cache');
  1756. }
  1757. header('Accept-Ranges: none'); // Do not allow byteserving when caching disabled
  1758. }
  1759. if (empty($filter)) {
  1760. $filtered = false;
  1761. if ($mimetype == 'text/html' && !empty($CFG->usesid)) {
  1762. //cookieless mode - rewrite links
  1763. header('Content-Type: text/html');
  1764. $text = $stored_file->get_content();
  1765. $text = sid_ob_rewrite($text);
  1766. $filesize = strlen($text);
  1767. $filtered = true;
  1768. } else if ($mimetype == 'text/plain') {
  1769. header('Content-Type: Text/plain; charset=utf-8'); //add encoding
  1770. } else {
  1771. header('Content-Type: '.$mimetype);
  1772. }
  1773. header('Content-Length: '.$filesize);
  1774. //flush the buffers - save memory and disable sid rewrite
  1775. //this also disables zlib compression
  1776. prepare_file_content_sending();
  1777. // send the contents
  1778. if ($filtered) {
  1779. echo $text;
  1780. } else {
  1781. $stored_file->readfile();
  1782. }
  1783. } else { // Try to put the file through filters
  1784. if ($mimetype == 'text/html') {
  1785. $options = new stdClass();
  1786. $options->noclean = true;
  1787. $options->nocache = true; // temporary workaround for MDL-5136
  1788. $text = $stored_file->get_content();
  1789. $text = file_modify_html_header($text);
  1790. $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
  1791. if (!empty($CFG->usesid)) {
  1792. //cookieless mode - rewrite links
  1793. $output = sid_ob_rewrite($output);
  1794. }
  1795. header('Content-Length: '.strlen($output));
  1796. header('Content-Type: text/html');
  1797. //flush the buffers - save memory and disable sid rewrite
  1798. //this also disables zlib compression
  1799. prepare_file_content_sending();
  1800. // send the contents
  1801. echo $output;
  1802. } else if (($mimetype == 'text/plain') and ($filter == 1)) {
  1803. // only filter text if filter all files is selected
  1804. $options = new stdClass();
  1805. $options->newlines = false;
  1806. $options->noclean = true;
  1807. $text = $stored_file->get_content();
  1808. $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
  1809. if (!empty($CFG->usesid)) {
  1810. //cookieless mode - rewrite links
  1811. $output = sid_ob_rewrite($output);
  1812. }
  1813. header('Content-Length: '.strlen($output));
  1814. header('Content-Type: text/html; charset=utf-8'); //add encoding
  1815. //flush the buffers - save memory and disable sid rewrite
  1816. //this also disables zlib compression
  1817. prepare_file_content_sending();
  1818. // send the contents
  1819. echo $output;
  1820. } else { // Just send it out raw
  1821. header('Content-Length: '.$filesize);
  1822. header('Content-Type: '.$mimetype);
  1823. //flush the buffers - save memory and disable sid rewrite
  1824. //this also disables zlib compression
  1825. prepare_file_content_sending();
  1826. // send the contents
  1827. $stored_file->readfile();
  1828. }
  1829. }
  1830. if ($dontdie) {
  1831. return;
  1832. }
  1833. die; //no more chars to output!!!
  1834. }
  1835. /**
  1836. * Retrieves an array of records from a CSV file and places
  1837. * them into a given table structure
  1838. *
  1839. * @global object
  1840. * @global object
  1841. * @param string $file The path to a CSV file
  1842. * @param string $table The table to retrieve columns from
  1843. * @return bool|array Returns an array of CSV records or false
  1844. */
  1845. function get_records_csv($file, $table) {
  1846. global $CFG, $DB;
  1847. if (!$metacolumns = $DB->get_columns($table)) {
  1848. return false;
  1849. }
  1850. if(!($handle = @fopen($file, 'r'))) {
  1851. print_error('get_records_csv failed to open '.$file);
  1852. }
  1853. $fieldnames = fgetcsv($handle, 4096);
  1854. if(empty($fieldnames)) {
  1855. fclose($handle);
  1856. return false;
  1857. }
  1858. $columns = array();
  1859. foreach($metacolumns as $metacolumn) {
  1860. $ord = array_search($metacolumn->name, $fieldnames);
  1861. if(is_int($ord)) {
  1862. $columns[$metacolumn->name] = $ord;
  1863. }
  1864. }
  1865. $rows = array();
  1866. while (($data = fgetcsv($handle, 4096)) !== false) {
  1867. $item = new stdClass;
  1868. foreach($columns as $name => $ord) {
  1869. $item->$name = $data[$ord];
  1870. }
  1871. $rows[] = $item;
  1872. }
  1873. fclose($handle);
  1874. return $rows;
  1875. }
  1876. /**
  1877. *
  1878. * @global object
  1879. * @global object
  1880. * @param string $file The file to put the CSV content into
  1881. * @param array $records An array of records to write to a CSV file
  1882. * @param string $table The table to get columns from
  1883. * @return bool success
  1884. */
  1885. function put_records_csv($file, $records, $table = NULL) {
  1886. global $CFG, $DB;
  1887. if (empty($records)) {
  1888. return true;
  1889. }
  1890. $metacolumns = NULL;
  1891. if ($table !== NULL && !$metacolumns = $DB->get_columns($table)) {
  1892. return false;
  1893. }
  1894. echo "x";
  1895. if(!($fp = @fopen($CFG->dataroot.'/temp/'.$file, 'w'))) {
  1896. print_error('put_records_csv failed to open '.$file);
  1897. }
  1898. $proto = reset($records);
  1899. if(is_object($proto)) {
  1900. $fields_records = array_keys(get_object_vars($proto));
  1901. }
  1902. else if(is_array($proto)) {
  1903. $fields_records = array_keys($proto);
  1904. }
  1905. else {
  1906. return false;
  1907. }
  1908. echo "x";
  1909. if(!empty($metacolumns)) {
  1910. $fields_table = array_map(create_function('$a', 'return $a->name;'), $metacolumns);
  1911. $fields = array_intersect($fields_records, $fields_table);
  1912. }
  1913. else {
  1914. $fields = $fields_records;
  1915. }
  1916. fwrite($fp, implode(',', $fields));
  1917. fwrite($fp, "\r\n");
  1918. foreach($records as $record) {
  1919. $array = (array)$record;
  1920. $values = array();
  1921. foreach($fields as $field) {
  1922. if(strpos($array[$field], ',')) {
  1923. $values[] = '"'.str_replace('"', '\"', $array[$field]).'"';
  1924. }
  1925. else {
  1926. $values[] = $array[$field];
  1927. }
  1928. }
  1929. fwrite($fp, implode(',', $values)."\r\n");
  1930. }
  1931. fclose($fp);
  1932. return true;
  1933. }
  1934. /**
  1935. * Recursively delete the file or folder with path $location. That is,
  1936. * if it is a file delete it. If it is a folder, delete all its content
  1937. * then delete it. If $location does not exist to start, that is not
  1938. * considered an error.
  1939. *
  1940. * @param string $location the path to remove.
  1941. * @return bool
  1942. */
  1943. function fulldelete($location) {
  1944. if (empty($location)) {
  1945. // extra safety against wrong param
  1946. return false;
  1947. }
  1948. if (is_dir($location)) {
  1949. $currdir = opendir($location);
  1950. while (false !== ($file = readdir($currdir))) {
  1951. if ($file <> ".." && $file <> ".") {
  1952. $fullfile = $location."/".$file;
  1953. if (is_dir($fullfile)) {
  1954. if (!fulldelete($fullfile)) {
  1955. return false;
  1956. }
  1957. } else {
  1958. if (!unlink($fullfile)) {
  1959. return false;
  1960. }
  1961. }
  1962. }
  1963. }
  1964. closedir($currdir);
  1965. if (! rmdir($location)) {
  1966. return false;
  1967. }
  1968. } else if (file_exists($location)) {
  1969. if (!unlink($location)) {
  1970. return false;
  1971. }
  1972. }
  1973. return true;
  1974. }
  1975. /**
  1976. * Send requested byterange of file.
  1977. *
  1978. * @param object $handle A file handle
  1979. * @param string $mimetype The mimetype for the output
  1980. * @param array $ranges An array of ranges to send
  1981. * @param string $filesize The size of the content if only one range is used
  1982. */
  1983. function byteserving_send_file($handle, $mimetype, $ranges, $filesize) {
  1984. $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
  1985. if ($handle === false) {
  1986. die;
  1987. }
  1988. if (count($ranges) == 1) { //only one range requested
  1989. $length = $ranges[0][2] - $ranges[0][1] + 1;
  1990. header('HTTP/1.1 206 Partial content');
  1991. header('Content-Length: '.$length);
  1992. header('Content-Range: bytes '.$ranges[0][1].'-'.$ranges[0][2].'/'.$filesize);
  1993. header('Content-Type: '.$mimetype);
  1994. //flush the buffers - save memory and disable sid rewrite
  1995. //this also disables zlib compression
  1996. prepare_file_content_sending();
  1997. $buffer = '';
  1998. fseek($handle, $ranges[0][1]);
  1999. while (!feof($handle) && $length > 0) {
  2000. @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
  2001. $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
  2002. echo $buffer;
  2003. flush();
  2004. $length -= strlen($buffer);
  2005. }
  2006. fclose($handle);
  2007. die;
  2008. } else { // multiple ranges requested - not tested much
  2009. $totallength = 0;
  2010. foreach($ranges as $range) {
  2011. $totallength += strlen($range[0]) + $range[2] - $range[1] + 1;
  2012. }
  2013. $totallength += strlen("\r\n--".BYTESERVING_BOUNDARY."--\r\n");
  2014. header('HTTP/1.1 206 Partial content');
  2015. header('Content-Length: '.$totallength);
  2016. header('Content-Type: multipart/byteranges; boundary='.BYTESERVING_BOUNDARY);
  2017. //TODO: check if "multipart/x-byteranges" is more compatible with current readers/browsers/servers
  2018. //flush the buffers - save memory and disable sid rewrite
  2019. //this also disables zlib compression
  2020. prepare_file_content_sending();
  2021. foreach($ranges as $range) {
  2022. $length = $range[2] - $range[1] + 1;
  2023. echo $range[0];
  2024. $buffer = '';
  2025. fseek($handle, $range[1]);
  2026. while (!feof($handle) && $length > 0) {
  2027. @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
  2028. $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
  2029. echo $buffer;
  2030. flush();
  2031. $length -= strlen($buffer);
  2032. }
  2033. }
  2034. echo "\r\n--".BYTESERVING_BOUNDARY."--\r\n";
  2035. fclose($handle);
  2036. die;
  2037. }
  2038. }
  2039. /**
  2040. * add includes (js and css) into uploaded files
  2041. * before returning them, useful for themes and utf.js includes
  2042. *
  2043. * @global object
  2044. * @param string $text text to search and replace
  2045. * @return string text with added head includes
  2046. */
  2047. function file_modify_html_header($text) {
  2048. // first look for <head> tag
  2049. global $CFG;
  2050. $stylesheetshtml = '';
  2051. /* foreach ($CFG->stylesheets as $stylesheet) {
  2052. //TODO: MDL-21120
  2053. $stylesheetshtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
  2054. }*/
  2055. $ufo = '';
  2056. if (filter_is_enabled('filter/mediaplugin')) {
  2057. // this script is needed by most media filter plugins.
  2058. $attributes = array('type'=>'text/javascript', 'src'=>$CFG->httpswwwroot . '/lib/ufo.js');
  2059. $ufo = html_writer::tag('script', '', $attributes) . "\n";
  2060. }
  2061. preg_match('/\<head\>|\<HEAD\>/', $text, $matches);
  2062. if ($matches) {
  2063. $replacement = '<head>'.$ufo.$stylesheetshtml;
  2064. $text = preg_replace('/\<head\>|\<HEAD\>/', $replacement, $text, 1);
  2065. return $text;
  2066. }
  2067. // if not, look for <html> tag, and stick <head> right after
  2068. preg_match('/\<html\>|\<HTML\>/', $text, $matches);
  2069. if ($matches) {
  2070. // replace <html> tag with <html><head>includes</head>
  2071. $replacement = '<html>'."\n".'<head>'.$ufo.$stylesheetshtml.'</head>';
  2072. $text = preg_replace('/\<html\>|\<HTML\>/', $replacement, $text, 1);
  2073. return $text;
  2074. }
  2075. // if not, look for <body> tag, and stick <head> before body
  2076. preg_match('/\<body\>|\<BODY\>/', $text, $matches);
  2077. if ($matches) {
  2078. $replacement = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".'<body>';
  2079. $text = preg_replace('/\<body\>|\<BODY\>/', $replacement, $text, 1);
  2080. return $text;
  2081. }
  2082. // if not, just stick a <head> tag at the beginning
  2083. $text = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".$text;
  2084. return $text;
  2085. }
  2086. /**
  2087. * RESTful cURL class
  2088. *
  2089. * This is a wrapper class for curl, it is quite easy to use:
  2090. * <code>
  2091. * $c = new curl;
  2092. * // enable cache
  2093. * $c = new curl(array('cache'=>true));
  2094. * // enable cookie
  2095. * $c = new curl(array('cookie'=>true));
  2096. * // enable proxy
  2097. * $c = new curl(array('proxy'=>true));
  2098. *
  2099. * // HTTP GET Method
  2100. * $html = $c->get('http://example.com');
  2101. * // HTTP POST Method
  2102. * $html = $c->post('http://example.com/', array('q'=>'words', 'name'=>'moodle'));
  2103. * // HTTP PUT Method
  2104. * $html = $c->put('http://example.com/', array('file'=>'/var/www/test.txt');
  2105. * </code>
  2106. *
  2107. * @package core
  2108. * @subpackage file
  2109. * @author Dongsheng Cai <dongsheng@cvs.moodle.org>
  2110. * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
  2111. */
  2112. class curl {
  2113. /** @var bool */
  2114. public $cache = false;
  2115. public $proxy = false;
  2116. /** @var string */
  2117. public $version = '0.4 dev';
  2118. /** @var array */
  2119. public $response = array();
  2120. public $header = array();
  2121. /** @var string */
  2122. public $info;
  2123. public $error;
  2124. /** @var array */
  2125. private $options;
  2126. /** @var string */
  2127. private $proxy_host = '';
  2128. private $proxy_auth = '';
  2129. private $proxy_type = '';
  2130. /** @var bool */
  2131. private $debug = false;
  2132. private $cookie = false;
  2133. /**
  2134. * @global object
  2135. * @param array $options
  2136. */
  2137. public function __construct($options = array()){
  2138. global $CFG;
  2139. if (!function_exists('curl_init')) {
  2140. $this->error = 'cURL module must be enabled!';
  2141. trigger_error($this->error, E_USER_ERROR);
  2142. return false;
  2143. }
  2144. // the options of curl should be init here.
  2145. $this->resetopt();
  2146. if (!empty($options['debug'])) {
  2147. $this->debug = true;
  2148. }
  2149. if(!empty($options['cookie'])) {
  2150. if($options['cookie'] === true) {
  2151. $this->cookie = $CFG->dataroot.'/curl_cookie.txt';
  2152. } else {
  2153. $this->cookie = $options['cookie'];
  2154. }
  2155. }
  2156. if (!empty($options['cache'])) {
  2157. if (class_exists('curl_cache')) {
  2158. if (!empty($options['module_cache'])) {
  2159. $this->cache = new curl_cache($options['module_cache']);
  2160. } else {
  2161. $this->cache = new curl_cache('misc');
  2162. }
  2163. }
  2164. }
  2165. if (!empty($CFG->proxyhost)) {
  2166. if (empty($CFG->proxyport)) {
  2167. $this->proxy_host = $CFG->proxyhost;
  2168. } else {
  2169. $this->proxy_host = $CFG->proxyhost.':'.$CFG->proxyport;
  2170. }
  2171. if (!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) {
  2172. $this->proxy_auth = $CFG->proxyuser.':'.$CFG->proxypassword;
  2173. $this->setopt(array(
  2174. 'proxyauth'=> CURLAUTH_BASIC | CURLAUTH_NTLM,
  2175. 'proxyuserpwd'=>$this->proxy_auth));
  2176. }
  2177. if (!empty($CFG->proxytype)) {
  2178. if ($CFG->proxytype == 'SOCKS5') {
  2179. $this->proxy_type = CURLPROXY_SOCKS5;
  2180. } else {
  2181. $this->proxy_type = CURLPROXY_HTTP;
  2182. $this->setopt(array('httpproxytunnel'=>false));
  2183. }
  2184. $this->setopt(array('proxytype'=>$this->proxy_type));
  2185. }
  2186. }
  2187. if (!empty($this->proxy_host)) {
  2188. $this->proxy = array('proxy'=>$this->proxy_host);
  2189. }
  2190. }
  2191. /**
  2192. * Resets the CURL options that have already been set
  2193. */
  2194. public function resetopt(){
  2195. $this->options = array();
  2196. $this->options['CURLOPT_USERAGENT'] = 'MoodleBot/1.0';
  2197. // True to include the header in the output
  2198. $this->options['CURLOPT_HEADER'] = 0;
  2199. // True to Exclude the body from the output
  2200. $this->options['CURLOPT_NOBODY'] = 0;
  2201. // TRUE to follow any "Location: " header that the server
  2202. // sends as part of the HTTP header (note this is recursive,
  2203. // PHP will follow as many "Location: " headers that it is sent,
  2204. // unless CURLOPT_MAXREDIRS is set).
  2205. //$this->options['CURLOPT_FOLLOWLOCATION'] = 1;
  2206. $this->options['CURLOPT_MAXREDIRS'] = 10;
  2207. $this->options['CURLOPT_ENCODING'] = '';
  2208. // TRUE to return the transfer as a string of the return
  2209. // value of curl_exec() instead of outputting it out directly.
  2210. $this->options['CURLOPT_RETURNTRANSFER'] = 1;
  2211. $this->options['CURLOPT_BINARYTRANSFER'] = 0;
  2212. $this->options['CURLOPT_SSL_VERIFYPEER'] = 0;
  2213. $this->options['CURLOPT_SSL_VERIFYHOST'] = 2;
  2214. $this->options['CURLOPT_CONNECTTIMEOUT'] = 30;
  2215. }
  2216. /**
  2217. * Reset Cookie
  2218. */
  2219. public function resetcookie() {
  2220. if (!empty($this->cookie)) {
  2221. if (is_file($this->cookie)) {
  2222. $fp = fopen($this->cookie, 'w');
  2223. if (!empty($fp)) {
  2224. fwrite($fp, '');
  2225. fclose($fp);
  2226. }
  2227. }
  2228. }
  2229. }
  2230. /**
  2231. * Set curl options
  2232. *
  2233. * @param array $options If array is null, this function will
  2234. * reset the options to default value.
  2235. *
  2236. */
  2237. public function setopt($options = array()) {
  2238. if (is_array($options)) {
  2239. foreach($options as $name => $val){
  2240. if (stripos($name, 'CURLOPT_') === false) {
  2241. $name = strtoupper('CURLOPT_'.$name);
  2242. }
  2243. $this->options[$name] = $val;
  2244. }
  2245. }
  2246. }
  2247. /**
  2248. * Reset http method
  2249. *
  2250. */
  2251. public function cleanopt(){
  2252. unset($this->options['CURLOPT_HTTPGET']);
  2253. unset($this->options['CURLOPT_POST']);
  2254. unset($this->options['CURLOPT_POSTFIELDS']);
  2255. unset($this->options['CURLOPT_PUT']);
  2256. unset($this->options['CURLOPT_INFILE']);
  2257. unset($this->options['CURLOPT_INFILESIZE']);
  2258. unset($this->options['CURLOPT_CUSTOMREQUEST']);
  2259. }
  2260. /**
  2261. * Set HTTP Request Header
  2262. *
  2263. * @param array $headers
  2264. *
  2265. */
  2266. public function setHeader($header) {
  2267. if (is_array($header)){
  2268. foreach ($header as $v) {
  2269. $this->setHeader($v);
  2270. }
  2271. } else {
  2272. $this->header[] = $header;
  2273. }
  2274. }
  2275. /**
  2276. * Set HTTP Response Header
  2277. *
  2278. */
  2279. public function getResponse(){
  2280. return $this->response;
  2281. }
  2282. /**
  2283. * private callback function
  2284. * Formatting HTTP Response Header
  2285. *
  2286. * @param mixed $ch Apparently not used
  2287. * @param string $header
  2288. * @return int The strlen of the header
  2289. */
  2290. private function formatHeader($ch, $header)
  2291. {
  2292. $this->count++;
  2293. if (strlen($header) > 2) {
  2294. list($key, $value) = explode(" ", rtrim($header, "\r\n"), 2);
  2295. $key = rtrim($key, ':');
  2296. if (!empty($this->response[$key])) {
  2297. if (is_array($this->response[$key])){
  2298. $this->response[$key][] = $value;
  2299. } else {
  2300. $tmp = $this->response[$key];
  2301. $this->response[$key] = array();
  2302. $this->response[$key][] = $tmp;
  2303. $this->response[$key][] = $value;
  2304. }
  2305. } else {
  2306. $this->response[$key] = $value;
  2307. }
  2308. }
  2309. return strlen($header);
  2310. }
  2311. /**
  2312. * Set options for individual curl instance
  2313. *
  2314. * @param object $curl A curl handle
  2315. * @param array $options
  2316. * @return object The curl handle
  2317. */
  2318. private function apply_opt($curl, $options) {
  2319. // Clean up
  2320. $this->cleanopt();
  2321. // set cookie
  2322. if (!empty($this->cookie) || !empty($options['cookie'])) {
  2323. $this->setopt(array('cookiejar'=>$this->cookie,
  2324. 'cookiefile'=>$this->cookie
  2325. ));
  2326. }
  2327. // set proxy
  2328. if (!empty($this->proxy) || !empty($options['proxy'])) {
  2329. $this->setopt($this->proxy);
  2330. }
  2331. $this->setopt($options);
  2332. // reset before set options
  2333. curl_setopt($curl, CURLOPT_HEADERFUNCTION, array(&$this,'formatHeader'));
  2334. // set headers
  2335. if (empty($this->header)){
  2336. $this->setHeader(array(
  2337. 'User-Agent: MoodleBot/1.0',
  2338. 'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7',
  2339. 'Connection: keep-alive'
  2340. ));
  2341. }
  2342. curl_setopt($curl, CURLOPT_HTTPHEADER, $this->header);
  2343. if ($this->debug){
  2344. echo '<h1>Options</h1>';
  2345. var_dump($this->options);
  2346. echo '<h1>Header</h1>';
  2347. var_dump($this->header);
  2348. }
  2349. // set options
  2350. foreach($this->options as $name => $val) {
  2351. if (is_string($name)) {
  2352. $name = constant(strtoupper($name));
  2353. }
  2354. curl_setopt($curl, $name, $val);
  2355. }
  2356. return $curl;
  2357. }
  2358. /**
  2359. * Download multiple files in parallel
  2360. *
  2361. * Calls {@link multi()} with specific download headers
  2362. *
  2363. * <code>
  2364. * $c = new curl;
  2365. * $c->download(array(
  2366. * array('url'=>'http://localhost/', 'file'=>fopen('a', 'wb')),
  2367. * array('url'=>'http://localhost/20/', 'file'=>fopen('b', 'wb'))
  2368. * ));
  2369. * </code>
  2370. *
  2371. * @param array $requests An array of files to request
  2372. * @param array $options An array of options to set
  2373. * @return array An array of results
  2374. */
  2375. public function download($requests, $options = array()) {
  2376. $options['CURLOPT_BINARYTRANSFER'] = 1;
  2377. $options['RETURNTRANSFER'] = false;
  2378. return $this->multi($requests, $options);
  2379. }
  2380. /*
  2381. * Mulit HTTP Requests
  2382. * This function could run multi-requests in parallel.
  2383. *
  2384. * @param array $requests An array of files to request
  2385. * @param array $options An array of options to set
  2386. * @return array An array of results
  2387. */
  2388. protected function multi($requests, $options = array()) {
  2389. $count = count($requests);
  2390. $handles = array();
  2391. $results = array();
  2392. $main = curl_multi_init();
  2393. for ($i = 0; $i < $count; $i++) {
  2394. $url = $requests[$i];
  2395. foreach($url as $n=>$v){
  2396. $options[$n] = $url[$n];
  2397. }
  2398. $handles[$i] = curl_init($url['url']);
  2399. $this->apply_opt($handles[$i], $options);
  2400. curl_multi_add_handle($main, $handles[$i]);
  2401. }
  2402. $running = 0;
  2403. do {
  2404. curl_multi_exec($main, $running);
  2405. } while($running > 0);
  2406. for ($i = 0; $i < $count; $i++) {
  2407. if (!empty($options['CURLOPT_RETURNTRANSFER'])) {
  2408. $results[] = true;
  2409. } else {
  2410. $results[] = curl_multi_getcontent($handles[$i]);
  2411. }
  2412. curl_multi_remove_handle($main, $handles[$i]);
  2413. }
  2414. curl_multi_close($main);
  2415. return $results;
  2416. }
  2417. /**
  2418. * Single HTTP Request
  2419. *
  2420. * @param string $url The URL to request
  2421. * @param array $options
  2422. * @return bool
  2423. */
  2424. protected function request($url, $options = array()){
  2425. // create curl instance
  2426. $curl = curl_init($url);
  2427. $options['url'] = $url;
  2428. $this->apply_opt($curl, $options);
  2429. if ($this->cache && $ret = $this->cache->get($this->options)) {
  2430. return $ret;
  2431. } else {
  2432. $ret = curl_exec($curl);
  2433. if ($this->cache) {
  2434. $this->cache->set($this->options, $ret);
  2435. }
  2436. }
  2437. $this->info = curl_getinfo($curl);
  2438. $this->error = curl_error($curl);
  2439. if ($this->debug){
  2440. echo '<h1>Return Data</h1>';
  2441. var_dump($ret);
  2442. echo '<h1>Info</h1>';
  2443. var_dump($this->info);
  2444. echo '<h1>Error</h1>';
  2445. var_dump($this->error);
  2446. }
  2447. curl_close($curl);
  2448. if (empty($this->error)){
  2449. return $ret;
  2450. } else {
  2451. return $this->error;
  2452. // exception is not ajax friendly
  2453. //throw new moodle_exception($this->error, 'curl');
  2454. }
  2455. }
  2456. /**
  2457. * HTTP HEAD method
  2458. *
  2459. * @see request()
  2460. *
  2461. * @param string $url
  2462. * @param array $options
  2463. * @return bool
  2464. */
  2465. public function head($url, $options = array()){
  2466. $options['CURLOPT_HTTPGET'] = 0;
  2467. $options['CURLOPT_HEADER'] = 1;
  2468. $options['CURLOPT_NOBODY'] = 1;
  2469. return $this->request($url, $options);
  2470. }
  2471. /**
  2472. * HTTP POST method
  2473. *
  2474. * @param string $url
  2475. * @param array|string $params
  2476. * @param array $options
  2477. * @return bool
  2478. */
  2479. public function post($url, $params = '', $options = array()){
  2480. $options['CURLOPT_POST'] = 1;
  2481. if (is_array($params)) {
  2482. $this->_tmp_file_post_params = array();
  2483. foreach ($params as $key => $value) {
  2484. if ($value instanceof stored_file) {
  2485. $value->add_to_curl_request($this, $key);
  2486. } else {
  2487. $this->_tmp_file_post_params[$key] = $value;
  2488. }
  2489. }
  2490. $options['CURLOPT_POSTFIELDS'] = $this->_tmp_file_post_params;
  2491. unset($this->_tmp_file_post_params);
  2492. } else {
  2493. // $params is the raw post data
  2494. $options['CURLOPT_POSTFIELDS'] = $params;
  2495. }
  2496. return $this->request($url, $options);
  2497. }
  2498. /**
  2499. * HTTP GET method
  2500. *
  2501. * @param string $url
  2502. * @param array $params
  2503. * @param array $options
  2504. * @return bool
  2505. */
  2506. public function get($url, $params = array(), $options = array()){
  2507. $options['CURLOPT_HTTPGET'] = 1;
  2508. if (!empty($params)){
  2509. $url .= (stripos($url, '?') !== false) ? '&' : '?';
  2510. $url .= http_build_query($params, '', '&');
  2511. }
  2512. return $this->request($url, $options);
  2513. }
  2514. /**
  2515. * HTTP PUT method
  2516. *
  2517. * @param string $url
  2518. * @param array $params
  2519. * @param array $options
  2520. * @return bool
  2521. */
  2522. public function put($url, $params = array(), $options = array()){
  2523. $file = $params['file'];
  2524. if (!is_file($file)){
  2525. return null;
  2526. }
  2527. $fp = fopen($file, 'r');
  2528. $size = filesize($file);
  2529. $options['CURLOPT_PUT'] = 1;
  2530. $options['CURLOPT_INFILESIZE'] = $size;
  2531. $options['CURLOPT_INFILE'] = $fp;
  2532. if (!isset($this->options['CURLOPT_USERPWD'])){
  2533. $this->setopt(array('CURLOPT_USERPWD'=>'anonymous: noreply@moodle.org'));
  2534. }
  2535. $ret = $this->request($url, $options);
  2536. fclose($fp);
  2537. return $ret;
  2538. }
  2539. /**
  2540. * HTTP DELETE method
  2541. *
  2542. * @param string $url
  2543. * @param array $params
  2544. * @param array $options
  2545. * @return bool
  2546. */
  2547. public function delete($url, $param = array(), $options = array()){
  2548. $options['CURLOPT_CUSTOMREQUEST'] = 'DELETE';
  2549. if (!isset($options['CURLOPT_USERPWD'])) {
  2550. $options['CURLOPT_USERPWD'] = 'anonymous: noreply@moodle.org';
  2551. }
  2552. $ret = $this->request($url, $options);
  2553. return $ret;
  2554. }
  2555. /**
  2556. * HTTP TRACE method
  2557. *
  2558. * @param string $url
  2559. * @param array $options
  2560. * @return bool
  2561. */
  2562. public function trace($url, $options = array()){
  2563. $options['CURLOPT_CUSTOMREQUEST'] = 'TRACE';
  2564. $ret = $this->request($url, $options);
  2565. return $ret;
  2566. }
  2567. /**
  2568. * HTTP OPTIONS method
  2569. *
  2570. * @param string $url
  2571. * @param array $options
  2572. * @return bool
  2573. */
  2574. public function options($url, $options = array()){
  2575. $options['CURLOPT_CUSTOMREQUEST'] = 'OPTIONS';
  2576. $ret = $this->request($url, $options);
  2577. return $ret;
  2578. }
  2579. public function get_info() {
  2580. return $this->info;
  2581. }
  2582. }
  2583. /**
  2584. * This class is used by cURL class, use case:
  2585. *
  2586. * <code>
  2587. * $CFG->repositorycacheexpire = 120;
  2588. * $CFG->curlcache = 120;
  2589. *
  2590. * $c = new curl(array('cache'=>true), 'module_cache'=>'repository');
  2591. * $ret = $c->get('http://www.google.com');
  2592. * </code>
  2593. *
  2594. * @package core
  2595. * @subpackage file
  2596. * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
  2597. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  2598. */
  2599. class curl_cache {
  2600. /** @var string */
  2601. public $dir = '';
  2602. /**
  2603. *
  2604. * @global object
  2605. * @param string @module which module is using curl_cache
  2606. *
  2607. */
  2608. function __construct($module = 'repository'){
  2609. global $CFG;
  2610. if (!empty($module)) {
  2611. $this->dir = $CFG->dataroot.'/cache/'.$module.'/';
  2612. } else {
  2613. $this->dir = $CFG->dataroot.'/cache/misc/';
  2614. }
  2615. if (!file_exists($this->dir)) {
  2616. mkdir($this->dir, $CFG->directorypermissions, true);
  2617. }
  2618. if ($module == 'repository') {
  2619. if (empty($CFG->repositorycacheexpire)) {
  2620. $CFG->repositorycacheexpire = 120;
  2621. }
  2622. $this->ttl = $CFG->repositorycacheexpire;
  2623. } else {
  2624. if (empty($CFG->curlcache)) {
  2625. $CFG->curlcache = 120;
  2626. }
  2627. $this->ttl = $CFG->curlcache;
  2628. }
  2629. }
  2630. /**
  2631. * Get cached value
  2632. *
  2633. * @global object
  2634. * @global object
  2635. * @param mixed $param
  2636. * @return bool|string
  2637. */
  2638. public function get($param){
  2639. global $CFG, $USER;
  2640. $this->cleanup($this->ttl);
  2641. $filename = 'u'.$USER->id.'_'.md5(serialize($param));
  2642. if(file_exists($this->dir.$filename)) {
  2643. $lasttime = filemtime($this->dir.$filename);
  2644. if(time()-$lasttime > $this->ttl)
  2645. {
  2646. return false;
  2647. } else {
  2648. $fp = fopen($this->dir.$filename, 'r');
  2649. $size = filesize($this->dir.$filename);
  2650. $content = fread($fp, $size);
  2651. return unserialize($content);
  2652. }
  2653. }
  2654. return false;
  2655. }
  2656. /**
  2657. * Set cache value
  2658. *
  2659. * @global object $CFG
  2660. * @global object $USER
  2661. * @param mixed $param
  2662. * @param mixed $val
  2663. */
  2664. public function set($param, $val){
  2665. global $CFG, $USER;
  2666. $filename = 'u'.$USER->id.'_'.md5(serialize($param));
  2667. $fp = fopen($this->dir.$filename, 'w');
  2668. fwrite($fp, serialize($val));
  2669. fclose($fp);
  2670. }
  2671. /**
  2672. * Remove cache files
  2673. *
  2674. * @param int $expire The number os seconds before expiry
  2675. */
  2676. public function cleanup($expire){
  2677. if($dir = opendir($this->dir)){
  2678. while (false !== ($file = readdir($dir))) {
  2679. if(!is_dir($file) && $file != '.' && $file != '..') {
  2680. $lasttime = @filemtime($this->dir.$file);
  2681. if(time() - $lasttime > $expire){
  2682. @unlink($this->dir.$file);
  2683. }
  2684. }
  2685. }
  2686. }
  2687. }
  2688. /**
  2689. * delete current user's cache file
  2690. *
  2691. * @global object $CFG
  2692. * @global object $USER
  2693. */
  2694. public function refresh(){
  2695. global $CFG, $USER;
  2696. if($dir = opendir($this->dir)){
  2697. while (false !== ($file = readdir($dir))) {
  2698. if(!is_dir($file) && $file != '.' && $file != '..') {
  2699. if(strpos($file, 'u'.$USER->id.'_')!==false){
  2700. @unlink($this->dir.$file);
  2701. }
  2702. }
  2703. }
  2704. }
  2705. }
  2706. }
  2707. /**
  2708. * This class is used to parse lib/file/file_types.mm which help get file
  2709. * extensions by file types.
  2710. * The file_types.mm file can be edited by freemind in graphic environment.
  2711. *
  2712. * @package core
  2713. * @subpackage file
  2714. * @copyright 2009 Dongsheng Cai <dongsheng@moodle.com>
  2715. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  2716. */
  2717. class filetype_parser {
  2718. /**
  2719. * Check file_types.mm file, setup variables
  2720. *
  2721. * @global object $CFG
  2722. * @param string $file
  2723. */
  2724. public function __construct($file = '') {
  2725. global $CFG;
  2726. if (empty($file)) {
  2727. $this->file = $CFG->libdir.'/filestorage/file_types.mm';
  2728. } else {
  2729. $this->file = $file;
  2730. }
  2731. $this->tree = array();
  2732. $this->result = array();
  2733. }
  2734. /**
  2735. * A private function to browse xml nodes
  2736. *
  2737. * @param array $parent
  2738. * @param array $types
  2739. */
  2740. private function _browse_nodes($parent, $types) {
  2741. $key = (string)$parent['TEXT'];
  2742. if(isset($parent->node)) {
  2743. $this->tree[$key] = array();
  2744. if (in_array((string)$parent['TEXT'], $types)) {
  2745. $this->_select_nodes($parent, $this->result);
  2746. } else {
  2747. foreach($parent->node as $v){
  2748. $this->_browse_nodes($v, $types);
  2749. }
  2750. }
  2751. } else {
  2752. $this->tree[] = $key;
  2753. }
  2754. }
  2755. /**
  2756. * A private function to select text nodes
  2757. *
  2758. * @param array $parent
  2759. */
  2760. private function _select_nodes($parent){
  2761. if(isset($parent->node)) {
  2762. foreach($parent->node as $v){
  2763. $this->_select_nodes($v, $this->result);
  2764. }
  2765. } else {
  2766. $this->result[] = (string)$parent['TEXT'];
  2767. }
  2768. }
  2769. /**
  2770. * Get file extensions by file types names.
  2771. *
  2772. * @param array $types
  2773. * @return mixed
  2774. */
  2775. public function get_extensions($types) {
  2776. if (!is_array($types)) {
  2777. $types = array($types);
  2778. }
  2779. $this->result = array();
  2780. if ((is_array($types) && in_array('*', $types)) ||
  2781. $types == '*' || empty($types)) {
  2782. return array('*');
  2783. }
  2784. foreach ($types as $key=>$value){
  2785. if (strpos($value, '.') !== false) {
  2786. $this->result[] = $value;
  2787. unset($types[$key]);
  2788. }
  2789. }
  2790. if (file_exists($this->file)) {
  2791. $xml = simplexml_load_file($this->file);
  2792. foreach($xml->node->node as $v){
  2793. if (in_array((string)$v['TEXT'], $types)) {
  2794. $this->_select_nodes($v);
  2795. } else {
  2796. $this->_browse_nodes($v, $types);
  2797. }
  2798. }
  2799. } else {
  2800. exit('Failed to open file lib/filestorage/file_types.mm');
  2801. }
  2802. return $this->result;
  2803. }
  2804. }