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