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