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