PageRenderTime 62ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/filelib.php

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