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