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