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