3 define('BYTESERVING_BOUNDARY', 's1k2o3d4a5k6s7'); //unique string constant
5 function get_file_url($path, $options=null, $type='coursefile') {
8 $path = str_replace('//', '/', $path);
9 $path = trim($path, '/'); // no leading and trailing slashes
14 $url = $CFG->wwwroot
."/question/exportfile.php";
17 $url = $CFG->wwwroot
."/rss/file.php";
20 $url = $CFG->wwwroot
."/user/pix.php";
23 $url = $CFG->wwwroot
."/user/pixgroup.php";
25 case 'httpscoursefile':
26 $url = $CFG->httpswwwroot
."/file.php";
30 $url = $CFG->wwwroot
."/file.php";
33 if ($CFG->slasharguments
) {
34 $parts = explode('/', $path);
35 $parts = array_map('rawurlencode', $parts);
36 $path = implode('/', $parts);
37 $ffurl = $url.'/'.$path;
40 $path = rawurlencode('/'.$path);
41 $ffurl = $url.'?file='.$path;
46 foreach ($options as $name=>$value) {
47 $ffurl = $ffurl.$separator.$name.'='.$value;
56 * Fetches content of file from Internet (using proxy if defined). Uses cURL extension if present.
57 * Due to security concerns only downloads from http(s) sources are supported.
59 * @param string $url file url starting with http(s)://
60 * @param array $headers http headers, null if none. If set, should be an
61 * associative array of header name => value pairs.
62 * @param array $postdata array means use POST request with given parameters
63 * @param bool $fullresponse return headers, responses, etc in a similar way snoopy does
64 * (if false, just returns content)
65 * @param int $timeout timeout for complete download process including all file transfer
67 * @param int $connecttimeout timeout for connection to server; this is the timeout that
68 * usually happens if the remote server is completely down (default 20 seconds);
69 * may not work when using proxy
70 * @param bool $skipcertverify If true, the peer's SSL certificate will not be checked. Only use this when already in a trusted location.
71 * @return mixed false if request failed or content of the file as string if ok.
73 function download_file_content($url, $headers=null, $postdata=null, $fullresponse=false, $timeout=300, $connecttimeout=20, $skipcertverify=false) {
76 // some extra security
77 $newlines = array("\r", "\n");
78 if (is_array($headers) ) {
79 foreach ($headers as $key => $value) {
80 $headers[$key] = str_replace($newlines, '', $value);
83 $url = str_replace($newlines, '', $url);
84 if (!preg_match('|^https?://|i', $url)) {
86 $response = new object();
87 $response->status
= 0;
88 $response->headers
= array();
89 $response->response_code
= 'Invalid protocol specified in url';
90 $response->results
= '';
91 $response->error
= 'Invalid protocol specified in url';
99 if (!extension_loaded('curl') or ($ch = curl_init($url)) === false) {
100 require_once($CFG->libdir
.'/snoopy/Snoopy.class.inc');
101 $snoopy = new Snoopy();
102 $snoopy->read_timeout
= $timeout;
103 $snoopy->_fp_timeout
= $connecttimeout;
104 $snoopy->proxy_host
= $CFG->proxyhost
;
105 $snoopy->proxy_port
= $CFG->proxyport
;
106 if (!empty($CFG->proxyuser
) and !empty($CFG->proxypassword
)) {
107 // this will probably fail, but let's try it anyway
108 $snoopy->proxy_user
= $CFG->proxyuser
;
109 $snoopy->proxy_password
= $CFG->proxypassword
;
111 if (is_array($headers) ) {
112 $client->rawheaders
= $headers;
115 if (is_array($postdata)) {
116 $fetch = @$snoopy->fetch($url, $postdata); // use more specific debug code bellow
118 $fetch = @$snoopy->fetch($url); // use more specific debug code bellow
123 //fix header line endings
124 foreach ($snoopy->headers
as $key=>$unused) {
125 $snoopy->headers
[$key] = trim($snoopy->headers
[$key]);
127 $response = new object();
128 $response->status
= $snoopy->status
;
129 $response->headers
= $snoopy->headers
;
130 $response->response_code
= trim($snoopy->response_code
);
131 $response->results
= $snoopy->results
;
132 $response->error
= $snoopy->error
;
135 } else if ($snoopy->status
!= 200) {
136 debugging("Snoopy request for \"$url\" failed, http response code: ".$snoopy->response_code
, DEBUG_ALL
);
140 return $snoopy->results
;
144 $response = new object();
145 $response->status
= $snoopy->status
;
146 $response->headers
= array();
147 $response->response_code
= $snoopy->response_code
;
148 $response->results
= '';
149 $response->error
= $snoopy->error
;
152 debugging("Snoopy request for \"$url\" failed with: ".$snoopy->error
, DEBUG_ALL
);
159 if (is_array($headers) ) {
161 foreach ($headers as $key => $value) {
162 $headers2[] = "$key: $value";
164 curl_setopt($ch, CURLOPT_HTTPHEADER
, $headers2);
168 if ($skipcertverify) {
169 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER
, false);
172 // use POST if requested
173 if (is_array($postdata)) {
174 foreach ($postdata as $k=>$v) {
175 $postdata[$k] = urlencode($k).'='.urlencode($v);
177 $postdata = implode('&', $postdata);
178 curl_setopt($ch, CURLOPT_POST
, true);
179 curl_setopt($ch, CURLOPT_POSTFIELDS
, $postdata);
182 curl_setopt($ch, CURLOPT_RETURNTRANSFER
, true);
183 curl_setopt($ch, CURLOPT_HEADER
, true);
184 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT
, $connecttimeout);
185 curl_setopt($ch, CURLOPT_TIMEOUT
, $timeout);
186 if (!ini_get('open_basedir') and !ini_get('safe_mode')) {
187 // TODO: add version test for '7.10.5'
188 curl_setopt($ch, CURLOPT_FOLLOWLOCATION
, true);
189 curl_setopt($ch, CURLOPT_MAXREDIRS
, 5);
192 if (!empty($CFG->proxyhost
)) {
193 // SOCKS supported in PHP5 only
194 if (!empty($CFG->proxytype
) and ($CFG->proxytype
== 'SOCKS5')) {
195 if (defined('CURLPROXY_SOCKS5')) {
196 curl_setopt($ch, CURLOPT_PROXYTYPE
, CURLPROXY_SOCKS5
);
200 $response = new object();
201 $response->status
= '0';
202 $response->headers
= array();
203 $response->response_code
= 'SOCKS5 proxy is not supported in PHP4';
204 $response->results
= '';
205 $response->error
= 'SOCKS5 proxy is not supported in PHP4';
208 debugging("SOCKS5 proxy is not supported in PHP4.", DEBUG_ALL
);
214 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL
, false);
216 if (empty($CFG->proxyport
)) {
217 curl_setopt($ch, CURLOPT_PROXY
, $CFG->proxyhost
);
219 curl_setopt($ch, CURLOPT_PROXY
, $CFG->proxyhost
.':'.$CFG->proxyport
);
222 if (!empty($CFG->proxyuser
) and !empty($CFG->proxypassword
)) {
223 curl_setopt($ch, CURLOPT_PROXYUSERPWD
, $CFG->proxyuser
.':'.$CFG->proxypassword
);
224 if (defined('CURLOPT_PROXYAUTH')) {
225 // any proxy authentication if PHP 5.1
226 curl_setopt($ch, CURLOPT_PROXYAUTH
, CURLAUTH_BASIC | CURLAUTH_NTLM
);
231 $data = curl_exec($ch);
233 // try to detect encoding problems
234 if ((curl_errno($ch) == 23 or curl_errno($ch) == 61) and defined('CURLOPT_ENCODING')) {
235 curl_setopt($ch, CURLOPT_ENCODING
, 'none');
236 $data = curl_exec($ch);
239 if (curl_errno($ch)) {
240 $error = curl_error($ch);
241 $error_no = curl_errno($ch);
245 $response = new object();
246 if ($error_no == 28) {
247 $response->status
= '-100'; // mimic snoopy
249 $response->status
= '0';
251 $response->headers
= array();
252 $response->response_code
= $error;
253 $response->results
= '';
254 $response->error
= $error;
257 debugging("cURL request for \"$url\" failed with: $error ($error_no)", DEBUG_ALL
);
262 $info = curl_getinfo($ch);
265 if (empty($info['http_code'])) {
266 // for security reasons we support only true http connections (Location: file:// exploit prevention)
267 $response = new object();
268 $response->status
= '0';
269 $response->headers
= array();
270 $response->response_code
= 'Unknown cURL error';
271 $response->results
= ''; // do NOT change this!
272 $response->error
= 'Unknown cURL error';
275 // strip redirect headers and get headers array and content
276 $data = explode("\r\n\r\n", $data, $info['redirect_count'] +
2);
277 $results = array_pop($data);
278 $headers = array_pop($data);
279 $headers = explode("\r\n", trim($headers));
281 $response = new object();;
282 $response->status
= (string)$info['http_code'];
283 $response->headers
= $headers;
284 $response->response_code
= $headers[0];
285 $response->results
= $results;
286 $response->error
= '';
291 } else if ($info['http_code'] != 200) {
292 debugging("cURL request for \"$url\" failed, HTTP response code: ".$response->response_code
, DEBUG_ALL
);
295 return $response->results
;
301 * @return List of information about file types based on extensions.
302 * Associative array of extension (lower-case) to associative array
303 * from 'element name' to data. Current element names are 'type' and 'icon'.
304 * Unknown types should use the 'xxx' entry which includes defaults.
306 function get_mimetypes_array() {
308 'xxx' => array ('type'=>'document/unknown', 'icon'=>'unknown.gif'),
309 '3gp' => array ('type'=>'video/quicktime', 'icon'=>'video.gif'),
310 'ai' => array ('type'=>'application/postscript', 'icon'=>'image.gif'),
311 'aif' => array ('type'=>'audio/x-aiff', 'icon'=>'audio.gif'),
312 'aiff' => array ('type'=>'audio/x-aiff', 'icon'=>'audio.gif'),
313 'aifc' => array ('type'=>'audio/x-aiff', 'icon'=>'audio.gif'),
314 'applescript' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
315 'asc' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
316 'asm' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
317 'au' => array ('type'=>'audio/au', 'icon'=>'audio.gif'),
318 'avi' => array ('type'=>'video/x-ms-wm', 'icon'=>'avi.gif'),
319 'bmp' => array ('type'=>'image/bmp', 'icon'=>'image.gif'),
320 'c' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
321 'cct' => array ('type'=>'shockwave/director', 'icon'=>'flash.gif'),
322 'cpp' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
323 'cs' => array ('type'=>'application/x-csh', 'icon'=>'text.gif'),
324 'css' => array ('type'=>'text/css', 'icon'=>'text.gif'),
325 'csv' => array ('type'=>'text/csv', 'icon'=>'excel.gif'),
326 'dv' => array ('type'=>'video/x-dv', 'icon'=>'video.gif'),
327 'dmg' => array ('type'=>'application/octet-stream', 'icon'=>'dmg.gif'),
328 'doc' => array ('type'=>'application/msword', 'icon'=>'word.gif'),
329 'docx' => array ('type'=>'application/msword', 'icon'=>'docx.gif'),
330 'docm' => array ('type'=>'application/msword', 'icon'=>'docm.gif'),
331 'dotx' => array ('type'=>'application/msword', 'icon'=>'dotx.gif'),
332 'dcr' => array ('type'=>'application/x-director', 'icon'=>'flash.gif'),
333 'dif' => array ('type'=>'video/x-dv', 'icon'=>'video.gif'),
334 'dir' => array ('type'=>'application/x-director', 'icon'=>'flash.gif'),
335 'dxr' => array ('type'=>'application/x-director', 'icon'=>'flash.gif'),
336 'eps' => array ('type'=>'application/postscript', 'icon'=>'pdf.gif'),
337 'fdf' => array ('type'=>'application/pdf', 'icon'=>'pdf.gif'),
338 'flv' => array ('type'=>'video/x-flv', 'icon'=>'video.gif'),
339 'gif' => array ('type'=>'image/gif', 'icon'=>'image.gif'),
340 'gtar' => array ('type'=>'application/x-gtar', 'icon'=>'zip.gif'),
341 'tgz' => array ('type'=>'application/g-zip', 'icon'=>'zip.gif'),
342 'gz' => array ('type'=>'application/g-zip', 'icon'=>'zip.gif'),
343 'gzip' => array ('type'=>'application/g-zip', 'icon'=>'zip.gif'),
344 'h' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
345 'hpp' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
346 'hqx' => array ('type'=>'application/mac-binhex40', 'icon'=>'zip.gif'),
347 'htc' => array ('type'=>'text/x-component', 'icon'=>'text.gif'),
348 'html' => array ('type'=>'text/html', 'icon'=>'html.gif'),
349 'xhtml'=> array ('type'=>'application/xhtml+xml', 'icon'=>'html.gif'),
350 'htm' => array ('type'=>'text/html', 'icon'=>'html.gif'),
351 'ico' => array ('type'=>'image/vnd.microsoft.icon', 'icon'=>'image.gif'),
352 'ics' => array ('type'=>'text/calendar', 'icon'=>'text.gif'),
353 'isf' => array ('type'=>'application/inspiration', 'icon'=>'isf.gif'),
354 'ist' => array ('type'=>'application/inspiration.template', 'icon'=>'isf.gif'),
355 'java' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
356 'jcb' => array ('type'=>'text/xml', 'icon'=>'jcb.gif'),
357 'jcl' => array ('type'=>'text/xml', 'icon'=>'jcl.gif'),
358 'jcw' => array ('type'=>'text/xml', 'icon'=>'jcw.gif'),
359 'jmt' => array ('type'=>'text/xml', 'icon'=>'jmt.gif'),
360 'jmx' => array ('type'=>'text/xml', 'icon'=>'jmx.gif'),
361 'jpe' => array ('type'=>'image/jpeg', 'icon'=>'image.gif'),
362 'jpeg' => array ('type'=>'image/jpeg', 'icon'=>'image.gif'),
363 'jpg' => array ('type'=>'image/jpeg', 'icon'=>'image.gif'),
364 'jqz' => array ('type'=>'text/xml', 'icon'=>'jqz.gif'),
365 'js' => array ('type'=>'application/x-javascript', 'icon'=>'text.gif'),
366 'latex'=> array ('type'=>'application/x-latex', 'icon'=>'text.gif'),
367 'm' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
368 'mov' => array ('type'=>'video/quicktime', 'icon'=>'video.gif'),
369 'movie'=> array ('type'=>'video/x-sgi-movie', 'icon'=>'video.gif'),
370 'm3u' => array ('type'=>'audio/x-mpegurl', 'icon'=>'audio.gif'),
371 'mp3' => array ('type'=>'audio/mp3', 'icon'=>'audio.gif'),
372 'mp4' => array ('type'=>'video/mp4', 'icon'=>'video.gif'),
373 'mpeg' => array ('type'=>'video/mpeg', 'icon'=>'video.gif'),
374 'mpe' => array ('type'=>'video/mpeg', 'icon'=>'video.gif'),
375 'mpg' => array ('type'=>'video/mpeg', 'icon'=>'video.gif'),
377 'odt' => array ('type'=>'application/vnd.oasis.opendocument.text', 'icon'=>'odt.gif'),
378 'ott' => array ('type'=>'application/vnd.oasis.opendocument.text-template', 'icon'=>'odt.gif'),
379 'oth' => array ('type'=>'application/vnd.oasis.opendocument.text-web', 'icon'=>'odt.gif'),
380 'odm' => array ('type'=>'application/vnd.oasis.opendocument.text-master', 'icon'=>'odm.gif'),
381 'odg' => array ('type'=>'application/vnd.oasis.opendocument.graphics', 'icon'=>'odg.gif'),
382 'otg' => array ('type'=>'application/vnd.oasis.opendocument.graphics-template', 'icon'=>'odg.gif'),
383 'odp' => array ('type'=>'application/vnd.oasis.opendocument.presentation', 'icon'=>'odp.gif'),
384 'otp' => array ('type'=>'application/vnd.oasis.opendocument.presentation-template', 'icon'=>'odp.gif'),
385 'ods' => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet', 'icon'=>'ods.gif'),
386 'ots' => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet-template', 'icon'=>'ods.gif'),
387 'odc' => array ('type'=>'application/vnd.oasis.opendocument.chart', 'icon'=>'odc.gif'),
388 'odf' => array ('type'=>'application/vnd.oasis.opendocument.formula', 'icon'=>'odf.gif'),
389 'odb' => array ('type'=>'application/vnd.oasis.opendocument.database', 'icon'=>'odb.gif'),
390 'odi' => array ('type'=>'application/vnd.oasis.opendocument.image', 'icon'=>'odi.gif'),
392 'pct' => array ('type'=>'image/pict', 'icon'=>'image.gif'),
393 'pdf' => array ('type'=>'application/pdf', 'icon'=>'pdf.gif'),
394 'php' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
395 'pic' => array ('type'=>'image/pict', 'icon'=>'image.gif'),
396 'pict' => array ('type'=>'image/pict', 'icon'=>'image.gif'),
397 'png' => array ('type'=>'image/png', 'icon'=>'image.gif'),
398 'pps' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'powerpoint.gif'),
399 'ppt' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'powerpoint.gif'),
400 'pptx' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'pptx.gif'),
401 'pptm' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'pptm.gif'),
402 'potx' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'potx.gif'),
403 'potm' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'potm.gif'),
404 'ppam' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'ppam.gif'),
405 'ppsx' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'ppsx.gif'),
406 'ppsm' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'ppsm.gif'),
407 'ps' => array ('type'=>'application/postscript', 'icon'=>'pdf.gif'),
408 'qt' => array ('type'=>'video/quicktime', 'icon'=>'video.gif'),
409 'ra' => array ('type'=>'audio/x-realaudio', 'icon'=>'audio.gif'),
410 'ram' => array ('type'=>'audio/x-pn-realaudio', 'icon'=>'audio.gif'),
411 'rhb' => array ('type'=>'text/xml', 'icon'=>'xml.gif'),
412 'rm' => array ('type'=>'audio/x-pn-realaudio', 'icon'=>'audio.gif'),
413 'rtf' => array ('type'=>'text/rtf', 'icon'=>'text.gif'),
414 'rtx' => array ('type'=>'text/richtext', 'icon'=>'text.gif'),
415 'sh' => array ('type'=>'application/x-sh', 'icon'=>'text.gif'),
416 'sit' => array ('type'=>'application/x-stuffit', 'icon'=>'zip.gif'),
417 'smi' => array ('type'=>'application/smil', 'icon'=>'text.gif'),
418 'smil' => array ('type'=>'application/smil', 'icon'=>'text.gif'),
419 'sqt' => array ('type'=>'text/xml', 'icon'=>'xml.gif'),
420 'svg' => array ('type'=>'image/svg+xml', 'icon'=>'image.gif'),
421 'svgz' => array ('type'=>'image/svg+xml', 'icon'=>'image.gif'),
422 'swa' => array ('type'=>'application/x-director', 'icon'=>'flash.gif'),
423 'swf' => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash.gif'),
424 'swfl' => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash.gif'),
426 'sxw' => array ('type'=>'application/vnd.sun.xml.writer', 'icon'=>'odt.gif'),
427 'stw' => array ('type'=>'application/vnd.sun.xml.writer.template', 'icon'=>'odt.gif'),
428 'sxc' => array ('type'=>'application/vnd.sun.xml.calc', 'icon'=>'odt.gif'),
429 'stc' => array ('type'=>'application/vnd.sun.xml.calc.template', 'icon'=>'odt.gif'),
430 'sxd' => array ('type'=>'application/vnd.sun.xml.draw', 'icon'=>'odt.gif'),
431 'std' => array ('type'=>'application/vnd.sun.xml.draw.template', 'icon'=>'odt.gif'),
432 'sxi' => array ('type'=>'application/vnd.sun.xml.impress', 'icon'=>'odt.gif'),
433 'sti' => array ('type'=>'application/vnd.sun.xml.impress.template', 'icon'=>'odt.gif'),
434 'sxg' => array ('type'=>'application/vnd.sun.xml.writer.global', 'icon'=>'odt.gif'),
435 'sxm' => array ('type'=>'application/vnd.sun.xml.math', 'icon'=>'odt.gif'),
437 'tar' => array ('type'=>'application/x-tar', 'icon'=>'zip.gif'),
438 'tif' => array ('type'=>'image/tiff', 'icon'=>'image.gif'),
439 'tiff' => array ('type'=>'image/tiff', 'icon'=>'image.gif'),
440 'tex' => array ('type'=>'application/x-tex', 'icon'=>'text.gif'),
441 'texi' => array ('type'=>'application/x-texinfo', 'icon'=>'text.gif'),
442 'texinfo' => array ('type'=>'application/x-texinfo', 'icon'=>'text.gif'),
443 'tsv' => array ('type'=>'text/tab-separated-values', 'icon'=>'text.gif'),
444 'txt' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
445 'wav' => array ('type'=>'audio/wav', 'icon'=>'audio.gif'),
446 'wmv' => array ('type'=>'video/x-ms-wmv', 'icon'=>'avi.gif'),
447 'asf' => array ('type'=>'video/x-ms-asf', 'icon'=>'avi.gif'),
448 'xdp' => array ('type'=>'application/pdf', 'icon'=>'pdf.gif'),
449 'xfd' => array ('type'=>'application/pdf', 'icon'=>'pdf.gif'),
450 'xfdf' => array ('type'=>'application/pdf', 'icon'=>'pdf.gif'),
451 'xls' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'excel.gif'),
452 'xlsx' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'xlsx.gif'),
453 'xlsm' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'xlsm.gif'),
454 'xltx' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'xltx.gif'),
455 'xltm' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'xltm.gif'),
456 'xlsb' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'xlsb.gif'),
457 'xlam' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'xlam.gif'),
458 'xml' => array ('type'=>'application/xml', 'icon'=>'xml.gif'),
459 'xsl' => array ('type'=>'text/xml', 'icon'=>'xml.gif'),
460 'zip' => array ('type'=>'application/zip', 'icon'=>'zip.gif')
465 * Obtains information about a filetype based on its extension. Will
466 * use a default if no information is present about that particular
468 * @param string $element Desired information (usually 'icon'
469 * for icon filename or 'type' for MIME type)
470 * @param string $filename Filename we're looking up
471 * @return string Requested piece of information from array
473 function mimeinfo($element, $filename) {
474 static $mimeinfo = null;
475 if (is_null($mimeinfo)) {
476 $mimeinfo = get_mimetypes_array();
479 if (eregi('\.([a-z0-9]+)$', $filename, $match)) {
480 if (isset($mimeinfo[strtolower($match[1])][$element])) {
481 return $mimeinfo[strtolower($match[1])][$element];
483 return $mimeinfo['xxx'][$element]; // By default
486 return $mimeinfo['xxx'][$element]; // By default
491 * Obtains information about a filetype based on the MIME type rather than
492 * the other way around.
493 * @param string $element Desired information (usually 'icon')
494 * @param string $mimetype MIME type we're looking up
495 * @return string Requested piece of information from array
497 function mimeinfo_from_type($element, $mimetype) {
499 $mimeinfo=get_mimetypes_array();
501 foreach($mimeinfo as $values) {
502 if($values['type']==$mimetype) {
503 if(isset($values[$element])) {
504 return $values[$element];
509 return $mimeinfo['xxx'][$element]; // Default
513 * Get information about a filetype based on the icon file.
514 * @param string $element Desired information (usually 'icon')
515 * @param string $icon Icon file path.
516 * @return string Requested piece of information from array
518 function mimeinfo_from_icon($element, $icon) {
520 $mimeinfo=get_mimetypes_array();
522 if (preg_match("/\/(.*)/", $icon, $matches)) {
525 $info = $mimeinfo['xxx'][$element]; // Default
526 foreach($mimeinfo as $values) {
527 if($values['icon']==$icon) {
528 if(isset($values[$element])) {
529 $info = $values[$element];
531 //No break, for example for 'excel.gif' we don't want 'csv'!
538 * Obtains descriptions for file types (e.g. 'Microsoft Word document') from the
539 * mimetypes.php language file.
540 * @param string $mimetype MIME type (can be obtained using the mimeinfo function)
541 * @param bool $capitalise If true, capitalises first character of result
542 * @return string Text description
544 function get_mimetype_description($mimetype,$capitalise=false) {
545 $result=get_string($mimetype,'mimetypes');
546 // Surrounded by square brackets indicates that there isn't a string for that
547 // (maybe there is a better way to find this out?)
548 if(strpos($result,'[')===0) {
549 $result=get_string('document/unknown','mimetypes');
552 $result=ucfirst($result);
558 * Handles the sending of temporary file to user, download is forced.
559 * File is deleted after abort or succesful sending.
560 * @param string $path path to file, preferably from moodledata/temp/something; or content of file itself
561 * @param string $filename proposed file name when saving file
562 * @param bool $path is content of file
564 function send_temp_file($path, $filename, $pathisstring=false) {
567 // close session - not needed anymore
568 @session_write_close
();
570 if (!$pathisstring) {
571 if (!file_exists($path)) {
572 header('HTTP/1.0 404 not found');
573 error(get_string('filenotfound', 'error'), $CFG->wwwroot
.'/');
575 // executed after normal finish or abort
576 @register_shutdown_function
('send_temp_file_finished', $path);
579 //IE compatibiltiy HACK!
580 if (ini_get('zlib.output_compression')) {
581 ini_set('zlib.output_compression', 'Off');
584 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
585 if (check_browser_version('MSIE')) {
586 $filename = urlencode($filename);
589 $filesize = $pathisstring ?
strlen($path) : filesize($path);
591 @header
('Content-Disposition: attachment; filename='.$filename);
592 @header
('Content-Length: '.$filesize);
593 if (strpos($CFG->wwwroot
, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
594 @header
('Cache-Control: max-age=10');
595 @header
('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
597 } else { //normal http - prevent caching at all cost
598 @header
('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
599 @header
('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
600 @header
('Pragma: no-cache');
602 @header
('Accept-Ranges: none'); // Do not allow byteserving
604 while (@ob_end_flush
()); //flush the buffers - save memory and disable sid rewrite
608 readfile_chunked($path);
611 die; //no more chars to output
615 * Internal callnack function used by send_temp_file()
617 function send_temp_file_finished($path) {
618 if (file_exists($path)) {
624 * Handles the sending of file data to the user's browser, including support for
626 * @param string $path Path of file on disk (including real filename), or actual content of file as string
627 * @param string $filename Filename to send
628 * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
629 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
630 * @param bool $pathisstring If true (default false), $path is the content to send and not the pathname
631 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
632 * @param string $mimetype Include to specify the MIME type; leave blank to have it guess the type from $filename
634 function send_file($path, $filename, $lifetime = 'default' , $filter=0, $pathisstring=false, $forcedownload=false, $mimetype='') {
635 global $CFG, $COURSE;
637 // MDL-11789, apply $CFG->filelifetime here
638 if ($lifetime === 'default') {
639 if (!empty($CFG->filelifetime
)) {
640 $filetime = $CFG->filelifetime
;
646 // Use given MIME type if specified, otherwise guess it using mimeinfo.
647 // IE, Konqueror and Opera open html file directly in browser from web even when directed to save it to disk :-O
648 // only Firefox saves all files locally before opening when content-disposition: attachment stated
649 $isFF = check_browser_version('Firefox', '1.5'); // only FF > 1.5 properly tested
650 $mimetype = ($forcedownload and !$isFF) ?
'application/x-forcedownload' :
651 ($mimetype ?
$mimetype : mimeinfo('type', $filename));
652 $lastmodified = $pathisstring ?
time() : filemtime($path);
653 $filesize = $pathisstring ?
strlen($path) : filesize($path);
656 //Adobe Acrobat Reader XSS prevention
657 if ($mimetype=='application/pdf' or mimeinfo('type', $filename)=='application/pdf') {
658 //please note that it prevents opening of pdfs in browser when http referer disabled
659 //or file linked from another site; browser caching of pdfs is now disabled too
660 if (!empty($_SERVER['HTTP_RANGE'])) {
661 //already byteserving
662 $lifetime = 1; // >0 needed for byteserving
663 } else if (empty($_SERVER['HTTP_REFERER']) or strpos($_SERVER['HTTP_REFERER'], $CFG->wwwroot)!==0) {
664 $mimetype = 'application/x-forcedownload';
665 $forcedownload = true;
668 $lifetime = 1; // >0 needed for byteserving
673 //IE compatibiltiy HACK!
674 if (ini_get('zlib.output_compression')) {
675 ini_set('zlib.output_compression', 'Off');
678 //try to disable automatic sid rewrite in cookieless mode
679 @ini_set
("session.use_trans_sid", "false");
681 //do not put '@' before the next header to detect incorrect moodle configurations,
682 //error should be better than "weird" empty lines for admins/users
683 //TODO: should we remove all those @ before the header()? Are all of the values supported on all servers?
684 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
686 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
687 if (check_browser_version('MSIE')) {
688 $filename = rawurlencode($filename);
691 if ($forcedownload) {
692 @header
('Content-Disposition: attachment; filename="'.$filename.'"');
694 @header
('Content-Disposition: inline; filename="'.$filename.'"');
698 @header
('Cache-Control: max-age='.$lifetime);
699 @header
('Expires: '. gmdate('D, d M Y H:i:s', time() +
$lifetime) .' GMT');
702 if (empty($CFG->disablebyteserving
) && !$pathisstring && $mimetype != 'text/plain' && $mimetype != 'text/html') {
704 @header
('Accept-Ranges: bytes');
706 if (!empty($_SERVER['HTTP_RANGE']) && strpos($_SERVER['HTTP_RANGE'],'bytes=') !== FALSE) {
707 // byteserving stuff - for acrobat reader and download accelerators
708 // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
709 // inspired by: http://www.coneural.org/florian/papers/04_byteserving.php
711 if (preg_match_all('/(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER
)) {
712 foreach ($ranges as $key=>$value) {
713 if ($ranges[$key][1] == '') {
715 $ranges[$key][1] = $filesize - $ranges[$key][2];
716 $ranges[$key][2] = $filesize - 1;
717 } else if ($ranges[$key][2] == '' ||
$ranges[$key][2] > $filesize - 1) {
719 $ranges[$key][2] = $filesize - 1;
721 if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
722 //invalid byte-range ==> ignore header
726 //prepare multipart header
727 $ranges[$key][0] = "\r\n--".BYTESERVING_BOUNDARY
."\r\nContent-Type: $mimetype\r\n";
728 $ranges[$key][0] .= "Content-Range: bytes {$ranges[$key][1]}-{$ranges[$key][2]}/$filesize\r\n\r\n";
734 byteserving_send_file($path, $mimetype, $ranges);
738 /// Do not byteserve (disabled, strings, text and html files).
739 @header
('Accept-Ranges: none');
741 } else { // Do not cache files in proxies and browsers
742 if (strpos($CFG->wwwroot
, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
743 @header
('Cache-Control: max-age=10');
744 @header
('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
746 } else { //normal http - prevent caching at all cost
747 @header
('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
748 @header
('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
749 @header
('Pragma: no-cache');
751 @header
('Accept-Ranges: none'); // Do not allow byteserving when caching disabled
754 if (empty($filter)) {
755 if ($mimetype == 'text/html' && !empty($CFG->usesid
) && empty($_COOKIE['MoodleSession'.$CFG->sessioncookie
])) {
756 //cookieless mode - rewrite links
757 @header
('Content-Type: text/html');
758 $path = $pathisstring ?
$path : implode('', file($path));
759 $path = sid_ob_rewrite($path);
760 $filesize = strlen($path);
761 $pathisstring = true;
762 } else if ($mimetype == 'text/plain') {
763 @header
('Content-Type: Text/plain; charset=utf-8'); //add encoding
765 @header
('Content-Type: '.$mimetype);
767 @header
('Content-Length: '.$filesize);
768 while (@ob_end_flush
()); //flush the buffers - save memory and disable sid rewrite
772 readfile_chunked($path);
774 } else { // Try to put the file through filters
775 if ($mimetype == 'text/html') {
776 $options = new object();
777 $options->noclean
= true;
778 $options->nocache
= true; // temporary workaround for MDL-5136
779 $text = $pathisstring ?
$path : implode('', file($path));
781 $text = file_modify_html_header($text);
782 $output = format_text($text, FORMAT_HTML
, $options, $COURSE->id
);
783 if (!empty($CFG->usesid
) && empty($_COOKIE['MoodleSession'.$CFG->sessioncookie
])) {
784 //cookieless mode - rewrite links
785 $output = sid_ob_rewrite($output);
788 @header
('Content-Length: '.strlen($output));
789 @header
('Content-Type: text/html');
790 while (@ob_end_flush
()); //flush the buffers - save memory and disable sid rewrite
792 // only filter text if filter all files is selected
793 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
794 $options = new object();
795 $options->newlines
= false;
796 $options->noclean
= true;
797 $text = htmlentities($pathisstring ?
$path : implode('', file($path)));
798 $output = '<pre>'. format_text($text, FORMAT_MOODLE
, $options, $COURSE->id
) .'</pre>';
799 if (!empty($CFG->usesid
) && empty($_COOKIE['MoodleSession'.$CFG->sessioncookie
])) {
800 //cookieless mode - rewrite links
801 $output = sid_ob_rewrite($output);
804 @header
('Content-Length: '.strlen($output));
805 @header
('Content-Type: text/html; charset=utf-8'); //add encoding
806 while (@ob_end_flush
()); //flush the buffers - save memory and disable sid rewrite
808 } else { // Just send it out raw
809 @header
('Content-Length: '.$filesize);
810 @header
('Content-Type: '.$mimetype);
811 while (@ob_end_flush
()); //flush the buffers - save memory and disable sid rewrite
815 readfile_chunked($path);
819 die; //no more chars to output!!!
822 function get_records_csv($file, $table) {
825 if (!$metacolumns = $db->MetaColumns($CFG->prefix
. $table)) {
829 if(!($handle = @fopen
($file, 'r'))) {
830 error('get_records_csv failed to open '.$file);
833 $fieldnames = fgetcsv($handle, 4096);
834 if(empty($fieldnames)) {
841 foreach($metacolumns as $metacolumn) {
842 $ord = array_search($metacolumn->name
, $fieldnames);
844 $columns[$metacolumn->name
] = $ord;
850 while (($data = fgetcsv($handle, 4096)) !== false) {
851 $item = new stdClass
;
852 foreach($columns as $name => $ord) {
853 $item->$name = $data[$ord];
862 function put_records_csv($file, $records, $table = NULL) {
865 if (empty($records)) {
870 if ($table !== NULL && !$metacolumns = $db->MetaColumns($CFG->prefix
. $table)) {
876 if(!($fp = @fopen
($CFG->dataroot
.'/temp/'.$file, 'w'))) {
877 error('put_records_csv failed to open '.$file);
880 $proto = reset($records);
881 if(is_object($proto)) {
882 $fields_records = array_keys(get_object_vars($proto));
884 else if(is_array($proto)) {
885 $fields_records = array_keys($proto);
892 if(!empty($metacolumns)) {
893 $fields_table = array_map(create_function('$a', 'return $a->name;'), $metacolumns);
894 $fields = array_intersect($fields_records, $fields_table);
897 $fields = $fields_records;
900 fwrite($fp, implode(',', $fields));
903 foreach($records as $record) {
904 $array = (array)$record;
906 foreach($fields as $field) {
907 if(strpos($array[$field], ',')) {
908 $values[] = '"'.str_replace('"', '\"', $array[$field]).'"';
911 $values[] = $array[$field];
914 fwrite($fp, implode(',', $values)."\r\n");
923 * Recursively delete the file or folder with path $location. That is,
924 * if it is a file delete it. If it is a folder, delete all its content
925 * then delete it. If $location does not exist to start, that is not
926 * considered an error.
928 * @param $location the path to remove.
930 function fulldelete($location) {
931 if (is_dir($location)) {
932 $currdir = opendir($location);
933 while (false !== ($file = readdir($currdir))) {
934 if ($file <> ".." && $file <> ".") {
935 $fullfile = $location."/".$file;
936 if (is_dir($fullfile)) {
937 if (!fulldelete($fullfile)) {
941 if (!unlink($fullfile)) {
948 if (! rmdir($location)) {
952 } else if (file_exists($location)) {
953 if (!unlink($location)) {
961 * Improves memory consumptions and works around buggy readfile() in PHP 5.0.4 (2MB readfile limit).
963 function readfile_chunked($filename, $retbytes=true) {
964 $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
967 $handle = fopen($filename, 'rb');
968 if ($handle === false) {
972 while (!feof($handle)) {
973 @set_time_limit
(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
974 $buffer = fread($handle, $chunksize);
978 $cnt +
= strlen($buffer);
981 $status = fclose($handle);
982 if ($retbytes && $status) {
983 return $cnt; // return num. bytes delivered like readfile() does.
989 * Send requested byterange of file.
991 function byteserving_send_file($filename, $mimetype, $ranges) {
992 $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
993 $handle = fopen($filename, 'rb');
994 if ($handle === false) {
997 if (count($ranges) == 1) { //only one range requested
998 $length = $ranges[0][2] - $ranges[0][1] +
1;
999 @header
('HTTP/1.1 206 Partial content');
1000 @header
('Content-Length: '.$length);
1001 @header
('Content-Range: bytes '.$ranges[0][1].'-'.$ranges[0][2].'/'.filesize($filename));
1002 @header
('Content-Type: '.$mimetype);
1003 while (@ob_end_flush
()); //flush the buffers - save memory and disable sid rewrite
1005 fseek($handle, $ranges[0][1]);
1006 while (!feof($handle) && $length > 0) {
1007 @set_time_limit
(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
1008 $buffer = fread($handle, ($chunksize < $length ?
$chunksize : $length));
1011 $length -= strlen($buffer);
1015 } else { // multiple ranges requested - not tested much
1017 foreach($ranges as $range) {
1018 $totallength +
= strlen($range[0]) +
$range[2] - $range[1] +
1;
1020 $totallength +
= strlen("\r\n--".BYTESERVING_BOUNDARY
."--\r\n");
1021 @header
('HTTP/1.1 206 Partial content');
1022 @header
('Content-Length: '.$totallength);
1023 @header
('Content-Type: multipart/byteranges; boundary='.BYTESERVING_BOUNDARY
);
1024 //TODO: check if "multipart/x-byteranges" is more compatible with current readers/browsers/servers
1025 while (@ob_end_flush
()); //flush the buffers - save memory and disable sid rewrite
1026 foreach($ranges as $range) {
1027 $length = $range[2] - $range[1] +
1;
1030 fseek($handle, $range[1]);
1031 while (!feof($handle) && $length > 0) {
1032 @set_time_limit
(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
1033 $buffer = fread($handle, ($chunksize < $length ?
$chunksize : $length));
1036 $length -= strlen($buffer);
1039 echo "\r\n--".BYTESERVING_BOUNDARY
."--\r\n";
1046 * add includes (js and css) into uploaded files
1047 * before returning them, useful for themes and utf.js includes
1048 * @param string text - text to search and replace
1049 * @return string - text with added head includes
1051 function file_modify_html_header($text) {
1052 // first look for <head> tag
1055 $stylesheetshtml = '';
1056 foreach ($CFG->stylesheets
as $stylesheet) {
1057 $stylesheetshtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
1060 $filters = explode(",", $CFG->textfilters
);
1061 if (in_array('filter/mediaplugin', $filters)) {
1062 // this script is needed by most media filter plugins.
1063 $ufo = "\n".'<script type="text/javascript" src="'.$CFG->wwwroot
.'/lib/ufo.js"></script>'."\n";
1068 preg_match('/\<head\>|\<HEAD\>/', $text, $matches);
1070 $replacement = '<head>'.$ufo.$stylesheetshtml;
1071 $text = preg_replace('/\<head\>|\<HEAD\>/', $replacement, $text, 1);
1075 // if not, look for <html> tag, and stick <head> right after
1076 preg_match('/\<html\>|\<HTML\>/', $text, $matches);
1078 // replace <html> tag with <html><head>includes</head>
1079 $replacement = '<html>'."\n".'<head>'.$ufo.$stylesheetshtml.'</head>';
1080 $text = preg_replace('/\<html\>|\<HTML\>/', $replacement, $text, 1);
1084 // if not, look for <body> tag, and stick <head> before body
1085 preg_match('/\<body\>|\<BODY\>/', $text, $matches);
1087 $replacement = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".'<body>';
1088 $text = preg_replace('/\<body\>|\<BODY\>/', $replacement, $text, 1);
1092 // if not, just stick a <head> tag at the beginning
1093 $text = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".$text;