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