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