PageRenderTime 73ms CodeModel.GetById 18ms RepoModel.GetById 0ms app.codeStats 1ms

/moodle/lib/filelib.php

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