do not send stored file if nothing to send given
[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
c87c428e 1477/**
1478 * Handles the sending of temporary file to user, download is forced.
34ff25a6 1479 * File is deleted after abort or successful sending.
ba21c9d4 1480 *
1481 * @global object
c87c428e 1482 * @param string $path path to file, preferably from moodledata/temp/something; or content of file itself
1483 * @param string $filename proposed file name when saving file
1484 * @param bool $path is content of file
45c0d224 1485 * @return does not return, script terminated
c87c428e 1486 */
45c0d224 1487function send_temp_file($path, $filename, $pathisstring=false) {
c87c428e 1488 global $CFG;
1489
1490 // close session - not needed anymore
56949c17 1491 @session_get_instance()->write_close();
c87c428e 1492
1493 if (!$pathisstring) {
1494 if (!file_exists($path)) {
1495 header('HTTP/1.0 404 not found');
45c0d224 1496 print_error('filenotfound', 'error', $CFG->wwwroot.'/');
c87c428e 1497 }
1498 // executed after normal finish or abort
1499 @register_shutdown_function('send_temp_file_finished', $path);
1500 }
1501
34ff25a6 1502 //IE compatibility HACK!
c87c428e 1503 if (ini_get('zlib.output_compression')) {
1504 ini_set('zlib.output_compression', 'Off');
1505 }
1506
1507 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
1508 if (check_browser_version('MSIE')) {
1509 $filename = urlencode($filename);
1510 }
1511
1512 $filesize = $pathisstring ? strlen($path) : filesize($path);
1513
1514 @header('Content-Disposition: attachment; filename='.$filename);
1515 @header('Content-Length: '.$filesize);
1516 if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
1517 @header('Cache-Control: max-age=10');
1518 @header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
1519 @header('Pragma: ');
1520 } else { //normal http - prevent caching at all cost
1521 @header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
1522 @header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
1523 @header('Pragma: no-cache');
1524 }
1525 @header('Accept-Ranges: none'); // Do not allow byteserving
1526
1527 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
1528 if ($pathisstring) {
1529 echo $path;
1530 } else {
29e3d7e2 1531 @readfile($path);
c87c428e 1532 }
1533
1534 die; //no more chars to output
1535}
1536
1537/**
34ff25a6 1538 * Internal callback function used by send_temp_file()
c87c428e 1539 */
1540function send_temp_file_finished($path) {
1541 if (file_exists($path)) {
1542 @unlink($path);
1543 }
1544}
1545
76ca1ff1 1546/**
1547 * Handles the sending of file data to the user's browser, including support for
1548 * byteranges etc.
ba21c9d4 1549 *
1550 * @global object
1551 * @global object
1552 * @global object
ba75ad94 1553 * @param string $path Path of file on disk (including real filename), or actual content of file as string
1554 * @param string $filename Filename to send
1555 * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
1556 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
1557 * @param bool $pathisstring If true (default false), $path is the content to send and not the pathname
1558 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
1559 * @param string $mimetype Include to specify the MIME type; leave blank to have it guess the type from $filename
b379f7d9 1560 * @param bool $dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
1561 * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
29e3d7e2 1562 * you must detect this case when control is returned using connection_aborted. Please not that session is closed
1563 * and should not be reopened.
1564 * @return no return or void, script execution stopped unless $dontdie is true
b9709b76 1565 */
b379f7d9 1566function send_file($path, $filename, $lifetime = 'default' , $filter=0, $pathisstring=false, $forcedownload=false, $mimetype='', $dontdie=false) {
6800d78e 1567 global $CFG, $COURSE, $SESSION;
50f95991 1568
b379f7d9 1569 if ($dontdie) {
15325f55 1570 ignore_user_abort(true);
b379f7d9 1571 }
1572
c8a5c6a4 1573 // MDL-11789, apply $CFG->filelifetime here
1574 if ($lifetime === 'default') {
1575 if (!empty($CFG->filelifetime)) {
0cde3ede 1576 $lifetime = $CFG->filelifetime;
c8a5c6a4 1577 } else {
0cde3ede 1578 $lifetime = 86400;
c8a5c6a4 1579 }
1580 }
1581
56949c17 1582 session_get_instance()->write_close(); // unlock session during fileserving
172dd12c 1583
ba4e0b05 1584 // Use given MIME type if specified, otherwise guess it using mimeinfo.
1585 // IE, Konqueror and Opera open html file directly in browser from web even when directed to save it to disk :-O
1586 // only Firefox saves all files locally before opening when content-disposition: attachment stated
1587 $isFF = check_browser_version('Firefox', '1.5'); // only FF > 1.5 properly tested
76ca1ff1 1588 $mimetype = ($forcedownload and !$isFF) ? 'application/x-forcedownload' :
ba4e0b05 1589 ($mimetype ? $mimetype : mimeinfo('type', $filename));
b5bbeaf0 1590
f1e0649c 1591 $lastmodified = $pathisstring ? time() : filemtime($path);
1592 $filesize = $pathisstring ? strlen($path) : filesize($path);
1593
36bddcf5 1594/* - MDL-13949
ee7f231d 1595 //Adobe Acrobat Reader XSS prevention
1596 if ($mimetype=='application/pdf' or mimeinfo('type', $filename)=='application/pdf') {
1597 //please note that it prevents opening of pdfs in browser when http referer disabled
1598 //or file linked from another site; browser caching of pdfs is now disabled too
c57d8874 1599 if (!empty($_SERVER['HTTP_RANGE'])) {
1600 //already byteserving
76ca1ff1 1601 $lifetime = 1; // >0 needed for byteserving
c57d8874 1602 } else if (empty($_SERVER['HTTP_REFERER']) or strpos($_SERVER['HTTP_REFERER'], $CFG->wwwroot)!==0) {
ee7f231d 1603 $mimetype = 'application/x-forcedownload';
1604 $forcedownload = true;
1605 $lifetime = 0;
1606 } else {
76ca1ff1 1607 $lifetime = 1; // >0 needed for byteserving
ee7f231d 1608 }
b8806ccc 1609 }
36bddcf5 1610*/
f3f7610c 1611
69faecce 1612 //IE compatibiltiy HACK!
4c8c65ec 1613 if (ini_get('zlib.output_compression')) {
69faecce 1614 ini_set('zlib.output_compression', 'Off');
1615 }
1616
4c8c65ec 1617 //try to disable automatic sid rewrite in cookieless mode
8914cb82 1618 @ini_set("session.use_trans_sid", "false");
4c8c65ec 1619
1620 //do not put '@' before the next header to detect incorrect moodle configurations,
1621 //error should be better than "weird" empty lines for admins/users
1622 //TODO: should we remove all those @ before the header()? Are all of the values supported on all servers?
1623 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
1624
4f047de2 1625 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
1626 if (check_browser_version('MSIE')) {
4638009b 1627 $filename = rawurlencode($filename);
4f047de2 1628 }
1629
4c8c65ec 1630 if ($forcedownload) {
4638009b 1631 @header('Content-Disposition: attachment; filename="'.$filename.'"');
4c8c65ec 1632 } else {
4638009b 1633 @header('Content-Disposition: inline; filename="'.$filename.'"');
4c8c65ec 1634 }
1635
f1e0649c 1636 if ($lifetime > 0) {
4c8c65ec 1637 @header('Cache-Control: max-age='.$lifetime);
1638 @header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
f1e0649c 1639 @header('Pragma: ');
4c8c65ec 1640
1641 if (empty($CFG->disablebyteserving) && !$pathisstring && $mimetype != 'text/plain' && $mimetype != 'text/html') {
1642
1643 @header('Accept-Ranges: bytes');
1644
1645 if (!empty($_SERVER['HTTP_RANGE']) && strpos($_SERVER['HTTP_RANGE'],'bytes=') !== FALSE) {
1646 // byteserving stuff - for acrobat reader and download accelerators
1647 // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
1648 // inspired by: http://www.coneural.org/florian/papers/04_byteserving.php
1649 $ranges = false;
1650 if (preg_match_all('/(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER)) {
1651 foreach ($ranges as $key=>$value) {
1652 if ($ranges[$key][1] == '') {
1653 //suffix case
1654 $ranges[$key][1] = $filesize - $ranges[$key][2];
1655 $ranges[$key][2] = $filesize - 1;
1656 } else if ($ranges[$key][2] == '' || $ranges[$key][2] > $filesize - 1) {
1657 //fix range length
1658 $ranges[$key][2] = $filesize - 1;
1659 }
1660 if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
1661 //invalid byte-range ==> ignore header
1662 $ranges = false;
1663 break;
1664 }
1665 //prepare multipart header
1666 $ranges[$key][0] = "\r\n--".BYTESERVING_BOUNDARY."\r\nContent-Type: $mimetype\r\n";
1667 $ranges[$key][0] .= "Content-Range: bytes {$ranges[$key][1]}-{$ranges[$key][2]}/$filesize\r\n\r\n";
1668 }
1669 } else {
1670 $ranges = false;
1671 }
1672 if ($ranges) {
172dd12c 1673 $handle = fopen($filename, 'rb');
1674 byteserving_send_file($handle, $mimetype, $ranges, $filesize);
4c8c65ec 1675 }
1676 }
1677 } else {
1678 /// Do not byteserve (disabled, strings, text and html files).
1679 @header('Accept-Ranges: none');
1680 }
1681 } else { // Do not cache files in proxies and browsers
85e00626 1682 if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
1683 @header('Cache-Control: max-age=10');
4c8c65ec 1684 @header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
85e00626 1685 @header('Pragma: ');
1686 } else { //normal http - prevent caching at all cost
1687 @header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
4c8c65ec 1688 @header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
85e00626 1689 @header('Pragma: no-cache');
1690 }
4c8c65ec 1691 @header('Accept-Ranges: none'); // Do not allow byteserving when caching disabled
69faecce 1692 }
f1e0649c 1693
b9709b76 1694 if (empty($filter)) {
0a2092a3 1695 if ($mimetype == 'text/html' && !empty($CFG->usesid)) {
4c8c65ec 1696 //cookieless mode - rewrite links
1697 @header('Content-Type: text/html');
1698 $path = $pathisstring ? $path : implode('', file($path));
0ad6b20c 1699 $path = sid_ob_rewrite($path);
4c8c65ec 1700 $filesize = strlen($path);
1701 $pathisstring = true;
1702 } else if ($mimetype == 'text/plain') {
810944af 1703 @header('Content-Type: Text/plain; charset=utf-8'); //add encoding
f1e0649c 1704 } else {
4c8c65ec 1705 @header('Content-Type: '.$mimetype);
f1e0649c 1706 }
4c8c65ec 1707 @header('Content-Length: '.$filesize);
1708 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
f1e0649c 1709 if ($pathisstring) {
1710 echo $path;
4c8c65ec 1711 } else {
29e3d7e2 1712 @readfile($path);
f1e0649c 1713 }
1714 } else { // Try to put the file through filters
f1e0649c 1715 if ($mimetype == 'text/html') {
365a5941 1716 $options = new stdClass();
f1e0649c 1717 $options->noclean = true;
a17c57b5 1718 $options->nocache = true; // temporary workaround for MDL-5136
f1e0649c 1719 $text = $pathisstring ? $path : implode('', file($path));
76ca1ff1 1720
3ace5ee4 1721 $text = file_modify_html_header($text);
60f9e36e 1722 $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
0a2092a3 1723 if (!empty($CFG->usesid)) {
4c8c65ec 1724 //cookieless mode - rewrite links
0ad6b20c 1725 $output = sid_ob_rewrite($output);
4c8c65ec 1726 }
f1e0649c 1727
4c8c65ec 1728 @header('Content-Length: '.strlen($output));
1729 @header('Content-Type: text/html');
1730 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
f1e0649c 1731 echo $output;
b9709b76 1732 // only filter text if filter all files is selected
1733 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
365a5941 1734 $options = new stdClass();
f1e0649c 1735 $options->newlines = false;
1736 $options->noclean = true;
1737 $text = htmlentities($pathisstring ? $path : implode('', file($path)));
60f9e36e 1738 $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
0a2092a3 1739 if (!empty($CFG->usesid)) {
4c8c65ec 1740 //cookieless mode - rewrite links
0ad6b20c 1741 $output = sid_ob_rewrite($output);
4c8c65ec 1742 }
f1e0649c 1743
4c8c65ec 1744 @header('Content-Length: '.strlen($output));
810944af 1745 @header('Content-Type: text/html; charset=utf-8'); //add encoding
4c8c65ec 1746 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
f1e0649c 1747 echo $output;
1748 } else { // Just send it out raw
4c8c65ec 1749 @header('Content-Length: '.$filesize);
1750 @header('Content-Type: '.$mimetype);
1751 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
f1e0649c 1752 if ($pathisstring) {
1753 echo $path;
1754 }else {
29e3d7e2 1755 @readfile($path);
f1e0649c 1756 }
1757 }
1758 }
b379f7d9 1759 if ($dontdie) {
1760 return;
1761 }
f1e0649c 1762 die; //no more chars to output!!!
1763}
1764
172dd12c 1765/**
1766 * Handles the sending of file data to the user's browser, including support for
1767 * byteranges etc.
ba21c9d4 1768 *
1769 * @global object
1770 * @global object
1771 * @global object
172dd12c 1772 * @param object $stored_file local file object
1773 * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
1774 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
1775 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
1776 * @param string $filename Override filename
b379f7d9 1777 * @param bool $dontdie - return control to caller afterwards. this is not recommended and only used for cleanup tasks.
1778 * if this is passed as true, ignore_user_abort is called. if you don't want your processing to continue on cancel,
29e3d7e2 1779 * you must detect this case when control is returned using connection_aborted. Please not that session is closed
1780 * and should not be reopened.
ba21c9d4 1781 * @return void no return or void, script execution stopped unless $dontdie is true
172dd12c 1782 */
b379f7d9 1783function send_stored_file($stored_file, $lifetime=86400 , $filter=0, $forcedownload=false, $filename=null, $dontdie=false) {
172dd12c 1784 global $CFG, $COURSE, $SESSION;
1785
2f657978
PS
1786 if (!$stored_file or $stored_file->is_directory()) {
1787 // nothing to serve
1788 if ($dontdie) {
1789 return;
1790 }
1791 die;
1792 }
1793
b379f7d9 1794 if ($dontdie) {
15325f55 1795 ignore_user_abort(true);
b379f7d9 1796 }
1797
56949c17 1798 session_get_instance()->write_close(); // unlock session during fileserving
172dd12c 1799
1800 // Use given MIME type if specified, otherwise guess it using mimeinfo.
1801 // IE, Konqueror and Opera open html file directly in browser from web even when directed to save it to disk :-O
1802 // only Firefox saves all files locally before opening when content-disposition: attachment stated
1803 $filename = is_null($filename) ? $stored_file->get_filename() : $filename;
1804 $isFF = check_browser_version('Firefox', '1.5'); // only FF > 1.5 properly tested
1805 $mimetype = ($forcedownload and !$isFF) ? 'application/x-forcedownload' :
1806 ($stored_file->get_mimetype() ? $stored_file->get_mimetype() : mimeinfo('type', $filename));
b5bbeaf0 1807
172dd12c 1808 $lastmodified = $stored_file->get_timemodified();
1809 $filesize = $stored_file->get_filesize();
1810
1811 //IE compatibiltiy HACK!
1812 if (ini_get('zlib.output_compression')) {
1813 ini_set('zlib.output_compression', 'Off');
1814 }
1815
1816 //try to disable automatic sid rewrite in cookieless mode
1817 @ini_set("session.use_trans_sid", "false");
1818
1819 //do not put '@' before the next header to detect incorrect moodle configurations,
1820 //error should be better than "weird" empty lines for admins/users
1821 //TODO: should we remove all those @ before the header()? Are all of the values supported on all servers?
1822 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
1823
1824 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
1825 if (check_browser_version('MSIE')) {
1826 $filename = rawurlencode($filename);
1827 }
1828
1829 if ($forcedownload) {
1830 @header('Content-Disposition: attachment; filename="'.$filename.'"');
1831 } else {
1832 @header('Content-Disposition: inline; filename="'.$filename.'"');
1833 }
1834
1835 if ($lifetime > 0) {
1836 @header('Cache-Control: max-age='.$lifetime);
1837 @header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
1838 @header('Pragma: ');
1839
1840 if (empty($CFG->disablebyteserving) && $mimetype != 'text/plain' && $mimetype != 'text/html') {
1841
1842 @header('Accept-Ranges: bytes');
1843
1844 if (!empty($_SERVER['HTTP_RANGE']) && strpos($_SERVER['HTTP_RANGE'],'bytes=') !== FALSE) {
1845 // byteserving stuff - for acrobat reader and download accelerators
1846 // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
1847 // inspired by: http://www.coneural.org/florian/papers/04_byteserving.php
1848 $ranges = false;
1849 if (preg_match_all('/(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER)) {
1850 foreach ($ranges as $key=>$value) {
1851 if ($ranges[$key][1] == '') {
1852 //suffix case
1853 $ranges[$key][1] = $filesize - $ranges[$key][2];
1854 $ranges[$key][2] = $filesize - 1;
1855 } else if ($ranges[$key][2] == '' || $ranges[$key][2] > $filesize - 1) {
1856 //fix range length
1857 $ranges[$key][2] = $filesize - 1;
1858 }
1859 if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
1860 //invalid byte-range ==> ignore header
1861 $ranges = false;
1862 break;
1863 }
1864 //prepare multipart header
1865 $ranges[$key][0] = "\r\n--".BYTESERVING_BOUNDARY."\r\nContent-Type: $mimetype\r\n";
1866 $ranges[$key][0] .= "Content-Range: bytes {$ranges[$key][1]}-{$ranges[$key][2]}/$filesize\r\n\r\n";
1867 }
1868 } else {
1869 $ranges = false;
1870 }
1871 if ($ranges) {
1872 byteserving_send_file($stored_file->get_content_file_handle(), $mimetype, $ranges, $filesize);
1873 }
1874 }
1875 } else {
1876 /// Do not byteserve (disabled, strings, text and html files).
1877 @header('Accept-Ranges: none');
1878 }
1879 } else { // Do not cache files in proxies and browsers
1880 if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
1881 @header('Cache-Control: max-age=10');
1882 @header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
1883 @header('Pragma: ');
1884 } else { //normal http - prevent caching at all cost
1885 @header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
1886 @header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
1887 @header('Pragma: no-cache');
1888 }
1889 @header('Accept-Ranges: none'); // Do not allow byteserving when caching disabled
1890 }
1891
1892 if (empty($filter)) {
1893 $filtered = false;
0a2092a3 1894 if ($mimetype == 'text/html' && !empty($CFG->usesid)) {
172dd12c 1895 //cookieless mode - rewrite links
1896 @header('Content-Type: text/html');
1897 $text = $stored_file->get_content();
0ad6b20c 1898 $text = sid_ob_rewrite($text);
172dd12c 1899 $filesize = strlen($text);
1900 $filtered = true;
1901 } else if ($mimetype == 'text/plain') {
1902 @header('Content-Type: Text/plain; charset=utf-8'); //add encoding
1903 } else {
1904 @header('Content-Type: '.$mimetype);
1905 }
1906 @header('Content-Length: '.$filesize);
1907 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
1908 if ($filtered) {
1909 echo $text;
1910 } else {
1911 $stored_file->readfile();
1912 }
1913
1914 } else { // Try to put the file through filters
1915 if ($mimetype == 'text/html') {
365a5941 1916 $options = new stdClass();
172dd12c 1917 $options->noclean = true;
1918 $options->nocache = true; // temporary workaround for MDL-5136
1919 $text = $stored_file->get_content();
1920 $text = file_modify_html_header($text);
1921 $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
0a2092a3 1922 if (!empty($CFG->usesid)) {
172dd12c 1923 //cookieless mode - rewrite links
0ad6b20c 1924 $output = sid_ob_rewrite($output);
172dd12c 1925 }
1926
1927 @header('Content-Length: '.strlen($output));
1928 @header('Content-Type: text/html');
1929 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
1930 echo $output;
1931 // only filter text if filter all files is selected
1932 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
365a5941 1933 $options = new stdClass();
172dd12c 1934 $options->newlines = false;
1935 $options->noclean = true;
1936 $text = $stored_file->get_content();
1937 $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
0a2092a3 1938 if (!empty($CFG->usesid)) {
172dd12c 1939 //cookieless mode - rewrite links
0ad6b20c 1940 $output = sid_ob_rewrite($output);
172dd12c 1941 }
1942
1943 @header('Content-Length: '.strlen($output));
1944 @header('Content-Type: text/html; charset=utf-8'); //add encoding
1945 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
1946 echo $output;
1947 } else { // Just send it out raw
1948 @header('Content-Length: '.$filesize);
1949 @header('Content-Type: '.$mimetype);
1950 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
1951 $stored_file->readfile();
1952 }
1953 }
b379f7d9 1954 if ($dontdie) {
1955 return;
1956 }
172dd12c 1957 die; //no more chars to output!!!
1958}
1959
ba21c9d4 1960/**
34ff25a6 1961 * Retrieves an array of records from a CSV file and places
ba21c9d4 1962 * them into a given table structure
1963 *
1964 * @global object
1965 * @global object
1966 * @param string $file The path to a CSV file
1967 * @param string $table The table to retrieve columns from
1968 * @return bool|array Returns an array of CSV records or false
1969 */
a43b5308 1970function get_records_csv($file, $table) {
f33e1ed4 1971 global $CFG, $DB;
599f38f9 1972
f33e1ed4 1973 if (!$metacolumns = $DB->get_columns($table)) {
599f38f9 1974 return false;
1975 }
1976
a77b98eb 1977 if(!($handle = @fopen($file, 'r'))) {
5a2a5331 1978 print_error('get_records_csv failed to open '.$file);
599f38f9 1979 }
1980
1981 $fieldnames = fgetcsv($handle, 4096);
1982 if(empty($fieldnames)) {
1983 fclose($handle);
1984 return false;
1985 }
1986
1987 $columns = array();
1988
1989 foreach($metacolumns as $metacolumn) {
1990 $ord = array_search($metacolumn->name, $fieldnames);
1991 if(is_int($ord)) {
1992 $columns[$metacolumn->name] = $ord;
1993 }
1994 }
1995
1996 $rows = array();
1997
1998 while (($data = fgetcsv($handle, 4096)) !== false) {
1999 $item = new stdClass;
2000 foreach($columns as $name => $ord) {
2001 $item->$name = $data[$ord];
2002 }
2003 $rows[] = $item;
2004 }
2005
2006 fclose($handle);
2007 return $rows;
2008}
2009
ba21c9d4 2010/**
117bd748 2011 *
ba21c9d4 2012 * @global object
2013 * @global object
2014 * @param string $file The file to put the CSV content into
2015 * @param array $records An array of records to write to a CSV file
2016 * @param string $table The table to get columns from
2017 * @return bool success
2018 */
a77b98eb 2019function put_records_csv($file, $records, $table = NULL) {
f33e1ed4 2020 global $CFG, $DB;
a77b98eb 2021
a1e93da2 2022 if (empty($records)) {
a77b98eb 2023 return true;
2024 }
2025
2026 $metacolumns = NULL;
f33e1ed4 2027 if ($table !== NULL && !$metacolumns = $DB->get_columns($table)) {
a77b98eb 2028 return false;
2029 }
2030
a1e93da2 2031 echo "x";
2032
a77b98eb 2033 if(!($fp = @fopen($CFG->dataroot.'/temp/'.$file, 'w'))) {
5a2a5331 2034 print_error('put_records_csv failed to open '.$file);
a77b98eb 2035 }
2036
a43b5308 2037 $proto = reset($records);
2038 if(is_object($proto)) {
2039 $fields_records = array_keys(get_object_vars($proto));
2040 }
2041 else if(is_array($proto)) {
2042 $fields_records = array_keys($proto);
2043 }
2044 else {
2045 return false;
2046 }
a1e93da2 2047 echo "x";
a77b98eb 2048
2049 if(!empty($metacolumns)) {
2050 $fields_table = array_map(create_function('$a', 'return $a->name;'), $metacolumns);
2051 $fields = array_intersect($fields_records, $fields_table);
2052 }
2053 else {
2054 $fields = $fields_records;
2055 }
2056
2057 fwrite($fp, implode(',', $fields));
2058 fwrite($fp, "\r\n");
2059
2060 foreach($records as $record) {
a43b5308 2061 $array = (array)$record;
a77b98eb 2062 $values = array();
2063 foreach($fields as $field) {
a43b5308 2064 if(strpos($array[$field], ',')) {
2065 $values[] = '"'.str_replace('"', '\"', $array[$field]).'"';
a77b98eb 2066 }
2067 else {
a43b5308 2068 $values[] = $array[$field];
a77b98eb 2069 }
2070 }
2071 fwrite($fp, implode(',', $values)."\r\n");
2072 }
2073
2074 fclose($fp);
2075 return true;
2076}
2077
f401cc97 2078
34763a79 2079/**
76ca1ff1 2080 * Recursively delete the file or folder with path $location. That is,
34763a79 2081 * if it is a file delete it. If it is a folder, delete all its content
db3a0b34 2082 * then delete it. If $location does not exist to start, that is not
2083 * considered an error.
76ca1ff1 2084 *
eab8ed9f 2085 * @param string $location the path to remove.
ba21c9d4 2086 * @return bool
34763a79 2087 */
4c8c65ec 2088function fulldelete($location) {
1e06adb4
PS
2089 if (empty($location)) {
2090 // extra safety against wrong param
2091 return false;
2092 }
f401cc97 2093 if (is_dir($location)) {
2094 $currdir = opendir($location);
2095 while (false !== ($file = readdir($currdir))) {
2096 if ($file <> ".." && $file <> ".") {
2097 $fullfile = $location."/".$file;
4c8c65ec 2098 if (is_dir($fullfile)) {
f401cc97 2099 if (!fulldelete($fullfile)) {
2100 return false;
2101 }
2102 } else {
2103 if (!unlink($fullfile)) {
2104 return false;
2105 }
4c8c65ec 2106 }
f401cc97 2107 }
4c8c65ec 2108 }
f401cc97 2109 closedir($currdir);
2110 if (! rmdir($location)) {
2111 return false;
2112 }
2113
34763a79 2114 } else if (file_exists($location)) {
f401cc97 2115 if (!unlink($location)) {
2116 return false;
2117 }
2118 }
2119 return true;
2120}
2121
4c8c65ec 2122/**
2123 * Send requested byterange of file.
ba21c9d4 2124 *
2125 * @param object $handle A file handle
2126 * @param string $mimetype The mimetype for the output
2127 * @param array $ranges An array of ranges to send
2128 * @param string $filesize The size of the content if only one range is used
4c8c65ec 2129 */
172dd12c 2130function byteserving_send_file($handle, $mimetype, $ranges, $filesize) {
4c8c65ec 2131 $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
4c8c65ec 2132 if ($handle === false) {
2133 die;
2134 }
2135 if (count($ranges) == 1) { //only one range requested
2136 $length = $ranges[0][2] - $ranges[0][1] + 1;
2137 @header('HTTP/1.1 206 Partial content');
2138 @header('Content-Length: '.$length);
172dd12c 2139 @header('Content-Range: bytes '.$ranges[0][1].'-'.$ranges[0][2].'/'.$filesize);
4c8c65ec 2140 @header('Content-Type: '.$mimetype);
2141 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
2142 $buffer = '';
2143 fseek($handle, $ranges[0][1]);
2144 while (!feof($handle) && $length > 0) {
68913aec 2145 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
4c8c65ec 2146 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
2147 echo $buffer;
2148 flush();
2149 $length -= strlen($buffer);
2150 }
2151 fclose($handle);
2152 die;
2153 } else { // multiple ranges requested - not tested much
2154 $totallength = 0;
2155 foreach($ranges as $range) {
aba588a7 2156 $totallength += strlen($range[0]) + $range[2] - $range[1] + 1;
4c8c65ec 2157 }
aba588a7 2158 $totallength += strlen("\r\n--".BYTESERVING_BOUNDARY."--\r\n");
4c8c65ec 2159 @header('HTTP/1.1 206 Partial content');
2160 @header('Content-Length: '.$totallength);
2161 @header('Content-Type: multipart/byteranges; boundary='.BYTESERVING_BOUNDARY);
2162 //TODO: check if "multipart/x-byteranges" is more compatible with current readers/browsers/servers
2163 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
2164 foreach($ranges as $range) {
2165 $length = $range[2] - $range[1] + 1;
2166 echo $range[0];
2167 $buffer = '';
2168 fseek($handle, $range[1]);
2169 while (!feof($handle) && $length > 0) {
68913aec 2170 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
4c8c65ec 2171 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
2172 echo $buffer;
2173 flush();
2174 $length -= strlen($buffer);
2175 }
2176 }
2177 echo "\r\n--".BYTESERVING_BOUNDARY."--\r\n";
2178 fclose($handle);
2179 die;
2180 }
2181}
f401cc97 2182
3ace5ee4 2183/**
2184 * add includes (js and css) into uploaded files
2185 * before returning them, useful for themes and utf.js includes
ba21c9d4 2186 *
2187 * @global object
2188 * @param string $text text to search and replace
2189 * @return string text with added head includes
3ace5ee4 2190 */
2191function file_modify_html_header($text) {
2192 // first look for <head> tag
2193 global $CFG;
76ca1ff1 2194
3ace5ee4 2195 $stylesheetshtml = '';
78946b9b
PS
2196/* foreach ($CFG->stylesheets as $stylesheet) {
2197 //TODO: MDL-21120
3ace5ee4 2198 $stylesheetshtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
78946b9b 2199 }*/
76ca1ff1 2200
5b8fa09b 2201 $ufo = '';
2202 if (filter_is_enabled('filter/mediaplugin')) {
76ca1ff1 2203 // this script is needed by most media filter plugins.
f2ab0d06 2204 $attributes = array('type'=>'text/javascript', 'src'=>$CFG->httpswwwroot . '/lib/ufo.js');
26acc814 2205 $ufo = html_writer::tag('script', '', $attributes) . "\n";
3ace5ee4 2206 }
76ca1ff1 2207
3ace5ee4 2208 preg_match('/\<head\>|\<HEAD\>/', $text, $matches);
2209 if ($matches) {
2210 $replacement = '<head>'.$ufo.$stylesheetshtml;
2211 $text = preg_replace('/\<head\>|\<HEAD\>/', $replacement, $text, 1);
76ca1ff1 2212 return $text;
3ace5ee4 2213 }
76ca1ff1 2214
3ace5ee4 2215 // if not, look for <html> tag, and stick <head> right after
2216 preg_match('/\<html\>|\<HTML\>/', $text, $matches);
2217 if ($matches) {
2218 // replace <html> tag with <html><head>includes</head>
13534ef7 2219 $replacement = '<html>'."\n".'<head>'.$ufo.$stylesheetshtml.'</head>';
3ace5ee4 2220 $text = preg_replace('/\<html\>|\<HTML\>/', $replacement, $text, 1);
76ca1ff1 2221 return $text;
3ace5ee4 2222 }
76ca1ff1 2223
3ace5ee4 2224 // if not, look for <body> tag, and stick <head> before body
2225 preg_match('/\<body\>|\<BODY\>/', $text, $matches);
2226 if ($matches) {
13534ef7 2227 $replacement = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".'<body>';
3ace5ee4 2228 $text = preg_replace('/\<body\>|\<BODY\>/', $replacement, $text, 1);
76ca1ff1 2229 return $text;
2230 }
2231
3ace5ee4 2232 // if not, just stick a <head> tag at the beginning
2233 $text = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".$text;
2234 return $text;
2235}
2236
bb2c046d 2237/**
2238 * RESTful cURL class
2239 *
2240 * This is a wrapper class for curl, it is quite easy to use:
ba21c9d4 2241 * <code>
bb2c046d 2242 * $c = new curl;
2243 * // enable cache
2244 * $c = new curl(array('cache'=>true));
2245 * // enable cookie
2246 * $c = new curl(array('cookie'=>true));
2247 * // enable proxy
2248 * $c = new curl(array('proxy'=>true));
2249 *
2250 * // HTTP GET Method
2251 * $html = $c->get('http://example.com');
2252 * // HTTP POST Method
2253 * $html = $c->post('http://example.com/', array('q'=>'words', 'name'=>'moodle'));
2254 * // HTTP PUT Method
2255 * $html = $c->put('http://example.com/', array('file'=>'/var/www/test.txt');
ba21c9d4 2256 * </code>
bb2c046d 2257 *
d078f6d3
PS
2258 * @package core
2259 * @subpackage file
2260 * @author Dongsheng Cai <dongsheng@cvs.moodle.org>
2261 * @license http://www.gnu.org/copyleft/gpl.html GNU Public License
bb2c046d 2262 */
2263
2264class curl {
ba21c9d4 2265 /** @var bool */
bb2c046d 2266 public $cache = false;
2267 public $proxy = false;
ba21c9d4 2268 /** @var string */
bb2c046d 2269 public $version = '0.4 dev';
ba21c9d4 2270 /** @var array */
bb2c046d 2271 public $response = array();
2272 public $header = array();
ba21c9d4 2273 /** @var string */
bb2c046d 2274 public $info;
2275 public $error;
117bd748 2276
ba21c9d4 2277 /** @var array */
bb2c046d 2278 private $options;
ba21c9d4 2279 /** @var string */
bb2c046d 2280 private $proxy_host = '';
2281 private $proxy_auth = '';
2282 private $proxy_type = '';
ba21c9d4 2283 /** @var bool */
bb2c046d 2284 private $debug = false;
2285 private $cookie = false;
2286
ba21c9d4 2287 /**
2288 * @global object
2289 * @param array $options
2290 */
bb2c046d 2291 public function __construct($options = array()){
2292 global $CFG;
2293 if (!function_exists('curl_init')) {
2294 $this->error = 'cURL module must be enabled!';
2295 trigger_error($this->error, E_USER_ERROR);
2296 return false;
2297 }
2298 // the options of curl should be init here.
2299 $this->resetopt();
2300 if (!empty($options['debug'])) {
2301 $this->debug = true;
2302 }
2303 if(!empty($options['cookie'])) {
2304 if($options['cookie'] === true) {
2305 $this->cookie = $CFG->dataroot.'/curl_cookie.txt';
2306 } else {
2307 $this->cookie = $options['cookie'];
2308 }
2309 }
2310 if (!empty($options['cache'])) {
2311 if (class_exists('curl_cache')) {
5430f05b 2312 if (!empty($options['module_cache'])) {
2313 $this->cache = new curl_cache($options['module_cache']);
2314 } else {
2315 $this->cache = new curl_cache('misc');
2316 }
bb2c046d 2317 }
2318 }
d04ce87f 2319 if (!empty($CFG->proxyhost)) {
2320 if (empty($CFG->proxyport)) {
2321 $this->proxy_host = $CFG->proxyhost;
2322 } else {
2323 $this->proxy_host = $CFG->proxyhost.':'.$CFG->proxyport;
2324 }
2325 if (!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) {
2326 $this->proxy_auth = $CFG->proxyuser.':'.$CFG->proxypassword;
2327 $this->setopt(array(
2328 'proxyauth'=> CURLAUTH_BASIC | CURLAUTH_NTLM,
2329 'proxyuserpwd'=>$this->proxy_auth));
2330 }
2331 if (!empty($CFG->proxytype)) {
2332 if ($CFG->proxytype == 'SOCKS5') {
2333 $this->proxy_type = CURLPROXY_SOCKS5;
bb2c046d 2334 } else {
d04ce87f 2335 $this->proxy_type = CURLPROXY_HTTP;
f6d3e2c4 2336 $this->setopt(array('httpproxytunnel'=>false));
bb2c046d 2337 }
d04ce87f 2338 $this->setopt(array('proxytype'=>$this->proxy_type));
bb2c046d 2339 }
d04ce87f 2340 }
2341 if (!empty($this->proxy_host)) {
2342 $this->proxy = array('proxy'=>$this->proxy_host);
bb2c046d 2343 }
2344 }
ba21c9d4 2345 /**
2346 * Resets the CURL options that have already been set
2347 */
bb2c046d 2348 public function resetopt(){
2349 $this->options = array();
2350 $this->options['CURLOPT_USERAGENT'] = 'MoodleBot/1.0';
2351 // True to include the header in the output
2352 $this->options['CURLOPT_HEADER'] = 0;
2353 // True to Exclude the body from the output
2354 $this->options['CURLOPT_NOBODY'] = 0;
2355 // TRUE to follow any "Location: " header that the server
2356 // sends as part of the HTTP header (note this is recursive,
2357 // PHP will follow as many "Location: " headers that it is sent,
2358 // unless CURLOPT_MAXREDIRS is set).
99eaca9d 2359 //$this->options['CURLOPT_FOLLOWLOCATION'] = 1;
bb2c046d 2360 $this->options['CURLOPT_MAXREDIRS'] = 10;
2361 $this->options['CURLOPT_ENCODING'] = '';
2362 // TRUE to return the transfer as a string of the return
2363 // value of curl_exec() instead of outputting it out directly.
2364 $this->options['CURLOPT_RETURNTRANSFER'] = 1;
2365 $this->options['CURLOPT_BINARYTRANSFER'] = 0;
2366 $this->options['CURLOPT_SSL_VERIFYPEER'] = 0;
2367 $this->options['CURLOPT_SSL_VERIFYHOST'] = 2;
6135bd45 2368 $this->options['CURLOPT_CONNECTTIMEOUT'] = 30;
bb2c046d 2369 }
2370
2371 /**
2372 * Reset Cookie
bb2c046d 2373 */
2374 public function resetcookie() {
2375 if (!empty($this->cookie)) {
2376 if (is_file($this->cookie)) {
2377 $fp = fopen($this->cookie, 'w');
2378 if (!empty($fp)) {
2379 fwrite($fp, '');
2380 fclose($fp);
2381 }
2382 }
2383 }
2384 }
2385
2386 /**
2387 * Set curl options
2388 *
2389 * @param array $options If array is null, this function will
2390 * reset the options to default value.
2391 *
2392 */
2393 public function setopt($options = array()) {
2394 if (is_array($options)) {
2395 foreach($options as $name => $val){
2396 if (stripos($name, 'CURLOPT_') === false) {
2397 $name = strtoupper('CURLOPT_'.$name);
2398 }
2399 $this->options[$name] = $val;
2400 }
2401 }
2402 }
2403 /**
2404 * Reset http method
2405 *
2406 */
2407 public function cleanopt(){
2408 unset($this->options['CURLOPT_HTTPGET']);
2409 unset($this->options['CURLOPT_POST']);
2410 unset($this->options['CURLOPT_POSTFIELDS']);
2411 unset($this->options['CURLOPT_PUT']);
2412 unset($this->options['CURLOPT_INFILE']);
2413 unset($this->options['CURLOPT_INFILESIZE']);
2414 unset($this->options['CURLOPT_CUSTOMREQUEST']);
2415 }
2416
2417 /**
2418 * Set HTTP Request Header
2419 *
2420 * @param array $headers
2421 *
2422 */
2423 public function setHeader($header) {
2424 if (is_array($header)){
2425 foreach ($header as $v) {
2426 $this->setHeader($v);
2427 }
2428 } else {
2429 $this->header[] = $header;
2430 }
2431 }
2432 /**
2433 * Set HTTP Response Header
2434 *
2435 */
2436 public function getResponse(){
2437 return $this->response;
2438 }
2439 /**
2440 * private callback function
2441 * Formatting HTTP Response Header
2442 *
ba21c9d4 2443 * @param mixed $ch Apparently not used
2444 * @param string $header
2445 * @return int The strlen of the header
bb2c046d 2446 */
2447 private function formatHeader($ch, $header)
2448 {
2449 $this->count++;
2450 if (strlen($header) > 2) {
2451 list($key, $value) = explode(" ", rtrim($header, "\r\n"), 2);
2452 $key = rtrim($key, ':');
2453 if (!empty($this->response[$key])) {
2454 if (is_array($this->response[$key])){
2455 $this->response[$key][] = $value;
2456 } else {
2457 $tmp = $this->response[$key];
2458 $this->response[$key] = array();
2459 $this->response[$key][] = $tmp;
2460 $this->response[$key][] = $value;
2461
2462 }
2463 } else {
2464 $this->response[$key] = $value;
2465 }
2466 }
2467 return strlen($header);
2468 }
2469
2470 /**
2471 * Set options for individual curl instance
ba21c9d4 2472 *
2473 * @param object $curl A curl handle
2474 * @param array $options
2475 * @return object The curl handle
bb2c046d 2476 */
2477 private function apply_opt($curl, $options) {
2478 // Clean up
2479 $this->cleanopt();
2480 // set cookie
2481 if (!empty($this->cookie) || !empty($options['cookie'])) {
2482 $this->setopt(array('cookiejar'=>$this->cookie,
2483 'cookiefile'=>$this->cookie
2484 ));
2485 }
2486
2487 // set proxy
2488 if (!empty($this->proxy) || !empty($options['proxy'])) {
2489 $this->setopt($this->proxy);
2490 }
2491 $this->setopt($options);
2492 // reset before set options
2493 curl_setopt($curl, CURLOPT_HEADERFUNCTION, array(&$this,'formatHeader'));
2494 // set headers
2495 if (empty($this->header)){
2496 $this->setHeader(array(
2497 'User-Agent: MoodleBot/1.0',
2498 'Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7',
2499 'Connection: keep-alive'
2500 ));
2501 }
2502 curl_setopt($curl, CURLOPT_HTTPHEADER, $this->header);
2503
2504 if ($this->debug){
2505 echo '<h1>Options</h1>';
2506 var_dump($this->options);
2507 echo '<h1>Header</h1>';
2508 var_dump($this->header);
2509 }
2510
2511 // set options
2512 foreach($this->options as $name => $val) {
2513 if (is_string($name)) {
2514 $name = constant(strtoupper($name));
2515 }
2516 curl_setopt($curl, $name, $val);
2517 }
2518 return $curl;
2519 }
ba21c9d4 2520 /**
bb2c046d 2521 * Download multiple files in parallel
ba21c9d4 2522 *
2523 * Calls {@link multi()} with specific download headers
2524 *
2525 * <code>
bb2c046d 2526 * $c = new curl;
2527 * $c->download(array(
172dd12c 2528 * array('url'=>'http://localhost/', 'file'=>fopen('a', 'wb')),
bb2c046d 2529 * array('url'=>'http://localhost/20/', 'file'=>fopen('b', 'wb'))
2530 * ));
ba21c9d4 2531 * </code>
2532 *
2533 * @param array $requests An array of files to request
2534 * @param array $options An array of options to set
2535 * @return array An array of results
bb2c046d 2536 */
2537 public function download($requests, $options = array()) {
2538 $options['CURLOPT_BINARYTRANSFER'] = 1;
2539 $options['RETURNTRANSFER'] = false;
2540 return $this->multi($requests, $options);
2541 }
2542 /*
2543 * Mulit HTTP Requests
2544 * This function could run multi-requests in parallel.
ba21c9d4 2545 *
2546 * @param array $requests An array of files to request
2547 * @param array $options An array of options to set
2548 * @return array An array of results
bb2c046d 2549 */
2550 protected function multi($requests, $options = array()) {
2551 $count = count($requests);
2552 $handles = array();
2553 $results = array();
2554 $main = curl_multi_init();
2555 for ($i = 0; $i < $count; $i++) {
2556 $url = $requests[$i];
2557 foreach($url as $n=>$v){
2558 $options[$n] = $url[$n];
2559 }
2560 $handles[$i] = curl_init($url['url']);
2561 $this->apply_opt($handles[$i], $options);
2562 curl_multi_add_handle($main, $handles[$i]);
2563 }
2564 $running = 0;
2565 do {
2566 curl_multi_exec($main, $running);
2567 } while($running > 0);
2568 for ($i = 0; $i < $count; $i++) {
ba4082f5 2569 if (!empty($options['CURLOPT_RETURNTRANSFER'])) {
bb2c046d 2570 $results[] = true;
2571 } else {
2572 $results[] = curl_multi_getcontent($handles[$i]);
2573 }
2574 curl_multi_remove_handle($main, $handles[$i]);
2575 }
2576 curl_multi_close($main);
2577 return $results;
2578 }
2579 /**
2580 * Single HTTP Request
ba21c9d4 2581 *
2582 * @param string $url The URL to request
2583 * @param array $options
2584 * @return bool
bb2c046d 2585 */
2586 protected function request($url, $options = array()){
2587 // create curl instance
2588 $curl = curl_init($url);
2589 $options['url'] = $url;
2590 $this->apply_opt($curl, $options);
2591 if ($this->cache && $ret = $this->cache->get($this->options)) {
2592 return $ret;
2593 } else {
6135bd45 2594 $ret = curl_exec($curl);
bb2c046d 2595 if ($this->cache) {
2596 $this->cache->set($this->options, $ret);
2597 }
2598 }
2599
2600 $this->info = curl_getinfo($curl);
2601 $this->error = curl_error($curl);
2602
2603 if ($this->debug){
2604 echo '<h1>Return Data</h1>';
2605 var_dump($ret);
2606 echo '<h1>Info</h1>';
2607 var_dump($this->info);
2608 echo '<h1>Error</h1>';
2609 var_dump($this->error);
2610 }
2611
2612 curl_close($curl);
2613
6135bd45 2614 if (empty($this->error)){
bb2c046d 2615 return $ret;
2616 } else {
4dbb2b05 2617 return $this->error;
2618 // exception is not ajax friendly
2619 //throw new moodle_exception($this->error, 'curl');
bb2c046d 2620 }
2621 }
2622
2623 /**
2624 * HTTP HEAD method
ba21c9d4 2625 *
117bd748 2626 * @see request()
ba21c9d4 2627 *
2628 * @param string $url
2629 * @param array $options
2630 * @return bool
bb2c046d 2631 */
2632 public function head($url, $options = array()){
2633 $options['CURLOPT_HTTPGET'] = 0;
2634 $options['CURLOPT_HEADER'] = 1;
2635 $options['CURLOPT_NOBODY'] = 1;
2636 return $this->request($url, $options);
2637 }
2638
2639 /**
2640 * HTTP POST method
ba21c9d4 2641 *
2642 * @param string $url
117bd748 2643 * @param array|string $params
ba21c9d4 2644 * @param array $options
2645 * @return bool
bb2c046d 2646 */
28c58294 2647 public function post($url, $params = '', $options = array()){
bb2c046d 2648 $options['CURLOPT_POST'] = 1;
28c58294 2649 if (is_array($params)) {
2650 $this->_tmp_file_post_params = array();
2651 foreach ($params as $key => $value) {
2652 if ($value instanceof stored_file) {
2653 $value->add_to_curl_request($this, $key);
2654 } else {
2655 $this->_tmp_file_post_params[$key] = $value;
2656 }
5035a8b4 2657 }
28c58294 2658 $options['CURLOPT_POSTFIELDS'] = $this->_tmp_file_post_params;
2659 unset($this->_tmp_file_post_params);
2660 } else {
2661 // $params is the raw post data
2662 $options['CURLOPT_POSTFIELDS'] = $params;
5035a8b4 2663 }
bb2c046d 2664 return $this->request($url, $options);
2665 }
2666
2667 /**
2668 * HTTP GET method
ba21c9d4 2669 *
2670 * @param string $url
117bd748 2671 * @param array $params
ba21c9d4 2672 * @param array $options
2673 * @return bool
bb2c046d 2674 */
2675 public function get($url, $params = array(), $options = array()){
2676 $options['CURLOPT_HTTPGET'] = 1;
2677
2678 if (!empty($params)){
2679 $url .= (stripos($url, '?') !== false) ? '&' : '?';
2680 $url .= http_build_query($params, '', '&');
2681 }
2682 return $this->request($url, $options);
2683 }
2684
2685 /**
2686 * HTTP PUT method
ba21c9d4 2687 *
2688 * @param string $url
117bd748 2689 * @param array $params
ba21c9d4 2690 * @param array $options
2691 * @return bool
bb2c046d 2692 */
2693 public function put($url, $params = array(), $options = array()){
2694 $file = $params['file'];
2695 if (!is_file($file)){
2696 return null;
2697 }
2698 $fp = fopen($file, 'r');
2699 $size = filesize($file);
2700 $options['CURLOPT_PUT'] = 1;
2701 $options['CURLOPT_INFILESIZE'] = $size;
2702 $options['CURLOPT_INFILE'] = $fp;
2703 if (!isset($this->options['CURLOPT_USERPWD'])){
2704 $this->setopt(array('CURLOPT_USERPWD'=>'anonymous: noreply@moodle.org'));
2705 }
2706 $ret = $this->request($url, $options);
2707 fclose($fp);
2708 return $ret;
2709 }
2710
2711 /**
2712 * HTTP DELETE method
ba21c9d4 2713 *
2714 * @param string $url
117bd748 2715 * @param array $params
ba21c9d4 2716 * @param array $options
2717 * @return bool
bb2c046d 2718 */
2719 public function delete($url, $param = array(), $options = array()){
2720 $options['CURLOPT_CUSTOMREQUEST'] = 'DELETE';
2721 if (!isset($options['CURLOPT_USERPWD'])) {
2722 $options['CURLOPT_USERPWD'] = 'anonymous: noreply@moodle.org';
2723 }
2724 $ret = $this->request($url, $options);
2725 return $ret;
2726 }
2727 /**
2728 * HTTP TRACE method
ba21c9d4 2729 *
2730 * @param string $url
2731 * @param array $options
2732 * @return bool
bb2c046d 2733 */
2734 public function trace($url, $options = array()){
2735 $options['CURLOPT_CUSTOMREQUEST'] = 'TRACE';
2736 $ret = $this->request($url, $options);
2737 return $ret;
2738 }
2739 /**
2740 * HTTP OPTIONS method
ba21c9d4 2741 *
2742 * @param string $url
2743 * @param array $options
2744 * @return bool
bb2c046d 2745 */
2746 public function options($url, $options = array()){
2747 $options['CURLOPT_CUSTOMREQUEST'] = 'OPTIONS';
2748 $ret = $this->request($url, $options);
2749 return $ret;
2750 }
4dbb2b05 2751 public function get_info() {
2752 return $this->info;
2753 }
bb2c046d 2754}
2755
2756/**
2757 * This class is used by cURL class, use case:
2758 *
ba21c9d4 2759 * <code>
5430f05b 2760 * $CFG->repositorycacheexpire = 120;
2761 * $CFG->curlcache = 120;
2762 *
2763 * $c = new curl(array('cache'=>true), 'module_cache'=>'repository');
bb2c046d 2764 * $ret = $c->get('http://www.google.com');
ba21c9d4 2765 * </code>
bb2c046d 2766 *
d078f6d3 2767 * @package core
ba21c9d4 2768 * @subpackage file
d078f6d3
PS
2769 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
2770 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
bb2c046d 2771 */
2772class curl_cache {
ba21c9d4 2773 /** @var string */
bb2c046d 2774 public $dir = '';
5430f05b 2775 /**
2776 *
ba21c9d4 2777 * @global object
2778 * @param string @module which module is using curl_cache
5430f05b 2779 *
2780 */
37051e58 2781 function __construct($module = 'repository'){
bb2c046d 2782 global $CFG;
5430f05b 2783 if (!empty($module)) {
2784 $this->dir = $CFG->dataroot.'/cache/'.$module.'/';
2785 } else {
2786 $this->dir = $CFG->dataroot.'/cache/misc/';
bb2c046d 2787 }
5430f05b 2788 if (!file_exists($this->dir)) {
35b622e1 2789 mkdir($this->dir, $CFG->directorypermissions, true);
bb2c046d 2790 }
5430f05b 2791 if ($module == 'repository') {
2792 if (empty($CFG->repositorycacheexpire)) {
2793 $CFG->repositorycacheexpire = 120;
2794 }
2795 $this->ttl = $CFG->repositorycacheexpire;
2796 } else {
2797 if (empty($CFG->curlcache)) {
2798 $CFG->curlcache = 120;
2799 }
2800 $this->ttl = $CFG->curlcache;
b933a139 2801 }
bb2c046d 2802 }
a08171c5 2803
509f67e3 2804 /**
e35194be 2805 * Get cached value
ba21c9d4 2806 *
2807 * @global object
2808 * @global object
2809 * @param mixed $param
2810 * @return bool|string
509f67e3 2811 */
bb2c046d 2812 public function get($param){
aae85978 2813 global $CFG, $USER;
5430f05b 2814 $this->cleanup($this->ttl);
aae85978 2815 $filename = 'u'.$USER->id.'_'.md5(serialize($param));
bb2c046d 2816 if(file_exists($this->dir.$filename)) {
2817 $lasttime = filemtime($this->dir.$filename);
5430f05b 2818 if(time()-$lasttime > $this->ttl)
d7e122d6 2819 {
bb2c046d 2820 return false;
2821 } else {
2822 $fp = fopen($this->dir.$filename, 'r');
2823 $size = filesize($this->dir.$filename);
2824 $content = fread($fp, $size);
2825 return unserialize($content);
2826 }
2827 }
2828 return false;
2829 }
a08171c5 2830
509f67e3 2831 /**
e35194be 2832 * Set cache value
ba21c9d4 2833 *
e35194be
DC
2834 * @global object $CFG
2835 * @global object $USER
ba21c9d4 2836 * @param mixed $param
2837 * @param mixed $val
509f67e3 2838 */
bb2c046d 2839 public function set($param, $val){
aae85978 2840 global $CFG, $USER;
2841 $filename = 'u'.$USER->id.'_'.md5(serialize($param));
bb2c046d 2842 $fp = fopen($this->dir.$filename, 'w');
2843 fwrite($fp, serialize($val));
2844 fclose($fp);
2845 }
a08171c5 2846
509f67e3 2847 /**
e35194be 2848 * Remove cache files
ba21c9d4 2849 *
2850 * @param int $expire The number os seconds before expiry
509f67e3 2851 */
bb2c046d 2852 public function cleanup($expire){
2853 if($dir = opendir($this->dir)){
2854 while (false !== ($file = readdir($dir))) {
2855 if(!is_dir($file) && $file != '.' && $file != '..') {
2856 $lasttime = @filemtime($this->dir.$file);
2857 if(time() - $lasttime > $expire){
2858 @unlink($this->dir.$file);
2859 }
2860 }
2861 }
2862 }
2863 }
aae85978 2864 /**
2865 * delete current user's cache file
2866 *
e35194be
DC
2867 * @global object $CFG
2868 * @global object $USER
aae85978 2869 */
2870 public function refresh(){
2871 global $CFG, $USER;
2872 if($dir = opendir($this->dir)){
2873 while (false !== ($file = readdir($dir))) {
2874 if(!is_dir($file) && $file != '.' && $file != '..') {
2875 if(strpos($file, 'u'.$USER->id.'_')!==false){
2876 @unlink($this->dir.$file);
2877 }
2878 }
2879 }
2880 }
2881 }
bb2c046d 2882}
509f67e3 2883
2884/**
f9fd0be9 2885 * This class is used to parse lib/file/file_types.mm which help get file
2f67a9b3 2886 * extensions by file types.
f9fd0be9 2887 * The file_types.mm file can be edited by freemind in graphic environment.
ba21c9d4 2888 *
d078f6d3 2889 * @package core
ba21c9d4 2890 * @subpackage file
d078f6d3
PS
2891 * @copyright 2009 Dongsheng Cai <dongsheng@moodle.com>
2892 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
509f67e3 2893 */
99eaca9d 2894class filetype_parser {
ba21c9d4 2895 /**
f9fd0be9
DC
2896 * Check file_types.mm file, setup variables
2897 *
2898 * @global object $CFG
ba21c9d4 2899 * @param string $file
2900 */
014c1ca0 2901 public function __construct($file = '') {
2902 global $CFG;
2903 if (empty($file)) {
64f93798 2904 $this->file = $CFG->libdir.'/filestorage/file_types.mm';
014c1ca0 2905 } else {
2906 $this->file = $file;
2907 }
2908 $this->tree = array();
2909 $this->result = array();
2910 }
a08171c5 2911
509f67e3 2912 /**
f9fd0be9
DC
2913 * A private function to browse xml nodes
2914 *
ba21c9d4 2915 * @param array $parent
2916 * @param array $types
509f67e3 2917 */
014c1ca0 2918 private function _browse_nodes($parent, $types) {
2919 $key = (string)$parent['TEXT'];
2920 if(isset($parent->node)) {
2921 $this->tree[$key] = array();
2922 if (in_array((string)$parent['TEXT'], $types)) {
2923 $this->_select_nodes($parent, $this->result);
2924 } else {
2925 foreach($parent->node as $v){
2926 $this->_browse_nodes($v, $types);
2927 }
2928 }
2929 } else {
2930 $this->tree[] = $key;
2931 }
2932 }
a08171c5 2933
509f67e3 2934 /**
f9fd0be9
DC
2935 * A private function to select text nodes
2936 *
ba21c9d4 2937 * @param array $parent
509f67e3 2938 */
014c1ca0 2939 private function _select_nodes($parent){
2940 if(isset($parent->node)) {
2941 foreach($parent->node as $v){
2942 $this->_select_nodes($v, $this->result);
2943 }
2944 } else {
2945 $this->result[] = (string)$parent['TEXT'];
2946 }
2947 }
2948
a08171c5 2949
509f67e3 2950 /**
f9fd0be9
DC
2951 * Get file extensions by file types names.
2952 *
ba21c9d4 2953 * @param array $types
2954 * @return mixed
509f67e3 2955 */
99eaca9d
DC
2956 public function get_extensions($types) {
2957 if (!is_array($types)) {
2958 $types = array($types);
2959 }
014c1ca0 2960 $this->result = array();
fc11edbf 2961 if ((is_array($types) && in_array('*', $types)) ||
b933b378 2962 $types == '*' || empty($types)) {
2963 return array('*');
014c1ca0 2964 }
2965 foreach ($types as $key=>$value){
2966 if (strpos($value, '.') !== false) {
2967 $this->result[] = $value;
2968 unset($types[$key]);
2969 }
2970 }
2971 if (file_exists($this->file)) {
2972 $xml = simplexml_load_file($this->file);
2973 foreach($xml->node->node as $v){
2974 if (in_array((string)$v['TEXT'], $types)) {
2975 $this->_select_nodes($v);
2976 } else {
2977 $this->_browse_nodes($v, $types);
2978 }
2979 }
2980 } else {
64f93798 2981 exit('Failed to open file lib/filestorage/file_types.mm');
014c1ca0 2982 }
2983 return $this->result;
2984 }
2985}