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