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