PageRenderTime 82ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/filelib.php

https://bitbucket.org/synergylearning/campusconnect
PHP | 4641 lines | 2952 code | 496 blank | 1193 comment | 841 complexity | e15babcf76eca6bbf660528573a12a06 MD5 | raw file
Possible License(s): MPL-2.0-no-copyleft-exception, LGPL-3.0, GPL-3.0, LGPL-2.1, Apache-2.0, BSD-3-Clause, AGPL-3.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_files
  20. * @copyright 1999 onwards Martin Dougiamas (http://dougiamas.com)
  21. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  22. */
  23. defined('MOODLE_INTERNAL') || die();
  24. /**
  25. * BYTESERVING_BOUNDARY - string unique string constant.
  26. */
  27. define('BYTESERVING_BOUNDARY', 's1k2o3d4a5k6s7');
  28. /**
  29. * Unlimited area size constant
  30. */
  31. define('FILE_AREA_MAX_BYTES_UNLIMITED', -1);
  32. require_once("$CFG->libdir/filestorage/file_exceptions.php");
  33. require_once("$CFG->libdir/filestorage/file_storage.php");
  34. require_once("$CFG->libdir/filestorage/zip_packer.php");
  35. require_once("$CFG->libdir/filebrowser/file_browser.php");
  36. /**
  37. * Encodes file serving url
  38. *
  39. * @deprecated use moodle_url factory methods instead
  40. *
  41. * @todo MDL-31071 deprecate this function
  42. * @global stdClass $CFG
  43. * @param string $urlbase
  44. * @param string $path /filearea/itemid/dir/dir/file.exe
  45. * @param bool $forcedownload
  46. * @param bool $https https url required
  47. * @return string encoded file url
  48. */
  49. function file_encode_url($urlbase, $path, $forcedownload=false, $https=false) {
  50. global $CFG;
  51. //TODO: deprecate this
  52. if ($CFG->slasharguments) {
  53. $parts = explode('/', $path);
  54. $parts = array_map('rawurlencode', $parts);
  55. $path = implode('/', $parts);
  56. $return = $urlbase.$path;
  57. if ($forcedownload) {
  58. $return .= '?forcedownload=1';
  59. }
  60. } else {
  61. $path = rawurlencode($path);
  62. $return = $urlbase.'?file='.$path;
  63. if ($forcedownload) {
  64. $return .= '&amp;forcedownload=1';
  65. }
  66. }
  67. if ($https) {
  68. $return = str_replace('http://', 'https://', $return);
  69. }
  70. return $return;
  71. }
  72. /**
  73. * Detects if area contains subdirs,
  74. * this is intended for file areas that are attached to content
  75. * migrated from 1.x where subdirs were allowed everywhere.
  76. *
  77. * @param context $context
  78. * @param string $component
  79. * @param string $filearea
  80. * @param string $itemid
  81. * @return bool
  82. */
  83. function file_area_contains_subdirs(context $context, $component, $filearea, $itemid) {
  84. global $DB;
  85. if (!isset($itemid)) {
  86. // Not initialised yet.
  87. return false;
  88. }
  89. // Detect if any directories are already present, this is necessary for content upgraded from 1.x.
  90. $select = "contextid = :contextid AND component = :component AND filearea = :filearea AND itemid = :itemid AND filepath <> '/' AND filename = '.'";
  91. $params = array('contextid'=>$context->id, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid);
  92. return $DB->record_exists_select('files', $select, $params);
  93. }
  94. /**
  95. * Prepares 'editor' formslib element from data in database
  96. *
  97. * The passed $data record must contain field foobar, foobarformat and optionally foobartrust. This
  98. * function then copies the embedded files into draft area (assigning itemids automatically),
  99. * creates the form element foobar_editor and rewrites the URLs so the embedded images can be
  100. * displayed.
  101. * In your mform definition, you must have an 'editor' element called foobar_editor. Then you call
  102. * your mform's set_data() supplying the object returned by this function.
  103. *
  104. * @category files
  105. * @param stdClass $data database field that holds the html text with embedded media
  106. * @param string $field the name of the database field that holds the html text with embedded media
  107. * @param array $options editor options (like maxifiles, maxbytes etc.)
  108. * @param stdClass $context context of the editor
  109. * @param string $component
  110. * @param string $filearea file area name
  111. * @param int $itemid item id, required if item exists
  112. * @return stdClass modified data object
  113. */
  114. function file_prepare_standard_editor($data, $field, array $options, $context=null, $component=null, $filearea=null, $itemid=null) {
  115. $options = (array)$options;
  116. if (!isset($options['trusttext'])) {
  117. $options['trusttext'] = false;
  118. }
  119. if (!isset($options['forcehttps'])) {
  120. $options['forcehttps'] = false;
  121. }
  122. if (!isset($options['subdirs'])) {
  123. $options['subdirs'] = false;
  124. }
  125. if (!isset($options['maxfiles'])) {
  126. $options['maxfiles'] = 0; // no files by default
  127. }
  128. if (!isset($options['noclean'])) {
  129. $options['noclean'] = false;
  130. }
  131. //sanity check for passed context. This function doesn't expect $option['context'] to be set
  132. //But this function is called before creating editor hence, this is one of the best places to check
  133. //if context is used properly. This check notify developer that they missed passing context to editor.
  134. if (isset($context) && !isset($options['context'])) {
  135. //if $context is not null then make sure $option['context'] is also set.
  136. debugging('Context for editor is not set in editoroptions. Hence editor will not respect editor filters', DEBUG_DEVELOPER);
  137. } else if (isset($options['context']) && isset($context)) {
  138. //If both are passed then they should be equal.
  139. if ($options['context']->id != $context->id) {
  140. $exceptionmsg = 'Editor context ['.$options['context']->id.'] is not equal to passed context ['.$context->id.']';
  141. throw new coding_exception($exceptionmsg);
  142. }
  143. }
  144. if (is_null($itemid) or is_null($context)) {
  145. $contextid = null;
  146. $itemid = null;
  147. if (!isset($data)) {
  148. $data = new stdClass();
  149. }
  150. if (!isset($data->{$field})) {
  151. $data->{$field} = '';
  152. }
  153. if (!isset($data->{$field.'format'})) {
  154. $data->{$field.'format'} = editors_get_preferred_format();
  155. }
  156. if (!$options['noclean']) {
  157. $data->{$field} = clean_text($data->{$field}, $data->{$field.'format'});
  158. }
  159. } else {
  160. if ($options['trusttext']) {
  161. // noclean ignored if trusttext enabled
  162. if (!isset($data->{$field.'trust'})) {
  163. $data->{$field.'trust'} = 0;
  164. }
  165. $data = trusttext_pre_edit($data, $field, $context);
  166. } else {
  167. if (!$options['noclean']) {
  168. $data->{$field} = clean_text($data->{$field}, $data->{$field.'format'});
  169. }
  170. }
  171. $contextid = $context->id;
  172. }
  173. if ($options['maxfiles'] != 0) {
  174. $draftid_editor = file_get_submitted_draft_itemid($field);
  175. $currenttext = file_prepare_draft_area($draftid_editor, $contextid, $component, $filearea, $itemid, $options, $data->{$field});
  176. $data->{$field.'_editor'} = array('text'=>$currenttext, 'format'=>$data->{$field.'format'}, 'itemid'=>$draftid_editor);
  177. } else {
  178. $data->{$field.'_editor'} = array('text'=>$data->{$field}, 'format'=>$data->{$field.'format'}, 'itemid'=>0);
  179. }
  180. return $data;
  181. }
  182. /**
  183. * Prepares the content of the 'editor' form element with embedded media files to be saved in database
  184. *
  185. * This function moves files from draft area to the destination area and
  186. * encodes URLs to the draft files so they can be safely saved into DB. The
  187. * form has to contain the 'editor' element named foobar_editor, where 'foobar'
  188. * is the name of the database field to hold the wysiwyg editor content. The
  189. * editor data comes as an array with text, format and itemid properties. This
  190. * function automatically adds $data properties foobar, foobarformat and
  191. * foobartrust, where foobar has URL to embedded files encoded.
  192. *
  193. * @category files
  194. * @param stdClass $data raw data submitted by the form
  195. * @param string $field name of the database field containing the html with embedded media files
  196. * @param array $options editor options (trusttext, subdirs, maxfiles, maxbytes etc.)
  197. * @param stdClass $context context, required for existing data
  198. * @param string $component file component
  199. * @param string $filearea file area name
  200. * @param int $itemid item id, required if item exists
  201. * @return stdClass modified data object
  202. */
  203. function file_postupdate_standard_editor($data, $field, array $options, $context, $component=null, $filearea=null, $itemid=null) {
  204. $options = (array)$options;
  205. if (!isset($options['trusttext'])) {
  206. $options['trusttext'] = false;
  207. }
  208. if (!isset($options['forcehttps'])) {
  209. $options['forcehttps'] = false;
  210. }
  211. if (!isset($options['subdirs'])) {
  212. $options['subdirs'] = false;
  213. }
  214. if (!isset($options['maxfiles'])) {
  215. $options['maxfiles'] = 0; // no files by default
  216. }
  217. if (!isset($options['maxbytes'])) {
  218. $options['maxbytes'] = 0; // unlimited
  219. }
  220. if ($options['trusttext']) {
  221. $data->{$field.'trust'} = trusttext_trusted($context);
  222. } else {
  223. $data->{$field.'trust'} = 0;
  224. }
  225. $editor = $data->{$field.'_editor'};
  226. if ($options['maxfiles'] == 0 or is_null($filearea) or is_null($itemid) or empty($editor['itemid'])) {
  227. $data->{$field} = $editor['text'];
  228. } else {
  229. $data->{$field} = file_save_draft_area_files($editor['itemid'], $context->id, $component, $filearea, $itemid, $options, $editor['text'], $options['forcehttps']);
  230. }
  231. $data->{$field.'format'} = $editor['format'];
  232. return $data;
  233. }
  234. /**
  235. * Saves text and files modified by Editor formslib element
  236. *
  237. * @category files
  238. * @param stdClass $data $database entry field
  239. * @param string $field name of data field
  240. * @param array $options various options
  241. * @param stdClass $context context - must already exist
  242. * @param string $component
  243. * @param string $filearea file area name
  244. * @param int $itemid must already exist, usually means data is in db
  245. * @return stdClass modified data obejct
  246. */
  247. function file_prepare_standard_filemanager($data, $field, array $options, $context=null, $component=null, $filearea=null, $itemid=null) {
  248. $options = (array)$options;
  249. if (!isset($options['subdirs'])) {
  250. $options['subdirs'] = false;
  251. }
  252. if (is_null($itemid) or is_null($context)) {
  253. $itemid = null;
  254. $contextid = null;
  255. } else {
  256. $contextid = $context->id;
  257. }
  258. $draftid_editor = file_get_submitted_draft_itemid($field.'_filemanager');
  259. file_prepare_draft_area($draftid_editor, $contextid, $component, $filearea, $itemid, $options);
  260. $data->{$field.'_filemanager'} = $draftid_editor;
  261. return $data;
  262. }
  263. /**
  264. * Saves files modified by File manager formslib element
  265. *
  266. * @todo MDL-31073 review this function
  267. * @category files
  268. * @param stdClass $data $database entry field
  269. * @param string $field name of data field
  270. * @param array $options various options
  271. * @param stdClass $context context - must already exist
  272. * @param string $component
  273. * @param string $filearea file area name
  274. * @param int $itemid must already exist, usually means data is in db
  275. * @return stdClass modified data obejct
  276. */
  277. function file_postupdate_standard_filemanager($data, $field, array $options, $context, $component, $filearea, $itemid) {
  278. $options = (array)$options;
  279. if (!isset($options['subdirs'])) {
  280. $options['subdirs'] = false;
  281. }
  282. if (!isset($options['maxfiles'])) {
  283. $options['maxfiles'] = -1; // unlimited
  284. }
  285. if (!isset($options['maxbytes'])) {
  286. $options['maxbytes'] = 0; // unlimited
  287. }
  288. if (empty($data->{$field.'_filemanager'})) {
  289. $data->$field = '';
  290. } else {
  291. file_save_draft_area_files($data->{$field.'_filemanager'}, $context->id, $component, $filearea, $itemid, $options);
  292. $fs = get_file_storage();
  293. if ($fs->get_area_files($context->id, $component, $filearea, $itemid)) {
  294. $data->$field = '1'; // TODO: this is an ugly hack (skodak)
  295. } else {
  296. $data->$field = '';
  297. }
  298. }
  299. return $data;
  300. }
  301. /**
  302. * Generate a draft itemid
  303. *
  304. * @category files
  305. * @global moodle_database $DB
  306. * @global stdClass $USER
  307. * @return int a random but available draft itemid that can be used to create a new draft
  308. * file area.
  309. */
  310. function file_get_unused_draft_itemid() {
  311. global $DB, $USER;
  312. if (isguestuser() or !isloggedin()) {
  313. // guests and not-logged-in users can not be allowed to upload anything!!!!!!
  314. print_error('noguest');
  315. }
  316. $contextid = context_user::instance($USER->id)->id;
  317. $fs = get_file_storage();
  318. $draftitemid = rand(1, 999999999);
  319. while ($files = $fs->get_area_files($contextid, 'user', 'draft', $draftitemid)) {
  320. $draftitemid = rand(1, 999999999);
  321. }
  322. return $draftitemid;
  323. }
  324. /**
  325. * Initialise a draft file area from a real one by copying the files. A draft
  326. * area will be created if one does not already exist. Normally you should
  327. * get $draftitemid by calling file_get_submitted_draft_itemid('elementname');
  328. *
  329. * @category files
  330. * @global stdClass $CFG
  331. * @global stdClass $USER
  332. * @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.
  333. * @param int $contextid This parameter and the next two identify the file area to copy files from.
  334. * @param string $component
  335. * @param string $filearea helps indentify the file area.
  336. * @param int $itemid helps identify the file area. Can be null if there are no files yet.
  337. * @param array $options text and file options ('subdirs'=>false, 'forcehttps'=>false)
  338. * @param string $text some html content that needs to have embedded links rewritten to point to the draft area.
  339. * @return string|null returns string if $text was passed in, the rewritten $text is returned. Otherwise NULL.
  340. */
  341. function file_prepare_draft_area(&$draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null) {
  342. global $CFG, $USER, $CFG;
  343. $options = (array)$options;
  344. if (!isset($options['subdirs'])) {
  345. $options['subdirs'] = false;
  346. }
  347. if (!isset($options['forcehttps'])) {
  348. $options['forcehttps'] = false;
  349. }
  350. $usercontext = context_user::instance($USER->id);
  351. $fs = get_file_storage();
  352. if (empty($draftitemid)) {
  353. // create a new area and copy existing files into
  354. $draftitemid = file_get_unused_draft_itemid();
  355. $file_record = array('contextid'=>$usercontext->id, 'component'=>'user', 'filearea'=>'draft', 'itemid'=>$draftitemid);
  356. if (!is_null($itemid) and $files = $fs->get_area_files($contextid, $component, $filearea, $itemid)) {
  357. foreach ($files as $file) {
  358. if ($file->is_directory() and $file->get_filepath() === '/') {
  359. // we need a way to mark the age of each draft area,
  360. // by not copying the root dir we force it to be created automatically with current timestamp
  361. continue;
  362. }
  363. if (!$options['subdirs'] and ($file->is_directory() or $file->get_filepath() !== '/')) {
  364. continue;
  365. }
  366. $draftfile = $fs->create_file_from_storedfile($file_record, $file);
  367. // XXX: This is a hack for file manager (MDL-28666)
  368. // File manager needs to know the original file information before copying
  369. // to draft area, so we append these information in mdl_files.source field
  370. // {@link file_storage::search_references()}
  371. // {@link file_storage::search_references_count()}
  372. $sourcefield = $file->get_source();
  373. $newsourcefield = new stdClass;
  374. $newsourcefield->source = $sourcefield;
  375. $original = new stdClass;
  376. $original->contextid = $contextid;
  377. $original->component = $component;
  378. $original->filearea = $filearea;
  379. $original->itemid = $itemid;
  380. $original->filename = $file->get_filename();
  381. $original->filepath = $file->get_filepath();
  382. $newsourcefield->original = file_storage::pack_reference($original);
  383. $draftfile->set_source(serialize($newsourcefield));
  384. // End of file manager hack
  385. }
  386. }
  387. if (!is_null($text)) {
  388. // at this point there should not be any draftfile links yet,
  389. // because this is a new text from database that should still contain the @@pluginfile@@ links
  390. // this happens when developers forget to post process the text
  391. $text = str_replace("\"$CFG->httpswwwroot/draftfile.php", "\"$CFG->httpswwwroot/brokenfile.php#", $text);
  392. }
  393. } else {
  394. // nothing to do
  395. }
  396. if (is_null($text)) {
  397. return null;
  398. }
  399. // relink embedded files - editor can not handle @@PLUGINFILE@@ !
  400. return file_rewrite_pluginfile_urls($text, 'draftfile.php', $usercontext->id, 'user', 'draft', $draftitemid, $options);
  401. }
  402. /**
  403. * Convert encoded URLs in $text from the @@PLUGINFILE@@/... form to an actual URL.
  404. *
  405. * @category files
  406. * @global stdClass $CFG
  407. * @param string $text The content that may contain ULRs in need of rewriting.
  408. * @param string $file The script that should be used to serve these files. pluginfile.php, draftfile.php, etc.
  409. * @param int $contextid This parameter and the next two identify the file area to use.
  410. * @param string $component
  411. * @param string $filearea helps identify the file area.
  412. * @param int $itemid helps identify the file area.
  413. * @param array $options text and file options ('forcehttps'=>false)
  414. * @return string the processed text.
  415. */
  416. function file_rewrite_pluginfile_urls($text, $file, $contextid, $component, $filearea, $itemid, array $options=null) {
  417. global $CFG;
  418. $options = (array)$options;
  419. if (!isset($options['forcehttps'])) {
  420. $options['forcehttps'] = false;
  421. }
  422. if (!$CFG->slasharguments) {
  423. $file = $file . '?file=';
  424. }
  425. $baseurl = "$CFG->wwwroot/$file/$contextid/$component/$filearea/";
  426. if ($itemid !== null) {
  427. $baseurl .= "$itemid/";
  428. }
  429. if ($options['forcehttps']) {
  430. $baseurl = str_replace('http://', 'https://', $baseurl);
  431. }
  432. return str_replace('@@PLUGINFILE@@/', $baseurl, $text);
  433. }
  434. /**
  435. * Returns information about files in a draft area.
  436. *
  437. * @global stdClass $CFG
  438. * @global stdClass $USER
  439. * @param int $draftitemid the draft area item id.
  440. * @param string $filepath path to the directory from which the information have to be retrieved.
  441. * @return array with the following entries:
  442. * 'filecount' => number of files in the draft area.
  443. * 'filesize' => total size of the files in the draft area.
  444. * 'foldercount' => number of folders in the draft area.
  445. * 'filesize_without_references' => total size of the area excluding file references.
  446. * (more information will be added as needed).
  447. */
  448. function file_get_draft_area_info($draftitemid, $filepath = '/') {
  449. global $CFG, $USER;
  450. $usercontext = context_user::instance($USER->id);
  451. $fs = get_file_storage();
  452. $results = array(
  453. 'filecount' => 0,
  454. 'foldercount' => 0,
  455. 'filesize' => 0,
  456. 'filesize_without_references' => 0
  457. );
  458. if ($filepath != '/') {
  459. $draftfiles = $fs->get_directory_files($usercontext->id, 'user', 'draft', $draftitemid, $filepath, true, true);
  460. } else {
  461. $draftfiles = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftitemid, 'id', true);
  462. }
  463. foreach ($draftfiles as $file) {
  464. if ($file->is_directory()) {
  465. $results['foldercount'] += 1;
  466. } else {
  467. $results['filecount'] += 1;
  468. }
  469. $filesize = $file->get_filesize();
  470. $results['filesize'] += $filesize;
  471. if (!$file->is_external_file()) {
  472. $results['filesize_without_references'] += $filesize;
  473. }
  474. }
  475. return $results;
  476. }
  477. /**
  478. * Returns whether a draft area has exceeded/will exceed its size limit.
  479. *
  480. * Please note that the unlimited value for $areamaxbytes is -1 {@link FILE_AREA_MAX_BYTES_UNLIMITED}, not 0.
  481. *
  482. * @param int $draftitemid the draft area item id.
  483. * @param int $areamaxbytes the maximum size allowed in this draft area.
  484. * @param int $newfilesize the size that would be added to the current area.
  485. * @param bool $includereferences true to include the size of the references in the area size.
  486. * @return bool true if the area will/has exceeded its limit.
  487. * @since 2.4
  488. */
  489. function file_is_draft_area_limit_reached($draftitemid, $areamaxbytes, $newfilesize = 0, $includereferences = false) {
  490. if ($areamaxbytes != FILE_AREA_MAX_BYTES_UNLIMITED) {
  491. $draftinfo = file_get_draft_area_info($draftitemid);
  492. $areasize = $draftinfo['filesize_without_references'];
  493. if ($includereferences) {
  494. $areasize = $draftinfo['filesize'];
  495. }
  496. if ($areasize + $newfilesize > $areamaxbytes) {
  497. return true;
  498. }
  499. }
  500. return false;
  501. }
  502. /**
  503. * Get used space of files
  504. * @global moodle_database $DB
  505. * @global stdClass $USER
  506. * @return int total bytes
  507. */
  508. function file_get_user_used_space() {
  509. global $DB, $USER;
  510. $usercontext = context_user::instance($USER->id);
  511. $sql = "SELECT SUM(files1.filesize) AS totalbytes FROM {files} files1
  512. JOIN (SELECT contenthash, filename, MAX(id) AS id
  513. FROM {files}
  514. WHERE contextid = ? AND component = ? AND filearea != ?
  515. GROUP BY contenthash, filename) files2 ON files1.id = files2.id";
  516. $params = array('contextid'=>$usercontext->id, 'component'=>'user', 'filearea'=>'draft');
  517. $record = $DB->get_record_sql($sql, $params);
  518. return (int)$record->totalbytes;
  519. }
  520. /**
  521. * Convert any string to a valid filepath
  522. * @todo review this function
  523. * @param string $str
  524. * @return string path
  525. */
  526. function file_correct_filepath($str) { //TODO: what is this? (skodak) - No idea (Fred)
  527. if ($str == '/' or empty($str)) {
  528. return '/';
  529. } else {
  530. return '/'.trim($str, '/').'/';
  531. }
  532. }
  533. /**
  534. * Generate a folder tree of draft area of current USER recursively
  535. *
  536. * @todo MDL-31073 use normal return value instead, this does not fit the rest of api here (skodak)
  537. * @param int $draftitemid
  538. * @param string $filepath
  539. * @param mixed $data
  540. */
  541. function file_get_drafarea_folders($draftitemid, $filepath, &$data) {
  542. global $USER, $OUTPUT, $CFG;
  543. $data->children = array();
  544. $context = context_user::instance($USER->id);
  545. $fs = get_file_storage();
  546. if ($files = $fs->get_directory_files($context->id, 'user', 'draft', $draftitemid, $filepath, false)) {
  547. foreach ($files as $file) {
  548. if ($file->is_directory()) {
  549. $item = new stdClass();
  550. $item->sortorder = $file->get_sortorder();
  551. $item->filepath = $file->get_filepath();
  552. $foldername = explode('/', trim($item->filepath, '/'));
  553. $item->fullname = trim(array_pop($foldername), '/');
  554. $item->id = uniqid();
  555. file_get_drafarea_folders($draftitemid, $item->filepath, $item);
  556. $data->children[] = $item;
  557. } else {
  558. continue;
  559. }
  560. }
  561. }
  562. }
  563. /**
  564. * Listing all files (including folders) in current path (draft area)
  565. * used by file manager
  566. * @param int $draftitemid
  567. * @param string $filepath
  568. * @return stdClass
  569. */
  570. function file_get_drafarea_files($draftitemid, $filepath = '/') {
  571. global $USER, $OUTPUT, $CFG;
  572. $context = context_user::instance($USER->id);
  573. $fs = get_file_storage();
  574. $data = new stdClass();
  575. $data->path = array();
  576. $data->path[] = array('name'=>get_string('files'), 'path'=>'/');
  577. // will be used to build breadcrumb
  578. $trail = '/';
  579. if ($filepath !== '/') {
  580. $filepath = file_correct_filepath($filepath);
  581. $parts = explode('/', $filepath);
  582. foreach ($parts as $part) {
  583. if ($part != '' && $part != null) {
  584. $trail .= ($part.'/');
  585. $data->path[] = array('name'=>$part, 'path'=>$trail);
  586. }
  587. }
  588. }
  589. $list = array();
  590. $maxlength = 12;
  591. if ($files = $fs->get_directory_files($context->id, 'user', 'draft', $draftitemid, $filepath, false)) {
  592. foreach ($files as $file) {
  593. $item = new stdClass();
  594. $item->filename = $file->get_filename();
  595. $item->filepath = $file->get_filepath();
  596. $item->fullname = trim($item->filename, '/');
  597. $filesize = $file->get_filesize();
  598. $item->size = $filesize ? $filesize : null;
  599. $item->filesize = $filesize ? display_size($filesize) : '';
  600. $item->sortorder = $file->get_sortorder();
  601. $item->author = $file->get_author();
  602. $item->license = $file->get_license();
  603. $item->datemodified = $file->get_timemodified();
  604. $item->datecreated = $file->get_timecreated();
  605. $item->isref = $file->is_external_file();
  606. if ($item->isref && $file->get_status() == 666) {
  607. $item->originalmissing = true;
  608. }
  609. // find the file this draft file was created from and count all references in local
  610. // system pointing to that file
  611. $source = @unserialize($file->get_source());
  612. if (isset($source->original)) {
  613. $item->refcount = $fs->search_references_count($source->original);
  614. }
  615. if ($file->is_directory()) {
  616. $item->filesize = 0;
  617. $item->icon = $OUTPUT->pix_url(file_folder_icon(24))->out(false);
  618. $item->type = 'folder';
  619. $foldername = explode('/', trim($item->filepath, '/'));
  620. $item->fullname = trim(array_pop($foldername), '/');
  621. $item->thumbnail = $OUTPUT->pix_url(file_folder_icon(90))->out(false);
  622. } else {
  623. // do NOT use file browser here!
  624. $item->mimetype = get_mimetype_description($file);
  625. if (file_extension_in_typegroup($file->get_filename(), 'archive')) {
  626. $item->type = 'zip';
  627. } else {
  628. $item->type = 'file';
  629. }
  630. $itemurl = moodle_url::make_draftfile_url($draftitemid, $item->filepath, $item->filename);
  631. $item->url = $itemurl->out();
  632. $item->icon = $OUTPUT->pix_url(file_file_icon($file, 24))->out(false);
  633. $item->thumbnail = $OUTPUT->pix_url(file_file_icon($file, 90))->out(false);
  634. if ($imageinfo = $file->get_imageinfo()) {
  635. $item->realthumbnail = $itemurl->out(false, array('preview' => 'thumb', 'oid' => $file->get_timemodified()));
  636. $item->realicon = $itemurl->out(false, array('preview' => 'tinyicon', 'oid' => $file->get_timemodified()));
  637. $item->image_width = $imageinfo['width'];
  638. $item->image_height = $imageinfo['height'];
  639. }
  640. }
  641. $list[] = $item;
  642. }
  643. }
  644. $data->itemid = $draftitemid;
  645. $data->list = $list;
  646. return $data;
  647. }
  648. /**
  649. * Returns draft area itemid for a given element.
  650. *
  651. * @category files
  652. * @param string $elname name of formlib editor element, or a hidden form field that stores the draft area item id, etc.
  653. * @return int the itemid, or 0 if there is not one yet.
  654. */
  655. function file_get_submitted_draft_itemid($elname) {
  656. // this is a nasty hack, ideally all new elements should use arrays here or there should be a new parameter
  657. if (!isset($_REQUEST[$elname])) {
  658. return 0;
  659. }
  660. if (is_array($_REQUEST[$elname])) {
  661. $param = optional_param_array($elname, 0, PARAM_INT);
  662. if (!empty($param['itemid'])) {
  663. $param = $param['itemid'];
  664. } else {
  665. debugging('Missing itemid, maybe caused by unset maxfiles option', DEBUG_DEVELOPER);
  666. return false;
  667. }
  668. } else {
  669. $param = optional_param($elname, 0, PARAM_INT);
  670. }
  671. if ($param) {
  672. require_sesskey();
  673. }
  674. return $param;
  675. }
  676. /**
  677. * Restore the original source field from draft files
  678. *
  679. * Do not use this function because it makes field files.source inconsistent
  680. * for draft area files. This function will be deprecated in 2.6
  681. *
  682. * @param stored_file $storedfile This only works with draft files
  683. * @return stored_file
  684. */
  685. function file_restore_source_field_from_draft_file($storedfile) {
  686. $source = @unserialize($storedfile->get_source());
  687. if (!empty($source)) {
  688. if (is_object($source)) {
  689. $restoredsource = $source->source;
  690. $storedfile->set_source($restoredsource);
  691. } else {
  692. throw new moodle_exception('invalidsourcefield', 'error');
  693. }
  694. }
  695. return $storedfile;
  696. }
  697. /**
  698. * Saves files from a draft file area to a real one (merging the list of files).
  699. * Can rewrite URLs in some content at the same time if desired.
  700. *
  701. * @category files
  702. * @global stdClass $USER
  703. * @param int $draftitemid the id of the draft area to use. Normally obtained
  704. * from file_get_submitted_draft_itemid('elementname') or similar.
  705. * @param int $contextid This parameter and the next two identify the file area to save to.
  706. * @param string $component
  707. * @param string $filearea indentifies the file area.
  708. * @param int $itemid helps identifies the file area.
  709. * @param array $options area options (subdirs=>false, maxfiles=-1, maxbytes=0)
  710. * @param string $text some html content that needs to have embedded links rewritten
  711. * to the @@PLUGINFILE@@ form for saving in the database.
  712. * @param bool $forcehttps force https urls.
  713. * @return string|null if $text was passed in, the rewritten $text is returned. Otherwise NULL.
  714. */
  715. function file_save_draft_area_files($draftitemid, $contextid, $component, $filearea, $itemid, array $options=null, $text=null, $forcehttps=false) {
  716. global $USER;
  717. $usercontext = context_user::instance($USER->id);
  718. $fs = get_file_storage();
  719. $options = (array)$options;
  720. if (!isset($options['subdirs'])) {
  721. $options['subdirs'] = false;
  722. }
  723. if (!isset($options['maxfiles'])) {
  724. $options['maxfiles'] = -1; // unlimited
  725. }
  726. if (!isset($options['maxbytes']) || $options['maxbytes'] == USER_CAN_IGNORE_FILE_SIZE_LIMITS) {
  727. $options['maxbytes'] = 0; // unlimited
  728. }
  729. if (!isset($options['areamaxbytes'])) {
  730. $options['areamaxbytes'] = FILE_AREA_MAX_BYTES_UNLIMITED; // Unlimited.
  731. }
  732. $allowreferences = true;
  733. if (isset($options['return_types']) && !($options['return_types'] & FILE_REFERENCE)) {
  734. // we assume that if $options['return_types'] is NOT specified, we DO allow references.
  735. // this is not exactly right. BUT there are many places in code where filemanager options
  736. // are not passed to file_save_draft_area_files()
  737. $allowreferences = false;
  738. }
  739. // Check if the draft area has exceeded the authorised limit. This should never happen as validation
  740. // should have taken place before, unless the user is doing something nauthly. If so, let's just not save
  741. // anything at all in the next area.
  742. if (file_is_draft_area_limit_reached($draftitemid, $options['areamaxbytes'])) {
  743. return null;
  744. }
  745. $draftfiles = $fs->get_area_files($usercontext->id, 'user', 'draft', $draftitemid, 'id');
  746. $oldfiles = $fs->get_area_files($contextid, $component, $filearea, $itemid, 'id');
  747. // One file in filearea means it is empty (it has only top-level directory '.').
  748. if (count($draftfiles) > 1 || count($oldfiles) > 1) {
  749. // we have to merge old and new files - we want to keep file ids for files that were not changed
  750. // we change time modified for all new and changed files, we keep time created as is
  751. $newhashes = array();
  752. $filecount = 0;
  753. foreach ($draftfiles as $file) {
  754. if (!$options['subdirs'] && $file->get_filepath() !== '/') {
  755. continue;
  756. }
  757. if (!$allowreferences && $file->is_external_file()) {
  758. continue;
  759. }
  760. if (!$file->is_directory()) {
  761. if ($options['maxbytes'] and $options['maxbytes'] < $file->get_filesize()) {
  762. // oversized file - should not get here at all
  763. continue;
  764. }
  765. if ($options['maxfiles'] != -1 and $options['maxfiles'] <= $filecount) {
  766. // more files - should not get here at all
  767. continue;
  768. }
  769. $filecount++;
  770. }
  771. $newhash = $fs->get_pathname_hash($contextid, $component, $filearea, $itemid, $file->get_filepath(), $file->get_filename());
  772. $newhashes[$newhash] = $file;
  773. }
  774. // Loop through oldfiles and decide which we need to delete and which to update.
  775. // After this cycle the array $newhashes will only contain the files that need to be added.
  776. foreach ($oldfiles as $oldfile) {
  777. $oldhash = $oldfile->get_pathnamehash();
  778. if (!isset($newhashes[$oldhash])) {
  779. // delete files not needed any more - deleted by user
  780. $oldfile->delete();
  781. continue;
  782. }
  783. $newfile = $newhashes[$oldhash];
  784. // Now we know that we have $oldfile and $newfile for the same path.
  785. // Let's check if we can update this file or we need to delete and create.
  786. if ($newfile->is_directory()) {
  787. // Directories are always ok to just update.
  788. } else if (($source = @unserialize($newfile->get_source())) && isset($source->original)) {
  789. // File has the 'original' - we need to update the file (it may even have not been changed at all).
  790. $original = file_storage::unpack_reference($source->original);
  791. if ($original['filename'] !== $oldfile->get_filename() || $original['filepath'] !== $oldfile->get_filepath()) {
  792. // Very odd, original points to another file. Delete and create file.
  793. $oldfile->delete();
  794. continue;
  795. }
  796. } else {
  797. // The same file name but absence of 'original' means that file was deteled and uploaded again.
  798. // By deleting and creating new file we properly manage all existing references.
  799. $oldfile->delete();
  800. continue;
  801. }
  802. // status changed, we delete old file, and create a new one
  803. if ($oldfile->get_status() != $newfile->get_status()) {
  804. // file was changed, use updated with new timemodified data
  805. $oldfile->delete();
  806. // This file will be added later
  807. continue;
  808. }
  809. // Updated author
  810. if ($oldfile->get_author() != $newfile->get_author()) {
  811. $oldfile->set_author($newfile->get_author());
  812. }
  813. // Updated license
  814. if ($oldfile->get_license() != $newfile->get_license()) {
  815. $oldfile->set_license($newfile->get_license());
  816. }
  817. // Updated file source
  818. // Field files.source for draftarea files contains serialised object with source and original information.
  819. // We only store the source part of it for non-draft file area.
  820. $newsource = $newfile->get_source();
  821. if ($source = @unserialize($newfile->get_source())) {
  822. $newsource = $source->source;
  823. }
  824. if ($oldfile->get_source() !== $newsource) {
  825. $oldfile->set_source($newsource);
  826. }
  827. // Updated sort order
  828. if ($oldfile->get_sortorder() != $newfile->get_sortorder()) {
  829. $oldfile->set_sortorder($newfile->get_sortorder());
  830. }
  831. // Update file timemodified
  832. if ($oldfile->get_timemodified() != $newfile->get_timemodified()) {
  833. $oldfile->set_timemodified($newfile->get_timemodified());
  834. }
  835. // Replaced file content
  836. if (!$oldfile->is_directory() &&
  837. ($oldfile->get_contenthash() != $newfile->get_contenthash() ||
  838. $oldfile->get_filesize() != $newfile->get_filesize() ||
  839. $oldfile->get_referencefileid() != $newfile->get_referencefileid() ||
  840. $oldfile->get_userid() != $newfile->get_userid())) {
  841. $oldfile->replace_file_with($newfile);
  842. }
  843. // unchanged file or directory - we keep it as is
  844. unset($newhashes[$oldhash]);
  845. }
  846. // Add fresh file or the file which has changed status
  847. // the size and subdirectory tests are extra safety only, the UI should prevent it
  848. foreach ($newhashes as $file) {
  849. $file_record = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'timemodified'=>time());
  850. if ($source = @unserialize($file->get_source())) {
  851. // Field files.source for draftarea files contains serialised object with source and original information.
  852. // We only store the source part of it for non-draft file area.
  853. $file_record['source'] = $source->source;
  854. }
  855. if ($file->is_external_file()) {
  856. $repoid = $file->get_repository_id();
  857. if (!empty($repoid)) {
  858. $file_record['repositoryid'] = $repoid;
  859. $file_record['reference'] = $file->get_reference();
  860. }
  861. }
  862. $fs->create_file_from_storedfile($file_record, $file);
  863. }
  864. }
  865. // note: do not purge the draft area - we clean up areas later in cron,
  866. // the reason is that user might press submit twice and they would loose the files,
  867. // also sometimes we might want to use hacks that save files into two different areas
  868. if (is_null($text)) {
  869. return null;
  870. } else {
  871. return file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps);
  872. }
  873. }
  874. /**
  875. * Convert the draft file area URLs in some content to @@PLUGINFILE@@ tokens
  876. * ready to be saved in the database. Normally, this is done automatically by
  877. * {@link file_save_draft_area_files()}.
  878. *
  879. * @category files
  880. * @param string $text the content to process.
  881. * @param int $draftitemid the draft file area the content was using.
  882. * @param bool $forcehttps whether the content contains https URLs. Default false.
  883. * @return string the processed content.
  884. */
  885. function file_rewrite_urls_to_pluginfile($text, $draftitemid, $forcehttps = false) {
  886. global $CFG, $USER;
  887. $usercontext = context_user::instance($USER->id);
  888. $wwwroot = $CFG->wwwroot;
  889. if ($forcehttps) {
  890. $wwwroot = str_replace('http://', 'https://', $wwwroot);
  891. }
  892. // relink embedded files if text submitted - no absolute links allowed in database!
  893. $text = str_ireplace("$wwwroot/draftfile.php/$usercontext->id/user/draft/$draftitemid/", '@@PLUGINFILE@@/', $text);
  894. if (strpos($text, 'draftfile.php?file=') !== false) {
  895. $matches = array();
  896. preg_match_all("!$wwwroot/draftfile.php\?file=%2F{$usercontext->id}%2Fuser%2Fdraft%2F{$draftitemid}%2F[^'\",&<>|`\s:\\\\]+!iu", $text, $matches);
  897. if ($matches) {
  898. foreach ($matches[0] as $match) {
  899. $replace = str_ireplace('%2F', '/', $match);
  900. $text = str_replace($match, $replace, $text);
  901. }
  902. }
  903. $text = str_ireplace("$wwwroot/draftfile.php?file=/$usercontext->id/user/draft/$draftitemid/", '@@PLUGINFILE@@/', $text);
  904. }
  905. return $text;
  906. }
  907. /**
  908. * Set file sort order
  909. *
  910. * @global moodle_database $DB
  911. * @param int $contextid the context id
  912. * @param string $component file component
  913. * @param string $filearea file area.
  914. * @param int $itemid itemid.
  915. * @param string $filepath file path.
  916. * @param string $filename file name.
  917. * @param int $sortorder the sort order of file.
  918. * @return bool
  919. */
  920. function file_set_sortorder($contextid, $component, $filearea, $itemid, $filepath, $filename, $sortorder) {
  921. global $DB;
  922. $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea, 'itemid'=>$itemid, 'filepath'=>$filepath, 'filename'=>$filename);
  923. if ($file_record = $DB->get_record('files', $conditions)) {
  924. $sortorder = (int)$sortorder;
  925. $file_record->sortorder = $sortorder;
  926. $DB->update_record('files', $file_record);
  927. return true;
  928. }
  929. return false;
  930. }
  931. /**
  932. * reset file sort order number to 0
  933. * @global moodle_database $DB
  934. * @param int $contextid the context id
  935. * @param string $component
  936. * @param string $filearea file area.
  937. * @param int|bool $itemid itemid.
  938. * @return bool
  939. */
  940. function file_reset_sortorder($contextid, $component, $filearea, $itemid=false) {
  941. global $DB;
  942. $conditions = array('contextid'=>$contextid, 'component'=>$component, 'filearea'=>$filearea);
  943. if ($itemid !== false) {
  944. $conditions['itemid'] = $itemid;
  945. }
  946. $file_records = $DB->get_records('files', $conditions);
  947. foreach ($file_records as $file_record) {
  948. $file_record->sortorder = 0;
  949. $DB->update_record('files', $file_record);
  950. }
  951. return true;
  952. }
  953. /**
  954. * Returns description of upload error
  955. *
  956. * @param int $errorcode found in $_FILES['filename.ext']['error']
  957. * @return string error description string, '' if ok
  958. */
  959. function file_get_upload_error($errorcode) {
  960. switch ($errorcode) {
  961. case 0: // UPLOAD_ERR_OK - no error
  962. $errmessage = '';
  963. break;
  964. case 1: // UPLOAD_ERR_INI_SIZE
  965. $errmessage = get_string('uploadserverlimit');
  966. break;
  967. case 2: // UPLOAD_ERR_FORM_SIZE
  968. $errmessage = get_string('uploadformlimit');
  969. break;
  970. case 3: // UPLOAD_ERR_PARTIAL
  971. $errmessage = get_string('uploadpartialfile');
  972. break;
  973. case 4: // UPLOAD_ERR_NO_FILE
  974. $errmessage = get_string('uploadnofilefound');
  975. break;
  976. // Note: there is no error with a value of 5
  977. case 6: // UPLOAD_ERR_NO_TMP_DIR
  978. $errmessage = get_string('uploadnotempdir');
  979. break;
  980. case 7: // UPLOAD_ERR_CANT_WRITE
  981. $errmessage = get_string('uploadcantwrite');
  982. break;
  983. case 8: // UPLOAD_ERR_EXTENSION
  984. $errmessage = get_string('uploadextension');
  985. break;
  986. default:
  987. $errmessage = get_string('uploadproblem');
  988. }
  989. return $errmessage;
  990. }
  991. /**
  992. * Recursive function formating an array in POST parameter
  993. * @param array $arraydata - the array that we are going to format and add into &$data array
  994. * @param string $currentdata - a row of the final postdata array at instant T
  995. * when finish, it's assign to $data under this format: name[keyname][][]...[]='value'
  996. * @param array $data - the final data array containing all POST parameters : 1 row = 1 parameter
  997. */
  998. function format_array_postdata_for_curlcall($arraydata, $currentdata, &$data) {
  999. foreach ($arraydata as $k=>$v) {
  1000. $newcurrentdata = $currentdata;
  1001. if (is_array($v)) { //the value is an array, call the function recursively
  1002. $newcurrentdata = $newcurrentdata.'['.urlencode($k).']';
  1003. format_array_postdata_for_curlcall($v, $newcurrentdata, $data);
  1004. } else { //add the POST parameter to the $data array
  1005. $data[] = $newcurrentdata.'['.urlencode($k).']='.urlencode($v);
  1006. }
  1007. }
  1008. }
  1009. /**
  1010. * Transform a PHP array into POST parameter
  1011. * (see the recursive function format_array_postdata_for_curlcall)
  1012. * @param array $postdata
  1013. * @return array containing all POST parameters (1 row = 1 POST parameter)
  1014. */
  1015. function format_postdata_for_curlcall($postdata) {
  1016. $data = array();
  1017. foreach ($postdata as $k=>$v) {
  1018. if (is_array($v)) {
  1019. $currentdata = urlencode($k);
  1020. format_array_postdata_for_curlcall($v, $currentdata, $data);
  1021. } else {
  1022. $data[] = urlencode($k).'='.urlencode($v);
  1023. }
  1024. }
  1025. $convertedpostdata = implode('&', $data);
  1026. return $convertedpostdata;
  1027. }
  1028. /**
  1029. * Fetches content of file from Internet (using proxy if defined). Uses cURL extension if present.
  1030. * Due to security concerns only downloads from http(s) sources are supported.
  1031. *
  1032. * @category files
  1033. * @param string $url file url starting with http(s)://
  1034. * @param array $headers http headers, null if none. If set, should be an
  1035. * associative array of header name => value pairs.
  1036. * @param array $postdata array means use POST request with given parameters
  1037. * @param bool $fullresponse return headers, responses, etc in a similar way snoopy does
  1038. * (if false, just returns content)
  1039. * @param int $timeout timeout for complete download process including all file transfer
  1040. * (default 5 minutes)
  1041. * @param int $connecttimeout timeout for connection to server; this is the timeout that
  1042. * usually happens if the remote server is completely down (default 20 seconds);
  1043. * may not work when using proxy
  1044. * @param bool $skipcertverify If true, the peer's SSL certificate will not be checked.
  1045. * Only use this when already in a trusted location.
  1046. * @param string $tofile store the downloaded content to file instead of returning it.
  1047. * @param bool $calctimeout false by default, true enables an extra head request to try and determine
  1048. * filesize and appropriately larger timeout based on $CFG->curltimeoutkbitrate
  1049. * @return stdClass|string|bool stdClass object if $fullresponse is true, false if request failed, true
  1050. * if file downloaded into $tofile successfully or the file content as a string.
  1051. */
  1052. function download_file_content($url, $headers=null, $postdata=null, $fullresponse=false, $timeout=300, $connecttimeout=20, $skipcertverify=false, $tofile=NULL, $calctimeout=false) {
  1053. global $CFG;
  1054. // Only http and https links supported.
  1055. if (!preg_match('|^https?://|i', $url)) {
  1056. if ($fullresponse) {
  1057. $response = new stdClass();
  1058. $response->status = 0;
  1059. $response->headers = array();
  1060. $response->response_code = 'Invalid protocol specified in url';
  1061. $response->results = '';
  1062. $response->error = 'Invalid protocol specified in url';
  1063. return $response;
  1064. } else {
  1065. return false;
  1066. }
  1067. }
  1068. $options = array();
  1069. $headers2 = array();
  1070. if (is_array($headers)) {
  1071. foreach ($headers as $key => $value) {
  1072. if (is_numeric($key)) {
  1073. $headers2[] = $value;
  1074. } else {
  1075. $headers2[] = "$key: $value";
  1076. }
  1077. }
  1078. }
  1079. if ($skipcertverify) {
  1080. $options['CURLOPT_SSL_VERIFYPEER'] = false;
  1081. } else {
  1082. $options['CURLOPT_SSL_VERIFYPEER'] = true;
  1083. }
  1084. $options['CURLOPT_CONNECTTIMEOUT'] = $connecttimeout;
  1085. $options['CURLOPT_FOLLOWLOCATION'] = 1;
  1086. $options['CURLOPT_MAXREDIRS'] = 5;
  1087. // Use POST if requested.
  1088. if (is_array($postdata)) {
  1089. $postdata = format_postdata_for_curlcall($postdata);
  1090. } else if (empty($postdata)) {
  1091. $postdata = null;
  1092. }
  1093. // Optionally attempt to get more correct timeout by fetching the file size.
  1094. if (!isset($CFG->curltimeoutkbitrate)) {
  1095. // Use very slow rate of 56kbps as a timeout speed when not set.
  1096. $bitrate = 56;
  1097. } else {
  1098. $bitrate = $CFG->curltimeoutkbitrate;
  1099. }
  1100. if ($calctimeout and !isset($postdata)) {
  1101. $curl = new curl();
  1102. $curl->setHeader($headers2);
  1103. $curl->head($url, $postdata, $options);
  1104. $info = $curl->get_info();
  1105. $error_no = $curl->get_errno();
  1106. if (!$error_no && $info['download_content_length'] > 0) {
  1107. // No curl errors - adjust for large files only - take max timeout.
  1108. $timeout = max($timeout, ceil($info['download_content_length'] * 8 / ($bitrate * 1024)));
  1109. }
  1110. }
  1111. $curl = new curl();
  1112. $curl->setHeader($headers2);
  1113. $options['CURLOPT_RETURNTRANSFER'] = true;
  1114. $options['CURLOPT_NOBODY'] = false;
  1115. $options['CURLOPT_TIMEOUT'] = $timeout;
  1116. if ($tofile) {
  1117. $fh = fopen($tofile, 'w');
  1118. if (!$fh) {
  1119. if ($fullresponse) {
  1120. $response = new stdClass();
  1121. $response->status = 0;
  1122. $response->headers = array();
  1123. $response->response_code = 'Can not write to file';
  1124. $response->results = false;
  1125. $response->error = 'Can not write to file';
  1126. return $response;
  1127. } else {
  1128. return false;
  1129. }
  1130. }
  1131. $options['CURLOPT_FILE'] = $fh;
  1132. }
  1133. if (isset($postdata)) {
  1134. $content = $curl->post($url, $postdata, $options);
  1135. } else {
  1136. $content = $curl->get($url, null, $options);
  1137. }
  1138. if ($tofile) {
  1139. fclose($fh);
  1140. @chmod($tofile, $CFG->filepermissions);
  1141. }
  1142. /*
  1143. // Try to detect encoding problems.
  1144. if ((curl_errno($ch) == 23 or curl_errno($ch) == 61) and defined('CURLOPT_ENCODING')) {
  1145. curl_setopt($ch, CURLOPT_ENCODING, 'none');
  1146. $result = curl_exec($ch);
  1147. }
  1148. */
  1149. $info = $curl->get_info();
  1150. $error_no = $curl->get_errno();
  1151. $rawheaders = $curl->get_raw_response();
  1152. if ($error_no) {
  1153. $error = $content;
  1154. if (!$fullresponse) {
  1155. debugging("cURL request for \"$url\" failed with: $error ($error_no)", DEBUG_ALL);
  1156. return false;
  1157. }
  1158. $response = new stdClass();
  1159. if ($error_no == 28) {
  1160. $response->status = '-100'; // Mimic snoopy.
  1161. } else {
  1162. $response->status = '0';
  1163. }
  1164. $response->headers = array();
  1165. $response->response_code = $error;
  1166. $response->results = false;
  1167. $response->error = $error;
  1168. return $response;
  1169. }
  1170. if ($tofile) {
  1171. $content = true;
  1172. }
  1173. if (empty($info['http_code'])) {
  1174. // For security reasons we support only true http connections (Location: file:// exploit prevention).
  1175. $response = new stdClass();
  1176. $response->status = '0';
  1177. $response->headers = array();
  1178. $response->response_code = 'Unknown cURL error';
  1179. $response->results = false; // do NOT change this, we really want to ignore the result!
  1180. $response->error = 'Unknown cURL error';
  1181. } else {
  1182. $response = new stdClass();
  1183. $response->status = (string)$info['http_code'];
  1184. $response->headers = $rawheaders;
  1185. $response->results = $content;
  1186. $response->error = '';
  1187. // There might be multiple headers on redirect, find the status of the last one.
  1188. $firstline = true;
  1189. foreach ($rawheaders as $line) {
  1190. if ($firstline) {
  1191. $response->response_code = $line;
  1192. $firstline = false;
  1193. }
  1194. if (trim($line, "\r\n") === '') {
  1195. $firstline = true;
  1196. }
  1197. }
  1198. }
  1199. if ($fullresponse) {
  1200. return $response;
  1201. }
  1202. if ($info['http_code'] != 200) {
  1203. debugging("cURL request for \"$url\" failed, HTTP response code: ".$response->response_code, DEBUG_ALL);
  1204. return false;
  1205. }
  1206. return $response->results;
  1207. }
  1208. /**
  1209. * Returns a list of information about file types based on extensions.
  1210. *
  1211. * The following elements expected in value array for each extension:
  1212. * 'type' - mimetype
  1213. * 'icon' - location of the icon file. If value is FILENAME, then either pix/f/FILENAME.gif
  1214. * or pix/f/FILENAME.png must be present in moodle and contain 16x16 filetype icon;
  1215. * also files with bigger sizes under names
  1216. * FILENAME-24, FILENAME-32, FILENAME-64, FILENAME-128, FILENAME-256 are recommended.
  1217. * 'groups' (optional) - array of filetype groups this filetype extension is part of;
  1218. * commonly used in moodle the following groups:
  1219. * - web_image - image that can be included as <img> in HTML
  1220. * - image - image that we can parse using GD to find it's dimensions, also used for portfolio format
  1221. * - video - file that can be imported as video in text editor
  1222. * - audio - file that can be imported as audio in text editor
  1223. * - archive - we can extract files from this archive
  1224. * - spreadsheet - used for portfolio format
  1225. * - document - used for portfolio format
  1226. * - presentation - used for portfolio format
  1227. * 'string' (optional) - the name of the string from lang/en/mimetypes.php that displays
  1228. * human-readable description for this filetype;
  1229. * Function {@link get_mimetype_description()} first looks at the presence of string for
  1230. * particular mimetype (value of 'type'), if not found looks for string specified in 'string'
  1231. * attribute, if not found returns the value of 'type';
  1232. * 'defaulticon' (boolean, optional) - used by function {@link file_mimetype_icon()} to find
  1233. * an icon for mimetype. If an entry with 'defaulticon' is not found for a particular mimetype,
  1234. * this function will return first found icon; Especially usefull for types such as 'text/plain'
  1235. *
  1236. * @category files
  1237. * @return array List of information about file types based on extensions.
  1238. * Associative array of extension (lower-case) to associative array
  1239. * from 'element name' to data. Current element names are 'type' and 'icon'.
  1240. * Unknown types should use the 'xxx' entry which includes defaults.
  1241. */
  1242. function &get_mimetypes_array() {
  1243. static $mimearray = array (
  1244. 'xxx' => array ('type'=>'document/unknown', 'icon'=>'unknown'),
  1245. '3gp' => array ('type'=>'video/quicktime', 'icon'=>'quicktime', 'groups'=>array('video'), 'string'=>'video'),
  1246. 'aac' => array ('type'=>'audio/aac', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
  1247. 'accdb' => array ('type'=>'application/msaccess', 'icon'=>'base'),
  1248. 'ai' => array ('type'=>'application/postscript', 'icon'=>'eps', 'groups'=>array('image'), 'string'=>'image'),
  1249. 'aif' => array ('type'=>'audio/x-aiff', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
  1250. 'aiff' => array ('type'=>'audio/x-aiff', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
  1251. 'aifc' => array ('type'=>'audio/x-aiff', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
  1252. 'applescript' => array ('type'=>'text/plain', 'icon'=>'text'),
  1253. 'asc' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
  1254. 'asm' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
  1255. 'au' => array ('type'=>'audio/au', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
  1256. 'avi' => array ('type'=>'video/x-ms-wm', 'icon'=>'avi', 'groups'=>array('video','web_video'), 'string'=>'video'),
  1257. 'bmp' => array ('type'=>'image/bmp', 'icon'=>'bmp', 'groups'=>array('image'), 'string'=>'image'),
  1258. 'c' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
  1259. 'cct' => array ('type'=>'shockwave/director', 'icon'=>'flash'),
  1260. 'cpp' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
  1261. 'cs' => array ('type'=>'application/x-csh', 'icon'=>'sourcecode'),
  1262. 'css' => array ('type'=>'text/css', 'icon'=>'text', 'groups'=>array('web_file')),
  1263. 'csv' => array ('type'=>'text/csv', 'icon'=>'spreadsheet', 'groups'=>array('spreadsheet')),
  1264. 'dv' => array ('type'=>'video/x-dv', 'icon'=>'quicktime', 'groups'=>array('video'), 'string'=>'video'),
  1265. 'dmg' => array ('type'=>'application/octet-stream', 'icon'=>'unknown'),
  1266. 'doc' => array ('type'=>'application/msword', 'icon'=>'document', 'groups'=>array('document')),
  1267. 'bdoc' => array ('type'=>'application/x-digidoc', 'icon'=>'document', 'groups'=>array('archive')),
  1268. 'cdoc' => array ('type'=>'application/x-digidoc', 'icon'=>'document', 'groups'=>array('archive')),
  1269. 'ddoc' => array ('type'=>'application/x-digidoc', 'icon'=>'document', 'groups'=>array('archive')),
  1270. 'docx' => array ('type'=>'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'icon'=>'document', 'groups'=>array('document')),
  1271. 'docm' => array ('type'=>'application/vnd.ms-word.document.macroEnabled.12', 'icon'=>'document'),
  1272. 'dotx' => array ('type'=>'application/vnd.openxmlformats-officedocument.wordprocessingml.template', 'icon'=>'document'),
  1273. 'dotm' => array ('type'=>'application/vnd.ms-word.template.macroEnabled.12', 'icon'=>'document'),
  1274. 'dcr' => array ('type'=>'application/x-director', 'icon'=>'flash'),
  1275. 'dif' => array ('type'=>'video/x-dv', 'icon'=>'quicktime', 'groups'=>array('video'), 'string'=>'video'),
  1276. 'dir' => array ('type'=>'application/x-director', 'icon'=>'flash'),
  1277. 'dxr' => array ('type'=>'application/x-director', 'icon'=>'flash'),
  1278. 'eps' => array ('type'=>'application/postscript', 'icon'=>'eps'),
  1279. 'epub' => array ('type'=>'application/epub+zip', 'icon'=>'epub', 'groups'=>array('document')),
  1280. 'fdf' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
  1281. 'flv' => array ('type'=>'video/x-flv', 'icon'=>'flash', 'groups'=>array('video','web_video'), 'string'=>'video'),
  1282. 'f4v' => array ('type'=>'video/mp4', 'icon'=>'flash', 'groups'=>array('video','web_video'), 'string'=>'video'),
  1283. 'gallery' => array ('type'=>'application/x-smarttech-notebook', 'icon'=>'archive'),
  1284. 'galleryitem' => array ('type'=>'application/x-smarttech-notebook', 'icon'=>'archive'),
  1285. 'gallerycollection' => array ('type'=>'application/x-smarttech-notebook', 'icon'=>'archive'),
  1286. 'gif' => array ('type'=>'image/gif', 'icon'=>'gif', 'groups'=>array('image', 'web_image'), 'string'=>'image'),
  1287. 'gtar' => array ('type'=>'application/x-gtar', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
  1288. 'tgz' => array ('type'=>'application/g-zip', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
  1289. 'gz' => array ('type'=>'application/g-zip', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
  1290. 'gzip' => array ('type'=>'application/g-zip', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
  1291. 'h' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
  1292. 'hpp' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
  1293. 'hqx' => array ('type'=>'application/mac-binhex40', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
  1294. 'htc' => array ('type'=>'text/x-component', 'icon'=>'markup'),
  1295. 'html' => array ('type'=>'text/html', 'icon'=>'html', 'groups'=>array('web_file')),
  1296. 'xhtml'=> array ('type'=>'application/xhtml+xml', 'icon'=>'html', 'groups'=>array('web_file')),
  1297. 'htm' => array ('type'=>'text/html', 'icon'=>'html', 'groups'=>array('web_file')),
  1298. 'ico' => array ('type'=>'image/vnd.microsoft.icon', 'icon'=>'image', 'groups'=>array('image'), 'string'=>'image'),
  1299. 'ics' => array ('type'=>'text/calendar', 'icon'=>'text'),
  1300. 'isf' => array ('type'=>'application/inspiration', 'icon'=>'isf'),
  1301. 'ist' => array ('type'=>'application/inspiration.template', 'icon'=>'isf'),
  1302. 'java' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
  1303. 'jar' => array ('type'=>'application/java-archive', 'icon' => 'archive'),
  1304. 'jcb' => array ('type'=>'text/xml', 'icon'=>'markup'),
  1305. 'jcl' => array ('type'=>'text/xml', 'icon'=>'markup'),
  1306. 'jcw' => array ('type'=>'text/xml', 'icon'=>'markup'),
  1307. 'jmt' => array ('type'=>'text/xml', 'icon'=>'markup'),
  1308. 'jmx' => array ('type'=>'text/xml', 'icon'=>'markup'),
  1309. 'jnlp' => array ('type'=>'application/x-java-jnlp-file', 'icon'=>'markup'),
  1310. 'jpe' => array ('type'=>'image/jpeg', 'icon'=>'jpeg', 'groups'=>array('image', 'web_image'), 'string'=>'image'),
  1311. 'jpeg' => array ('type'=>'image/jpeg', 'icon'=>'jpeg', 'groups'=>array('image', 'web_image'), 'string'=>'image'),
  1312. 'jpg' => array ('type'=>'image/jpeg', 'icon'=>'jpeg', 'groups'=>array('image', 'web_image'), 'string'=>'image'),
  1313. 'jqz' => array ('type'=>'text/xml', 'icon'=>'markup'),
  1314. 'js' => array ('type'=>'application/x-javascript', 'icon'=>'text', 'groups'=>array('web_file')),
  1315. 'latex'=> array ('type'=>'application/x-latex', 'icon'=>'text'),
  1316. 'm' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
  1317. 'mbz' => array ('type'=>'application/vnd.moodle.backup', 'icon'=>'moodle'),
  1318. 'mdb' => array ('type'=>'application/x-msaccess', 'icon'=>'base'),
  1319. 'mht' => array ('type'=>'message/rfc822', 'icon'=>'archive'),
  1320. 'mhtml'=> array ('type'=>'message/rfc822', 'icon'=>'archive'),
  1321. 'mov' => array ('type'=>'video/quicktime', 'icon'=>'quicktime', 'groups'=>array('video','web_video'), 'string'=>'video'),
  1322. 'movie'=> array ('type'=>'video/x-sgi-movie', 'icon'=>'quicktime', 'groups'=>array('video'), 'string'=>'video'),
  1323. 'mw' => array ('type'=>'application/maple', 'icon'=>'math'),
  1324. 'mws' => array ('type'=>'application/maple', 'icon'=>'math'),
  1325. 'm3u' => array ('type'=>'audio/x-mpegurl', 'icon'=>'mp3', 'groups'=>array('audio'), 'string'=>'audio'),
  1326. 'mp3' => array ('type'=>'audio/mp3', 'icon'=>'mp3', 'groups'=>array('audio','web_audio'), 'string'=>'audio'),
  1327. 'mp4' => array ('type'=>'video/mp4', 'icon'=>'mpeg', 'groups'=>array('video','web_video'), 'string'=>'video'),
  1328. 'm4v' => array ('type'=>'video/mp4', 'icon'=>'mpeg', 'groups'=>array('video','web_video'), 'string'=>'video'),
  1329. 'm4a' => array ('type'=>'audio/mp4', 'icon'=>'mp3', 'groups'=>array('audio'), 'string'=>'audio'),
  1330. 'mpeg' => array ('type'=>'video/mpeg', 'icon'=>'mpeg', 'groups'=>array('video','web_video'), 'string'=>'video'),
  1331. 'mpe' => array ('type'=>'video/mpeg', 'icon'=>'mpeg', 'groups'=>array('video','web_video'), 'string'=>'video'),
  1332. 'mpg' => array ('type'=>'video/mpeg', 'icon'=>'mpeg', 'groups'=>array('video','web_video'), 'string'=>'video'),
  1333. 'mpr' => array ('type'=>'application/vnd.moodle.profiling', 'icon'=>'moodle'),
  1334. 'nbk' => array ('type'=>'application/x-smarttech-notebook', 'icon'=>'archive'),
  1335. 'notebook' => array ('type'=>'application/x-smarttech-notebook', 'icon'=>'archive'),
  1336. 'odt' => array ('type'=>'application/vnd.oasis.opendocument.text', 'icon'=>'writer', 'groups'=>array('document')),
  1337. 'ott' => array ('type'=>'application/vnd.oasis.opendocument.text-template', 'icon'=>'writer', 'groups'=>array('document')),
  1338. 'oth' => array ('type'=>'application/vnd.oasis.opendocument.text-web', 'icon'=>'oth', 'groups'=>array('document')),
  1339. 'odm' => array ('type'=>'application/vnd.oasis.opendocument.text-master', 'icon'=>'writer'),
  1340. 'odg' => array ('type'=>'application/vnd.oasis.opendocument.graphics', 'icon'=>'draw'),
  1341. 'otg' => array ('type'=>'application/vnd.oasis.opendocument.graphics-template', 'icon'=>'draw'),
  1342. 'odp' => array ('type'=>'application/vnd.oasis.opendocument.presentation', 'icon'=>'impress'),
  1343. 'otp' => array ('type'=>'application/vnd.oasis.opendocument.presentation-template', 'icon'=>'impress'),
  1344. 'ods' => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet', 'icon'=>'calc', 'groups'=>array('spreadsheet')),
  1345. 'ots' => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet-template', 'icon'=>'calc', 'groups'=>array('spreadsheet')),
  1346. 'odc' => array ('type'=>'application/vnd.oasis.opendocument.chart', 'icon'=>'chart'),
  1347. 'odf' => array ('type'=>'application/vnd.oasis.opendocument.formula', 'icon'=>'math'),
  1348. 'odb' => array ('type'=>'application/vnd.oasis.opendocument.database', 'icon'=>'base'),
  1349. 'odi' => array ('type'=>'application/vnd.oasis.opendocument.image', 'icon'=>'draw'),
  1350. 'oga' => array ('type'=>'audio/ogg', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
  1351. 'ogg' => array ('type'=>'audio/ogg', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
  1352. 'ogv' => array ('type'=>'video/ogg', 'icon'=>'video', 'groups'=>array('video'), 'string'=>'video'),
  1353. 'pct' => array ('type'=>'image/pict', 'icon'=>'image', 'groups'=>array('image'), 'string'=>'image'),
  1354. 'pdf' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
  1355. 'php' => array ('type'=>'text/plain', 'icon'=>'sourcecode'),
  1356. 'pic' => array ('type'=>'image/pict', 'icon'=>'image', 'groups'=>array('image'), 'string'=>'image'),
  1357. 'pict' => array ('type'=>'image/pict', 'icon'=>'image', 'groups'=>array('image'), 'string'=>'image'),
  1358. 'png' => array ('type'=>'image/png', 'icon'=>'png', 'groups'=>array('image', 'web_image'), 'string'=>'image'),
  1359. 'pps' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'powerpoint', 'groups'=>array('presentation')),
  1360. 'ppt' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'powerpoint', 'groups'=>array('presentation')),
  1361. 'pptx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'icon'=>'powerpoint'),
  1362. 'pptm' => array ('type'=>'application/vnd.ms-powerpoint.presentation.macroEnabled.12', 'icon'=>'powerpoint'),
  1363. 'potx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.template', 'icon'=>'powerpoint'),
  1364. 'potm' => array ('type'=>'application/vnd.ms-powerpoint.template.macroEnabled.12', 'icon'=>'powerpoint'),
  1365. 'ppam' => array ('type'=>'application/vnd.ms-powerpoint.addin.macroEnabled.12', 'icon'=>'powerpoint'),
  1366. 'ppsx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.slideshow', 'icon'=>'powerpoint'),
  1367. 'ppsm' => array ('type'=>'application/vnd.ms-powerpoint.slideshow.macroEnabled.12', 'icon'=>'powerpoint'),
  1368. 'ps' => array ('type'=>'application/postscript', 'icon'=>'pdf'),
  1369. 'pub' => array ('type'=>'application/x-mspublisher', 'icon'=>'publisher', 'groups'=>array('presentation')),
  1370. 'qt' => array ('type'=>'video/quicktime', 'icon'=>'quicktime', 'groups'=>array('video','web_video'), 'string'=>'video'),
  1371. 'ra' => array ('type'=>'audio/x-realaudio-plugin', 'icon'=>'audio', 'groups'=>array('audio','web_audio'), 'string'=>'audio'),
  1372. 'ram' => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
  1373. 'rhb' => array ('type'=>'text/xml', 'icon'=>'markup'),
  1374. 'rm' => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
  1375. 'rmvb' => array ('type'=>'application/vnd.rn-realmedia-vbr', 'icon'=>'video', 'groups'=>array('video'), 'string'=>'video'),
  1376. 'rtf' => array ('type'=>'text/rtf', 'icon'=>'text', 'groups'=>array('document')),
  1377. 'rtx' => array ('type'=>'text/richtext', 'icon'=>'text'),
  1378. 'rv' => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'audio', 'groups'=>array('video'), 'string'=>'video'),
  1379. 'sh' => array ('type'=>'application/x-sh', 'icon'=>'sourcecode'),
  1380. 'sit' => array ('type'=>'application/x-stuffit', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
  1381. 'smi' => array ('type'=>'application/smil', 'icon'=>'text'),
  1382. 'smil' => array ('type'=>'application/smil', 'icon'=>'text'),
  1383. 'sqt' => array ('type'=>'text/xml', 'icon'=>'markup'),
  1384. 'svg' => array ('type'=>'image/svg+xml', 'icon'=>'image', 'groups'=>array('image','web_image'), 'string'=>'image'),
  1385. 'svgz' => array ('type'=>'image/svg+xml', 'icon'=>'image', 'groups'=>array('image','web_image'), 'string'=>'image'),
  1386. 'swa' => array ('type'=>'application/x-director', 'icon'=>'flash'),
  1387. 'swf' => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash', 'groups'=>array('video','web_video')),
  1388. 'swfl' => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash', 'groups'=>array('video','web_video')),
  1389. 'sxw' => array ('type'=>'application/vnd.sun.xml.writer', 'icon'=>'writer'),
  1390. 'stw' => array ('type'=>'application/vnd.sun.xml.writer.template', 'icon'=>'writer'),
  1391. 'sxc' => array ('type'=>'application/vnd.sun.xml.calc', 'icon'=>'calc'),
  1392. 'stc' => array ('type'=>'application/vnd.sun.xml.calc.template', 'icon'=>'calc'),
  1393. 'sxd' => array ('type'=>'application/vnd.sun.xml.draw', 'icon'=>'draw'),
  1394. 'std' => array ('type'=>'application/vnd.sun.xml.draw.template', 'icon'=>'draw'),
  1395. 'sxi' => array ('type'=>'application/vnd.sun.xml.impress', 'icon'=>'impress'),
  1396. 'sti' => array ('type'=>'application/vnd.sun.xml.impress.template', 'icon'=>'impress'),
  1397. 'sxg' => array ('type'=>'application/vnd.sun.xml.writer.global', 'icon'=>'writer'),
  1398. 'sxm' => array ('type'=>'application/vnd.sun.xml.math', 'icon'=>'math'),
  1399. 'tar' => array ('type'=>'application/x-tar', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive'),
  1400. 'tif' => array ('type'=>'image/tiff', 'icon'=>'tiff', 'groups'=>array('image'), 'string'=>'image'),
  1401. 'tiff' => array ('type'=>'image/tiff', 'icon'=>'tiff', 'groups'=>array('image'), 'string'=>'image'),
  1402. 'tex' => array ('type'=>'application/x-tex', 'icon'=>'text'),
  1403. 'texi' => array ('type'=>'application/x-texinfo', 'icon'=>'text'),
  1404. 'texinfo' => array ('type'=>'application/x-texinfo', 'icon'=>'text'),
  1405. 'tsv' => array ('type'=>'text/tab-separated-values', 'icon'=>'text'),
  1406. 'txt' => array ('type'=>'text/plain', 'icon'=>'text', 'defaulticon'=>true),
  1407. 'wav' => array ('type'=>'audio/wav', 'icon'=>'wav', 'groups'=>array('audio'), 'string'=>'audio'),
  1408. 'webm' => array ('type'=>'video/webm', 'icon'=>'video', 'groups'=>array('video'), 'string'=>'video'),
  1409. 'wmv' => array ('type'=>'video/x-ms-wmv', 'icon'=>'wmv', 'groups'=>array('video'), 'string'=>'video'),
  1410. 'asf' => array ('type'=>'video/x-ms-asf', 'icon'=>'wmv', 'groups'=>array('video'), 'string'=>'video'),
  1411. 'wma' => array ('type'=>'audio/x-ms-wma', 'icon'=>'audio', 'groups'=>array('audio'), 'string'=>'audio'),
  1412. 'xbk' => array ('type'=>'application/x-smarttech-notebook', 'icon'=>'archive'),
  1413. 'xdp' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
  1414. 'xfd' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
  1415. 'xfdf' => array ('type'=>'application/pdf', 'icon'=>'pdf'),
  1416. 'xls' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'spreadsheet', 'groups'=>array('spreadsheet')),
  1417. 'xlsx' => array ('type'=>'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'icon'=>'spreadsheet'),
  1418. 'xlsm' => array ('type'=>'application/vnd.ms-excel.sheet.macroEnabled.12', 'icon'=>'spreadsheet', 'groups'=>array('spreadsheet')),
  1419. 'xltx' => array ('type'=>'application/vnd.openxmlformats-officedocument.spreadsheetml.template', 'icon'=>'spreadsheet'),
  1420. 'xltm' => array ('type'=>'application/vnd.ms-excel.template.macroEnabled.12', 'icon'=>'spreadsheet'),
  1421. 'xlsb' => array ('type'=>'application/vnd.ms-excel.sheet.binary.macroEnabled.12', 'icon'=>'spreadsheet'),
  1422. 'xlam' => array ('type'=>'application/vnd.ms-excel.addin.macroEnabled.12', 'icon'=>'spreadsheet'),
  1423. 'xml' => array ('type'=>'application/xml', 'icon'=>'markup'),
  1424. 'xsl' => array ('type'=>'text/xml', 'icon'=>'markup'),
  1425. 'zip' => array ('type'=>'application/zip', 'icon'=>'archive', 'groups'=>array('archive'), 'string'=>'archive')
  1426. );
  1427. return $mimearray;
  1428. }
  1429. /**
  1430. * Obtains information about a filetype based on its extension. Will
  1431. * use a default if no information is present about that particular
  1432. * extension.
  1433. *
  1434. * @category files
  1435. * @param string $element Desired information (usually 'icon'
  1436. * for icon filename or 'type' for MIME type. Can also be
  1437. * 'icon24', ...32, 48, 64, 72, 80, 96, 128, 256)
  1438. * @param string $filename Filename we're looking up
  1439. * @return string Requested piece of information from array
  1440. */
  1441. function mimeinfo($element, $filename) {
  1442. global $CFG;
  1443. $mimeinfo = & get_mimetypes_array();
  1444. static $iconpostfixes = array(256=>'-256', 128=>'-128', 96=>'-96', 80=>'-80', 72=>'-72', 64=>'-64', 48=>'-48', 32=>'-32', 24=>'-24', 16=>'');
  1445. $filetype = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
  1446. if (empty($filetype)) {
  1447. $filetype = 'xxx'; // file without extension
  1448. }
  1449. if (preg_match('/^icon(\d*)$/', $element, $iconsizematch)) {
  1450. $iconsize = max(array(16, (int)$iconsizematch[1]));
  1451. $filenames = array($mimeinfo['xxx']['icon']);
  1452. if ($filetype != 'xxx' && isset($mimeinfo[$filetype]['icon'])) {
  1453. array_unshift($filenames, $mimeinfo[$filetype]['icon']);
  1454. }
  1455. // find the file with the closest size, first search for specific icon then for default icon
  1456. foreach ($filenames as $filename) {
  1457. foreach ($iconpostfixes as $size => $postfix) {
  1458. $fullname = $CFG->dirroot.'/pix/f/'.$filename.$postfix;
  1459. if ($iconsize >= $size && (file_exists($fullname.'.png') || file_exists($fullname.'.gif'))) {
  1460. return $filename.$postfix;
  1461. }
  1462. }
  1463. }
  1464. } else if (isset($mimeinfo[$filetype][$element])) {
  1465. return $mimeinfo[$filetype][$element];
  1466. } else if (isset($mimeinfo['xxx'][$element])) {
  1467. return $mimeinfo['xxx'][$element]; // By default
  1468. } else {
  1469. return null;
  1470. }
  1471. }
  1472. /**
  1473. * Obtains information about a filetype based on the MIME type rather than
  1474. * the other way around.
  1475. *
  1476. * @category files
  1477. * @param string $element Desired information ('extension', 'icon', 'icon-24', etc.)
  1478. * @param string $mimetype MIME type we're looking up
  1479. * @return string Requested piece of information from array
  1480. */
  1481. function mimeinfo_from_type($element, $mimetype) {
  1482. /* array of cached mimetype->extension associations */
  1483. static $cached = array();
  1484. $mimeinfo = & get_mimetypes_array();
  1485. if (!array_key_exists($mimetype, $cached)) {
  1486. $cached[$mimetype] = null;
  1487. foreach($mimeinfo as $filetype => $values) {
  1488. if ($values['type'] == $mimetype) {
  1489. if ($cached[$mimetype] === null) {
  1490. $cached[$mimetype] = '.'.$filetype;
  1491. }
  1492. if (!empty($values['defaulticon'])) {
  1493. $cached[$mimetype] = '.'.$filetype;
  1494. break;
  1495. }
  1496. }
  1497. }
  1498. if (empty($cached[$mimetype])) {
  1499. $cached[$mimetype] = '.xxx';
  1500. }
  1501. }
  1502. if ($element === 'extension') {
  1503. return $cached[$mimetype];
  1504. } else {
  1505. return mimeinfo($element, $cached[$mimetype]);
  1506. }
  1507. }
  1508. /**
  1509. * Return the relative icon path for a given file
  1510. *
  1511. * Usage:
  1512. * <code>
  1513. * // $file - instance of stored_file or file_info
  1514. * $icon = $OUTPUT->pix_url(file_file_icon($file))->out();
  1515. * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => get_mimetype_description($file)));
  1516. * </code>
  1517. * or
  1518. * <code>
  1519. * echo $OUTPUT->pix_icon(file_file_icon($file), get_mimetype_description($file));
  1520. * </code>
  1521. *
  1522. * @param stored_file|file_info|stdClass|array $file (in case of object attributes $file->filename
  1523. * and $file->mimetype are expected)
  1524. * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
  1525. * @return string
  1526. */
  1527. function file_file_icon($file, $size = null) {
  1528. if (!is_object($file)) {
  1529. $file = (object)$file;
  1530. }
  1531. if (isset($file->filename)) {
  1532. $filename = $file->filename;
  1533. } else if (method_exists($file, 'get_filename')) {
  1534. $filename = $file->get_filename();
  1535. } else if (method_exists($file, 'get_visible_name')) {
  1536. $filename = $file->get_visible_name();
  1537. } else {
  1538. $filename = '';
  1539. }
  1540. if (isset($file->mimetype)) {
  1541. $mimetype = $file->mimetype;
  1542. } else if (method_exists($file, 'get_mimetype')) {
  1543. $mimetype = $file->get_mimetype();
  1544. } else {
  1545. $mimetype = '';
  1546. }
  1547. $mimetypes = &get_mimetypes_array();
  1548. if ($filename) {
  1549. $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
  1550. if ($extension && !empty($mimetypes[$extension])) {
  1551. // if file name has known extension, return icon for this extension
  1552. return file_extension_icon($filename, $size);
  1553. }
  1554. }
  1555. return file_mimetype_icon($mimetype, $size);
  1556. }
  1557. /**
  1558. * Return the relative icon path for a folder image
  1559. *
  1560. * Usage:
  1561. * <code>
  1562. * $icon = $OUTPUT->pix_url(file_folder_icon())->out();
  1563. * echo html_writer::empty_tag('img', array('src' => $icon));
  1564. * </code>
  1565. * or
  1566. * <code>
  1567. * echo $OUTPUT->pix_icon(file_folder_icon(32));
  1568. * </code>
  1569. *
  1570. * @param int $iconsize The size of the icon. Defaults to 16 can also be 24, 32, 48, 64, 72, 80, 96, 128, 256
  1571. * @return string
  1572. */
  1573. function file_folder_icon($iconsize = null) {
  1574. global $CFG;
  1575. static $iconpostfixes = array(256=>'-256', 128=>'-128', 96=>'-96', 80=>'-80', 72=>'-72', 64=>'-64', 48=>'-48', 32=>'-32', 24=>'-24', 16=>'');
  1576. static $cached = array();
  1577. $iconsize = max(array(16, (int)$iconsize));
  1578. if (!array_key_exists($iconsize, $cached)) {
  1579. foreach ($iconpostfixes as $size => $postfix) {
  1580. $fullname = $CFG->dirroot.'/pix/f/folder'.$postfix;
  1581. if ($iconsize >= $size && (file_exists($fullname.'.png') || file_exists($fullname.'.gif'))) {
  1582. $cached[$iconsize] = 'f/folder'.$postfix;
  1583. break;
  1584. }
  1585. }
  1586. }
  1587. return $cached[$iconsize];
  1588. }
  1589. /**
  1590. * Returns the relative icon path for a given mime type
  1591. *
  1592. * This function should be used in conjunction with $OUTPUT->pix_url to produce
  1593. * a return the full path to an icon.
  1594. *
  1595. * <code>
  1596. * $mimetype = 'image/jpg';
  1597. * $icon = $OUTPUT->pix_url(file_mimetype_icon($mimetype))->out();
  1598. * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => get_mimetype_description($mimetype)));
  1599. * </code>
  1600. *
  1601. * @category files
  1602. * @todo MDL-31074 When an $OUTPUT->icon method is available this function should be altered
  1603. * to conform with that.
  1604. * @param string $mimetype The mimetype to fetch an icon for
  1605. * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
  1606. * @return string The relative path to the icon
  1607. */
  1608. function file_mimetype_icon($mimetype, $size = NULL) {
  1609. return 'f/'.mimeinfo_from_type('icon'.$size, $mimetype);
  1610. }
  1611. /**
  1612. * Returns the relative icon path for a given file name
  1613. *
  1614. * This function should be used in conjunction with $OUTPUT->pix_url to produce
  1615. * a return the full path to an icon.
  1616. *
  1617. * <code>
  1618. * $filename = '.jpg';
  1619. * $icon = $OUTPUT->pix_url(file_extension_icon($filename))->out();
  1620. * echo html_writer::empty_tag('img', array('src' => $icon, 'alt' => '...'));
  1621. * </code>
  1622. *
  1623. * @todo MDL-31074 When an $OUTPUT->icon method is available this function should be altered
  1624. * to conform with that.
  1625. * @todo MDL-31074 Implement $size
  1626. * @category files
  1627. * @param string $filename The filename to get the icon for
  1628. * @param int $size The size of the icon. Defaults to 16 can also be 24, 32, 64, 128, 256
  1629. * @return string
  1630. */
  1631. function file_extension_icon($filename, $size = NULL) {
  1632. return 'f/'.mimeinfo('icon'.$size, $filename);
  1633. }
  1634. /**
  1635. * Obtains descriptions for file types (e.g. 'Microsoft Word document') from the
  1636. * mimetypes.php language file.
  1637. *
  1638. * @param mixed $obj - instance of stored_file or file_info or array/stdClass with field
  1639. * 'filename' and 'mimetype', or just a string with mimetype (though it is recommended to
  1640. * have filename); In case of array/stdClass the field 'mimetype' is optional.
  1641. * @param bool $capitalise If true, capitalises first character of result
  1642. * @return string Text description
  1643. */
  1644. function get_mimetype_description($obj, $capitalise=false) {
  1645. $filename = $mimetype = '';
  1646. if (is_object($obj) && method_exists($obj, 'get_filename') && method_exists($obj, 'get_mimetype')) {
  1647. // this is an instance of stored_file
  1648. $mimetype = $obj->get_mimetype();
  1649. $filename = $obj->get_filename();
  1650. } else if (is_object($obj) && method_exists($obj, 'get_visible_name') && method_exists($obj, 'get_mimetype')) {
  1651. // this is an instance of file_info
  1652. $mimetype = $obj->get_mimetype();
  1653. $filename = $obj->get_visible_name();
  1654. } else if (is_array($obj) || is_object ($obj)) {
  1655. $obj = (array)$obj;
  1656. if (!empty($obj['filename'])) {
  1657. $filename = $obj['filename'];
  1658. }
  1659. if (!empty($obj['mimetype'])) {
  1660. $mimetype = $obj['mimetype'];
  1661. }
  1662. } else {
  1663. $mimetype = $obj;
  1664. }
  1665. $mimetypefromext = mimeinfo('type', $filename);
  1666. if (empty($mimetype) || $mimetypefromext !== 'document/unknown') {
  1667. // if file has a known extension, overwrite the specified mimetype
  1668. $mimetype = $mimetypefromext;
  1669. }
  1670. $extension = strtolower(pathinfo($filename, PATHINFO_EXTENSION));
  1671. if (empty($extension)) {
  1672. $mimetypestr = mimeinfo_from_type('string', $mimetype);
  1673. $extension = str_replace('.', '', mimeinfo_from_type('extension', $mimetype));
  1674. } else {
  1675. $mimetypestr = mimeinfo('string', $filename);
  1676. }
  1677. $chunks = explode('/', $mimetype, 2);
  1678. $chunks[] = '';
  1679. $attr = array(
  1680. 'mimetype' => $mimetype,
  1681. 'ext' => $extension,
  1682. 'mimetype1' => $chunks[0],
  1683. 'mimetype2' => $chunks[1],
  1684. );
  1685. $a = array();
  1686. foreach ($attr as $key => $value) {
  1687. $a[$key] = $value;
  1688. $a[strtoupper($key)] = strtoupper($value);
  1689. $a[ucfirst($key)] = ucfirst($value);
  1690. }
  1691. // MIME types may include + symbol but this is not permitted in string ids.
  1692. $safemimetype = str_replace('+', '_', $mimetype);
  1693. $safemimetypestr = str_replace('+', '_', $mimetypestr);
  1694. if (get_string_manager()->string_exists($safemimetype, 'mimetypes')) {
  1695. $result = get_string($safemimetype, 'mimetypes', (object)$a);
  1696. } else if (get_string_manager()->string_exists($safemimetypestr, 'mimetypes')) {
  1697. $result = get_string($safemimetypestr, 'mimetypes', (object)$a);
  1698. } else if (get_string_manager()->string_exists('default', 'mimetypes')) {
  1699. $result = get_string('default', 'mimetypes', (object)$a);
  1700. } else {
  1701. $result = $mimetype;
  1702. }
  1703. if ($capitalise) {
  1704. $result=ucfirst($result);
  1705. }
  1706. return $result;
  1707. }
  1708. /**
  1709. * Returns array of elements of type $element in type group(s)
  1710. *
  1711. * @param string $element name of the element we are interested in, usually 'type' or 'extension'
  1712. * @param string|array $groups one group or array of groups/extensions/mimetypes
  1713. * @return array
  1714. */
  1715. function file_get_typegroup($element, $groups) {
  1716. static $cached = array();
  1717. if (!is_array($groups)) {
  1718. $groups = array($groups);
  1719. }
  1720. if (!array_key_exists($element, $cached)) {
  1721. $cached[$element] = array();
  1722. }
  1723. $result = array();
  1724. foreach ($groups as $group) {
  1725. if (!array_key_exists($group, $cached[$element])) {
  1726. // retrieive and cache all elements of type $element for group $group
  1727. $mimeinfo = & get_mimetypes_array();
  1728. $cached[$element][$group] = array();
  1729. foreach ($mimeinfo as $extension => $value) {
  1730. $value['extension'] = '.'.$extension;
  1731. if (empty($value[$element])) {
  1732. continue;
  1733. }
  1734. if (($group === '.'.$extension || $group === $value['type'] ||
  1735. (!empty($value['groups']) && in_array($group, $value['groups']))) &&
  1736. !in_array($value[$element], $cached[$element][$group])) {
  1737. $cached[$element][$group][] = $value[$element];
  1738. }
  1739. }
  1740. }
  1741. $result = array_merge($result, $cached[$element][$group]);
  1742. }
  1743. return array_values(array_unique($result));
  1744. }
  1745. /**
  1746. * Checks if file with name $filename has one of the extensions in groups $groups
  1747. *
  1748. * @see get_mimetypes_array()
  1749. * @param string $filename name of the file to check
  1750. * @param string|array $groups one group or array of groups to check
  1751. * @param bool $checktype if true and extension check fails, find the mimetype and check if
  1752. * file mimetype is in mimetypes in groups $groups
  1753. * @return bool
  1754. */
  1755. function file_extension_in_typegroup($filename, $groups, $checktype = false) {
  1756. $extension = pathinfo($filename, PATHINFO_EXTENSION);
  1757. if (!empty($extension) && in_array('.'.strtolower($extension), file_get_typegroup('extension', $groups))) {
  1758. return true;
  1759. }
  1760. return $checktype && file_mimetype_in_typegroup(mimeinfo('type', $filename), $groups);
  1761. }
  1762. /**
  1763. * Checks if mimetype $mimetype belongs to one of the groups $groups
  1764. *
  1765. * @see get_mimetypes_array()
  1766. * @param string $mimetype
  1767. * @param string|array $groups one group or array of groups to check
  1768. * @return bool
  1769. */
  1770. function file_mimetype_in_typegroup($mimetype, $groups) {
  1771. return !empty($mimetype) && in_array($mimetype, file_get_typegroup('type', $groups));
  1772. }
  1773. /**
  1774. * Requested file is not found or not accessible, does not return, terminates script
  1775. *
  1776. * @global stdClass $CFG
  1777. * @global stdClass $COURSE
  1778. */
  1779. function send_file_not_found() {
  1780. global $CFG, $COURSE;
  1781. send_header_404();
  1782. print_error('filenotfound', 'error', $CFG->wwwroot.'/course/view.php?id='.$COURSE->id); //this is not displayed on IIS??
  1783. }
  1784. /**
  1785. * Helper function to send correct 404 for server.
  1786. */
  1787. function send_header_404() {
  1788. if (substr(php_sapi_name(), 0, 3) == 'cgi') {
  1789. header("Status: 404 Not Found");
  1790. } else {
  1791. header('HTTP/1.0 404 not found');
  1792. }
  1793. }
  1794. /**
  1795. * The readfile function can fail when files are larger than 2GB (even on 64-bit
  1796. * platforms). This wrapper uses readfile for small files and custom code for
  1797. * large ones.
  1798. *
  1799. * @param string $path Path to file
  1800. * @param int $filesize Size of file (if left out, will get it automatically)
  1801. * @return int|bool Size read (will always be $filesize) or false if failed
  1802. */
  1803. function readfile_allow_large($path, $filesize = -1) {
  1804. // Automatically get size if not specified.
  1805. if ($filesize === -1) {
  1806. $filesize = filesize($path);
  1807. }
  1808. if ($filesize <= 2147483647) {
  1809. // If the file is up to 2^31 - 1, send it normally using readfile.
  1810. return readfile($path);
  1811. } else {
  1812. // For large files, read and output in 64KB chunks.
  1813. $handle = fopen($path, 'r');
  1814. if ($handle === false) {
  1815. return false;
  1816. }
  1817. $left = $filesize;
  1818. while ($left > 0) {
  1819. $size = min($left, 65536);
  1820. $buffer = fread($handle, $size);
  1821. if ($buffer === false) {
  1822. return false;
  1823. }
  1824. echo $buffer;
  1825. $left -= $size;
  1826. }
  1827. return $filesize;
  1828. }
  1829. }
  1830. /**
  1831. * Enhanced readfile() with optional acceleration.
  1832. * @param string|stored_file $file
  1833. * @param string $mimetype
  1834. * @param bool $accelerate
  1835. * @return void
  1836. */
  1837. function readfile_accel($file, $mimetype, $accelerate) {
  1838. global $CFG;
  1839. if ($mimetype === 'text/plain') {
  1840. // there is no encoding specified in text files, we need something consistent
  1841. header('Content-Type: text/plain; charset=utf-8');
  1842. } else {
  1843. header('Content-Type: '.$mimetype);
  1844. }
  1845. $lastmodified = is_object($file) ? $file->get_timemodified() : filemtime($file);
  1846. header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
  1847. if (is_object($file)) {
  1848. header('Etag: "' . $file->get_contenthash() . '"');
  1849. if (isset($_SERVER['HTTP_IF_NONE_MATCH']) and trim($_SERVER['HTTP_IF_NONE_MATCH'], '"') === $file->get_contenthash()) {
  1850. header('HTTP/1.1 304 Not Modified');
  1851. return;
  1852. }
  1853. }
  1854. // if etag present for stored file rely on it exclusively
  1855. if (!empty($_SERVER['HTTP_IF_MODIFIED_SINCE']) and (empty($_SERVER['HTTP_IF_NONE_MATCH']) or !is_object($file))) {
  1856. // get unixtime of request header; clip extra junk off first
  1857. $since = strtotime(preg_replace('/;.*$/', '', $_SERVER["HTTP_IF_MODIFIED_SINCE"]));
  1858. if ($since && $since >= $lastmodified) {
  1859. header('HTTP/1.1 304 Not Modified');
  1860. return;
  1861. }
  1862. }
  1863. if ($accelerate and !empty($CFG->xsendfile)) {
  1864. if (empty($CFG->disablebyteserving) and $mimetype !== 'text/plain') {
  1865. header('Accept-Ranges: bytes');
  1866. } else {
  1867. header('Accept-Ranges: none');
  1868. }
  1869. if (is_object($file)) {
  1870. $fs = get_file_storage();
  1871. if ($fs->xsendfile($file->get_contenthash())) {
  1872. return;
  1873. }
  1874. } else {
  1875. require_once("$CFG->libdir/xsendfilelib.php");
  1876. if (xsendfile($file)) {
  1877. return;
  1878. }
  1879. }
  1880. }
  1881. $filesize = is_object($file) ? $file->get_filesize() : filesize($file);
  1882. header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
  1883. if ($accelerate and empty($CFG->disablebyteserving) and $mimetype !== 'text/plain') {
  1884. header('Accept-Ranges: bytes');
  1885. if (!empty($_SERVER['HTTP_RANGE']) and strpos($_SERVER['HTTP_RANGE'],'bytes=') !== FALSE) {
  1886. // byteserving stuff - for acrobat reader and download accelerators
  1887. // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
  1888. // inspired by: http://www.coneural.org/florian/papers/04_byteserving.php
  1889. $ranges = false;
  1890. if (preg_match_all('/(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER)) {
  1891. foreach ($ranges as $key=>$value) {
  1892. if ($ranges[$key][1] == '') {
  1893. //suffix case
  1894. $ranges[$key][1] = $filesize - $ranges[$key][2];
  1895. $ranges[$key][2] = $filesize - 1;
  1896. } else if ($ranges[$key][2] == '' || $ranges[$key][2] > $filesize - 1) {
  1897. //fix range length
  1898. $ranges[$key][2] = $filesize - 1;
  1899. }
  1900. if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
  1901. //invalid byte-range ==> ignore header
  1902. $ranges = false;
  1903. break;
  1904. }
  1905. //prepare multipart header
  1906. $ranges[$key][0] = "\r\n--".BYTESERVING_BOUNDARY."\r\nContent-Type: $mimetype\r\n";
  1907. $ranges[$key][0] .= "Content-Range: bytes {$ranges[$key][1]}-{$ranges[$key][2]}/$filesize\r\n\r\n";
  1908. }
  1909. } else {
  1910. $ranges = false;
  1911. }
  1912. if ($ranges) {
  1913. if (is_object($file)) {
  1914. $handle = $file->get_content_file_handle();
  1915. } else {
  1916. $handle = fopen($file, 'rb');
  1917. }
  1918. byteserving_send_file($handle, $mimetype, $ranges, $filesize);
  1919. }
  1920. }
  1921. } else {
  1922. // Do not byteserve
  1923. header('Accept-Ranges: none');
  1924. }
  1925. header('Content-Length: '.$filesize);
  1926. if ($filesize > 10000000) {
  1927. // for large files try to flush and close all buffers to conserve memory
  1928. while(@ob_get_level()) {
  1929. if (!@ob_end_flush()) {
  1930. break;
  1931. }
  1932. }
  1933. }
  1934. // send the whole file content
  1935. if (is_object($file)) {
  1936. $file->readfile();
  1937. } else {
  1938. readfile_allow_large($file, $filesize);
  1939. }
  1940. }
  1941. /**
  1942. * Similar to readfile_accel() but designed for strings.
  1943. * @param string $string
  1944. * @param string $mimetype
  1945. * @param bool $accelerate
  1946. * @return void
  1947. */
  1948. function readstring_accel($string, $mimetype, $accelerate) {
  1949. global $CFG;
  1950. if ($mimetype === 'text/plain') {
  1951. // there is no encoding specified in text files, we need something consistent
  1952. header('Content-Type: text/plain; charset=utf-8');
  1953. } else {
  1954. header('Content-Type: '.$mimetype);
  1955. }
  1956. header('Last-Modified: '. gmdate('D, d M Y H:i:s', time()) .' GMT');
  1957. header('Accept-Ranges: none');
  1958. if ($accelerate and !empty($CFG->xsendfile)) {
  1959. $fs = get_file_storage();
  1960. if ($fs->xsendfile(sha1($string))) {
  1961. return;
  1962. }
  1963. }
  1964. header('Content-Length: '.strlen($string));
  1965. echo $string;
  1966. }
  1967. /**
  1968. * Handles the sending of temporary file to user, download is forced.
  1969. * File is deleted after abort or successful sending, does not return, script terminated
  1970. *
  1971. * @param string $path path to file, preferably from moodledata/temp/something; or content of file itself
  1972. * @param string $filename proposed file name when saving file
  1973. * @param bool $pathisstring If the path is string
  1974. */
  1975. function send_temp_file($path, $filename, $pathisstring=false) {
  1976. global $CFG;
  1977. if (core_useragent::is_firefox()) {
  1978. // only FF is known to correctly save to disk before opening...
  1979. $mimetype = mimeinfo('type', $filename);
  1980. } else {
  1981. $mimetype = 'application/x-forcedownload';
  1982. }
  1983. // close session - not needed anymore
  1984. \core\session\manager::write_close();
  1985. if (!$pathisstring) {
  1986. if (!file_exists($path)) {
  1987. send_header_404();
  1988. print_error('filenotfound', 'error', $CFG->wwwroot.'/');
  1989. }
  1990. // executed after normal finish or abort
  1991. core_shutdown_manager::register_function('send_temp_file_finished', array($path));
  1992. }
  1993. // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
  1994. if (core_useragent::is_ie()) {
  1995. $filename = urlencode($filename);
  1996. }
  1997. header('Content-Disposition: attachment; filename="'.$filename.'"');
  1998. if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
  1999. header('Cache-Control: private, max-age=10, no-transform');
  2000. header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
  2001. header('Pragma: ');
  2002. } else { //normal http - prevent caching at all cost
  2003. header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0, no-transform');
  2004. header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
  2005. header('Pragma: no-cache');
  2006. }
  2007. // send the contents - we can not accelerate this because the file will be deleted asap
  2008. if ($pathisstring) {
  2009. readstring_accel($path, $mimetype, false);
  2010. } else {
  2011. readfile_accel($path, $mimetype, false);
  2012. @unlink($path);
  2013. }
  2014. die; //no more chars to output
  2015. }
  2016. /**
  2017. * Internal callback function used by send_temp_file()
  2018. *
  2019. * @param string $path
  2020. */
  2021. function send_temp_file_finished($path) {
  2022. if (file_exists($path)) {
  2023. @unlink($path);
  2024. }
  2025. }
  2026. /**
  2027. * Handles the sending of file data to the user's browser, including support for
  2028. * byteranges etc.
  2029. *
  2030. * @category files
  2031. * @param string $path Path of file on disk (including real filename), or actual content of file as string
  2032. * @param string $filename Filename to send
  2033. * @param int $lifetime Number of seconds before the file should expire from caches (null means $CFG->filelifetime)
  2034. * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
  2035. * @param bool $pathisstring If true (default false), $path is the content to send and not the pathname
  2036. * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
  2037. * @param string $mimetype Include to specify the MIME type; leave blank to have it guess the type from $filename
  2038. * @param bool $dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
  2039. * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
  2040. * you must detect this case when control is returned using connection_aborted. Please not that session is closed
  2041. * and should not be reopened.
  2042. * @return null script execution stopped unless $dontdie is true
  2043. */
  2044. function send_file($path, $filename, $lifetime = null , $filter=0, $pathisstring=false, $forcedownload=false, $mimetype='', $dontdie=false) {
  2045. global $CFG, $COURSE;
  2046. if ($dontdie) {
  2047. ignore_user_abort(true);
  2048. }
  2049. if ($lifetime === 'default' or is_null($lifetime)) {
  2050. $lifetime = $CFG->filelifetime;
  2051. }
  2052. \core\session\manager::write_close(); // Unlock session during file serving.
  2053. // Use given MIME type if specified, otherwise guess it using mimeinfo.
  2054. // IE, Konqueror and Opera open html file directly in browser from web even when directed to save it to disk :-O
  2055. // only Firefox saves all files locally before opening when content-disposition: attachment stated
  2056. $isFF = core_useragent::is_firefox(); // only FF properly tested
  2057. $mimetype = ($forcedownload and !$isFF) ? 'application/x-forcedownload' :
  2058. ($mimetype ? $mimetype : mimeinfo('type', $filename));
  2059. // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
  2060. if (core_useragent::is_ie()) {
  2061. $filename = rawurlencode($filename);
  2062. }
  2063. if ($forcedownload) {
  2064. header('Content-Disposition: attachment; filename="'.$filename.'"');
  2065. } else {
  2066. header('Content-Disposition: inline; filename="'.$filename.'"');
  2067. }
  2068. if ($lifetime > 0) {
  2069. $private = '';
  2070. if (isloggedin() and !isguestuser()) {
  2071. $private = ' private,';
  2072. }
  2073. $nobyteserving = false;
  2074. header('Cache-Control:'.$private.' max-age='.$lifetime.', no-transform');
  2075. header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
  2076. header('Pragma: ');
  2077. } else { // Do not cache files in proxies and browsers
  2078. $nobyteserving = true;
  2079. if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
  2080. header('Cache-Control: private, max-age=10, no-transform');
  2081. header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
  2082. header('Pragma: ');
  2083. } else { //normal http - prevent caching at all cost
  2084. header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0, no-transform');
  2085. header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
  2086. header('Pragma: no-cache');
  2087. }
  2088. }
  2089. if (empty($filter)) {
  2090. // send the contents
  2091. if ($pathisstring) {
  2092. readstring_accel($path, $mimetype, !$dontdie);
  2093. } else {
  2094. readfile_accel($path, $mimetype, !$dontdie);
  2095. }
  2096. } else {
  2097. // Try to put the file through filters
  2098. if ($mimetype == 'text/html') {
  2099. $options = new stdClass();
  2100. $options->noclean = true;
  2101. $options->nocache = true; // temporary workaround for MDL-5136
  2102. $text = $pathisstring ? $path : implode('', file($path));
  2103. $text = file_modify_html_header($text);
  2104. $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
  2105. readstring_accel($output, $mimetype, false);
  2106. } else if (($mimetype == 'text/plain') and ($filter == 1)) {
  2107. // only filter text if filter all files is selected
  2108. $options = new stdClass();
  2109. $options->newlines = false;
  2110. $options->noclean = true;
  2111. $text = htmlentities($pathisstring ? $path : implode('', file($path)), ENT_QUOTES, 'UTF-8');
  2112. $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
  2113. readstring_accel($output, $mimetype, false);
  2114. } else {
  2115. // send the contents
  2116. if ($pathisstring) {
  2117. readstring_accel($path, $mimetype, !$dontdie);
  2118. } else {
  2119. readfile_accel($path, $mimetype, !$dontdie);
  2120. }
  2121. }
  2122. }
  2123. if ($dontdie) {
  2124. return;
  2125. }
  2126. die; //no more chars to output!!!
  2127. }
  2128. /**
  2129. * Handles the sending of file data to the user's browser, including support for
  2130. * byteranges etc.
  2131. *
  2132. * The $options parameter supports the following keys:
  2133. * (string|null) preview - send the preview of the file (e.g. "thumb" for a thumbnail)
  2134. * (string|null) filename - overrides the implicit filename
  2135. * (bool) dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
  2136. * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
  2137. * you must detect this case when control is returned using connection_aborted. Please not that session is closed
  2138. * and should not be reopened.
  2139. *
  2140. * @category files
  2141. * @param stored_file $stored_file local file object
  2142. * @param int $lifetime Number of seconds before the file should expire from caches (null means $CFG->filelifetime)
  2143. * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
  2144. * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
  2145. * @param array $options additional options affecting the file serving
  2146. * @return null script execution stopped unless $options['dontdie'] is true
  2147. */
  2148. function send_stored_file($stored_file, $lifetime=null, $filter=0, $forcedownload=false, array $options=array()) {
  2149. global $CFG, $COURSE;
  2150. if (empty($options['filename'])) {
  2151. $filename = null;
  2152. } else {
  2153. $filename = $options['filename'];
  2154. }
  2155. if (empty($options['dontdie'])) {
  2156. $dontdie = false;
  2157. } else {
  2158. $dontdie = true;
  2159. }
  2160. if ($lifetime === 'default' or is_null($lifetime)) {
  2161. $lifetime = $CFG->filelifetime;
  2162. }
  2163. if (!empty($options['preview'])) {
  2164. // replace the file with its preview
  2165. $fs = get_file_storage();
  2166. $preview_file = $fs->get_file_preview($stored_file, $options['preview']);
  2167. if (!$preview_file) {
  2168. // unable to create a preview of the file, send its default mime icon instead
  2169. if ($options['preview'] === 'tinyicon') {
  2170. $size = 24;
  2171. } else if ($options['preview'] === 'thumb') {
  2172. $size = 90;
  2173. } else {
  2174. $size = 256;
  2175. }
  2176. $fileicon = file_file_icon($stored_file, $size);
  2177. send_file($CFG->dirroot.'/pix/'.$fileicon.'.png', basename($fileicon).'.png');
  2178. } else {
  2179. // preview images have fixed cache lifetime and they ignore forced download
  2180. // (they are generated by GD and therefore they are considered reasonably safe).
  2181. $stored_file = $preview_file;
  2182. $lifetime = DAYSECS;
  2183. $filter = 0;
  2184. $forcedownload = false;
  2185. }
  2186. }
  2187. // handle external resource
  2188. if ($stored_file && $stored_file->is_external_file() && !isset($options['sendcachedexternalfile'])) {
  2189. $stored_file->send_file($lifetime, $filter, $forcedownload, $options);
  2190. die;
  2191. }
  2192. if (!$stored_file or $stored_file->is_directory()) {
  2193. // nothing to serve
  2194. if ($dontdie) {
  2195. return;
  2196. }
  2197. die;
  2198. }
  2199. if ($dontdie) {
  2200. ignore_user_abort(true);
  2201. }
  2202. \core\session\manager::write_close(); // Unlock session during file serving.
  2203. // Use given MIME type if specified, otherwise guess it using mimeinfo.
  2204. // IE, Konqueror and Opera open html file directly in browser from web even when directed to save it to disk :-O
  2205. // only Firefox saves all files locally before opening when content-disposition: attachment stated
  2206. $filename = is_null($filename) ? $stored_file->get_filename() : $filename;
  2207. $isFF = core_useragent::is_firefox(); // only FF properly tested
  2208. $mimetype = ($forcedownload and !$isFF) ? 'application/x-forcedownload' :
  2209. ($stored_file->get_mimetype() ? $stored_file->get_mimetype() : mimeinfo('type', $filename));
  2210. // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
  2211. if (core_useragent::is_ie()) {
  2212. $filename = rawurlencode($filename);
  2213. }
  2214. if ($forcedownload) {
  2215. header('Content-Disposition: attachment; filename="'.$filename.'"');
  2216. } else {
  2217. header('Content-Disposition: inline; filename="'.$filename.'"');
  2218. }
  2219. if ($lifetime > 0) {
  2220. $private = '';
  2221. if (isloggedin() and !isguestuser()) {
  2222. $private = ' private,';
  2223. }
  2224. header('Cache-Control:'.$private.' max-age='.$lifetime.', no-transform');
  2225. header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
  2226. header('Pragma: ');
  2227. } else { // Do not cache files in proxies and browsers
  2228. if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
  2229. header('Cache-Control: private, max-age=10, no-transform');
  2230. header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
  2231. header('Pragma: ');
  2232. } else { //normal http - prevent caching at all cost
  2233. header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0, no-transform');
  2234. header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
  2235. header('Pragma: no-cache');
  2236. }
  2237. }
  2238. if (empty($filter)) {
  2239. // send the contents
  2240. readfile_accel($stored_file, $mimetype, !$dontdie);
  2241. } else { // Try to put the file through filters
  2242. if ($mimetype == 'text/html') {
  2243. $options = new stdClass();
  2244. $options->noclean = true;
  2245. $options->nocache = true; // temporary workaround for MDL-5136
  2246. $text = $stored_file->get_content();
  2247. $text = file_modify_html_header($text);
  2248. $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
  2249. readstring_accel($output, $mimetype, false);
  2250. } else if (($mimetype == 'text/plain') and ($filter == 1)) {
  2251. // only filter text if filter all files is selected
  2252. $options = new stdClass();
  2253. $options->newlines = false;
  2254. $options->noclean = true;
  2255. $text = $stored_file->get_content();
  2256. $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
  2257. readstring_accel($output, $mimetype, false);
  2258. } else { // Just send it out raw
  2259. readfile_accel($stored_file, $mimetype, !$dontdie);
  2260. }
  2261. }
  2262. if ($dontdie) {
  2263. return;
  2264. }
  2265. die; //no more chars to output!!!
  2266. }
  2267. /**
  2268. * Retrieves an array of records from a CSV file and places
  2269. * them into a given table structure
  2270. *
  2271. * @global stdClass $CFG
  2272. * @global moodle_database $DB
  2273. * @param string $file The path to a CSV file
  2274. * @param string $table The table to retrieve columns from
  2275. * @return bool|array Returns an array of CSV records or false
  2276. */
  2277. function get_records_csv($file, $table) {
  2278. global $CFG, $DB;
  2279. if (!$metacolumns = $DB->get_columns($table)) {
  2280. return false;
  2281. }
  2282. if(!($handle = @fopen($file, 'r'))) {
  2283. print_error('get_records_csv failed to open '.$file);
  2284. }
  2285. $fieldnames = fgetcsv($handle, 4096);
  2286. if(empty($fieldnames)) {
  2287. fclose($handle);
  2288. return false;
  2289. }
  2290. $columns = array();
  2291. foreach($metacolumns as $metacolumn) {
  2292. $ord = array_search($metacolumn->name, $fieldnames);
  2293. if(is_int($ord)) {
  2294. $columns[$metacolumn->name] = $ord;
  2295. }
  2296. }
  2297. $rows = array();
  2298. while (($data = fgetcsv($handle, 4096)) !== false) {
  2299. $item = new stdClass;
  2300. foreach($columns as $name => $ord) {
  2301. $item->$name = $data[$ord];
  2302. }
  2303. $rows[] = $item;
  2304. }
  2305. fclose($handle);
  2306. return $rows;
  2307. }
  2308. /**
  2309. * Create a file with CSV contents
  2310. *
  2311. * @global stdClass $CFG
  2312. * @global moodle_database $DB
  2313. * @param string $file The file to put the CSV content into
  2314. * @param array $records An array of records to write to a CSV file
  2315. * @param string $table The table to get columns from
  2316. * @return bool success
  2317. */
  2318. function put_records_csv($file, $records, $table = NULL) {
  2319. global $CFG, $DB;
  2320. if (empty($records)) {
  2321. return true;
  2322. }
  2323. $metacolumns = NULL;
  2324. if ($table !== NULL && !$metacolumns = $DB->get_columns($table)) {
  2325. return false;
  2326. }
  2327. echo "x";
  2328. if(!($fp = @fopen($CFG->tempdir.'/'.$file, 'w'))) {
  2329. print_error('put_records_csv failed to open '.$file);
  2330. }
  2331. $proto = reset($records);
  2332. if(is_object($proto)) {
  2333. $fields_records = array_keys(get_object_vars($proto));
  2334. }
  2335. else if(is_array($proto)) {
  2336. $fields_records = array_keys($proto);
  2337. }
  2338. else {
  2339. return false;
  2340. }
  2341. echo "x";
  2342. if(!empty($metacolumns)) {
  2343. $fields_table = array_map(create_function('$a', 'return $a->name;'), $metacolumns);
  2344. $fields = array_intersect($fields_records, $fields_table);
  2345. }
  2346. else {
  2347. $fields = $fields_records;
  2348. }
  2349. fwrite($fp, implode(',', $fields));
  2350. fwrite($fp, "\r\n");
  2351. foreach($records as $record) {
  2352. $array = (array)$record;
  2353. $values = array();
  2354. foreach($fields as $field) {
  2355. if(strpos($array[$field], ',')) {
  2356. $values[] = '"'.str_replace('"', '\"', $array[$field]).'"';
  2357. }
  2358. else {
  2359. $values[] = $array[$field];
  2360. }
  2361. }
  2362. fwrite($fp, implode(',', $values)."\r\n");
  2363. }
  2364. fclose($fp);
  2365. @chmod($CFG->tempdir.'/'.$file, $CFG->filepermissions);
  2366. return true;
  2367. }
  2368. /**
  2369. * Recursively delete the file or folder with path $location. That is,
  2370. * if it is a file delete it. If it is a folder, delete all its content
  2371. * then delete it. If $location does not exist to start, that is not
  2372. * considered an error.
  2373. *
  2374. * @param string $location the path to remove.
  2375. * @return bool
  2376. */
  2377. function fulldelete($location) {
  2378. if (empty($location)) {
  2379. // extra safety against wrong param
  2380. return false;
  2381. }
  2382. if (is_dir($location)) {
  2383. if (!$currdir = opendir($location)) {
  2384. return false;
  2385. }
  2386. while (false !== ($file = readdir($currdir))) {
  2387. if ($file <> ".." && $file <> ".") {
  2388. $fullfile = $location."/".$file;
  2389. if (is_dir($fullfile)) {
  2390. if (!fulldelete($fullfile)) {
  2391. return false;
  2392. }
  2393. } else {
  2394. if (!unlink($fullfile)) {
  2395. return false;
  2396. }
  2397. }
  2398. }
  2399. }
  2400. closedir($currdir);
  2401. if (! rmdir($location)) {
  2402. return false;
  2403. }
  2404. } else if (file_exists($location)) {
  2405. if (!unlink($location)) {
  2406. return false;
  2407. }
  2408. }
  2409. return true;
  2410. }
  2411. /**
  2412. * Send requested byterange of file.
  2413. *
  2414. * @param resource $handle A file handle
  2415. * @param string $mimetype The mimetype for the output
  2416. * @param array $ranges An array of ranges to send
  2417. * @param string $filesize The size of the content if only one range is used
  2418. */
  2419. function byteserving_send_file($handle, $mimetype, $ranges, $filesize) {
  2420. // better turn off any kind of compression and buffering
  2421. @ini_set('zlib.output_compression', 'Off');
  2422. $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
  2423. if ($handle === false) {
  2424. die;
  2425. }
  2426. if (count($ranges) == 1) { //only one range requested
  2427. $length = $ranges[0][2] - $ranges[0][1] + 1;
  2428. header('HTTP/1.1 206 Partial content');
  2429. header('Content-Length: '.$length);
  2430. header('Content-Range: bytes '.$ranges[0][1].'-'.$ranges[0][2].'/'.$filesize);
  2431. header('Content-Type: '.$mimetype);
  2432. while(@ob_get_level()) {
  2433. if (!@ob_end_flush()) {
  2434. break;
  2435. }
  2436. }
  2437. fseek($handle, $ranges[0][1]);
  2438. while (!feof($handle) && $length > 0) {
  2439. @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
  2440. $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
  2441. echo $buffer;
  2442. flush();
  2443. $length -= strlen($buffer);
  2444. }
  2445. fclose($handle);
  2446. die;
  2447. } else { // multiple ranges requested - not tested much
  2448. $totallength = 0;
  2449. foreach($ranges as $range) {
  2450. $totallength += strlen($range[0]) + $range[2] - $range[1] + 1;
  2451. }
  2452. $totallength += strlen("\r\n--".BYTESERVING_BOUNDARY."--\r\n");
  2453. header('HTTP/1.1 206 Partial content');
  2454. header('Content-Length: '.$totallength);
  2455. header('Content-Type: multipart/byteranges; boundary='.BYTESERVING_BOUNDARY);
  2456. while(@ob_get_level()) {
  2457. if (!@ob_end_flush()) {
  2458. break;
  2459. }
  2460. }
  2461. foreach($ranges as $range) {
  2462. $length = $range[2] - $range[1] + 1;
  2463. echo $range[0];
  2464. fseek($handle, $range[1]);
  2465. while (!feof($handle) && $length > 0) {
  2466. @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
  2467. $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
  2468. echo $buffer;
  2469. flush();
  2470. $length -= strlen($buffer);
  2471. }
  2472. }
  2473. echo "\r\n--".BYTESERVING_BOUNDARY."--\r\n";
  2474. fclose($handle);
  2475. die;
  2476. }
  2477. }
  2478. /**
  2479. * add includes (js and css) into uploaded files
  2480. * before returning them, useful for themes and utf.js includes
  2481. *
  2482. * @global stdClass $CFG
  2483. * @param string $text text to search and replace
  2484. * @return string text with added head includes
  2485. * @todo MDL-21120
  2486. */
  2487. function file_modify_html_header($text) {
  2488. // first look for <head> tag
  2489. global $CFG;
  2490. $stylesheetshtml = '';
  2491. /* foreach ($CFG->stylesheets as $stylesheet) {
  2492. //TODO: MDL-21120
  2493. $stylesheetshtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
  2494. }*/
  2495. $ufo = '';
  2496. if (filter_is_enabled('mediaplugin')) {
  2497. // this script is needed by most media filter plugins.
  2498. $attributes = array('type'=>'text/javascript', 'src'=>$CFG->httpswwwroot . '/lib/ufo.js');
  2499. $ufo = html_writer::tag('script', '', $attributes) . "\n";
  2500. }
  2501. preg_match('/\<head\>|\<HEAD\>/', $text, $matches);
  2502. if ($matches) {
  2503. $replacement = '<head>'.$ufo.$stylesheetshtml;
  2504. $text = preg_replace('/\<head\>|\<HEAD\>/', $replacement, $text, 1);
  2505. return $text;
  2506. }
  2507. // if not, look for <html> tag, and stick <head> right after
  2508. preg_match('/\<html\>|\<HTML\>/', $text, $matches);
  2509. if ($matches) {
  2510. // replace <html> tag with <html><head>includes</head>
  2511. $replacement = '<html>'."\n".'<head>'.$ufo.$stylesheetshtml.'</head>';
  2512. $text = preg_replace('/\<html\>|\<HTML\>/', $replacement, $text, 1);
  2513. return $text;
  2514. }
  2515. // if not, look for <body> tag, and stick <head> before body
  2516. preg_match('/\<body\>|\<BODY\>/', $text, $matches);
  2517. if ($matches) {
  2518. $replacement = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".'<body>';
  2519. $text = preg_replace('/\<body\>|\<BODY\>/', $replacement, $text, 1);
  2520. return $text;
  2521. }
  2522. // if not, just stick a <head> tag at the beginning
  2523. $text = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".$text;
  2524. return $text;
  2525. }
  2526. /**
  2527. * RESTful cURL class
  2528. *
  2529. * This is a wrapper class for curl, it is quite easy to use:
  2530. * <code>
  2531. * $c = new curl;
  2532. * // enable cache
  2533. * $c = new curl(array('cache'=>true));
  2534. * // enable cookie
  2535. * $c = new curl(array('cookie'=>true));
  2536. * // enable proxy
  2537. * $c = new curl(array('proxy'=>true));
  2538. *
  2539. * // HTTP GET Method
  2540. * $html = $c->get('http://example.com');
  2541. * // HTTP POST Method
  2542. * $html = $c->post('http://example.com/', array('q'=>'words', 'name'=>'moodle'));
  2543. * // HTTP PUT Method
  2544. * $html = $c->put('http://example.com/', array('file'=>'/var/www/test.txt');
  2545. * </code>
  2546. *
  2547. * @package core_files
  2548. * @category files
  2549. * @copyright Dongsheng Cai <dongsheng@moodle.com>
  2550. * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
  2551. */
  2552. class curl {
  2553. /** @var bool Caches http request contents */
  2554. public $cache = false;
  2555. /** @var bool Uses proxy, null means automatic based on URL */
  2556. public $proxy = null;
  2557. /** @var string library version */
  2558. public $version = '0.4 dev';
  2559. /** @var array http's response */
  2560. public $response = array();
  2561. /** @var array Raw response headers, needed for BC in download_file_content(). */
  2562. public $rawresponse = array();
  2563. /** @var array http header */
  2564. public $header = array();
  2565. /** @var string cURL information */
  2566. public $info;
  2567. /** @var string error */
  2568. public $error;
  2569. /** @var int error code */
  2570. public $errno;
  2571. /** @var bool use workaround for open_basedir restrictions, to be changed from unit tests only! */
  2572. public $emulateredirects = null;
  2573. /** @var array cURL options */
  2574. private $options;
  2575. /** @var string Proxy host */
  2576. private $proxy_host = '';
  2577. /** @var string Proxy auth */
  2578. private $proxy_auth = '';
  2579. /** @var string Proxy type */
  2580. private $proxy_type = '';
  2581. /** @var bool Debug mode on */
  2582. private $debug = false;
  2583. /** @var bool|string Path to cookie file */
  2584. private $cookie = false;
  2585. /** @var bool tracks multiple headers in response - redirect detection */
  2586. private $responsefinished = false;
  2587. /**
  2588. * Curl constructor.
  2589. *
  2590. * Allowed settings are:
  2591. * proxy: (bool) use proxy server, null means autodetect non-local from url
  2592. * debug: (bool) use debug output
  2593. * cookie: (string) path to cookie file, false if none
  2594. * cache: (bool) use cache
  2595. * module_cache: (string) type of cache
  2596. *
  2597. * @param array $settings
  2598. */
  2599. public function __construct($settings = array()) {
  2600. global $CFG;
  2601. if (!function_exists('curl_init')) {
  2602. $this->error = 'cURL module must be enabled!';
  2603. trigger_error($this->error, E_USER_ERROR);
  2604. return false;
  2605. }
  2606. // All settings of this class should be init here.
  2607. $this->resetopt();
  2608. if (!empty($settings['debug'])) {
  2609. $this->debug = true;
  2610. }
  2611. if (!empty($settings['cookie'])) {
  2612. if($settings['cookie'] === true) {
  2613. $this->cookie = $CFG->dataroot.'/curl_cookie.txt';
  2614. } else {
  2615. $this->cookie = $settings['cookie'];
  2616. }
  2617. }
  2618. if (!empty($settings['cache'])) {
  2619. if (class_exists('curl_cache')) {
  2620. if (!empty($settings['module_cache'])) {
  2621. $this->cache = new curl_cache($settings['module_cache']);
  2622. } else {
  2623. $this->cache = new curl_cache('misc');
  2624. }
  2625. }
  2626. }
  2627. if (!empty($CFG->proxyhost)) {
  2628. if (empty($CFG->proxyport)) {
  2629. $this->proxy_host = $CFG->proxyhost;
  2630. } else {
  2631. $this->proxy_host = $CFG->proxyhost.':'.$CFG->proxyport;
  2632. }
  2633. if (!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) {
  2634. $this->proxy_auth = $CFG->proxyuser.':'.$CFG->proxypassword;
  2635. $this->setopt(array(
  2636. 'proxyauth'=> CURLAUTH_BASIC | CURLAUTH_NTLM,
  2637. 'proxyuserpwd'=>$this->proxy_auth));
  2638. }
  2639. if (!empty($CFG->proxytype)) {
  2640. if ($CFG->proxytype == 'SOCKS5') {
  2641. $this->proxy_type = CURLPROXY_SOCKS5;
  2642. } else {
  2643. $this->proxy_type = CURLPROXY_HTTP;
  2644. $this->setopt(array('httpproxytunnel'=>false));
  2645. }
  2646. $this->setopt(array('proxytype'=>$this->proxy_type));
  2647. }
  2648. if (isset($settings['proxy'])) {
  2649. $this->proxy = $settings['proxy'];
  2650. }
  2651. } else {
  2652. $this->proxy = false;
  2653. }
  2654. if (!isset($this->emulateredirects)) {
  2655. $this->emulateredirects = (ini_get('open_basedir') or ini_get('safe_mode'));
  2656. }
  2657. }
  2658. /**
  2659. * Resets the CURL options that have already been set
  2660. */
  2661. public function resetopt() {
  2662. $this->options = array();
  2663. $this->options['CURLOPT_USERAGENT'] = 'MoodleBot/1.0';
  2664. // True to include the header in the output
  2665. $this->options['CURLOPT_HEADER'] = 0;
  2666. // True to Exclude the body from the output
  2667. $this->options['CURLOPT_NOBODY'] = 0;
  2668. // Redirect ny default.
  2669. $this->options['CURLOPT_FOLLOWLOCATION'] = 1;
  2670. $this->options['CURLOPT_MAXREDIRS'] = 10;
  2671. $this->options['CURLOPT_ENCODING'] = '';
  2672. // TRUE to return the transfer as a string of the return
  2673. // value of curl_exec() instead of outputting it out directly.
  2674. $this->options['CURLOPT_RETURNTRANSFER'] = 1;
  2675. $this->options['CURLOPT_SSL_VERIFYPEER'] = 0;
  2676. $this->options['CURLOPT_SSL_VERIFYHOST'] = 2;
  2677. $this->options['CURLOPT_CONNECTTIMEOUT'] = 30;
  2678. if ($cacert = self::get_cacert()) {
  2679. $this->options['CURLOPT_CAINFO'] = $cacert;
  2680. }
  2681. }
  2682. /**
  2683. * Get the location of ca certificates.
  2684. * @return string absolute file path or empty if default used
  2685. */
  2686. public static function get_cacert() {
  2687. global $CFG;
  2688. // Bundle in dataroot always wins.
  2689. if (is_readable("$CFG->dataroot/moodleorgca.crt")) {
  2690. return realpath("$CFG->dataroot/moodleorgca.crt");
  2691. }
  2692. // Next comes the default from php.ini
  2693. $cacert = ini_get('curl.cainfo');
  2694. if (!empty($cacert) and is_readable($cacert)) {
  2695. return realpath($cacert);
  2696. }
  2697. // Windows PHP does not have any certs, we need to use something.
  2698. if ($CFG->ostype === 'WINDOWS') {
  2699. if (is_readable("$CFG->libdir/cacert.pem")) {
  2700. return realpath("$CFG->libdir/cacert.pem");
  2701. }
  2702. }
  2703. // Use default, this should work fine on all properly configured *nix systems.
  2704. return null;
  2705. }
  2706. /**
  2707. * Reset Cookie
  2708. */
  2709. public function resetcookie() {
  2710. if (!empty($this->cookie)) {
  2711. if (is_file($this->cookie)) {
  2712. $fp = fopen($this->cookie, 'w');
  2713. if (!empty($fp)) {
  2714. fwrite($fp, '');
  2715. fclose($fp);
  2716. }
  2717. }
  2718. }
  2719. }
  2720. /**
  2721. * Set curl options.
  2722. *
  2723. * Do not use the curl constants to define the options, pass a string
  2724. * corresponding to that constant. Ie. to set CURLOPT_MAXREDIRS, pass
  2725. * array('CURLOPT_MAXREDIRS' => 10) or array('maxredirs' => 10) to this method.
  2726. *
  2727. * @param array $options If array is null, this function will reset the options to default value.
  2728. * @return void
  2729. * @throws coding_exception If an option uses constant value instead of option name.
  2730. */
  2731. public function setopt($options = array()) {
  2732. if (is_array($options)) {
  2733. foreach ($options as $name => $val) {
  2734. if (!is_string($name)) {
  2735. throw new coding_exception('Curl options should be defined using strings, not constant values.');
  2736. }
  2737. if (stripos($name, 'CURLOPT_') === false) {
  2738. $name = strtoupper('CURLOPT_'.$name);
  2739. } else {
  2740. $name = strtoupper($name);
  2741. }
  2742. $this->options[$name] = $val;
  2743. }
  2744. }
  2745. }
  2746. /**
  2747. * Reset http method
  2748. */
  2749. public function cleanopt() {
  2750. unset($this->options['CURLOPT_HTTPGET']);
  2751. unset($this->options['CURLOPT_POST']);
  2752. unset($this->options['CURLOPT_POSTFIELDS']);
  2753. unset($this->options['CURLOPT_PUT']);
  2754. unset($this->options['CURLOPT_INFILE']);
  2755. unset($this->options['CURLOPT_INFILESIZE']);
  2756. unset($this->options['CURLOPT_CUSTOMREQUEST']);
  2757. unset($this->options['CURLOPT_FILE']);
  2758. }
  2759. /**
  2760. * Resets the HTTP Request headers (to prepare for the new request)
  2761. */
  2762. public function resetHeader() {
  2763. $this->header = array();
  2764. }
  2765. /**
  2766. * Set HTTP Request Header
  2767. *
  2768. * @param array $header
  2769. */
  2770. public function setHeader($header) {
  2771. if (is_array($header)) {
  2772. foreach ($header as $v) {
  2773. $this->setHeader($v);
  2774. }
  2775. } else {
  2776. // Remove newlines, they are not allowed in headers.
  2777. $this->header[] = preg_replace('/[\r\n]/', '', $header);
  2778. }
  2779. }
  2780. /**
  2781. * Get HTTP Response Headers
  2782. * @return array of arrays
  2783. */
  2784. public function getResponse() {
  2785. return $this->response;
  2786. }
  2787. /**
  2788. * Get raw HTTP Response Headers
  2789. * @return array of strings
  2790. */
  2791. public function get_raw_response() {
  2792. return $this->rawresponse;
  2793. }
  2794. /**
  2795. * private callback function
  2796. * Formatting HTTP Response Header
  2797. *
  2798. * We only keep the last headers returned. For example during a redirect the
  2799. * redirect headers will not appear in {@link self::getResponse()}, if you need
  2800. * to use those headers, refer to {@link self::get_raw_response()}.
  2801. *
  2802. * @param resource $ch Apparently not used
  2803. * @param string $header
  2804. * @return int The strlen of the header
  2805. */
  2806. private function formatHeader($ch, $header) {
  2807. $this->rawresponse[] = $header;
  2808. if (trim($header, "\r\n") === '') {
  2809. // This must be the last header.
  2810. $this->responsefinished = true;
  2811. }
  2812. if (strlen($header) > 2) {
  2813. if ($this->responsefinished) {
  2814. // We still have headers after the supposedly last header, we must be
  2815. // in a redirect so let's empty the response to keep the last headers.
  2816. $this->responsefinished = false;
  2817. $this->response = array();
  2818. }
  2819. list($key, $value) = explode(" ", rtrim($header, "\r\n"), 2);
  2820. $key = rtrim($key, ':');
  2821. if (!empty($this->response[$key])) {
  2822. if (is_array($this->response[$key])) {
  2823. $this->response[$key][] = $value;
  2824. } else {
  2825. $tmp = $this->response[$key];
  2826. $this->response[$key] = array();
  2827. $this->response[$key][] = $tmp;
  2828. $this->response[$key][] = $value;
  2829. }
  2830. } else {
  2831. $this->response[$key] = $value;
  2832. }
  2833. }
  2834. return strlen($header);
  2835. }
  2836. /**
  2837. * Set options for individual curl instance
  2838. *
  2839. * @param resource $curl A curl handle
  2840. * @param array $options
  2841. * @return resource The curl handle
  2842. */
  2843. private function apply_opt($curl, $options) {
  2844. // Some more security first.
  2845. if (defined('CURLOPT_PROTOCOLS')) {
  2846. $this->options['CURLOPT_PROTOCOLS'] = (CURLPROTO_HTTP | CURLPROTO_HTTPS);
  2847. }
  2848. if (defined('CURLOPT_REDIR_PROTOCOLS')) {
  2849. $this->options['CURLOPT_REDIR_PROTOCOLS'] = (CURLPROTO_HTTP | CURLPROTO_HTTPS);
  2850. }
  2851. // Clean up
  2852. $this->cleanopt();
  2853. // set cookie
  2854. if (!empty($this->cookie) || !empty($options['cookie'])) {
  2855. $this->setopt(array('cookiejar'=>$this->cookie,
  2856. 'cookiefile'=>$this->cookie
  2857. ));
  2858. }
  2859. // Bypass proxy if required.
  2860. if ($this->proxy === null) {
  2861. if (!empty($this->options['CURLOPT_URL']) and is_proxybypass($this->options['CURLOPT_URL'])) {
  2862. $proxy = false;
  2863. } else {
  2864. $proxy = true;
  2865. }
  2866. } else {
  2867. $proxy = (bool)$this->proxy;
  2868. }
  2869. // Set proxy.
  2870. if ($proxy) {
  2871. $options['CURLOPT_PROXY'] = $this->proxy_host;
  2872. } else {
  2873. unset($this->options['CURLOPT_PROXY']);
  2874. }
  2875. $this->setopt($options);
  2876. // reset before set options
  2877. curl_setopt($curl, CURLOPT_HEADERFUNCTION, array(&$this,'formatHeader'));
  2878. // set headers
  2879. if (empty($this->header)) {
  2880. $this->setHeader(array(
  2881. 'User-Agent: MoodleBot/1.0',
  2882. 'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7',
  2883. 'Connection: keep-alive'
  2884. ));
  2885. }
  2886. curl_setopt($curl, CURLOPT_HTTPHEADER, $this->header);
  2887. if ($this->debug) {
  2888. echo '<h1>Options</h1>';
  2889. var_dump($this->options);
  2890. echo '<h1>Header</h1>';
  2891. var_dump($this->header);
  2892. }
  2893. // Do not allow infinite redirects.
  2894. if (!isset($this->options['CURLOPT_MAXREDIRS'])) {
  2895. $this->options['CURLOPT_MAXREDIRS'] = 0;
  2896. } else if ($this->options['CURLOPT_MAXREDIRS'] > 100) {
  2897. $this->options['CURLOPT_MAXREDIRS'] = 100;
  2898. } else {
  2899. $this->options['CURLOPT_MAXREDIRS'] = (int)$this->options['CURLOPT_MAXREDIRS'];
  2900. }
  2901. // Make sure we always know if redirects expected.
  2902. if (!isset($this->options['CURLOPT_FOLLOWLOCATION'])) {
  2903. $this->options['CURLOPT_FOLLOWLOCATION'] = 0;
  2904. }
  2905. // Set options.
  2906. foreach($this->options as $name => $val) {
  2907. if ($name === 'CURLOPT_PROTOCOLS' or $name === 'CURLOPT_REDIR_PROTOCOLS') {
  2908. // These can not be changed, sorry.
  2909. continue;
  2910. }
  2911. if ($name === 'CURLOPT_FOLLOWLOCATION' and $this->emulateredirects) {
  2912. // The redirects are emulated elsewhere.
  2913. curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 0);
  2914. continue;
  2915. }
  2916. $name = constant($name);
  2917. curl_setopt($curl, $name, $val);
  2918. }
  2919. return $curl;
  2920. }
  2921. /**
  2922. * Download multiple files in parallel
  2923. *
  2924. * Calls {@link multi()} with specific download headers
  2925. *
  2926. * <code>
  2927. * $c = new curl();
  2928. * $file1 = fopen('a', 'wb');
  2929. * $file2 = fopen('b', 'wb');
  2930. * $c->download(array(
  2931. * array('url'=>'http://localhost/', 'file'=>$file1),
  2932. * array('url'=>'http://localhost/20/', 'file'=>$file2)
  2933. * ));
  2934. * fclose($file1);
  2935. * fclose($file2);
  2936. * </code>
  2937. *
  2938. * or
  2939. *
  2940. * <code>
  2941. * $c = new curl();
  2942. * $c->download(array(
  2943. * array('url'=>'http://localhost/', 'filepath'=>'/tmp/file1.tmp'),
  2944. * array('url'=>'http://localhost/20/', 'filepath'=>'/tmp/file2.tmp')
  2945. * ));
  2946. * </code>
  2947. *
  2948. * @param array $requests An array of files to request {
  2949. * url => url to download the file [required]
  2950. * file => file handler, or
  2951. * filepath => file path
  2952. * }
  2953. * If 'file' and 'filepath' parameters are both specified in one request, the
  2954. * open file handle in the 'file' parameter will take precedence and 'filepath'
  2955. * will be ignored.
  2956. *
  2957. * @param array $options An array of options to set
  2958. * @return array An array of results
  2959. */
  2960. public function download($requests, $options = array()) {
  2961. $options['RETURNTRANSFER'] = false;
  2962. return $this->multi($requests, $options);
  2963. }
  2964. /**
  2965. * Multi HTTP Requests
  2966. * This function could run multi-requests in parallel.
  2967. *
  2968. * @param array $requests An array of files to request
  2969. * @param array $options An array of options to set
  2970. * @return array An array of results
  2971. */
  2972. protected function multi($requests, $options = array()) {
  2973. $count = count($requests);
  2974. $handles = array();
  2975. $results = array();
  2976. $main = curl_multi_init();
  2977. for ($i = 0; $i < $count; $i++) {
  2978. if (!empty($requests[$i]['filepath']) and empty($requests[$i]['file'])) {
  2979. // open file
  2980. $requests[$i]['file'] = fopen($requests[$i]['filepath'], 'w');
  2981. $requests[$i]['auto-handle'] = true;
  2982. }
  2983. foreach($requests[$i] as $n=>$v) {
  2984. $options[$n] = $v;
  2985. }
  2986. $handles[$i] = curl_init($requests[$i]['url']);
  2987. $this->apply_opt($handles[$i], $options);
  2988. curl_multi_add_handle($main, $handles[$i]);
  2989. }
  2990. $running = 0;
  2991. do {
  2992. curl_multi_exec($main, $running);
  2993. } while($running > 0);
  2994. for ($i = 0; $i < $count; $i++) {
  2995. if (!empty($options['CURLOPT_RETURNTRANSFER'])) {
  2996. $results[] = true;
  2997. } else {
  2998. $results[] = curl_multi_getcontent($handles[$i]);
  2999. }
  3000. curl_multi_remove_handle($main, $handles[$i]);
  3001. }
  3002. curl_multi_close($main);
  3003. for ($i = 0; $i < $count; $i++) {
  3004. if (!empty($requests[$i]['filepath']) and !empty($requests[$i]['auto-handle'])) {
  3005. // close file handler if file is opened in this function
  3006. fclose($requests[$i]['file']);
  3007. }
  3008. }
  3009. return $results;
  3010. }
  3011. /**
  3012. * Single HTTP Request
  3013. *
  3014. * @param string $url The URL to request
  3015. * @param array $options
  3016. * @return bool
  3017. */
  3018. protected function request($url, $options = array()) {
  3019. // Set the URL as a curl option.
  3020. $this->setopt(array('CURLOPT_URL' => $url));
  3021. // Create curl instance.
  3022. $curl = curl_init();
  3023. // Reset here so that the data is valid when result returned from cache.
  3024. $this->info = array();
  3025. $this->error = '';
  3026. $this->errno = 0;
  3027. $this->response = array();
  3028. $this->rawresponse = array();
  3029. $this->responsefinished = false;
  3030. $this->apply_opt($curl, $options);
  3031. if ($this->cache && $ret = $this->cache->get($this->options)) {
  3032. return $ret;
  3033. }
  3034. $ret = curl_exec($curl);
  3035. $this->info = curl_getinfo($curl);
  3036. $this->error = curl_error($curl);
  3037. $this->errno = curl_errno($curl);
  3038. // Note: $this->response and $this->rawresponse are filled by $hits->formatHeader callback.
  3039. if ($this->emulateredirects and $this->options['CURLOPT_FOLLOWLOCATION'] and $this->info['http_code'] != 200) {
  3040. $redirects = 0;
  3041. while($redirects <= $this->options['CURLOPT_MAXREDIRS']) {
  3042. if ($this->info['http_code'] == 301) {
  3043. // Moved Permanently - repeat the same request on new URL.
  3044. } else if ($this->info['http_code'] == 302) {
  3045. // Found - the standard redirect - repeat the same request on new URL.
  3046. } else if ($this->info['http_code'] == 303) {
  3047. // 303 See Other - repeat only if GET, do not bother with POSTs.
  3048. if (empty($this->options['CURLOPT_HTTPGET'])) {
  3049. break;
  3050. }
  3051. } else if ($this->info['http_code'] == 307) {
  3052. // Temporary Redirect - must repeat using the same request type.
  3053. } else if ($this->info['http_code'] == 308) {
  3054. // Permanent Redirect - must repeat using the same request type.
  3055. } else {
  3056. // Some other http code means do not retry!
  3057. break;
  3058. }
  3059. $redirects++;
  3060. $redirecturl = null;
  3061. if (isset($this->info['redirect_url'])) {
  3062. if (preg_match('|^https?://|i', $this->info['redirect_url'])) {
  3063. $redirecturl = $this->info['redirect_url'];
  3064. }
  3065. }
  3066. if (!$redirecturl) {
  3067. foreach ($this->response as $k => $v) {
  3068. if (strtolower($k) === 'location') {
  3069. $redirecturl = $v;
  3070. break;
  3071. }
  3072. }
  3073. if (preg_match('|^https?://|i', $redirecturl)) {
  3074. // Great, this is the correct location format!
  3075. } else if ($redirecturl) {
  3076. $current = curl_getinfo($curl, CURLINFO_EFFECTIVE_URL);
  3077. if (strpos($redirecturl, '/') === 0) {
  3078. // Relative to server root - just guess.
  3079. $pos = strpos('/', $current, 8);
  3080. if ($pos === false) {
  3081. $redirecturl = $current.$redirecturl;
  3082. } else {
  3083. $redirecturl = substr($current, 0, $pos).$redirecturl;
  3084. }
  3085. } else {
  3086. // Relative to current script.
  3087. $redirecturl = dirname($current).'/'.$redirecturl;
  3088. }
  3089. }
  3090. }
  3091. curl_setopt($curl, CURLOPT_URL, $redirecturl);
  3092. $ret = curl_exec($curl);
  3093. $this->info = curl_getinfo($curl);
  3094. $this->error = curl_error($curl);
  3095. $this->errno = curl_errno($curl);
  3096. $this->info['redirect_count'] = $redirects;
  3097. if ($this->info['http_code'] === 200) {
  3098. // Finally this is what we wanted.
  3099. break;
  3100. }
  3101. if ($this->errno != CURLE_OK) {
  3102. // Something wrong is going on.
  3103. break;
  3104. }
  3105. }
  3106. if ($redirects > $this->options['CURLOPT_MAXREDIRS']) {
  3107. $this->errno = CURLE_TOO_MANY_REDIRECTS;
  3108. $this->error = 'Maximum ('.$this->options['CURLOPT_MAXREDIRS'].') redirects followed';
  3109. }
  3110. }
  3111. if ($this->cache) {
  3112. $this->cache->set($this->options, $ret);
  3113. }
  3114. if ($this->debug) {
  3115. echo '<h1>Return Data</h1>';
  3116. var_dump($ret);
  3117. echo '<h1>Info</h1>';
  3118. var_dump($this->info);
  3119. echo '<h1>Error</h1>';
  3120. var_dump($this->error);
  3121. }
  3122. curl_close($curl);
  3123. if (empty($this->error)) {
  3124. return $ret;
  3125. } else {
  3126. return $this->error;
  3127. // exception is not ajax friendly
  3128. //throw new moodle_exception($this->error, 'curl');
  3129. }
  3130. }
  3131. /**
  3132. * HTTP HEAD method
  3133. *
  3134. * @see request()
  3135. *
  3136. * @param string $url
  3137. * @param array $options
  3138. * @return bool
  3139. */
  3140. public function head($url, $options = array()) {
  3141. $options['CURLOPT_HTTPGET'] = 0;
  3142. $options['CURLOPT_HEADER'] = 1;
  3143. $options['CURLOPT_NOBODY'] = 1;
  3144. return $this->request($url, $options);
  3145. }
  3146. /**
  3147. * HTTP POST method
  3148. *
  3149. * @param string $url
  3150. * @param array|string $params
  3151. * @param array $options
  3152. * @return bool
  3153. */
  3154. public function post($url, $params = '', $options = array()) {
  3155. $options['CURLOPT_POST'] = 1;
  3156. if (is_array($params)) {
  3157. $this->_tmp_file_post_params = array();
  3158. foreach ($params as $key => $value) {
  3159. if ($value instanceof stored_file) {
  3160. $value->add_to_curl_request($this, $key);
  3161. } else {
  3162. $this->_tmp_file_post_params[$key] = $value;
  3163. }
  3164. }
  3165. $options['CURLOPT_POSTFIELDS'] = $this->_tmp_file_post_params;
  3166. unset($this->_tmp_file_post_params);
  3167. } else {
  3168. // $params is the raw post data
  3169. $options['CURLOPT_POSTFIELDS'] = $params;
  3170. }
  3171. return $this->request($url, $options);
  3172. }
  3173. /**
  3174. * HTTP GET method
  3175. *
  3176. * @param string $url
  3177. * @param array $params
  3178. * @param array $options
  3179. * @return bool
  3180. */
  3181. public function get($url, $params = array(), $options = array()) {
  3182. $options['CURLOPT_HTTPGET'] = 1;
  3183. if (!empty($params)) {
  3184. $url .= (stripos($url, '?') !== false) ? '&' : '?';
  3185. $url .= http_build_query($params, '', '&');
  3186. }
  3187. return $this->request($url, $options);
  3188. }
  3189. /**
  3190. * Downloads one file and writes it to the specified file handler
  3191. *
  3192. * <code>
  3193. * $c = new curl();
  3194. * $file = fopen('savepath', 'w');
  3195. * $result = $c->download_one('http://localhost/', null,
  3196. * array('file' => $file, 'timeout' => 5, 'followlocation' => true, 'maxredirs' => 3));
  3197. * fclose($file);
  3198. * $download_info = $c->get_info();
  3199. * if ($result === true) {
  3200. * // file downloaded successfully
  3201. * } else {
  3202. * $error_text = $result;
  3203. * $error_code = $c->get_errno();
  3204. * }
  3205. * </code>
  3206. *
  3207. * <code>
  3208. * $c = new curl();
  3209. * $result = $c->download_one('http://localhost/', null,
  3210. * array('filepath' => 'savepath', 'timeout' => 5, 'followlocation' => true, 'maxredirs' => 3));
  3211. * // ... see above, no need to close handle and remove file if unsuccessful
  3212. * </code>
  3213. *
  3214. * @param string $url
  3215. * @param array|null $params key-value pairs to be added to $url as query string
  3216. * @param array $options request options. Must include either 'file' or 'filepath'
  3217. * @return bool|string true on success or error string on failure
  3218. */
  3219. public function download_one($url, $params, $options = array()) {
  3220. $options['CURLOPT_HTTPGET'] = 1;
  3221. if (!empty($params)) {
  3222. $url .= (stripos($url, '?') !== false) ? '&' : '?';
  3223. $url .= http_build_query($params, '', '&');
  3224. }
  3225. if (!empty($options['filepath']) && empty($options['file'])) {
  3226. // open file
  3227. if (!($options['file'] = fopen($options['filepath'], 'w'))) {
  3228. $this->errno = 100;
  3229. return get_string('cannotwritefile', 'error', $options['filepath']);
  3230. }
  3231. $filepath = $options['filepath'];
  3232. }
  3233. unset($options['filepath']);
  3234. $result = $this->request($url, $options);
  3235. if (isset($filepath)) {
  3236. fclose($options['file']);
  3237. if ($result !== true) {
  3238. unlink($filepath);
  3239. }
  3240. }
  3241. return $result;
  3242. }
  3243. /**
  3244. * HTTP PUT method
  3245. *
  3246. * @param string $url
  3247. * @param array $params
  3248. * @param array $options
  3249. * @return bool
  3250. */
  3251. public function put($url, $params = array(), $options = array()) {
  3252. $file = $params['file'];
  3253. if (!is_file($file)) {
  3254. return null;
  3255. }
  3256. $fp = fopen($file, 'r');
  3257. $size = filesize($file);
  3258. $options['CURLOPT_PUT'] = 1;
  3259. $options['CURLOPT_INFILESIZE'] = $size;
  3260. $options['CURLOPT_INFILE'] = $fp;
  3261. if (!isset($this->options['CURLOPT_USERPWD'])) {
  3262. $this->setopt(array('CURLOPT_USERPWD'=>'anonymous: noreply@moodle.org'));
  3263. }
  3264. $ret = $this->request($url, $options);
  3265. fclose($fp);
  3266. return $ret;
  3267. }
  3268. /**
  3269. * HTTP DELETE method
  3270. *
  3271. * @param string $url
  3272. * @param array $param
  3273. * @param array $options
  3274. * @return bool
  3275. */
  3276. public function delete($url, $param = array(), $options = array()) {
  3277. $options['CURLOPT_CUSTOMREQUEST'] = 'DELETE';
  3278. if (!isset($options['CURLOPT_USERPWD'])) {
  3279. $options['CURLOPT_USERPWD'] = 'anonymous: noreply@moodle.org';
  3280. }
  3281. $ret = $this->request($url, $options);
  3282. return $ret;
  3283. }
  3284. /**
  3285. * HTTP TRACE method
  3286. *
  3287. * @param string $url
  3288. * @param array $options
  3289. * @return bool
  3290. */
  3291. public function trace($url, $options = array()) {
  3292. $options['CURLOPT_CUSTOMREQUEST'] = 'TRACE';
  3293. $ret = $this->request($url, $options);
  3294. return $ret;
  3295. }
  3296. /**
  3297. * HTTP OPTIONS method
  3298. *
  3299. * @param string $url
  3300. * @param array $options
  3301. * @return bool
  3302. */
  3303. public function options($url, $options = array()) {
  3304. $options['CURLOPT_CUSTOMREQUEST'] = 'OPTIONS';
  3305. $ret = $this->request($url, $options);
  3306. return $ret;
  3307. }
  3308. /**
  3309. * Get curl information
  3310. *
  3311. * @return string
  3312. */
  3313. public function get_info() {
  3314. return $this->info;
  3315. }
  3316. /**
  3317. * Get curl error code
  3318. *
  3319. * @return int
  3320. */
  3321. public function get_errno() {
  3322. return $this->errno;
  3323. }
  3324. /**
  3325. * When using a proxy, an additional HTTP response code may appear at
  3326. * the start of the header. For example, when using https over a proxy
  3327. * there may be 'HTTP/1.0 200 Connection Established'. Other codes are
  3328. * also possible and some may come with their own headers.
  3329. *
  3330. * If using the return value containing all headers, this function can be
  3331. * called to remove unwanted doubles.
  3332. *
  3333. * Note that it is not possible to distinguish this situation from valid
  3334. * data unless you know the actual response part (below the headers)
  3335. * will not be included in this string, or else will not 'look like' HTTP
  3336. * headers. As a result it is not safe to call this function for general
  3337. * data.
  3338. *
  3339. * @param string $input Input HTTP response
  3340. * @return string HTTP response with additional headers stripped if any
  3341. */
  3342. public static function strip_double_headers($input) {
  3343. // I have tried to make this regular expression as specific as possible
  3344. // to avoid any case where it does weird stuff if you happen to put
  3345. // HTTP/1.1 200 at the start of any line in your RSS file. This should
  3346. // also make it faster because it can abandon regex processing as soon
  3347. // as it hits something that doesn't look like an http header. The
  3348. // header definition is taken from RFC 822, except I didn't support
  3349. // folding which is never used in practice.
  3350. $crlf = "\r\n";
  3351. return preg_replace(
  3352. // HTTP version and status code (ignore value of code).
  3353. '~^HTTP/1\..*' . $crlf .
  3354. // Header name: character between 33 and 126 decimal, except colon.
  3355. // Colon. Header value: any character except \r and \n. CRLF.
  3356. '(?:[\x21-\x39\x3b-\x7e]+:[^' . $crlf . ']+' . $crlf . ')*' .
  3357. // Headers are terminated by another CRLF (blank line).
  3358. $crlf .
  3359. // Second HTTP status code, this time must be 200.
  3360. '(HTTP/1.[01] 200 )~', '$1', $input);
  3361. }
  3362. }
  3363. /**
  3364. * This class is used by cURL class, use case:
  3365. *
  3366. * <code>
  3367. * $CFG->repositorycacheexpire = 120;
  3368. * $CFG->curlcache = 120;
  3369. *
  3370. * $c = new curl(array('cache'=>true), 'module_cache'=>'repository');
  3371. * $ret = $c->get('http://www.google.com');
  3372. * </code>
  3373. *
  3374. * @package core_files
  3375. * @copyright Dongsheng Cai <dongsheng@moodle.com>
  3376. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  3377. */
  3378. class curl_cache {
  3379. /** @var string Path to cache directory */
  3380. public $dir = '';
  3381. /**
  3382. * Constructor
  3383. *
  3384. * @global stdClass $CFG
  3385. * @param string $module which module is using curl_cache
  3386. */
  3387. public function __construct($module = 'repository') {
  3388. global $CFG;
  3389. if (!empty($module)) {
  3390. $this->dir = $CFG->cachedir.'/'.$module.'/';
  3391. } else {
  3392. $this->dir = $CFG->cachedir.'/misc/';
  3393. }
  3394. if (!file_exists($this->dir)) {
  3395. mkdir($this->dir, $CFG->directorypermissions, true);
  3396. }
  3397. if ($module == 'repository') {
  3398. if (empty($CFG->repositorycacheexpire)) {
  3399. $CFG->repositorycacheexpire = 120;
  3400. }
  3401. $this->ttl = $CFG->repositorycacheexpire;
  3402. } else {
  3403. if (empty($CFG->curlcache)) {
  3404. $CFG->curlcache = 120;
  3405. }
  3406. $this->ttl = $CFG->curlcache;
  3407. }
  3408. }
  3409. /**
  3410. * Get cached value
  3411. *
  3412. * @global stdClass $CFG
  3413. * @global stdClass $USER
  3414. * @param mixed $param
  3415. * @return bool|string
  3416. */
  3417. public function get($param) {
  3418. global $CFG, $USER;
  3419. $this->cleanup($this->ttl);
  3420. $filename = 'u'.$USER->id.'_'.md5(serialize($param));
  3421. if(file_exists($this->dir.$filename)) {
  3422. $lasttime = filemtime($this->dir.$filename);
  3423. if (time()-$lasttime > $this->ttl) {
  3424. return false;
  3425. } else {
  3426. $fp = fopen($this->dir.$filename, 'r');
  3427. $size = filesize($this->dir.$filename);
  3428. $content = fread($fp, $size);
  3429. return unserialize($content);
  3430. }
  3431. }
  3432. return false;
  3433. }
  3434. /**
  3435. * Set cache value
  3436. *
  3437. * @global object $CFG
  3438. * @global object $USER
  3439. * @param mixed $param
  3440. * @param mixed $val
  3441. */
  3442. public function set($param, $val) {
  3443. global $CFG, $USER;
  3444. $filename = 'u'.$USER->id.'_'.md5(serialize($param));
  3445. $fp = fopen($this->dir.$filename, 'w');
  3446. fwrite($fp, serialize($val));
  3447. fclose($fp);
  3448. @chmod($this->dir.$filename, $CFG->filepermissions);
  3449. }
  3450. /**
  3451. * Remove cache files
  3452. *
  3453. * @param int $expire The number of seconds before expiry
  3454. */
  3455. public function cleanup($expire) {
  3456. if ($dir = opendir($this->dir)) {
  3457. while (false !== ($file = readdir($dir))) {
  3458. if(!is_dir($file) && $file != '.' && $file != '..') {
  3459. $lasttime = @filemtime($this->dir.$file);
  3460. if (time() - $lasttime > $expire) {
  3461. @unlink($this->dir.$file);
  3462. }
  3463. }
  3464. }
  3465. closedir($dir);
  3466. }
  3467. }
  3468. /**
  3469. * delete current user's cache file
  3470. *
  3471. * @global object $CFG
  3472. * @global object $USER
  3473. */
  3474. public function refresh() {
  3475. global $CFG, $USER;
  3476. if ($dir = opendir($this->dir)) {
  3477. while (false !== ($file = readdir($dir))) {
  3478. if (!is_dir($file) && $file != '.' && $file != '..') {
  3479. if (strpos($file, 'u'.$USER->id.'_') !== false) {
  3480. @unlink($this->dir.$file);
  3481. }
  3482. }
  3483. }
  3484. }
  3485. }
  3486. }
  3487. /**
  3488. * This function delegates file serving to individual plugins
  3489. *
  3490. * @param string $relativepath
  3491. * @param bool $forcedownload
  3492. * @param null|string $preview the preview mode, defaults to serving the original file
  3493. * @todo MDL-31088 file serving improments
  3494. */
  3495. function file_pluginfile($relativepath, $forcedownload, $preview = null) {
  3496. global $DB, $CFG, $USER;
  3497. // relative path must start with '/'
  3498. if (!$relativepath) {
  3499. print_error('invalidargorconf');
  3500. } else if ($relativepath[0] != '/') {
  3501. print_error('pathdoesnotstartslash');
  3502. }
  3503. // extract relative path components
  3504. $args = explode('/', ltrim($relativepath, '/'));
  3505. if (count($args) < 3) { // always at least context, component and filearea
  3506. print_error('invalidarguments');
  3507. }
  3508. $contextid = (int)array_shift($args);
  3509. $component = clean_param(array_shift($args), PARAM_COMPONENT);
  3510. $filearea = clean_param(array_shift($args), PARAM_AREA);
  3511. list($context, $course, $cm) = get_context_info_array($contextid);
  3512. $fs = get_file_storage();
  3513. // ========================================================================================================================
  3514. if ($component === 'blog') {
  3515. // Blog file serving
  3516. if ($context->contextlevel != CONTEXT_SYSTEM) {
  3517. send_file_not_found();
  3518. }
  3519. if ($filearea !== 'attachment' and $filearea !== 'post') {
  3520. send_file_not_found();
  3521. }
  3522. if (empty($CFG->enableblogs)) {
  3523. print_error('siteblogdisable', 'blog');
  3524. }
  3525. $entryid = (int)array_shift($args);
  3526. if (!$entry = $DB->get_record('post', array('module'=>'blog', 'id'=>$entryid))) {
  3527. send_file_not_found();
  3528. }
  3529. if ($CFG->bloglevel < BLOG_GLOBAL_LEVEL) {
  3530. require_login();
  3531. if (isguestuser()) {
  3532. print_error('noguest');
  3533. }
  3534. if ($CFG->bloglevel == BLOG_USER_LEVEL) {
  3535. if ($USER->id != $entry->userid) {
  3536. send_file_not_found();
  3537. }
  3538. }
  3539. }
  3540. if ($entry->publishstate === 'public') {
  3541. if ($CFG->forcelogin) {
  3542. require_login();
  3543. }
  3544. } else if ($entry->publishstate === 'site') {
  3545. require_login();
  3546. //ok
  3547. } else if ($entry->publishstate === 'draft') {
  3548. require_login();
  3549. if ($USER->id != $entry->userid) {
  3550. send_file_not_found();
  3551. }
  3552. }
  3553. $filename = array_pop($args);
  3554. $filepath = $args ? '/'.implode('/', $args).'/' : '/';
  3555. if (!$file = $fs->get_file($context->id, $component, $filearea, $entryid, $filepath, $filename) or $file->is_directory()) {
  3556. send_file_not_found();
  3557. }
  3558. send_stored_file($file, 10*60, 0, true, array('preview' => $preview)); // download MUST be forced - security!
  3559. // ========================================================================================================================
  3560. } else if ($component === 'grade') {
  3561. if (($filearea === 'outcome' or $filearea === 'scale') and $context->contextlevel == CONTEXT_SYSTEM) {
  3562. // Global gradebook files
  3563. if ($CFG->forcelogin) {
  3564. require_login();
  3565. }
  3566. $fullpath = "/$context->id/$component/$filearea/".implode('/', $args);
  3567. if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
  3568. send_file_not_found();
  3569. }
  3570. \core\session\manager::write_close(); // Unlock session during file serving.
  3571. send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
  3572. } else if ($filearea === 'feedback' and $context->contextlevel == CONTEXT_COURSE) {
  3573. //TODO: nobody implemented this yet in grade edit form!!
  3574. send_file_not_found();
  3575. if ($CFG->forcelogin || $course->id != SITEID) {
  3576. require_login($course);
  3577. }
  3578. $fullpath = "/$context->id/$component/$filearea/".implode('/', $args);
  3579. if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
  3580. send_file_not_found();
  3581. }
  3582. \core\session\manager::write_close(); // Unlock session during file serving.
  3583. send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
  3584. } else {
  3585. send_file_not_found();
  3586. }
  3587. // ========================================================================================================================
  3588. } else if ($component === 'tag') {
  3589. if ($filearea === 'description' and $context->contextlevel == CONTEXT_SYSTEM) {
  3590. // All tag descriptions are going to be public but we still need to respect forcelogin
  3591. if ($CFG->forcelogin) {
  3592. require_login();
  3593. }
  3594. $fullpath = "/$context->id/tag/description/".implode('/', $args);
  3595. if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
  3596. send_file_not_found();
  3597. }
  3598. \core\session\manager::write_close(); // Unlock session during file serving.
  3599. send_stored_file($file, 60*60, 0, true, array('preview' => $preview));
  3600. } else {
  3601. send_file_not_found();
  3602. }
  3603. // ========================================================================================================================
  3604. } else if ($component === 'badges') {
  3605. require_once($CFG->libdir . '/badgeslib.php');
  3606. $badgeid = (int)array_shift($args);
  3607. $badge = new badge($badgeid);
  3608. $filename = array_pop($args);
  3609. if ($filearea === 'badgeimage') {
  3610. if ($filename !== 'f1' && $filename !== 'f2') {
  3611. send_file_not_found();
  3612. }
  3613. if (!$file = $fs->get_file($context->id, 'badges', 'badgeimage', $badge->id, '/', $filename.'.png')) {
  3614. send_file_not_found();
  3615. }
  3616. \core\session\manager::write_close();
  3617. send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
  3618. } else if ($filearea === 'userbadge' and $context->contextlevel == CONTEXT_USER) {
  3619. if (!$file = $fs->get_file($context->id, 'badges', 'userbadge', $badge->id, '/', $filename.'.png')) {
  3620. send_file_not_found();
  3621. }
  3622. \core\session\manager::write_close();
  3623. send_stored_file($file, 60*60, 0, true, array('preview' => $preview));
  3624. }
  3625. // ========================================================================================================================
  3626. } else if ($component === 'calendar') {
  3627. if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_SYSTEM) {
  3628. // All events here are public the one requirement is that we respect forcelogin
  3629. if ($CFG->forcelogin) {
  3630. require_login();
  3631. }
  3632. // Get the event if from the args array
  3633. $eventid = array_shift($args);
  3634. // Load the event from the database
  3635. if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'eventtype'=>'site'))) {
  3636. send_file_not_found();
  3637. }
  3638. // Get the file and serve if successful
  3639. $filename = array_pop($args);
  3640. $filepath = $args ? '/'.implode('/', $args).'/' : '/';
  3641. if (!$file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
  3642. send_file_not_found();
  3643. }
  3644. \core\session\manager::write_close(); // Unlock session during file serving.
  3645. send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
  3646. } else if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_USER) {
  3647. // Must be logged in, if they are not then they obviously can't be this user
  3648. require_login();
  3649. // Don't want guests here, potentially saves a DB call
  3650. if (isguestuser()) {
  3651. send_file_not_found();
  3652. }
  3653. // Get the event if from the args array
  3654. $eventid = array_shift($args);
  3655. // Load the event from the database - user id must match
  3656. if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'userid'=>$USER->id, 'eventtype'=>'user'))) {
  3657. send_file_not_found();
  3658. }
  3659. // Get the file and serve if successful
  3660. $filename = array_pop($args);
  3661. $filepath = $args ? '/'.implode('/', $args).'/' : '/';
  3662. if (!$file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
  3663. send_file_not_found();
  3664. }
  3665. \core\session\manager::write_close(); // Unlock session during file serving.
  3666. send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
  3667. } else if ($filearea === 'event_description' and $context->contextlevel == CONTEXT_COURSE) {
  3668. // Respect forcelogin and require login unless this is the site.... it probably
  3669. // should NEVER be the site
  3670. if ($CFG->forcelogin || $course->id != SITEID) {
  3671. require_login($course);
  3672. }
  3673. // Must be able to at least view the course. This does not apply to the front page.
  3674. if ($course->id != SITEID && (!is_enrolled($context)) && (!is_viewing($context))) {
  3675. //TODO: hmm, do we really want to block guests here?
  3676. send_file_not_found();
  3677. }
  3678. // Get the event id
  3679. $eventid = array_shift($args);
  3680. // Load the event from the database we need to check whether it is
  3681. // a) valid course event
  3682. // b) a group event
  3683. // Group events use the course context (there is no group context)
  3684. if (!$event = $DB->get_record('event', array('id'=>(int)$eventid, 'courseid'=>$course->id))) {
  3685. send_file_not_found();
  3686. }
  3687. // If its a group event require either membership of view all groups capability
  3688. if ($event->eventtype === 'group') {
  3689. if (!has_capability('moodle/site:accessallgroups', $context) && !groups_is_member($event->groupid, $USER->id)) {
  3690. send_file_not_found();
  3691. }
  3692. } else if ($event->eventtype === 'course' || $event->eventtype === 'site') {
  3693. // Ok. Please note that the event type 'site' still uses a course context.
  3694. } else {
  3695. // Some other type.
  3696. send_file_not_found();
  3697. }
  3698. // If we get this far we can serve the file
  3699. $filename = array_pop($args);
  3700. $filepath = $args ? '/'.implode('/', $args).'/' : '/';
  3701. if (!$file = $fs->get_file($context->id, $component, $filearea, $eventid, $filepath, $filename) or $file->is_directory()) {
  3702. send_file_not_found();
  3703. }
  3704. \core\session\manager::write_close(); // Unlock session during file serving.
  3705. send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
  3706. } else {
  3707. send_file_not_found();
  3708. }
  3709. // ========================================================================================================================
  3710. } else if ($component === 'user') {
  3711. if ($filearea === 'icon' and $context->contextlevel == CONTEXT_USER) {
  3712. if (count($args) == 1) {
  3713. $themename = theme_config::DEFAULT_THEME;
  3714. $filename = array_shift($args);
  3715. } else {
  3716. $themename = array_shift($args);
  3717. $filename = array_shift($args);
  3718. }
  3719. // fix file name automatically
  3720. if ($filename !== 'f1' and $filename !== 'f2' and $filename !== 'f3') {
  3721. $filename = 'f1';
  3722. }
  3723. if ((!empty($CFG->forcelogin) and !isloggedin()) ||
  3724. (!empty($CFG->forceloginforprofileimage) && (!isloggedin() || isguestuser()))) {
  3725. // protect images if login required and not logged in;
  3726. // also if login is required for profile images and is not logged in or guest
  3727. // do not use require_login() because it is expensive and not suitable here anyway
  3728. $theme = theme_config::load($themename);
  3729. redirect($theme->pix_url('u/'.$filename, 'moodle')); // intentionally not cached
  3730. }
  3731. if (!$file = $fs->get_file($context->id, 'user', 'icon', 0, '/', $filename.'.png')) {
  3732. if (!$file = $fs->get_file($context->id, 'user', 'icon', 0, '/', $filename.'.jpg')) {
  3733. if ($filename === 'f3') {
  3734. // f3 512x512px was introduced in 2.3, there might be only the smaller version.
  3735. if (!$file = $fs->get_file($context->id, 'user', 'icon', 0, '/', 'f1.png')) {
  3736. $file = $fs->get_file($context->id, 'user', 'icon', 0, '/', 'f1.jpg');
  3737. }
  3738. }
  3739. }
  3740. }
  3741. if (!$file) {
  3742. // bad reference - try to prevent future retries as hard as possible!
  3743. if ($user = $DB->get_record('user', array('id'=>$context->instanceid), 'id, picture')) {
  3744. if ($user->picture > 0) {
  3745. $DB->set_field('user', 'picture', 0, array('id'=>$user->id));
  3746. }
  3747. }
  3748. // no redirect here because it is not cached
  3749. $theme = theme_config::load($themename);
  3750. $imagefile = $theme->resolve_image_location('u/'.$filename, 'moodle', null);
  3751. send_file($imagefile, basename($imagefile), 60*60*24*14);
  3752. }
  3753. send_stored_file($file, 60*60*24*365, 0, false, array('preview' => $preview)); // enable long caching, there are many images on each page
  3754. } else if ($filearea === 'private' and $context->contextlevel == CONTEXT_USER) {
  3755. require_login();
  3756. if (isguestuser()) {
  3757. send_file_not_found();
  3758. }
  3759. if ($USER->id !== $context->instanceid) {
  3760. send_file_not_found();
  3761. }
  3762. $filename = array_pop($args);
  3763. $filepath = $args ? '/'.implode('/', $args).'/' : '/';
  3764. if (!$file = $fs->get_file($context->id, $component, $filearea, 0, $filepath, $filename) or $file->is_directory()) {
  3765. send_file_not_found();
  3766. }
  3767. \core\session\manager::write_close(); // Unlock session during file serving.
  3768. send_stored_file($file, 0, 0, true, array('preview' => $preview)); // must force download - security!
  3769. } else if ($filearea === 'profile' and $context->contextlevel == CONTEXT_USER) {
  3770. if ($CFG->forcelogin) {
  3771. require_login();
  3772. }
  3773. $userid = $context->instanceid;
  3774. if ($USER->id == $userid) {
  3775. // always can access own
  3776. } else if (!empty($CFG->forceloginforprofiles)) {
  3777. require_login();
  3778. if (isguestuser()) {
  3779. send_file_not_found();
  3780. }
  3781. // we allow access to site profile of all course contacts (usually teachers)
  3782. if (!has_coursecontact_role($userid) && !has_capability('moodle/user:viewdetails', $context)) {
  3783. send_file_not_found();
  3784. }
  3785. $canview = false;
  3786. if (has_capability('moodle/user:viewdetails', $context)) {
  3787. $canview = true;
  3788. } else {
  3789. $courses = enrol_get_my_courses();
  3790. }
  3791. while (!$canview && count($courses) > 0) {
  3792. $course = array_shift($courses);
  3793. if (has_capability('moodle/user:viewdetails', context_course::instance($course->id))) {
  3794. $canview = true;
  3795. }
  3796. }
  3797. }
  3798. $filename = array_pop($args);
  3799. $filepath = $args ? '/'.implode('/', $args).'/' : '/';
  3800. if (!$file = $fs->get_file($context->id, $component, $filearea, 0, $filepath, $filename) or $file->is_directory()) {
  3801. send_file_not_found();
  3802. }
  3803. \core\session\manager::write_close(); // Unlock session during file serving.
  3804. send_stored_file($file, 0, 0, true, array('preview' => $preview)); // must force download - security!
  3805. } else if ($filearea === 'profile' and $context->contextlevel == CONTEXT_COURSE) {
  3806. $userid = (int)array_shift($args);
  3807. $usercontext = context_user::instance($userid);
  3808. if ($CFG->forcelogin) {
  3809. require_login();
  3810. }
  3811. if (!empty($CFG->forceloginforprofiles)) {
  3812. require_login();
  3813. if (isguestuser()) {
  3814. print_error('noguest');
  3815. }
  3816. //TODO: review this logic of user profile access prevention
  3817. if (!has_coursecontact_role($userid) and !has_capability('moodle/user:viewdetails', $usercontext)) {
  3818. print_error('usernotavailable');
  3819. }
  3820. if (!has_capability('moodle/user:viewdetails', $context) && !has_capability('moodle/user:viewdetails', $usercontext)) {
  3821. print_error('cannotviewprofile');
  3822. }
  3823. if (!is_enrolled($context, $userid)) {
  3824. print_error('notenrolledprofile');
  3825. }
  3826. if (groups_get_course_groupmode($course) == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', $context)) {
  3827. print_error('groupnotamember');
  3828. }
  3829. }
  3830. $filename = array_pop($args);
  3831. $filepath = $args ? '/'.implode('/', $args).'/' : '/';
  3832. if (!$file = $fs->get_file($usercontext->id, 'user', 'profile', 0, $filepath, $filename) or $file->is_directory()) {
  3833. send_file_not_found();
  3834. }
  3835. \core\session\manager::write_close(); // Unlock session during file serving.
  3836. send_stored_file($file, 0, 0, true, array('preview' => $preview)); // must force download - security!
  3837. } else if ($filearea === 'backup' and $context->contextlevel == CONTEXT_USER) {
  3838. require_login();
  3839. if (isguestuser()) {
  3840. send_file_not_found();
  3841. }
  3842. $userid = $context->instanceid;
  3843. if ($USER->id != $userid) {
  3844. send_file_not_found();
  3845. }
  3846. $filename = array_pop($args);
  3847. $filepath = $args ? '/'.implode('/', $args).'/' : '/';
  3848. if (!$file = $fs->get_file($context->id, 'user', 'backup', 0, $filepath, $filename) or $file->is_directory()) {
  3849. send_file_not_found();
  3850. }
  3851. \core\session\manager::write_close(); // Unlock session during file serving.
  3852. send_stored_file($file, 0, 0, true, array('preview' => $preview)); // must force download - security!
  3853. } else {
  3854. send_file_not_found();
  3855. }
  3856. // ========================================================================================================================
  3857. } else if ($component === 'coursecat') {
  3858. if ($context->contextlevel != CONTEXT_COURSECAT) {
  3859. send_file_not_found();
  3860. }
  3861. if ($filearea === 'description') {
  3862. if ($CFG->forcelogin) {
  3863. // no login necessary - unless login forced everywhere
  3864. require_login();
  3865. }
  3866. $filename = array_pop($args);
  3867. $filepath = $args ? '/'.implode('/', $args).'/' : '/';
  3868. if (!$file = $fs->get_file($context->id, 'coursecat', 'description', 0, $filepath, $filename) or $file->is_directory()) {
  3869. send_file_not_found();
  3870. }
  3871. \core\session\manager::write_close(); // Unlock session during file serving.
  3872. send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
  3873. } else {
  3874. send_file_not_found();
  3875. }
  3876. // ========================================================================================================================
  3877. } else if ($component === 'course') {
  3878. if ($context->contextlevel != CONTEXT_COURSE) {
  3879. send_file_not_found();
  3880. }
  3881. if ($filearea === 'summary' || $filearea === 'overviewfiles') {
  3882. if ($CFG->forcelogin) {
  3883. require_login();
  3884. }
  3885. $filename = array_pop($args);
  3886. $filepath = $args ? '/'.implode('/', $args).'/' : '/';
  3887. if (!$file = $fs->get_file($context->id, 'course', $filearea, 0, $filepath, $filename) or $file->is_directory()) {
  3888. send_file_not_found();
  3889. }
  3890. \core\session\manager::write_close(); // Unlock session during file serving.
  3891. send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
  3892. } else if ($filearea === 'section') {
  3893. if ($CFG->forcelogin) {
  3894. require_login($course);
  3895. } else if ($course->id != SITEID) {
  3896. require_login($course);
  3897. }
  3898. $sectionid = (int)array_shift($args);
  3899. if (!$section = $DB->get_record('course_sections', array('id'=>$sectionid, 'course'=>$course->id))) {
  3900. send_file_not_found();
  3901. }
  3902. $filename = array_pop($args);
  3903. $filepath = $args ? '/'.implode('/', $args).'/' : '/';
  3904. if (!$file = $fs->get_file($context->id, 'course', 'section', $sectionid, $filepath, $filename) or $file->is_directory()) {
  3905. send_file_not_found();
  3906. }
  3907. \core\session\manager::write_close(); // Unlock session during file serving.
  3908. send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
  3909. } else {
  3910. send_file_not_found();
  3911. }
  3912. } else if ($component === 'group') {
  3913. if ($context->contextlevel != CONTEXT_COURSE) {
  3914. send_file_not_found();
  3915. }
  3916. require_course_login($course, true, null, false);
  3917. $groupid = (int)array_shift($args);
  3918. $group = $DB->get_record('groups', array('id'=>$groupid, 'courseid'=>$course->id), '*', MUST_EXIST);
  3919. if (($course->groupmodeforce and $course->groupmode == SEPARATEGROUPS) and !has_capability('moodle/site:accessallgroups', $context) and !groups_is_member($group->id, $USER->id)) {
  3920. // do not allow access to separate group info if not member or teacher
  3921. send_file_not_found();
  3922. }
  3923. if ($filearea === 'description') {
  3924. require_login($course);
  3925. $filename = array_pop($args);
  3926. $filepath = $args ? '/'.implode('/', $args).'/' : '/';
  3927. if (!$file = $fs->get_file($context->id, 'group', 'description', $group->id, $filepath, $filename) or $file->is_directory()) {
  3928. send_file_not_found();
  3929. }
  3930. \core\session\manager::write_close(); // Unlock session during file serving.
  3931. send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
  3932. } else if ($filearea === 'icon') {
  3933. $filename = array_pop($args);
  3934. if ($filename !== 'f1' and $filename !== 'f2') {
  3935. send_file_not_found();
  3936. }
  3937. if (!$file = $fs->get_file($context->id, 'group', 'icon', $group->id, '/', $filename.'.png')) {
  3938. if (!$file = $fs->get_file($context->id, 'group', 'icon', $group->id, '/', $filename.'.jpg')) {
  3939. send_file_not_found();
  3940. }
  3941. }
  3942. \core\session\manager::write_close(); // Unlock session during file serving.
  3943. send_stored_file($file, 60*60, 0, false, array('preview' => $preview));
  3944. } else {
  3945. send_file_not_found();
  3946. }
  3947. } else if ($component === 'grouping') {
  3948. if ($context->contextlevel != CONTEXT_COURSE) {
  3949. send_file_not_found();
  3950. }
  3951. require_login($course);
  3952. $groupingid = (int)array_shift($args);
  3953. // note: everybody has access to grouping desc images for now
  3954. if ($filearea === 'description') {
  3955. $filename = array_pop($args);
  3956. $filepath = $args ? '/'.implode('/', $args).'/' : '/';
  3957. if (!$file = $fs->get_file($context->id, 'grouping', 'description', $groupingid, $filepath, $filename) or $file->is_directory()) {
  3958. send_file_not_found();
  3959. }
  3960. \core\session\manager::write_close(); // Unlock session during file serving.
  3961. send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
  3962. } else {
  3963. send_file_not_found();
  3964. }
  3965. // ========================================================================================================================
  3966. } else if ($component === 'backup') {
  3967. if ($filearea === 'course' and $context->contextlevel == CONTEXT_COURSE) {
  3968. require_login($course);
  3969. require_capability('moodle/backup:downloadfile', $context);
  3970. $filename = array_pop($args);
  3971. $filepath = $args ? '/'.implode('/', $args).'/' : '/';
  3972. if (!$file = $fs->get_file($context->id, 'backup', 'course', 0, $filepath, $filename) or $file->is_directory()) {
  3973. send_file_not_found();
  3974. }
  3975. \core\session\manager::write_close(); // Unlock session during file serving.
  3976. send_stored_file($file, 0, 0, $forcedownload, array('preview' => $preview));
  3977. } else if ($filearea === 'section' and $context->contextlevel == CONTEXT_COURSE) {
  3978. require_login($course);
  3979. require_capability('moodle/backup:downloadfile', $context);
  3980. $sectionid = (int)array_shift($args);
  3981. $filename = array_pop($args);
  3982. $filepath = $args ? '/'.implode('/', $args).'/' : '/';
  3983. if (!$file = $fs->get_file($context->id, 'backup', 'section', $sectionid, $filepath, $filename) or $file->is_directory()) {
  3984. send_file_not_found();
  3985. }
  3986. \core\session\manager::write_close();
  3987. send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
  3988. } else if ($filearea === 'activity' and $context->contextlevel == CONTEXT_MODULE) {
  3989. require_login($course, false, $cm);
  3990. require_capability('moodle/backup:downloadfile', $context);
  3991. $filename = array_pop($args);
  3992. $filepath = $args ? '/'.implode('/', $args).'/' : '/';
  3993. if (!$file = $fs->get_file($context->id, 'backup', 'activity', 0, $filepath, $filename) or $file->is_directory()) {
  3994. send_file_not_found();
  3995. }
  3996. \core\session\manager::write_close();
  3997. send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
  3998. } else if ($filearea === 'automated' and $context->contextlevel == CONTEXT_COURSE) {
  3999. // Backup files that were generated by the automated backup systems.
  4000. require_login($course);
  4001. require_capability('moodle/site:config', $context);
  4002. $filename = array_pop($args);
  4003. $filepath = $args ? '/'.implode('/', $args).'/' : '/';
  4004. if (!$file = $fs->get_file($context->id, 'backup', 'automated', 0, $filepath, $filename) or $file->is_directory()) {
  4005. send_file_not_found();
  4006. }
  4007. \core\session\manager::write_close(); // Unlock session during file serving.
  4008. send_stored_file($file, 0, 0, $forcedownload, array('preview' => $preview));
  4009. } else {
  4010. send_file_not_found();
  4011. }
  4012. // ========================================================================================================================
  4013. } else if ($component === 'question') {
  4014. require_once($CFG->libdir . '/questionlib.php');
  4015. question_pluginfile($course, $context, 'question', $filearea, $args, $forcedownload);
  4016. send_file_not_found();
  4017. // ========================================================================================================================
  4018. } else if ($component === 'grading') {
  4019. if ($filearea === 'description') {
  4020. // files embedded into the form definition description
  4021. if ($context->contextlevel == CONTEXT_SYSTEM) {
  4022. require_login();
  4023. } else if ($context->contextlevel >= CONTEXT_COURSE) {
  4024. require_login($course, false, $cm);
  4025. } else {
  4026. send_file_not_found();
  4027. }
  4028. $formid = (int)array_shift($args);
  4029. $sql = "SELECT ga.id
  4030. FROM {grading_areas} ga
  4031. JOIN {grading_definitions} gd ON (gd.areaid = ga.id)
  4032. WHERE gd.id = ? AND ga.contextid = ?";
  4033. $areaid = $DB->get_field_sql($sql, array($formid, $context->id), IGNORE_MISSING);
  4034. if (!$areaid) {
  4035. send_file_not_found();
  4036. }
  4037. $fullpath = "/$context->id/$component/$filearea/$formid/".implode('/', $args);
  4038. if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
  4039. send_file_not_found();
  4040. }
  4041. \core\session\manager::write_close(); // Unlock session during file serving.
  4042. send_stored_file($file, 60*60, 0, $forcedownload, array('preview' => $preview));
  4043. }
  4044. // ========================================================================================================================
  4045. } else if (strpos($component, 'mod_') === 0) {
  4046. $modname = substr($component, 4);
  4047. if (!file_exists("$CFG->dirroot/mod/$modname/lib.php")) {
  4048. send_file_not_found();
  4049. }
  4050. require_once("$CFG->dirroot/mod/$modname/lib.php");
  4051. if ($context->contextlevel == CONTEXT_MODULE) {
  4052. if ($cm->modname !== $modname) {
  4053. // somebody tries to gain illegal access, cm type must match the component!
  4054. send_file_not_found();
  4055. }
  4056. }
  4057. if ($filearea === 'intro') {
  4058. if (!plugin_supports('mod', $modname, FEATURE_MOD_INTRO, true)) {
  4059. send_file_not_found();
  4060. }
  4061. require_course_login($course, true, $cm);
  4062. // all users may access it
  4063. $filename = array_pop($args);
  4064. $filepath = $args ? '/'.implode('/', $args).'/' : '/';
  4065. if (!$file = $fs->get_file($context->id, 'mod_'.$modname, 'intro', 0, $filepath, $filename) or $file->is_directory()) {
  4066. send_file_not_found();
  4067. }
  4068. // finally send the file
  4069. send_stored_file($file, null, 0, false, array('preview' => $preview));
  4070. }
  4071. $filefunction = $component.'_pluginfile';
  4072. $filefunctionold = $modname.'_pluginfile';
  4073. if (function_exists($filefunction)) {
  4074. // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
  4075. $filefunction($course, $cm, $context, $filearea, $args, $forcedownload, array('preview' => $preview));
  4076. } else if (function_exists($filefunctionold)) {
  4077. // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
  4078. $filefunctionold($course, $cm, $context, $filearea, $args, $forcedownload, array('preview' => $preview));
  4079. }
  4080. send_file_not_found();
  4081. // ========================================================================================================================
  4082. } else if (strpos($component, 'block_') === 0) {
  4083. $blockname = substr($component, 6);
  4084. // note: no more class methods in blocks please, that is ....
  4085. if (!file_exists("$CFG->dirroot/blocks/$blockname/lib.php")) {
  4086. send_file_not_found();
  4087. }
  4088. require_once("$CFG->dirroot/blocks/$blockname/lib.php");
  4089. if ($context->contextlevel == CONTEXT_BLOCK) {
  4090. $birecord = $DB->get_record('block_instances', array('id'=>$context->instanceid), '*',MUST_EXIST);
  4091. if ($birecord->blockname !== $blockname) {
  4092. // somebody tries to gain illegal access, cm type must match the component!
  4093. send_file_not_found();
  4094. }
  4095. $bprecord = $DB->get_record('block_positions', array('contextid' => $context->id, 'blockinstanceid' => $context->instanceid));
  4096. // User can't access file, if block is hidden or doesn't have block:view capability
  4097. if (($bprecord && !$bprecord->visible) || !has_capability('moodle/block:view', $context)) {
  4098. send_file_not_found();
  4099. }
  4100. } else {
  4101. $birecord = null;
  4102. }
  4103. $filefunction = $component.'_pluginfile';
  4104. if (function_exists($filefunction)) {
  4105. // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
  4106. $filefunction($course, $birecord, $context, $filearea, $args, $forcedownload, array('preview' => $preview));
  4107. }
  4108. send_file_not_found();
  4109. // ========================================================================================================================
  4110. } else if (strpos($component, '_') === false) {
  4111. // all core subsystems have to be specified above, no more guessing here!
  4112. send_file_not_found();
  4113. } else {
  4114. // try to serve general plugin file in arbitrary context
  4115. $dir = core_component::get_component_directory($component);
  4116. if (!file_exists("$dir/lib.php")) {
  4117. send_file_not_found();
  4118. }
  4119. include_once("$dir/lib.php");
  4120. $filefunction = $component.'_pluginfile';
  4121. if (function_exists($filefunction)) {
  4122. // if the function exists, it must send the file and terminate. Whatever it returns leads to "not found"
  4123. $filefunction($course, $cm, $context, $filearea, $args, $forcedownload, array('preview' => $preview));
  4124. }
  4125. send_file_not_found();
  4126. }
  4127. }