PageRenderTime 38ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/filelib.php

https://github.com/glovenone/moodle
PHP | 3128 lines | 2000 code | 278 blank | 850 comment | 456 complexity | f4972d74b7f0eac5d8867375b1253427 MD5 | raw file
Possible License(s): GPL-3.0, LGPL-2.1, BSD-3-Clause, AGPL-3.0, MPL-2.0-no-copyleft-exception, Apache-2.0
  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. * @param string $url file url starting with http(s)://
  803. * @param array $headers http headers, null if none. If set, should be an
  804. * associative array of header name => value pairs.
  805. * @param array $postdata array means use POST request with given parameters
  806. * @param bool $fullresponse return headers, responses, etc in a similar way snoopy does
  807. * (if false, just returns content)
  808. * @param int $timeout timeout for complete download process including all file transfer
  809. * (default 5 minutes)
  810. * @param int $connecttimeout timeout for connection to server; this is the timeout that
  811. * usually happens if the remote server is completely down (default 20 seconds);
  812. * may not work when using proxy
  813. * @param bool $skipcertverify If true, the peer's SSL certificate will not be checked.
  814. * Only use this when already in a trusted location.
  815. * @param string $tofile store the downloaded content to file instead of returning it.
  816. * @param bool $calctimeout false by default, true enables an extra head request to try and determine
  817. * filesize and appropriately larger timeout based on $CFG->curltimeoutkbitrate
  818. * @return mixed false if request failed or content of the file as string if ok. True if file downloaded into $tofile successfully.
  819. */
  820. function download_file_content($url, $headers=null, $postdata=null, $fullresponse=false, $timeout=300, $connecttimeout=20, $skipcertverify=false, $tofile=NULL, $calctimeout=false) {
  821. global $CFG;
  822. // some extra security
  823. $newlines = array("\r", "\n");
  824. if (is_array($headers) ) {
  825. foreach ($headers as $key => $value) {
  826. $headers[$key] = str_replace($newlines, '', $value);
  827. }
  828. }
  829. $url = str_replace($newlines, '', $url);
  830. if (!preg_match('|^https?://|i', $url)) {
  831. if ($fullresponse) {
  832. $response = new stdClass();
  833. $response->status = 0;
  834. $response->headers = array();
  835. $response->response_code = 'Invalid protocol specified in url';
  836. $response->results = '';
  837. $response->error = 'Invalid protocol specified in url';
  838. return $response;
  839. } else {
  840. return false;
  841. }
  842. }
  843. // check if proxy (if used) should be bypassed for this url
  844. $proxybypass = is_proxybypass($url);
  845. if (!$ch = curl_init($url)) {
  846. debugging('Can not init curl.');
  847. return false;
  848. }
  849. // set extra headers
  850. if (is_array($headers) ) {
  851. $headers2 = array();
  852. foreach ($headers as $key => $value) {
  853. $headers2[] = "$key: $value";
  854. }
  855. curl_setopt($ch, CURLOPT_HTTPHEADER, $headers2);
  856. }
  857. if ($skipcertverify) {
  858. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  859. }
  860. // use POST if requested
  861. if (is_array($postdata)) {
  862. $postdata = format_postdata_for_curlcall($postdata);
  863. curl_setopt($ch, CURLOPT_POST, true);
  864. curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
  865. }
  866. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  867. curl_setopt($ch, CURLOPT_HEADER, false);
  868. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $connecttimeout);
  869. if (!ini_get('open_basedir') and !ini_get('safe_mode')) {
  870. // TODO: add version test for '7.10.5'
  871. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
  872. curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
  873. }
  874. if (!empty($CFG->proxyhost) and !$proxybypass) {
  875. // SOCKS supported in PHP5 only
  876. if (!empty($CFG->proxytype) and ($CFG->proxytype == 'SOCKS5')) {
  877. if (defined('CURLPROXY_SOCKS5')) {
  878. curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
  879. } else {
  880. curl_close($ch);
  881. if ($fullresponse) {
  882. $response = new stdClass();
  883. $response->status = '0';
  884. $response->headers = array();
  885. $response->response_code = 'SOCKS5 proxy is not supported in PHP4';
  886. $response->results = '';
  887. $response->error = 'SOCKS5 proxy is not supported in PHP4';
  888. return $response;
  889. } else {
  890. debugging("SOCKS5 proxy is not supported in PHP4.", DEBUG_ALL);
  891. return false;
  892. }
  893. }
  894. }
  895. curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, false);
  896. if (empty($CFG->proxyport)) {
  897. curl_setopt($ch, CURLOPT_PROXY, $CFG->proxyhost);
  898. } else {
  899. curl_setopt($ch, CURLOPT_PROXY, $CFG->proxyhost.':'.$CFG->proxyport);
  900. }
  901. if (!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) {
  902. curl_setopt($ch, CURLOPT_PROXYUSERPWD, $CFG->proxyuser.':'.$CFG->proxypassword);
  903. if (defined('CURLOPT_PROXYAUTH')) {
  904. // any proxy authentication if PHP 5.1
  905. curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_BASIC | CURLAUTH_NTLM);
  906. }
  907. }
  908. }
  909. // set up header and content handlers
  910. $received = new stdClass();
  911. $received->headers = array(); // received headers array
  912. $received->tofile = $tofile;
  913. $received->fh = null;
  914. curl_setopt($ch, CURLOPT_HEADERFUNCTION, partial('download_file_content_header_handler', $received));
  915. if ($tofile) {
  916. curl_setopt($ch, CURLOPT_WRITEFUNCTION, partial('download_file_content_write_handler', $received));
  917. }
  918. if (!isset($CFG->curltimeoutkbitrate)) {
  919. //use very slow rate of 56kbps as a timeout speed when not set
  920. $bitrate = 56;
  921. } else {
  922. $bitrate = $CFG->curltimeoutkbitrate;
  923. }
  924. // try to calculate the proper amount for timeout from remote file size.
  925. // if disabled or zero, we won't do any checks nor head requests.
  926. if ($calctimeout && $bitrate > 0) {
  927. //setup header request only options
  928. curl_setopt_array ($ch, array(
  929. CURLOPT_RETURNTRANSFER => false,
  930. CURLOPT_NOBODY => true)
  931. );
  932. curl_exec($ch);
  933. $info = curl_getinfo($ch);
  934. $err = curl_error($ch);
  935. if ($err === '' && $info['download_content_length'] > 0) { //no curl errors
  936. $timeout = max($timeout, ceil($info['download_content_length'] * 8 / ($bitrate * 1024))); //adjust for large files only - take max timeout.
  937. }
  938. //reinstate affected curl options
  939. curl_setopt_array ($ch, array(
  940. CURLOPT_RETURNTRANSFER => true,
  941. CURLOPT_NOBODY => false)
  942. );
  943. }
  944. curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
  945. $result = curl_exec($ch);
  946. // try to detect encoding problems
  947. if ((curl_errno($ch) == 23 or curl_errno($ch) == 61) and defined('CURLOPT_ENCODING')) {
  948. curl_setopt($ch, CURLOPT_ENCODING, 'none');
  949. $result = curl_exec($ch);
  950. }
  951. if ($received->fh) {
  952. fclose($received->fh);
  953. }
  954. if (curl_errno($ch)) {
  955. $error = curl_error($ch);
  956. $error_no = curl_errno($ch);
  957. curl_close($ch);
  958. if ($fullresponse) {
  959. $response = new stdClass();
  960. if ($error_no == 28) {
  961. $response->status = '-100'; // mimic snoopy
  962. } else {
  963. $response->status = '0';
  964. }
  965. $response->headers = array();
  966. $response->response_code = $error;
  967. $response->results = false;
  968. $response->error = $error;
  969. return $response;
  970. } else {
  971. debugging("cURL request for \"$url\" failed with: $error ($error_no)", DEBUG_ALL);
  972. return false;
  973. }
  974. } else {
  975. $info = curl_getinfo($ch);
  976. curl_close($ch);
  977. if (empty($info['http_code'])) {
  978. // for security reasons we support only true http connections (Location: file:// exploit prevention)
  979. $response = new stdClass();
  980. $response->status = '0';
  981. $response->headers = array();
  982. $response->response_code = 'Unknown cURL error';
  983. $response->results = false; // do NOT change this, we really want to ignore the result!
  984. $response->error = 'Unknown cURL error';
  985. } else {
  986. $response = new stdClass();;
  987. $response->status = (string)$info['http_code'];
  988. $response->headers = $received->headers;
  989. $response->response_code = $received->headers[0];
  990. $response->results = $result;
  991. $response->error = '';
  992. }
  993. if ($fullresponse) {
  994. return $response;
  995. } else if ($info['http_code'] != 200) {
  996. debugging("cURL request for \"$url\" failed, HTTP response code: ".$response->response_code, DEBUG_ALL);
  997. return false;
  998. } else {
  999. return $response->results;
  1000. }
  1001. }
  1002. }
  1003. /**
  1004. * internal implementation
  1005. */
  1006. function download_file_content_header_handler($received, $ch, $header) {
  1007. $received->headers[] = $header;
  1008. return strlen($header);
  1009. }
  1010. /**
  1011. * internal implementation
  1012. */
  1013. function download_file_content_write_handler($received, $ch, $data) {
  1014. if (!$received->fh) {
  1015. $received->fh = fopen($received->tofile, 'w');
  1016. if ($received->fh === false) {
  1017. // bad luck, file creation or overriding failed
  1018. return 0;
  1019. }
  1020. }
  1021. if (fwrite($received->fh, $data) === false) {
  1022. // bad luck, write failed, let's abort completely
  1023. return 0;
  1024. }
  1025. return strlen($data);
  1026. }
  1027. /**
  1028. * @return array List of information about file types based on extensions.
  1029. * Associative array of extension (lower-case) to associative array
  1030. * from 'element name' to data. Current element names are 'type' and 'icon'.
  1031. * Unknown types should use the 'xxx' entry which includes defaults.
  1032. */
  1033. function get_mimetypes_array() {
  1034. static $mimearray = array (
  1035. 'xxx' => array ('type'=>'document/unknown', 'icon'=>'unknown'),
  1036. '3gp' => array ('type'=>'video/quicktime', 'icon'=>'video'),
  1037. 'aac' => array ('type'=>'audio/aac', 'icon'=>'audio'),
  1038. 'ai' => array ('type'=>'application/postscript', 'icon'=>'image'),
  1039. 'aif' => array ('type'=>'audio/x-aiff', 'icon'=>'audio'),
  1040. 'aiff' => array ('type'=>'audio/x-aiff', 'icon'=>'audio'),
  1041. 'aifc' => array ('type'=>'audio/x-aiff', 'icon'=>'audio'),
  1042. 'applescript' => array ('type'=>'text/plain', 'icon'=>'text'),
  1043. 'asc' => array ('type'=>'text/plain', 'icon'=>'text'),
  1044. 'asm' => array ('type'=>'text/plain', 'icon'=>'text'),
  1045. 'au' => array ('type'=>'audio/au', 'icon'=>'audio'),
  1046. 'avi' => array ('type'=>'video/x-ms-wm', 'icon'=>'avi'),
  1047. 'bmp' => array ('type'=>'image/bmp', 'icon'=>'image'),
  1048. 'c' => array ('type'=>'text/plain', 'icon'=>'text'),
  1049. 'cct' => array ('type'=>'shockwave/director', 'icon'=>'flash'),
  1050. 'cpp' => array ('type'=>'text/plain', 'icon'=>'text'),
  1051. 'cs' => array ('type'=>'application/x-csh', 'icon'=>'text'),
  1052. 'css' => array ('type'=>'text/css', 'icon'=>'text'),
  1053. 'csv' => array ('type'=>'text/csv', 'icon'=>'excel'),
  1054. 'dv' => array ('type'=>'video/x-dv', 'icon'=>'video'),
  1055. 'dmg' => array ('type'=>'application/octet-stream', 'icon'=>'dmg'),
  1056. 'doc' => array ('type'=>'application/msword', 'icon'=>'word'),
  1057. 'docx' => array ('type'=>'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'icon'=>'docx'),
  1058. 'docm' => array ('type'=>'application/vnd.ms-word.document.macroEnabled.12', 'icon'=>'docm'),
  1059. 'dotx' => array ('type'=>'application/vnd.openxmlformats-officedocument.wordprocessingml.template', 'icon'=>'dotx'),
  1060. 'dotm' => array ('type'=>'application/vnd.ms-word.template.macroEnabled.12', 'icon'=>'dotm'),
  1061. 'dcr' => array ('type'=>'application/x-director', 'icon'=>'flash'),
  1062. 'dif' => array ('type'=>'video/x-dv', 'icon'=>'video'),
  1063. 'dir' => array ('type'=>'application/x-director', 'icon'=>'flash'),
  1064. 'dxr' => array ('type'=>'application/x-director', 'icon'=>'flash'),
  1065. 'eps' => array ('type'=>'application/postscript', 'icon'=>'pdf'),
  1066. 'fdf' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
  1067. 'flv' => array ('type'=>'video/x-flv', 'icon'=>'video'),
  1068. 'f4v' => array ('type'=>'video/mp4', 'icon'=>'video'),
  1069. 'gif' => array ('type'=>'image/gif', 'icon'=>'image'),
  1070. 'gtar' => array ('type'=>'application/x-gtar', 'icon'=>'zip'),
  1071. 'tgz' => array ('type'=>'application/g-zip', 'icon'=>'zip'),
  1072. 'gz' => array ('type'=>'application/g-zip', 'icon'=>'zip'),
  1073. 'gzip' => array ('type'=>'application/g-zip', 'icon'=>'zip'),
  1074. 'h' => array ('type'=>'text/plain', 'icon'=>'text'),
  1075. 'hpp' => array ('type'=>'text/plain', 'icon'=>'text'),
  1076. 'hqx' => array ('type'=>'application/mac-binhex40', 'icon'=>'zip'),
  1077. 'htc' => array ('type'=>'text/x-component', 'icon'=>'text'),
  1078. 'html' => array ('type'=>'text/html', 'icon'=>'html'),
  1079. 'xhtml'=> array ('type'=>'application/xhtml+xml', 'icon'=>'html'),
  1080. 'htm' => array ('type'=>'text/html', 'icon'=>'html'),
  1081. 'ico' => array ('type'=>'image/vnd.microsoft.icon', 'icon'=>'image'),
  1082. 'ics' => array ('type'=>'text/calendar', 'icon'=>'text'),
  1083. 'isf' => array ('type'=>'application/inspiration', 'icon'=>'isf'),
  1084. 'ist' => array ('type'=>'application/inspiration.template', 'icon'=>'isf'),
  1085. 'java' => array ('type'=>'text/plain', 'icon'=>'text'),
  1086. 'jcb' => array ('type'=>'text/xml', 'icon'=>'jcb'),
  1087. 'jcl' => array ('type'=>'text/xml', 'icon'=>'jcl'),
  1088. 'jcw' => array ('type'=>'text/xml', 'icon'=>'jcw'),
  1089. 'jmt' => array ('type'=>'text/xml', 'icon'=>'jmt'),
  1090. 'jmx' => array ('type'=>'text/xml', 'icon'=>'jmx'),
  1091. 'jpe' => array ('type'=>'image/jpeg', 'icon'=>'image'),
  1092. 'jpeg' => array ('type'=>'image/jpeg', 'icon'=>'image'),
  1093. 'jpg' => array ('type'=>'image/jpeg', 'icon'=>'image'),
  1094. 'jqz' => array ('type'=>'text/xml', 'icon'=>'jqz'),
  1095. 'js' => array ('type'=>'application/x-javascript', 'icon'=>'text'),
  1096. 'latex'=> array ('type'=>'application/x-latex', 'icon'=>'text'),
  1097. 'm' => array ('type'=>'text/plain', 'icon'=>'text'),
  1098. 'mbz' => array ('type'=>'application/vnd.moodle.backup', 'icon'=>'moodle'),
  1099. 'mov' => array ('type'=>'video/quicktime', 'icon'=>'video'),
  1100. 'movie'=> array ('type'=>'video/x-sgi-movie', 'icon'=>'video'),
  1101. 'm3u' => array ('type'=>'audio/x-mpegurl', 'icon'=>'audio'),
  1102. 'mp3' => array ('type'=>'audio/mp3', 'icon'=>'audio'),
  1103. 'mp4' => array ('type'=>'video/mp4', 'icon'=>'video'),
  1104. 'm4v' => array ('type'=>'video/mp4', 'icon'=>'video'),
  1105. 'm4a' => array ('type'=>'audio/mp4', 'icon'=>'audio'),
  1106. 'mpeg' => array ('type'=>'video/mpeg', 'icon'=>'video'),
  1107. 'mpe' => array ('type'=>'video/mpeg', 'icon'=>'video'),
  1108. 'mpg' => array ('type'=>'video/mpeg', 'icon'=>'video'),
  1109. 'odt' => array ('type'=>'application/vnd.oasis.opendocument.text', 'icon'=>'odt'),
  1110. 'ott' => array ('type'=>'application/vnd.oasis.opendocument.text-template', 'icon'=>'odt'),
  1111. 'oth' => array ('type'=>'application/vnd.oasis.opendocument.text-web', 'icon'=>'odt'),
  1112. 'odm' => array ('type'=>'application/vnd.oasis.opendocument.text-master', 'icon'=>'odm'),
  1113. 'odg' => array ('type'=>'application/vnd.oasis.opendocument.graphics', 'icon'=>'odg'),
  1114. 'otg' => array ('type'=>'application/vnd.oasis.opendocument.graphics-template', 'icon'=>'odg'),
  1115. 'odp' => array ('type'=>'application/vnd.oasis.opendocument.presentation', 'icon'=>'odp'),
  1116. 'otp' => array ('type'=>'application/vnd.oasis.opendocument.presentation-template', 'icon'=>'odp'),
  1117. 'ods' => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet', 'icon'=>'ods'),
  1118. 'ots' => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet-template', 'icon'=>'ods'),
  1119. 'odc' => array ('type'=>'application/vnd.oasis.opendocument.chart', 'icon'=>'odc'),
  1120. 'odf' => array ('type'=>'application/vnd.oasis.opendocument.formula', 'icon'=>'odf'),
  1121. 'odb' => array ('type'=>'application/vnd.oasis.opendocument.database', 'icon'=>'odb'),
  1122. 'odi' => array ('type'=>'application/vnd.oasis.opendocument.image', 'icon'=>'odi'),
  1123. 'oga' => array ('type'=>'audio/ogg', 'icon'=>'audio'),
  1124. 'ogg' => array ('type'=>'audio/ogg', 'icon'=>'audio'),
  1125. 'ogv' => array ('type'=>'video/ogg', 'icon'=>'video'),
  1126. 'pct' => array ('type'=>'image/pict', 'icon'=>'image'),
  1127. 'pdf' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
  1128. 'php' => array ('type'=>'text/plain', 'icon'=>'text'),
  1129. 'pic' => array ('type'=>'image/pict', 'icon'=>'image'),
  1130. 'pict' => array ('type'=>'image/pict', 'icon'=>'image'),
  1131. 'png' => array ('type'=>'image/png', 'icon'=>'image'),
  1132. 'pps' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'powerpoint'),
  1133. 'ppt' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'powerpoint'),
  1134. 'pptx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'icon'=>'pptx'),
  1135. 'pptm' => array ('type'=>'application/vnd.ms-powerpoint.presentation.macroEnabled.12', 'icon'=>'pptm'),
  1136. 'potx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.template', 'icon'=>'potx'),
  1137. 'potm' => array ('type'=>'application/vnd.ms-powerpoint.template.macroEnabled.12', 'icon'=>'potm'),
  1138. 'ppam' => array ('type'=>'application/vnd.ms-powerpoint.addin.macroEnabled.12', 'icon'=>'ppam'),
  1139. 'ppsx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.slideshow', 'icon'=>'ppsx'),
  1140. 'ppsm' => array ('type'=>'application/vnd.ms-powerpoint.slideshow.macroEnabled.12', 'icon'=>'ppsm'),
  1141. 'ps' => array ('type'=>'application/postscript', 'icon'=>'pdf'),
  1142. 'qt' => array ('type'=>'video/quicktime', 'icon'=>'video'),
  1143. 'ra' => array ('type'=>'audio/x-realaudio-plugin', 'icon'=>'audio'),
  1144. 'ram' => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'audio'),
  1145. 'rhb' => array ('type'=>'text/xml', 'icon'=>'xml'),
  1146. 'rm' => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'audio'),
  1147. 'rmvb' => array ('type'=>'application/vnd.rn-realmedia-vbr', 'icon'=>'video'),
  1148. 'rtf' => array ('type'=>'text/rtf', 'icon'=>'text'),
  1149. 'rtx' => array ('type'=>'text/richtext', 'icon'=>'text'),
  1150. 'rv' => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'video'),
  1151. 'sh' => array ('type'=>'application/x-sh', 'icon'=>'text'),
  1152. 'sit' => array ('type'=>'application/x-stuffit', 'icon'=>'zip'),
  1153. 'smi' => array ('type'=>'application/smil', 'icon'=>'text'),
  1154. 'smil' => array ('type'=>'application/smil', 'icon'=>'text'),
  1155. 'sqt' => array ('type'=>'text/xml', 'icon'=>'xml'),
  1156. 'svg' => array ('type'=>'image/svg+xml', 'icon'=>'image'),
  1157. 'svgz' => array ('type'=>'image/svg+xml', 'icon'=>'image'),
  1158. 'swa' => array ('type'=>'application/x-director', 'icon'=>'flash'),
  1159. 'swf' => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash'),
  1160. 'swfl' => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash'),
  1161. 'sxw' => array ('type'=>'application/vnd.sun.xml.writer', 'icon'=>'odt'),
  1162. 'stw' => array ('type'=>'application/vnd.sun.xml.writer.template', 'icon'=>'odt'),
  1163. 'sxc' => array ('type'=>'application/vnd.sun.xml.calc', 'icon'=>'odt'),
  1164. 'stc' => array ('type'=>'application/vnd.sun.xml.calc.template', 'icon'=>'odt'),
  1165. 'sxd' => array ('type'=>'application/vnd.sun.xml.draw', 'icon'=>'odt'),
  1166. 'std' => array ('type'=>'application/vnd.sun.xml.draw.template', 'icon'=>'odt'),
  1167. 'sxi' => array ('type'=>'application/vnd.sun.xml.impress', 'icon'=>'odt'),
  1168. 'sti' => array ('type'=>'application/vnd.sun.xml.impress.template', 'icon'=>'odt'),
  1169. 'sxg' => array ('type'=>'application/vnd.sun.xml.writer.global', 'icon'=>'odt'),
  1170. 'sxm' => array ('type'=>'application/vnd.sun.xml.math', 'icon'=>'odt'),
  1171. 'tar' => array ('type'=>'application/x-tar', 'icon'=>'zip'),
  1172. 'tif' => array ('type'=>'image/tiff', 'icon'=>'image'),
  1173. 'tiff' => array ('type'=>'image/tiff', 'icon'=>'image'),
  1174. 'tex' => array ('type'=>'application/x-tex', 'icon'=>'text'),
  1175. 'texi' => array ('type'=>'application/x-texinfo', 'icon'=>'text'),
  1176. 'texinfo' => array ('type'=>'application/x-texinfo', 'icon'=>'text'),
  1177. 'tsv' => array ('type'=>'text/tab-separated-values', 'icon'=>'text'),
  1178. 'txt' => array ('type'=>'text/plain', 'icon'=>'text'),
  1179. 'wav' => array ('type'=>'audio/wav', 'icon'=>'audio'),
  1180. 'webm' => array ('type'=>'video/webm', 'icon'=>'video'),
  1181. 'wmv' => array ('type'=>'video/x-ms-wmv', 'icon'=>'avi'),
  1182. 'asf' => array ('type'=>'video/x-ms-asf', 'icon'=>'avi'),
  1183. 'xdp' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
  1184. 'xfd' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
  1185. 'xfdf' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
  1186. 'xls' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'excel'),
  1187. 'xlsx' => array ('type'=>'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'icon'=>'xlsx'),
  1188. 'xlsm' => array ('type'=>'application/vnd.ms-excel.sheet.macroEnabled.12', 'icon'=>'xlsm'),
  1189. 'xltx' => array ('type'=>'application/vnd.openxmlformats-officedocument.spreadsheetml.template', 'icon'=>'xltx'),
  1190. 'xltm' => array ('type'=>'application/vnd.ms-excel.template.macroEnabled.12', 'icon'=>'xltm'),
  1191. 'xlsb' => array ('type'=>'application/vnd.ms-excel.sheet.binary.macroEnabled.12', 'icon'=>'xlsb'),
  1192. 'xlam' => array ('type'=>'application/vnd.ms-excel.addin.macroEnabled.12', 'icon'=>'xlam'),
  1193. 'xml' => array ('type'=>'application/xml', 'icon'=>'xml'),
  1194. 'xsl' => array ('type'=>'text/xml', 'icon'=>'xml'),
  1195. 'zip' => array ('type'=>'application/zip', 'icon'=>'zip')
  1196. );
  1197. return $mimearray;
  1198. }
  1199. /**
  1200. * Obtains information about a filetype based on its extension. Will
  1201. * use a default if no information is present about that particular
  1202. * extension.
  1203. *
  1204. * @param string $element Desired information (usually 'icon'
  1205. * for icon filename or 'type' for MIME type)
  1206. * @param string $filename Filename we're looking up
  1207. * @return string Requested piece of information from array
  1208. */
  1209. function mimeinfo($element, $filename) {
  1210. global $CFG;
  1211. $mimeinfo = get_mimetypes_array();
  1212. if (preg_match('/\.([a-z0-9]+)$/i', $filename, $match)) {
  1213. if (isset($mimeinfo[strtolower($match[1])][$element])) {
  1214. return $mimeinfo[strtolower($match[1])][$element];
  1215. } else {
  1216. if ($element == 'icon32') {
  1217. if (isset($mimeinfo[strtolower($match[1])]['icon'])) {
  1218. $filename = $mimeinfo[strtolower($match[1])]['icon'];
  1219. } else {
  1220. $filename = 'unknown';
  1221. }
  1222. $filename .= '-32';
  1223. if (file_exists($CFG->dirroot.'/pix/f/'.$filename.'.png') or file_exists($CFG->dirroot.'/pix/f/'.$filename.'.gif')) {
  1224. return $filename;
  1225. } else {
  1226. return 'unknown-32';
  1227. }
  1228. } else {
  1229. return $mimeinfo['xxx'][$element]; // By default
  1230. }
  1231. }
  1232. } else {
  1233. if ($element == 'icon32') {
  1234. return 'unknown-32';
  1235. }
  1236. return $mimeinfo['xxx'][$element]; // By default
  1237. }
  1238. }
  1239. /**
  1240. * Obtains information about a filetype based on the MIME type rather than
  1241. * the other way around.
  1242. *
  1243. * @param string $element Desired information (usually 'icon')
  1244. * @param string $mimetype MIME type we're looking up
  1245. * @return string Requested piece of information from array
  1246. */
  1247. function mimeinfo_from_type($element, $mimetype) {
  1248. $mimeinfo = get_mimetypes_array();
  1249. foreach($mimeinfo as $values) {
  1250. if ($values['type']==$mimetype) {
  1251. if (isset($values[$element])) {
  1252. return $values[$element];
  1253. }
  1254. break;
  1255. }
  1256. }
  1257. return $mimeinfo['xxx'][$element]; // Default
  1258. }
  1259. /**
  1260. * Get information about a filetype based on the icon file.
  1261. *
  1262. * @param string $element Desired information (usually 'icon')
  1263. * @param string $icon Icon file name without extension
  1264. * @param boolean $all return all matching entries (defaults to false - best (by ext)/last match)
  1265. * @return string Requested piece of information from array
  1266. */
  1267. function mimeinfo_from_icon($element, $icon, $all=false) {
  1268. $mimeinfo = get_mimetypes_array();
  1269. if (preg_match("/\/(.*)/", $icon, $matches)) {
  1270. $icon = $matches[1];
  1271. }
  1272. // Try to get the extension
  1273. $extension = '';
  1274. if (($cutat = strrpos($icon, '.')) !== false && $cutat < strlen($icon)-1) {
  1275. $extension = substr($icon, $cutat + 1);
  1276. }
  1277. $info = array($mimeinfo['xxx'][$element]); // Default
  1278. foreach($mimeinfo as $key => $values) {
  1279. if ($values['icon']==$icon) {
  1280. if (isset($values[$element])) {
  1281. $info[$key] = $values[$element];
  1282. }
  1283. //No break, for example for 'excel' we don't want 'csv'!
  1284. }
  1285. }
  1286. if ($all) {
  1287. if (count($info) > 1) {
  1288. array_shift($info); // take off document/unknown if we have better options
  1289. }
  1290. return array_values($info); // Keep keys out when requesting all
  1291. }
  1292. // Requested only one, try to get the best by extension coincidence, else return the last
  1293. if ($extension && isset($info[$extension])) {
  1294. return $info[$extension];
  1295. }
  1296. return array_pop($info); // Return last match (mimicking behaviour/comment inside foreach loop)
  1297. }
  1298. /**
  1299. * Returns the relative icon path for a given mime type
  1300. *
  1301. * This function should be used in conjunction with $OUTPUT->pix_url to produce
  1302. * a return the full path to an icon.
  1303. *
  1304. * <code>
  1305. * $mimetype = 'image/jpg';
  1306. * $icon = $OUTPUT->pix_url(file_mimetype_icon($mimetype));
  1307. * echo '<img src="'.$icon.'" alt="'.$mimetype.'" />';
  1308. * </code>
  1309. *
  1310. * @todo When an $OUTPUT->icon method is available this function should be altered
  1311. * to conform with that.
  1312. *
  1313. * @param string $mimetype The mimetype to fetch an icon for
  1314. * @param int $size The size of the icon. Not yet implemented
  1315. * @return string The relative path to the icon
  1316. */
  1317. function file_mimetype_icon($mimetype, $size = NULL) {
  1318. global $CFG;
  1319. $icon = mimeinfo_from_type('icon', $mimetype);
  1320. if ($size) {
  1321. if (file_exists("$CFG->dirroot/pix/f/$icon-$size.png") or file_exists("$CFG->dirroot/pix/f/$icon-$size.gif")) {
  1322. $icon = "$icon-$size";
  1323. }
  1324. }
  1325. return 'f/'.$icon;
  1326. }
  1327. /**
  1328. * Returns the relative icon path for a given file name
  1329. *
  1330. * This function should be used in conjunction with $OUTPUT->pix_url to produce
  1331. * a return the full path to an icon.
  1332. *
  1333. * <code>
  1334. * $filename = 'jpg';
  1335. * $icon = $OUTPUT->pix_url(file_extension_icon($filename));
  1336. * echo '<img src="'.$icon.'" alt="blah" />';
  1337. * </code>
  1338. *
  1339. * @todo When an $OUTPUT->icon method is available this function should be altered
  1340. * to conform with that.
  1341. * @todo Implement $size
  1342. *
  1343. * @param string filename The filename to get the icon for
  1344. * @param int $size The size of the icon. Defaults to null can also be 32
  1345. * @return string
  1346. */
  1347. function file_extension_icon($filename, $size = NULL) {
  1348. global $CFG;
  1349. $icon = mimeinfo('icon', $filename);
  1350. if ($size) {
  1351. if (file_exists("$CFG->dirroot/pix/f/$icon-$size.png") or file_exists("$CFG->dirroot/pix/f/$icon-$size.gif")) {
  1352. $icon = "$icon-$size";
  1353. }
  1354. }
  1355. return 'f/'.$icon;
  1356. }
  1357. /**
  1358. * Obtains descriptions for file types (e.g. 'Microsoft Word document') from the
  1359. * mimetypes.php language file.
  1360. *
  1361. * @param string $mimetype MIME type (can be obtained using the mimeinfo function)
  1362. * @param bool $capitalise If true, capitalises first character of result
  1363. * @return string Text description
  1364. */
  1365. function get_mimetype_description($mimetype, $capitalise=false) {
  1366. if (get_string_manager()->string_exists($mimetype, 'mimetypes')) {
  1367. $result = get_string($mimetype, 'mimetypes');
  1368. } else {
  1369. $result = get_string('document/unknown','mimetypes');
  1370. }
  1371. if ($capitalise) {
  1372. $result=ucfirst($result);
  1373. }
  1374. return $result;
  1375. }
  1376. /**
  1377. * Requested file is not found or not accessible
  1378. *
  1379. * @return does not return, terminates script
  1380. */
  1381. function send_file_not_found() {
  1382. global $CFG, $COURSE;
  1383. header('HTTP/1.0 404 not found');
  1384. print_error('filenotfound', 'error', $CFG->wwwroot.'/course/view.php?id='.$COURSE->id); //this is not displayed on IIS??
  1385. }
  1386. /**
  1387. * Check output buffering settings before sending file.
  1388. * Please note you should not send any other headers after calling this function.
  1389. *
  1390. * @private to be called only from lib/filelib.php !
  1391. * @return void
  1392. */
  1393. function prepare_file_content_sending() {
  1394. // We needed to be able to send headers up until now
  1395. if (headers_sent()) {
  1396. throw new file_serving_exception('Headers already sent, can not serve file.');
  1397. }
  1398. $olddebug = error_reporting(0);
  1399. // IE compatibility HACK - it does not like zlib compression much
  1400. // there is also a problem with the length header in older PHP versions
  1401. if (ini_get_bool('zlib.output_compression')) {
  1402. ini_set('zlib.output_compression', 'Off');
  1403. }
  1404. // flush and close all buffers if possible
  1405. while(ob_get_level()) {
  1406. if (!ob_end_flush()) {
  1407. // prevent infinite loop when buffer can not be closed
  1408. break;
  1409. }
  1410. }
  1411. error_reporting($olddebug);
  1412. //NOTE: we can not reliable test headers_sent() here because
  1413. // the headers might be sent which trying to close the buffers,
  1414. // this happens especially if browser does not support gzip or deflate
  1415. }
  1416. /**
  1417. * Handles the sending of temporary file to user, download is forced.
  1418. * File is deleted after abort or successful sending.
  1419. *
  1420. * @param string $path path to file, preferably from moodledata/temp/something; or content of file itself
  1421. * @param string $filename proposed file name when saving file
  1422. * @param bool $path is content of file
  1423. * @return does not return, script terminated
  1424. */
  1425. function send_temp_file($path, $filename, $pathisstring=false) {
  1426. global $CFG;
  1427. // close session - not needed anymore
  1428. @session_get_instance()->write_close();
  1429. if (!$pathisstring) {
  1430. if (!file_exists($path)) {
  1431. header('HTTP/1.0 404 not found');
  1432. print_error('filenotfound', 'error', $CFG->wwwroot.'/');
  1433. }
  1434. // executed after normal finish or abort
  1435. @register_shutdown_function('send_temp_file_finished', $path);
  1436. }
  1437. // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
  1438. if (check_browser_version('MSIE')) {
  1439. $filename = urlencode($filename);
  1440. }
  1441. $filesize = $pathisstring ? strlen($path) : filesize($path);
  1442. header('Content-Disposition: attachment; filename='.$filename);
  1443. header('Content-Length: '.$filesize);
  1444. if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
  1445. header('Cache-Control: max-age=10');
  1446. header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
  1447. header('Pragma: ');
  1448. } else { //normal http - prevent caching at all cost
  1449. header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
  1450. header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
  1451. header('Pragma: no-cache');
  1452. }
  1453. header('Accept-Ranges: none'); // Do not allow byteserving
  1454. //flush the buffers - save memory and disable sid rewrite
  1455. // this also disables zlib compression
  1456. prepare_file_content_sending();
  1457. // send the contents
  1458. if ($pathisstring) {
  1459. echo $path;
  1460. } else {
  1461. @readfile($path);
  1462. }
  1463. die; //no more chars to output
  1464. }
  1465. /**
  1466. * Internal callback function used by send_temp_file()
  1467. */
  1468. function send_temp_file_finished($path) {
  1469. if (file_exists($path)) {
  1470. @unlink($path);
  1471. }
  1472. }
  1473. /**
  1474. * Handles the sending of file data to the user's browser, including support for
  1475. * byteranges etc.
  1476. *
  1477. * @global object
  1478. * @global object
  1479. * @global object
  1480. * @param string $path Path of file on disk (including real filename), or actual content of file as string
  1481. * @param string $filename Filename to send
  1482. * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
  1483. * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
  1484. * @param bool $pathisstring If true (default false), $path is the content to send and not the pathname
  1485. * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
  1486. * @param string $mimetype Include to specify the MIME type; leave blank to have it guess the type from $filename
  1487. * @param bool $dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
  1488. * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
  1489. * you must detect this case when control is returned using connection_aborted. Please not that session is closed
  1490. * and should not be reopened.
  1491. * @return no return or void, script execution stopped unless $dontdie is true
  1492. */
  1493. function send_file($path, $filename, $lifetime = 'default' , $filter=0, $pathisstring=false, $forcedownload=false, $mimetype='', $dontdie=false) {
  1494. global $CFG, $COURSE, $SESSION;
  1495. if ($dontdie) {
  1496. ignore_user_abort(true);
  1497. }
  1498. // MDL-11789, apply $CFG->filelifetime here
  1499. if ($lifetime === 'default') {
  1500. if (!empty($CFG->filelifetime)) {
  1501. $lifetime = $CFG->filelifetime;
  1502. } else {
  1503. $lifetime = 86400;
  1504. }
  1505. }
  1506. session_get_instance()->write_close(); // unlock session during fileserving
  1507. // Use given MIME type if specified, otherwise guess it using mimeinfo.
  1508. // IE, Konqueror and Opera open html file directly in browser from web even when directed to save it to disk :-O
  1509. // only Firefox saves all files locally before opening when content-disposition: attachment stated
  1510. $isFF = check_browser_version('Firefox', '1.5'); // only FF > 1.5 properly tested
  1511. $mimetype = ($forcedownload and !$isFF) ? 'application/x-forcedownload' :
  1512. ($mimetype ? $mimetype : mimeinfo('type', $filename));
  1513. $lastmodified = $pathisstring ? time() : filemtime($path);
  1514. $filesize = $pathisstring ? strlen($path) : filesize($path);
  1515. /* - MDL-13949
  1516. //Adobe Acrobat Reader XSS prevention
  1517. if ($mimetype=='application/pdf' or mimeinfo('type', $filename)=='application/pdf') {
  1518. //please note that it prevents opening of pdfs in browser when http referer disabled
  1519. //or file linked from another site; browser caching of pdfs is now disabled too
  1520. if (!empty($_SERVER['HTTP_RANGE'])) {
  1521. //already byteserving
  1522. $lifetime = 1; // >0 needed for byteserving
  1523. } else if (empty($_SERVER['HTTP_REFERER']) or strpos($_SERVER['HTTP_REFERER'], $CFG->wwwroot)!==0) {
  1524. $mimetype = 'application/x-forcedownload';
  1525. $forcedownload = true;
  1526. $lifetime = 0;
  1527. } else {
  1528. $lifetime = 1; // >0 needed for byteserving
  1529. }
  1530. }
  1531. */
  1532. //try to disable automatic sid rewrite in cookieless mode
  1533. @ini_set("session.use_trans_sid", "false");
  1534. //do not put '@' before the next header to detect incorrect moodle configurations,
  1535. //error should be better than "weird" empty lines for admins/users
  1536. header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
  1537. // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
  1538. if (check_browser_version('MSIE')) {
  1539. $filename = rawurlencode($filename);
  1540. }
  1541. if ($forcedownload) {
  1542. header('Content-Disposition: attachment; filename="'.$filename.'"');
  1543. } else {
  1544. header('Content-Disposition: inline; filename="'.$filename.'"');
  1545. }
  1546. if ($lifetime > 0) {
  1547. header('Cache-Control: max-age='.$lifetime);
  1548. header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
  1549. header('Pragma: ');
  1550. if (empty($CFG->disablebyteserving) && !$pathisstring && $mimetype != 'text/plain' && $mimetype != 'text/html') {
  1551. header('Accept-Ranges: bytes');
  1552. if (!empty($_SERVER['HTTP_RANGE']) && strpos($_SERVER['HTTP_RANGE'],'bytes=') !== FALSE) {
  1553. // byteserving stuff - for acrobat reader and download accelerators
  1554. // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
  1555. // inspired by: http://www.coneural.org/florian/papers/04_byteserving.php
  1556. $ranges = false;
  1557. if (preg_match_all('/(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER)) {
  1558. foreach ($ranges as $key=>$value) {
  1559. if ($ranges[$key][1] == '') {
  1560. //suffix case
  1561. $ranges[$key][1] = $filesize - $ranges[$key][2];
  1562. $ranges[$key][2] = $filesize - 1;
  1563. } else if ($ranges[$key][2] == '' || $ranges[$key][2] > $filesize - 1) {
  1564. //fix range length
  1565. $ranges[$key][2] = $filesize - 1;
  1566. }
  1567. if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
  1568. //invalid byte-range ==> ignore header
  1569. $ranges = false;
  1570. break;
  1571. }
  1572. //prepare multipart header
  1573. $ranges[$key][0] = "\r\n--".BYTESERVING_BOUNDARY."\r\nContent-Type: $mimetype\r\n";
  1574. $ranges[$key][0] .= "Content-Range: bytes {$ranges[$key][1]}-{$ranges[$key][2]}/$filesize\r\n\r\n";
  1575. }
  1576. } else {
  1577. $ranges = false;
  1578. }
  1579. if ($ranges) {
  1580. $handle = fopen($path, 'rb');
  1581. byteserving_send_file($handle, $mimetype, $ranges, $filesize);
  1582. }
  1583. }
  1584. } else {
  1585. /// Do not byteserve (disabled, strings, text and html files).
  1586. header('Accept-Ranges: none');
  1587. }
  1588. } else { // Do not cache files in proxies and browsers
  1589. if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
  1590. header('Cache-Control: max-age=10');
  1591. header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
  1592. header('Pragma: ');
  1593. } else { //normal http - prevent caching at all cost
  1594. header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
  1595. header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
  1596. header('Pragma: no-cache');
  1597. }
  1598. header('Accept-Ranges: none'); // Do not allow byteserving when caching disabled
  1599. }
  1600. if (empty($filter)) {
  1601. if ($mimetype == 'text/html' && !empty($CFG->usesid)) {
  1602. //cookieless mode - rewrite links
  1603. header('Content-Type: text/html');
  1604. $path = $pathisstring ? $path : implode('', file($path));
  1605. $path = sid_ob_rewrite($path);
  1606. $filesize = strlen($path);
  1607. $pathisstring = true;
  1608. } else if ($mimetype == 'text/plain') {
  1609. header('Content-Type: Text/plain; charset=utf-8'); //add encoding
  1610. } else {
  1611. header('Content-Type: '.$mimetype);
  1612. }
  1613. header('Content-Length: '.$filesize);
  1614. //flush the buffers - save memory and disable sid rewrite
  1615. //this also disables zlib compression
  1616. prepare_file_content_sending();
  1617. // send the contents
  1618. if ($pathisstring) {
  1619. echo $path;
  1620. } else {
  1621. @readfile($path);
  1622. }
  1623. } else { // Try to put the file through filters
  1624. if ($mimetype == 'text/html') {
  1625. $options = new stdClass();
  1626. $options->noclean = true;
  1627. $options->nocache = true; // temporary workaround for MDL-5136
  1628. $text = $pathisstring ? $path : implode('', file($path));
  1629. $text = file_modify_html_header($text);
  1630. $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
  1631. if (!empty($CFG->usesid)) {
  1632. //cookieless mode - rewrite links
  1633. $output = sid_ob_rewrite($output);
  1634. }
  1635. header('Content-Length: '.strlen($output));
  1636. header('Content-Type: text/html');
  1637. //flush the buffers - save memory and disable sid rewrite
  1638. //this also disables zlib compression
  1639. prepare_file_content_sending();
  1640. // send the contents
  1641. echo $output;
  1642. // only filter text if filter all files is selected
  1643. } else if (($mimetype == 'text/plain') and ($filter == 1)) {
  1644. $options = new stdClass();
  1645. $options->newlines = false;
  1646. $options->noclean = true;
  1647. $text = htmlentities($pathisstring ? $path : implode('', file($path)));
  1648. $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
  1649. if (!empty($CFG->usesid)) {
  1650. //cookieless mode - rewrite links
  1651. $output = sid_ob_rewrite($output);
  1652. }
  1653. header('Content-Length: '.strlen($output));
  1654. header('Content-Type: text/html; charset=utf-8'); //add encoding
  1655. //flush the buffers - save memory and disable sid rewrite
  1656. //this also disables zlib compression
  1657. prepare_file_content_sending();
  1658. // send the contents
  1659. echo $output;
  1660. } else { // Just send it out raw
  1661. header('Content-Length: '.$filesize);
  1662. header('Content-Type: '.$mimetype);
  1663. //flush the buffers - save memory and disable sid rewrite
  1664. //this also disables zlib compression
  1665. prepare_file_content_sending();
  1666. // send the contents
  1667. if ($pathisstring) {
  1668. echo $path;
  1669. }else {
  1670. @readfile($path);
  1671. }
  1672. }
  1673. }
  1674. if ($dontdie) {
  1675. return;
  1676. }
  1677. die; //no more chars to output!!!
  1678. }
  1679. /**
  1680. * Handles the sending of file data to the user's browser, including support for
  1681. * byteranges etc.
  1682. *
  1683. * @global object
  1684. * @global object
  1685. * @global object
  1686. * @param object $stored_file local file object
  1687. * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
  1688. * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
  1689. * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
  1690. * @param string $filename Override filename
  1691. * @param bool $dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
  1692. * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
  1693. * you must detect this case when control is returned using connection_aborted. Please not that session is closed
  1694. * and should not be reopened.
  1695. * @return void no return or void, script execution stopped unless $dontdie is true
  1696. */
  1697. function send_stored_file($stored_file, $lifetime=86400 , $filter=0, $forcedownload=false, $filename=null, $dontdie=false) {
  1698. global $CFG, $COURSE, $SESSION;
  1699. if (!$stored_file or $stored_file->is_directory()) {
  1700. // nothing to serve
  1701. if ($dontdie) {
  1702. return;
  1703. }
  1704. die;
  1705. }
  1706. if ($dontdie) {
  1707. ignore_user_abort(true);
  1708. }
  1709. session_get_instance()->write_close(); // unlock session during fileserving
  1710. // Use given MIME type if specified, otherwise guess it using mimeinfo.
  1711. // IE, Konqueror and Opera open html file directly in browser from web even when directed to save it to disk :-O
  1712. // only Firefox saves all files locally before opening when content-disposition: attachment stated
  1713. $filename = is_null($filename) ? $stored_file->get_filename() : $filename;
  1714. $isFF = check_browser_version('Firefox', '1.5'); // only FF > 1.5 properly tested
  1715. $mimetype = ($forcedownload and !$isFF) ? 'application/x-forcedownload' :
  1716. ($stored_file->get_mimetype() ? $stored_file->get_mimetype() : mimeinfo('type', $filename));
  1717. $lastmodified = $stored_file->get_timemodified();
  1718. $filesize = $stored_file->get_filesize();
  1719. //try to disable automatic sid rewrite in cookieless mode
  1720. @ini_set("session.use_trans_sid", "false");
  1721. //do not put '@' before the next header to detect incorrect moodle configurations,
  1722. //error should be better than "weird" empty lines for admins/users
  1723. //TODO: should we remove all those @ before the header()? Are all of the values supported on all servers?
  1724. header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
  1725. // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
  1726. if (check_browser_version('MSIE')) {
  1727. $filename = rawurlencode($filename);
  1728. }
  1729. if ($forcedownload) {
  1730. header('Content-Disposition: attachment; filename="'.$filename.'"');
  1731. } else {
  1732. header('Content-Disposition: inline; filename="'.$filename.'"');
  1733. }
  1734. if ($lifetime > 0) {
  1735. header('Cache-Control: max-age='.$lifetime);
  1736. header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
  1737. header('Pragma: ');
  1738. if (empty($CFG->disablebyteserving) && $mimetype != 'text/plain' && $mimetype != 'text/html') {
  1739. header('Accept-Ranges: bytes');
  1740. if (!empty($_SERVER['HTTP_RANGE']) && strpos($_SERVER['HTTP_RANGE'],'bytes=') !== FALSE) {
  1741. // byteserving stuff - for acrobat reader and download accelerators
  1742. // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
  1743. // inspired by: http://www.coneural.org/florian/papers/04_byteserving.php
  1744. $ranges = false;
  1745. if (preg_match_all('/(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER)) {
  1746. foreach ($ranges as $key=>$value) {
  1747. if ($ranges[$key][1] == '') {
  1748. //suffix case
  1749. $ranges[$key][1] = $filesize - $ranges[$key][2];
  1750. $ranges[$key][2] = $filesize - 1;
  1751. } else if ($ranges[$key][2] == '' || $ranges[$key][2] > $filesize - 1) {
  1752. //fix range length
  1753. $ranges[$key][2] = $filesize - 1;
  1754. }
  1755. if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
  1756. //invalid byte-range ==> ignore header
  1757. $ranges = false;
  1758. break;
  1759. }
  1760. //prepare multipart header
  1761. $ranges[$key][0] = "\r\n--".BYTESERVING_BOUNDARY."\r\nContent-Type: $mimetype\r\n";
  1762. $ranges[$key][0] .= "Content-Range: bytes {$ranges[$key][1]}-{$ranges[$key][2]}/$filesize\r\n\r\n";
  1763. }
  1764. } else {
  1765. $ranges = false;
  1766. }
  1767. if ($ranges) {
  1768. byteserving_send_file($stored_file->get_content_file_handle(), $mimetype, $ranges, $filesize);
  1769. }
  1770. }
  1771. } else {
  1772. /// Do not byteserve (disabled, strings, text and html files).
  1773. header('Accept-Ranges: none');
  1774. }
  1775. } else { // Do not cache files in proxies and browsers
  1776. if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
  1777. header('Cache-Control: max-age=10');
  1778. header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
  1779. header('Pragma: ');
  1780. } else { //normal http - prevent caching at all cost
  1781. header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
  1782. header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
  1783. header('Pragma: no-cache');
  1784. }
  1785. header('Accept-Ranges: none'); // Do not allow byteserving when caching disabled
  1786. }
  1787. if (empty($filter)) {
  1788. $filtered = false;
  1789. if ($mimetype == 'text/html' && !empty($CFG->usesid)) {
  1790. //cookieless mode - rewrite links
  1791. header('Content-Type: text/html');
  1792. $text = $stored_file->get_content();
  1793. $text = sid_ob_rewrite($text);
  1794. $filesize = strlen($text);
  1795. $filtered = true;
  1796. } else if ($mimetype == 'text/plain') {
  1797. header('Content-Type: Text/plain; charset=utf-8'); //add encoding
  1798. } else {
  1799. header('Content-Type: '.$mimetype);
  1800. }
  1801. header('Content-Length: '.$filesize);
  1802. //flush the buffers - save memory and disable sid rewrite
  1803. //this also disables zlib compression
  1804. prepare_file_content_sending();
  1805. // send the contents
  1806. if ($filtered) {
  1807. echo $text;
  1808. } else {
  1809. $stored_file->readfile();
  1810. }
  1811. } else { // Try to put the file through filters
  1812. if ($mimetype == 'text/html') {
  1813. $options = new stdClass();
  1814. $options->noclean = true;
  1815. $options->nocache = true; // temporary workaround for MDL-5136
  1816. $text = $stored_file->get_content();
  1817. $text = file_modify_html_header($text);
  1818. $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
  1819. if (!empty($CFG->usesid)) {
  1820. //cookieless mode - rewrite links
  1821. $output = sid_ob_rewrite($output);
  1822. }
  1823. header('Content-Length: '.strlen($output));
  1824. header('Content-Type: text/html');
  1825. //flush the buffers - save memory and disable sid rewrite
  1826. //this also disables zlib compression
  1827. prepare_file_content_sending();
  1828. // send the contents
  1829. echo $output;
  1830. } else if (($mimetype == 'text/plain') and ($filter == 1)) {
  1831. // only filter text if filter all files is selected
  1832. $options = new stdClass();
  1833. $options->newlines = false;
  1834. $options->noclean = true;
  1835. $text = $stored_file->get_content();
  1836. $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
  1837. if (!empty($CFG->usesid)) {
  1838. //cookieless mode - rewrite links
  1839. $output = sid_ob_rewrite($output);
  1840. }
  1841. header('Content-Length: '.strlen($output));
  1842. header('Content-Type: text/html; charset=utf-8'); //add encoding
  1843. //flush the buffers - save memory and disable sid rewrite
  1844. //this also disables zlib compression
  1845. prepare_file_content_sending();
  1846. // send the contents
  1847. echo $output;
  1848. } else { // Just send it out raw
  1849. header('Content-Length: '.$filesize);
  1850. header('Content-Type: '.$mimetype);
  1851. //flush the buffers - save memory and disable sid rewrite
  1852. //this also disables zlib compression
  1853. prepare_file_content_sending();
  1854. // send the contents
  1855. $stored_file->readfile();
  1856. }
  1857. }
  1858. if ($dontdie) {
  1859. return;
  1860. }
  1861. die; //no more chars to output!!!
  1862. }
  1863. /**
  1864. * Retrieves an array of records from a CSV file and places
  1865. * them into a given table structure
  1866. *
  1867. * @global object
  1868. * @global object
  1869. * @param string $file The path to a CSV file
  1870. * @param string $table The table to retrieve columns from
  1871. * @return bool|array Returns an array of CSV records or false
  1872. */
  1873. function get_records_csv($file, $table) {
  1874. global $CFG, $DB;
  1875. if (!$metacolumns = $DB->get_columns($table)) {
  1876. return false;
  1877. }
  1878. if(!($handle = @fopen($file, 'r'))) {
  1879. print_error('get_records_csv failed to open '.$file);
  1880. }
  1881. $fieldnames = fgetcsv($handle, 4096);
  1882. if(empty($fieldnames)) {
  1883. fclose($handle);
  1884. return false;
  1885. }
  1886. $columns = array();
  1887. foreach($metacolumns as $metacolumn) {
  1888. $ord = array_search($metacolumn->name, $fieldnames);
  1889. if(is_int($ord)) {
  1890. $columns[$metacolumn->name] = $ord;
  1891. }
  1892. }
  1893. $rows = array();
  1894. while (($data = fgetcsv($handle, 4096)) !== false) {
  1895. $item = new stdClass;
  1896. foreach($columns as $name => $ord) {
  1897. $item->$name = $data[$ord];
  1898. }
  1899. $rows[] = $item;
  1900. }
  1901. fclose($handle);
  1902. return $rows;
  1903. }
  1904. /**
  1905. *
  1906. * @global object
  1907. * @global object
  1908. * @param string $file The file to put the CSV content into
  1909. * @param array $records An array of records to write to a CSV file
  1910. * @param string $table The table to get columns from
  1911. * @return bool success
  1912. */
  1913. function put_records_csv($file, $records, $table = NULL) {
  1914. global $CFG, $DB;
  1915. if (empty($records)) {
  1916. return true;
  1917. }
  1918. $metacolumns = NULL;
  1919. if ($table !== NULL && !$metacolumns = $DB->get_columns($table)) {
  1920. return false;
  1921. }
  1922. echo "x";
  1923. if(!($fp = @fopen($CFG->dataroot.'/temp/'.$file, 'w'))) {
  1924. print_error('put_records_csv failed to open '.$file);
  1925. }
  1926. $proto = reset($records);
  1927. if(is_object($proto)) {
  1928. $fields_records = array_keys(get_object_vars($proto));
  1929. }
  1930. else if(is_array($proto)) {
  1931. $fields_records = array_keys($proto);
  1932. }
  1933. else {
  1934. return false;
  1935. }
  1936. echo "x";
  1937. if(!empty($metacolumns)) {
  1938. $fields_table = array_map(create_function('$a', 'return $a->name;'), $metacolumns);
  1939. $fields = array_intersect($fields_records, $fields_table);
  1940. }
  1941. else {
  1942. $fields = $fields_records;
  1943. }
  1944. fwrite($fp, implode(',', $fields));
  1945. fwrite($fp, "\r\n");
  1946. foreach($records as $record) {
  1947. $array = (array)$record;
  1948. $values = array();
  1949. foreach($fields as $field) {
  1950. if(strpos($array[$field], ',')) {
  1951. $values[] = '"'.str_replace('"', '\"', $array[$field]).'"';
  1952. }
  1953. else {
  1954. $values[] = $array[$field];
  1955. }
  1956. }
  1957. fwrite($fp, implode(',', $values)."\r\n");
  1958. }
  1959. fclose($fp);
  1960. return true;
  1961. }
  1962. /**
  1963. * Recursively delete the file or folder with path $location. That is,
  1964. * if it is a file delete it. If it is a folder, delete all its content
  1965. * then delete it. If $location does not exist to start, that is not
  1966. * considered an error.
  1967. *
  1968. * @param string $location the path to remove.
  1969. * @return bool
  1970. */
  1971. function fulldelete($location) {
  1972. if (empty($location)) {
  1973. // extra safety against wrong param
  1974. return false;
  1975. }
  1976. if (is_dir($location)) {
  1977. $currdir = opendir($location);
  1978. while (false !== ($file = readdir($currdir))) {
  1979. if ($file <> ".." && $file <> ".") {
  1980. $fullfile = $location."/".$file;
  1981. if (is_dir($fullfile)) {
  1982. if (!fulldelete($fullfile)) {
  1983. return false;
  1984. }
  1985. } else {
  1986. if (!unlink($fullfile)) {
  1987. return false;
  1988. }
  1989. }
  1990. }
  1991. }
  1992. closedir($currdir);
  1993. if (! rmdir($location)) {
  1994. return false;
  1995. }
  1996. } else if (file_exists($location)) {
  1997. if (!unlink($location)) {
  1998. return false;
  1999. }
  2000. }
  2001. return true;
  2002. }
  2003. /**
  2004. * Send requested byterange of file.
  2005. *
  2006. * @param object $handle A file handle
  2007. * @param string $mimetype The mimetype for the output
  2008. * @param array $ranges An array of ranges to send
  2009. * @param string $filesize The size of the content if only one range is used
  2010. */
  2011. function byteserving_send_file($handle, $mimetype, $ranges, $filesize) {
  2012. $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
  2013. if ($handle === false) {
  2014. die;
  2015. }
  2016. if (count($ranges) == 1) { //only one range requested
  2017. $length = $ranges[0][2] - $ranges[0][1] + 1;
  2018. header('HTTP/1.1 206 Partial content');
  2019. header('Content-Length: '.$length);
  2020. header('Content-Range: bytes '.$ranges[0][1].'-'.$ranges[0][2].'/'.$filesize);
  2021. header('Content-Type: '.$mimetype);
  2022. //flush the buffers - save memory and disable sid rewrite
  2023. //this also disables zlib compression
  2024. prepare_file_content_sending();
  2025. $buffer = '';
  2026. fseek($handle, $ranges[0][1]);
  2027. while (!feof($handle) && $length > 0) {
  2028. @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
  2029. $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
  2030. echo $buffer;
  2031. flush();
  2032. $length -= strlen($buffer);
  2033. }
  2034. fclose($handle);
  2035. die;
  2036. } else { // multiple ranges requested - not tested much
  2037. $totallength = 0;
  2038. foreach($ranges as $range) {
  2039. $totallength += strlen($range[0]) + $range[2] - $range[1] + 1;
  2040. }
  2041. $totallength += strlen("\r\n--".BYTESERVING_BOUNDARY."--\r\n");
  2042. header('HTTP/1.1 206 Partial content');
  2043. header('Content-Length: '.$totallength);
  2044. header('Content-Type: multipart/byteranges; boundary='.BYTESERVING_BOUNDARY);
  2045. //TODO: check if "multipart/x-byteranges" is more compatible with current readers/browsers/servers
  2046. //flush the buffers - save memory and disable sid rewrite
  2047. //this also disables zlib compression
  2048. prepare_file_content_sending();
  2049. foreach($ranges as $range) {
  2050. $length = $range[2] - $range[1] + 1;
  2051. echo $range[0];
  2052. $buffer = '';
  2053. fseek($handle, $range[1]);
  2054. while (!feof($handle) && $length > 0) {
  2055. @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
  2056. $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
  2057. echo $buffer;
  2058. flush();
  2059. $length -= strlen($buffer);
  2060. }
  2061. }
  2062. echo "\r\n--".BYTESERVING_BOUNDARY."--\r\n";
  2063. fclose($handle);
  2064. die;
  2065. }
  2066. }
  2067. /**
  2068. * add includes (js and css) into uploaded files
  2069. * before returning them, useful for themes and utf.js includes
  2070. *
  2071. * @global object
  2072. * @param string $text text to search and replace
  2073. * @return string text with added head includes
  2074. */
  2075. function file_modify_html_header($text) {
  2076. // first look for <head> tag
  2077. global $CFG;
  2078. $stylesheetshtml = '';
  2079. /* foreach ($CFG->stylesheets as $stylesheet) {
  2080. //TODO: MDL-21120
  2081. $stylesheetshtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
  2082. }*/
  2083. $ufo = '';
  2084. if (filter_is_enabled('filter/mediaplugin')) {
  2085. // this script is needed by most media filter plugins.
  2086. $attributes = array('type'=>'text/javascript', 'src'=>$CFG->httpswwwroot . '/lib/ufo.js');
  2087. $ufo = html_writer::tag('script', '', $attributes) . "\n";
  2088. }
  2089. preg_match('/\<head\>|\<HEAD\>/', $text, $matches);
  2090. if ($matches) {
  2091. $replacement = '<head>'.$ufo.$stylesheetshtml;
  2092. $text = preg_replace('/\<head\>|\<HEAD\>/', $replacement, $text, 1);
  2093. return $text;
  2094. }
  2095. // if not, look for <html> tag, and stick <head> right after
  2096. preg_match('/\<html\>|\<HTML\>/', $text, $matches);
  2097. if ($matches) {
  2098. // replace <html> tag with <html><head>includes</head>
  2099. $replacement = '<html>'."\n".'<head>'.$ufo.$stylesheetshtml.'</head>';
  2100. $text = preg_replace('/\<html\>|\<HTML\>/', $replacement, $text, 1);
  2101. return $text;
  2102. }
  2103. // if not, look for <body> tag, and stick <head> before body
  2104. preg_match('/\<body\>|\<BODY\>/', $text, $matches);
  2105. if ($matches) {
  2106. $replacement = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".'<body>';
  2107. $text = preg_replace('/\<body\>|\<BODY\>/', $replacement, $text, 1);
  2108. return $text;
  2109. }
  2110. // if not, just stick a <head> tag at the beginning
  2111. $text = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".$text;
  2112. return $text;
  2113. }
  2114. /**
  2115. * RESTful cURL class
  2116. *
  2117. * This is a wrapper class for curl, it is quite easy to use:
  2118. * <code>
  2119. * $c = new curl;
  2120. * // enable cache
  2121. * $c = new curl(array('cache'=>true));
  2122. * // enable cookie
  2123. * $c = new curl(array('cookie'=>true));
  2124. * // enable proxy
  2125. * $c = new curl(array('proxy'=>true));
  2126. *
  2127. * // HTTP GET Method
  2128. * $html = $c->get('http://example.com');
  2129. * // HTTP POST Method
  2130. * $html = $c->post('http://example.com/', array('q'=>'words', 'name'=>'moodle'));
  2131. * // HTTP PUT Method
  2132. * $html = $c->put('http://example.com/', array('file'=>'/var/www/test.txt');
  2133. * </code>
  2134. *
  2135. * @package core
  2136. * @subpackage file
  2137. * @author Dongsheng Cai <dongsheng@cvs.moodle.org>
  2138. * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
  2139. */
  2140. class curl {
  2141. /** @var bool */
  2142. public $cache = false;
  2143. public $proxy = false;
  2144. /** @var string */
  2145. public $version = '0.4 dev';
  2146. /** @var array */
  2147. public $response = array();
  2148. public $header = array();
  2149. /** @var string */
  2150. public $info;
  2151. public $error;
  2152. /** @var array */
  2153. private $options;
  2154. /** @var string */
  2155. private $proxy_host = '';
  2156. private $proxy_auth = '';
  2157. private $proxy_type = '';
  2158. /** @var bool */
  2159. private $debug = false;
  2160. private $cookie = false;
  2161. /**
  2162. * @global object
  2163. * @param array $options
  2164. */
  2165. public function __construct($options = array()){
  2166. global $CFG;
  2167. if (!function_exists('curl_init')) {
  2168. $this->error = 'cURL module must be enabled!';
  2169. trigger_error($this->error, E_USER_ERROR);
  2170. return false;
  2171. }
  2172. // the options of curl should be init here.
  2173. $this->resetopt();
  2174. if (!empty($options['debug'])) {
  2175. $this->debug = true;
  2176. }
  2177. if(!empty($options['cookie'])) {
  2178. if($options['cookie'] === true) {
  2179. $this->cookie = $CFG->dataroot.'/curl_cookie.txt';
  2180. } else {
  2181. $this->cookie = $options['cookie'];
  2182. }
  2183. }
  2184. if (!empty($options['cache'])) {
  2185. if (class_exists('curl_cache')) {
  2186. if (!empty($options['module_cache'])) {
  2187. $this->cache = new curl_cache($options['module_cache']);
  2188. } else {
  2189. $this->cache = new curl_cache('misc');
  2190. }
  2191. }
  2192. }
  2193. if (!empty($CFG->proxyhost)) {
  2194. if (empty($CFG->proxyport)) {
  2195. $this->proxy_host = $CFG->proxyhost;
  2196. } else {
  2197. $this->proxy_host = $CFG->proxyhost.':'.$CFG->proxyport;
  2198. }
  2199. if (!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) {
  2200. $this->proxy_auth = $CFG->proxyuser.':'.$CFG->proxypassword;
  2201. $this->setopt(array(
  2202. 'proxyauth'=> CURLAUTH_BASIC | CURLAUTH_NTLM,
  2203. 'proxyuserpwd'=>$this->proxy_auth));
  2204. }
  2205. if (!empty($CFG->proxytype)) {
  2206. if ($CFG->proxytype == 'SOCKS5') {
  2207. $this->proxy_type = CURLPROXY_SOCKS5;
  2208. } else {
  2209. $this->proxy_type = CURLPROXY_HTTP;
  2210. $this->setopt(array('httpproxytunnel'=>false));
  2211. }
  2212. $this->setopt(array('proxytype'=>$this->proxy_type));
  2213. }
  2214. }
  2215. if (!empty($this->proxy_host)) {
  2216. $this->proxy = array('proxy'=>$this->proxy_host);
  2217. }
  2218. }
  2219. /**
  2220. * Resets the CURL options that have already been set
  2221. */
  2222. public function resetopt(){
  2223. $this->options = array();
  2224. $this->options['CURLOPT_USERAGENT'] = 'MoodleBot/1.0';
  2225. // True to include the header in the output
  2226. $this->options['CURLOPT_HEADER'] = 0;
  2227. // True to Exclude the body from the output
  2228. $this->options['CURLOPT_NOBODY'] = 0;
  2229. // TRUE to follow any "Location: " header that the server
  2230. // sends as part of the HTTP header (note this is recursive,
  2231. // PHP will follow as many "Location: " headers that it is sent,
  2232. // unless CURLOPT_MAXREDIRS is set).
  2233. //$this->options['CURLOPT_FOLLOWLOCATION'] = 1;
  2234. $this->options['CURLOPT_MAXREDIRS'] = 10;
  2235. $this->options['CURLOPT_ENCODING'] = '';
  2236. // TRUE to return the transfer as a string of the return
  2237. // value of curl_exec() instead of outputting it out directly.
  2238. $this->options['CURLOPT_RETURNTRANSFER'] = 1;
  2239. $this->options['CURLOPT_BINARYTRANSFER'] = 0;
  2240. $this->options['CURLOPT_SSL_VERIFYPEER'] = 0;
  2241. $this->options['CURLOPT_SSL_VERIFYHOST'] = 2;
  2242. $this->options['CURLOPT_CONNECTTIMEOUT'] = 30;
  2243. }
  2244. /**
  2245. * Reset Cookie
  2246. */
  2247. public function resetcookie() {
  2248. if (!empty($this->cookie)) {
  2249. if (is_file($this->cookie)) {
  2250. $fp = fopen($this->cookie, 'w');
  2251. if (!empty($fp)) {
  2252. fwrite($fp, '');
  2253. fclose($fp);
  2254. }
  2255. }
  2256. }
  2257. }
  2258. /**
  2259. * Set curl options
  2260. *
  2261. * @param array $options If array is null, this function will
  2262. * reset the options to default value.
  2263. *
  2264. */
  2265. public function setopt($options = array()) {
  2266. if (is_array($options)) {
  2267. foreach($options as $name => $val){
  2268. if (stripos($name, 'CURLOPT_') === false) {
  2269. $name = strtoupper('CURLOPT_'.$name);
  2270. }
  2271. $this->options[$name] = $val;
  2272. }
  2273. }
  2274. }
  2275. /**
  2276. * Reset http method
  2277. *
  2278. */
  2279. public function cleanopt(){
  2280. unset($this->options['CURLOPT_HTTPGET']);
  2281. unset($this->options['CURLOPT_POST']);
  2282. unset($this->options['CURLOPT_POSTFIELDS']);
  2283. unset($this->options['CURLOPT_PUT']);
  2284. unset($this->options['CURLOPT_INFILE']);
  2285. unset($this->options['CURLOPT_INFILESIZE']);
  2286. unset($this->options['CURLOPT_CUSTOMREQUEST']);
  2287. }
  2288. /**
  2289. * Set HTTP Request Header
  2290. *
  2291. * @param array $headers
  2292. *
  2293. */
  2294. public function setHeader($header) {
  2295. if (is_array($header)){
  2296. foreach ($header as $v) {
  2297. $this->setHeader($v);
  2298. }
  2299. } else {
  2300. $this->header[] = $header;
  2301. }
  2302. }
  2303. /**
  2304. * Set HTTP Response Header
  2305. *
  2306. */
  2307. public function getResponse(){
  2308. return $this->response;
  2309. }
  2310. /**
  2311. * private callback function
  2312. * Formatting HTTP Response Header
  2313. *
  2314. * @param mixed $ch Apparently not used
  2315. * @param string $header
  2316. * @return int The strlen of the header
  2317. */
  2318. private function formatHeader($ch, $header)
  2319. {
  2320. $this->count++;
  2321. if (strlen($header) > 2) {
  2322. list($key, $value) = explode(" ", rtrim($header, "\r\n"), 2);
  2323. $key = rtrim($key, ':');
  2324. if (!empty($this->response[$key])) {
  2325. if (is_array($this->response[$key])){
  2326. $this->response[$key][] = $value;
  2327. } else {
  2328. $tmp = $this->response[$key];
  2329. $this->response[$key] = array();
  2330. $this->response[$key][] = $tmp;
  2331. $this->response[$key][] = $value;
  2332. }
  2333. } else {
  2334. $this->response[$key] = $value;
  2335. }
  2336. }
  2337. return strlen($header);
  2338. }
  2339. /**
  2340. * Set options for individual curl instance
  2341. *
  2342. * @param object $curl A curl handle
  2343. * @param array $options
  2344. * @return object The curl handle
  2345. */
  2346. private function apply_opt($curl, $options) {
  2347. // Clean up
  2348. $this->cleanopt();
  2349. // set cookie
  2350. if (!empty($this->cookie) || !empty($options['cookie'])) {
  2351. $this->setopt(array('cookiejar'=>$this->cookie,
  2352. 'cookiefile'=>$this->cookie
  2353. ));
  2354. }
  2355. // set proxy
  2356. if (!empty($this->proxy) || !empty($options['proxy'])) {
  2357. $this->setopt($this->proxy);
  2358. }
  2359. $this->setopt($options);
  2360. // reset before set options
  2361. curl_setopt($curl, CURLOPT_HEADERFUNCTION, array(&$this,'formatHeader'));
  2362. // set headers
  2363. if (empty($this->header)){
  2364. $this->setHeader(array(
  2365. 'User-Agent: MoodleBot/1.0',
  2366. 'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7',
  2367. 'Connection: keep-alive'
  2368. ));
  2369. }
  2370. curl_setopt($curl, CURLOPT_HTTPHEADER, $this->header);
  2371. if ($this->debug){
  2372. echo '<h1>Options</h1>';
  2373. var_dump($this->options);
  2374. echo '<h1>Header</h1>';
  2375. var_dump($this->header);
  2376. }
  2377. // set options
  2378. foreach($this->options as $name => $val) {
  2379. if (is_string($name)) {
  2380. $name = constant(strtoupper($name));
  2381. }
  2382. curl_setopt($curl, $name, $val);
  2383. }
  2384. return $curl;
  2385. }
  2386. /**
  2387. * Download multiple files in parallel
  2388. *
  2389. * Calls {@link multi()} with specific download headers
  2390. *
  2391. * <code>
  2392. * $c = new curl;
  2393. * $c->download(array(
  2394. * array('url'=>'http://localhost/', 'file'=>fopen('a', 'wb')),
  2395. * array('url'=>'http://localhost/20/', 'file'=>fopen('b', 'wb'))
  2396. * ));
  2397. * </code>
  2398. *
  2399. * @param array $requests An array of files to request
  2400. * @param array $options An array of options to set
  2401. * @return array An array of results
  2402. */
  2403. public function download($requests, $options = array()) {
  2404. $options['CURLOPT_BINARYTRANSFER'] = 1;
  2405. $options['RETURNTRANSFER'] = false;
  2406. return $this->multi($requests, $options);
  2407. }
  2408. /*
  2409. * Mulit HTTP Requests
  2410. * This function could run multi-requests in parallel.
  2411. *
  2412. * @param array $requests An array of files to request
  2413. * @param array $options An array of options to set
  2414. * @return array An array of results
  2415. */
  2416. protected function multi($requests, $options = array()) {
  2417. $count = count($requests);
  2418. $handles = array();
  2419. $results = array();
  2420. $main = curl_multi_init();
  2421. for ($i = 0; $i < $count; $i++) {
  2422. $url = $requests[$i];
  2423. foreach($url as $n=>$v){
  2424. $options[$n] = $url[$n];
  2425. }
  2426. $handles[$i] = curl_init($url['url']);
  2427. $this->apply_opt($handles[$i], $options);
  2428. curl_multi_add_handle($main, $handles[$i]);
  2429. }
  2430. $running = 0;
  2431. do {
  2432. curl_multi_exec($main, $running);
  2433. } while($running > 0);
  2434. for ($i = 0; $i < $count; $i++) {
  2435. if (!empty($options['CURLOPT_RETURNTRANSFER'])) {
  2436. $results[] = true;
  2437. } else {
  2438. $results[] = curl_multi_getcontent($handles[$i]);
  2439. }
  2440. curl_multi_remove_handle($main, $handles[$i]);
  2441. }
  2442. curl_multi_close($main);
  2443. return $results;
  2444. }
  2445. /**
  2446. * Single HTTP Request
  2447. *
  2448. * @param string $url The URL to request
  2449. * @param array $options
  2450. * @return bool
  2451. */
  2452. protected function request($url, $options = array()){
  2453. // create curl instance
  2454. $curl = curl_init($url);
  2455. $options['url'] = $url;
  2456. $this->apply_opt($curl, $options);
  2457. if ($this->cache && $ret = $this->cache->get($this->options)) {
  2458. return $ret;
  2459. } else {
  2460. $ret = curl_exec($curl);
  2461. if ($this->cache) {
  2462. $this->cache->set($this->options, $ret);
  2463. }
  2464. }
  2465. $this->info = curl_getinfo($curl);
  2466. $this->error = curl_error($curl);
  2467. if ($this->debug){
  2468. echo '<h1>Return Data</h1>';
  2469. var_dump($ret);
  2470. echo '<h1>Info</h1>';
  2471. var_dump($this->info);
  2472. echo '<h1>Error</h1>';
  2473. var_dump($this->error);
  2474. }
  2475. curl_close($curl);
  2476. if (empty($this->error)){
  2477. return $ret;
  2478. } else {
  2479. return $this->error;
  2480. // exception is not ajax friendly
  2481. //throw new moodle_exception($this->error, 'curl');
  2482. }
  2483. }
  2484. /**
  2485. * HTTP HEAD method
  2486. *
  2487. * @see request()
  2488. *
  2489. * @param string $url
  2490. * @param array $options
  2491. * @return bool
  2492. */
  2493. public function head($url, $options = array()){
  2494. $options['CURLOPT_HTTPGET'] = 0;
  2495. $options['CURLOPT_HEADER'] = 1;
  2496. $options['CURLOPT_NOBODY'] = 1;
  2497. return $this->request($url, $options);
  2498. }
  2499. /**
  2500. * HTTP POST method
  2501. *
  2502. * @param string $url
  2503. * @param array|string $params
  2504. * @param array $options
  2505. * @return bool
  2506. */
  2507. public function post($url, $params = '', $options = array()){
  2508. $options['CURLOPT_POST'] = 1;
  2509. if (is_array($params)) {
  2510. $this->_tmp_file_post_params = array();
  2511. foreach ($params as $key => $value) {
  2512. if ($value instanceof stored_file) {
  2513. $value->add_to_curl_request($this, $key);
  2514. } else {
  2515. $this->_tmp_file_post_params[$key] = $value;
  2516. }
  2517. }
  2518. $options['CURLOPT_POSTFIELDS'] = $this->_tmp_file_post_params;
  2519. unset($this->_tmp_file_post_params);
  2520. } else {
  2521. // $params is the raw post data
  2522. $options['CURLOPT_POSTFIELDS'] = $params;
  2523. }
  2524. return $this->request($url, $options);
  2525. }
  2526. /**
  2527. * HTTP GET method
  2528. *
  2529. * @param string $url
  2530. * @param array $params
  2531. * @param array $options
  2532. * @return bool
  2533. */
  2534. public function get($url, $params = array(), $options = array()){
  2535. $options['CURLOPT_HTTPGET'] = 1;
  2536. if (!empty($params)){
  2537. $url .= (stripos($url, '?') !== false) ? '&' : '?';
  2538. $url .= http_build_query($params, '', '&');
  2539. }
  2540. return $this->request($url, $options);
  2541. }
  2542. /**
  2543. * HTTP PUT method
  2544. *
  2545. * @param string $url
  2546. * @param array $params
  2547. * @param array $options
  2548. * @return bool
  2549. */
  2550. public function put($url, $params = array(), $options = array()){
  2551. $file = $params['file'];
  2552. if (!is_file($file)){
  2553. return null;
  2554. }
  2555. $fp = fopen($file, 'r');
  2556. $size = filesize($file);
  2557. $options['CURLOPT_PUT'] = 1;
  2558. $options['CURLOPT_INFILESIZE'] = $size;
  2559. $options['CURLOPT_INFILE'] = $fp;
  2560. if (!isset($this->options['CURLOPT_USERPWD'])){
  2561. $this->setopt(array('CURLOPT_USERPWD'=>'anonymous: noreply@moodle.org'));
  2562. }
  2563. $ret = $this->request($url, $options);
  2564. fclose($fp);
  2565. return $ret;
  2566. }
  2567. /**
  2568. * HTTP DELETE method
  2569. *
  2570. * @param string $url
  2571. * @param array $params
  2572. * @param array $options
  2573. * @return bool
  2574. */
  2575. public function delete($url, $param = array(), $options = array()){
  2576. $options['CURLOPT_CUSTOMREQUEST'] = 'DELETE';
  2577. if (!isset($options['CURLOPT_USERPWD'])) {
  2578. $options['CURLOPT_USERPWD'] = 'anonymous: noreply@moodle.org';
  2579. }
  2580. $ret = $this->request($url, $options);
  2581. return $ret;
  2582. }
  2583. /**
  2584. * HTTP TRACE method
  2585. *
  2586. * @param string $url
  2587. * @param array $options
  2588. * @return bool
  2589. */
  2590. public function trace($url, $options = array()){
  2591. $options['CURLOPT_CUSTOMREQUEST'] = 'TRACE';
  2592. $ret = $this->request($url, $options);
  2593. return $ret;
  2594. }
  2595. /**
  2596. * HTTP OPTIONS method
  2597. *
  2598. * @param string $url
  2599. * @param array $options
  2600. * @return bool
  2601. */
  2602. public function options($url, $options = array()){
  2603. $options['CURLOPT_CUSTOMREQUEST'] = 'OPTIONS';
  2604. $ret = $this->request($url, $options);
  2605. return $ret;
  2606. }
  2607. public function get_info() {
  2608. return $this->info;
  2609. }
  2610. }
  2611. /**
  2612. * This class is used by cURL class, use case:
  2613. *
  2614. * <code>
  2615. * $CFG->repositorycacheexpire = 120;
  2616. * $CFG->curlcache = 120;
  2617. *
  2618. * $c = new curl(array('cache'=>true), 'module_cache'=>'repository');
  2619. * $ret = $c->get('http://www.google.com');
  2620. * </code>
  2621. *
  2622. * @package core
  2623. * @subpackage file
  2624. * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
  2625. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  2626. */
  2627. class curl_cache {
  2628. /** @var string */
  2629. public $dir = '';
  2630. /**
  2631. *
  2632. * @global object
  2633. * @param string @module which module is using curl_cache
  2634. *
  2635. */
  2636. function __construct($module = 'repository'){
  2637. global $CFG;
  2638. if (!empty($module)) {
  2639. $this->dir = $CFG->dataroot.'/cache/'.$module.'/';
  2640. } else {
  2641. $this->dir = $CFG->dataroot.'/cache/misc/';
  2642. }
  2643. if (!file_exists($this->dir)) {
  2644. mkdir($this->dir, $CFG->directorypermissions, true);
  2645. }
  2646. if ($module == 'repository') {
  2647. if (empty($CFG->repositorycacheexpire)) {
  2648. $CFG->repositorycacheexpire = 120;
  2649. }
  2650. $this->ttl = $CFG->repositorycacheexpire;
  2651. } else {
  2652. if (empty($CFG->curlcache)) {
  2653. $CFG->curlcache = 120;
  2654. }
  2655. $this->ttl = $CFG->curlcache;
  2656. }
  2657. }
  2658. /**
  2659. * Get cached value
  2660. *
  2661. * @global object
  2662. * @global object
  2663. * @param mixed $param
  2664. * @return bool|string
  2665. */
  2666. public function get($param){
  2667. global $CFG, $USER;
  2668. $this->cleanup($this->ttl);
  2669. $filename = 'u'.$USER->id.'_'.md5(serialize($param));
  2670. if(file_exists($this->dir.$filename)) {
  2671. $lasttime = filemtime($this->dir.$filename);
  2672. if(time()-$lasttime > $this->ttl)
  2673. {
  2674. return false;
  2675. } else {
  2676. $fp = fopen($this->dir.$filename, 'r');
  2677. $size = filesize($this->dir.$filename);
  2678. $content = fread($fp, $size);
  2679. return unserialize($content);
  2680. }
  2681. }
  2682. return false;
  2683. }
  2684. /**
  2685. * Set cache value
  2686. *
  2687. * @global object $CFG
  2688. * @global object $USER
  2689. * @param mixed $param
  2690. * @param mixed $val
  2691. */
  2692. public function set($param, $val){
  2693. global $CFG, $USER;
  2694. $filename = 'u'.$USER->id.'_'.md5(serialize($param));
  2695. $fp = fopen($this->dir.$filename, 'w');
  2696. fwrite($fp, serialize($val));
  2697. fclose($fp);
  2698. }
  2699. /**
  2700. * Remove cache files
  2701. *
  2702. * @param int $expire The number os seconds before expiry
  2703. */
  2704. public function cleanup($expire){
  2705. if($dir = opendir($this->dir)){
  2706. while (false !== ($file = readdir($dir))) {
  2707. if(!is_dir($file) && $file != '.' && $file != '..') {
  2708. $lasttime = @filemtime($this->dir.$file);
  2709. if(time() - $lasttime > $expire){
  2710. @unlink($this->dir.$file);
  2711. }
  2712. }
  2713. }
  2714. }
  2715. }
  2716. /**
  2717. * delete current user's cache file
  2718. *
  2719. * @global object $CFG
  2720. * @global object $USER
  2721. */
  2722. public function refresh(){
  2723. global $CFG, $USER;
  2724. if($dir = opendir($this->dir)){
  2725. while (false !== ($file = readdir($dir))) {
  2726. if(!is_dir($file) && $file != '.' && $file != '..') {
  2727. if(strpos($file, 'u'.$USER->id.'_')!==false){
  2728. @unlink($this->dir.$file);
  2729. }
  2730. }
  2731. }
  2732. }
  2733. }
  2734. }
  2735. /**
  2736. * This class is used to parse lib/file/file_types.mm which help get file
  2737. * extensions by file types.
  2738. * The file_types.mm file can be edited by freemind in graphic environment.
  2739. *
  2740. * @package core
  2741. * @subpackage file
  2742. * @copyright 2009 Dongsheng Cai <dongsheng@moodle.com>
  2743. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  2744. */
  2745. class filetype_parser {
  2746. /**
  2747. * Check file_types.mm file, setup variables
  2748. *
  2749. * @global object $CFG
  2750. * @param string $file
  2751. */
  2752. public function __construct($file = '') {
  2753. global $CFG;
  2754. if (empty($file)) {
  2755. $this->file = $CFG->libdir.'/filestorage/file_types.mm';
  2756. } else {
  2757. $this->file = $file;
  2758. }
  2759. $this->tree = array();
  2760. $this->result = array();
  2761. }
  2762. /**
  2763. * A private function to browse xml nodes
  2764. *
  2765. * @param array $parent
  2766. * @param array $types
  2767. */
  2768. private function _browse_nodes($parent, $types) {
  2769. $key = (string)$parent['TEXT'];
  2770. if(isset($parent->node)) {
  2771. $this->tree[$key] = array();
  2772. if (in_array((string)$parent['TEXT'], $types)) {
  2773. $this->_select_nodes($parent, $this->result);
  2774. } else {
  2775. foreach($parent->node as $v){
  2776. $this->_browse_nodes($v, $types);
  2777. }
  2778. }
  2779. } else {
  2780. $this->tree[] = $key;
  2781. }
  2782. }
  2783. /**
  2784. * A private function to select text nodes
  2785. *
  2786. * @param array $parent
  2787. */
  2788. private function _select_nodes($parent){
  2789. if(isset($parent->node)) {
  2790. foreach($parent->node as $v){
  2791. $this->_select_nodes($v, $this->result);
  2792. }
  2793. } else {
  2794. $this->result[] = (string)$parent['TEXT'];
  2795. }
  2796. }
  2797. /**
  2798. * Get file extensions by file types names.
  2799. *
  2800. * @param array $types
  2801. * @return mixed
  2802. */
  2803. public function get_extensions($types) {
  2804. if (!is_array($types)) {
  2805. $types = array($types);
  2806. }
  2807. $this->result = array();
  2808. if ((is_array($types) && in_array('*', $types)) ||
  2809. $types == '*' || empty($types)) {
  2810. return array('*');
  2811. }
  2812. foreach ($types as $key=>$value){
  2813. if (strpos($value, '.') !== false) {
  2814. $this->result[] = $value;
  2815. unset($types[$key]);
  2816. }
  2817. }
  2818. if (file_exists($this->file)) {
  2819. $xml = simplexml_load_file($this->file);
  2820. foreach($xml->node->node as $v){
  2821. if (in_array((string)$v['TEXT'], $types)) {
  2822. $this->_select_nodes($v);
  2823. } else {
  2824. $this->_browse_nodes($v, $types);
  2825. }
  2826. }
  2827. } else {
  2828. exit('Failed to open file lib/filestorage/file_types.mm');
  2829. }
  2830. return $this->result;
  2831. }
  2832. }