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