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

/moodle/lib/filelib.php

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