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