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