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