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