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