(no commit message)
[moodle.git] / lib / filelib.php
CommitLineData
599f38f9 1<?php //$Id$
2
8ee88311 3require_once($CFG->libdir.'/libcurlemu/libcurlemu.inc.php'); // might be moved to setup.php later
4
4c8c65ec 5define('BYTESERVING_BOUNDARY', 's1k2o3d4a5k6s7'); //unique string constant
6
8ee88311 7/**
8 * Fetches content of file from Internet (using proxy if defined).
9 *
10 * @return mixed false if request failed or content of the file as string if ok.
11 */
12function download_file_content($url) {
13 $ch = curl_init($url);
14 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
15 curl_setopt($ch, CURLOPT_HEADER, false);
16 if (!empty($CFG->proxyhost)) {
17 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, true);
18 if (empty($CFG->proxyport)) {
19 curl_setopt($ch, CURLOPT_PROXY, $CFG->proxy);
20 } else {
21 curl_setopt($ch, CURLOPT_PROXY, $CFG->proxy.':'.$CFG->proxyport);
22 }
23 if(!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) {
24 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $CFG->proxyuser.':'.$CFG->proxypassword);
25 }
26 }
27 $result = curl_exec($ch);
28 curl_close($ch);
29 return $result;
30}
31
3ce73b14 32/**
76ca1ff1 33 * @return List of information about file types based on extensions.
3ce73b14 34 * Associative array of extension (lower-case) to associative array
35 * from 'element name' to data. Current element names are 'type' and 'icon'.
76ca1ff1 36 * Unknown types should use the 'xxx' entry which includes defaults.
3ce73b14 37 */
38function get_mimetypes_array() {
39 return array (
a370c895 40 'xxx' => array ('type'=>'document/unknown', 'icon'=>'unknown.gif'),
41 '3gp' => array ('type'=>'video/quicktime', 'icon'=>'video.gif'),
42 'ai' => array ('type'=>'application/postscript', 'icon'=>'image.gif'),
43 'aif' => array ('type'=>'audio/x-aiff', 'icon'=>'audio.gif'),
44 'aiff' => array ('type'=>'audio/x-aiff', 'icon'=>'audio.gif'),
45 'aifc' => array ('type'=>'audio/x-aiff', 'icon'=>'audio.gif'),
46 'applescript' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
47 'asc' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
18bf47ef 48 'asm' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
a370c895 49 'au' => array ('type'=>'audio/au', 'icon'=>'audio.gif'),
50 'avi' => array ('type'=>'video/x-ms-wm', 'icon'=>'avi.gif'),
51 'bmp' => array ('type'=>'image/bmp', 'icon'=>'image.gif'),
18bf47ef 52 'c' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
a370c895 53 'cct' => array ('type'=>'shockwave/director', 'icon'=>'flash.gif'),
18bf47ef 54 'cpp' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
a370c895 55 'cs' => array ('type'=>'application/x-csh', 'icon'=>'text.gif'),
76ca1ff1 56 'css' => array ('type'=>'text/css', 'icon'=>'text.gif'),
6ae5e482 57 'csv' => array ('type'=>'text/csv', 'icon'=>'excel.gif'),
a370c895 58 'dv' => array ('type'=>'video/x-dv', 'icon'=>'video.gif'),
609d84e3 59 'dmg' => array ('type'=>'application/octet-stream', 'icon'=>'dmg.gif'),
a370c895 60 'doc' => array ('type'=>'application/msword', 'icon'=>'word.gif'),
68da9722 61 'docx' => array ('type'=>'application/msword', 'icon'=>'docx.gif'),
62 'docm' => array ('type'=>'application/msword', 'icon'=>'docm.gif'),
63 'dotx' => array ('type'=>'application/msword', 'icon'=>'dotx.gif'),
a370c895 64 'dcr' => array ('type'=>'application/x-director', 'icon'=>'flash.gif'),
65 'dif' => array ('type'=>'video/x-dv', 'icon'=>'video.gif'),
66 'dir' => array ('type'=>'application/x-director', 'icon'=>'flash.gif'),
67 'dxr' => array ('type'=>'application/x-director', 'icon'=>'flash.gif'),
68 'eps' => array ('type'=>'application/postscript', 'icon'=>'pdf.gif'),
ee7f231d 69 'fdf' => array ('type'=>'application/pdf', 'icon'=>'pdf.gif'),
759bc3c8 70 'flv' => array ('type'=>'video/x-flv', 'icon'=>'video.gif'),
a370c895 71 'gif' => array ('type'=>'image/gif', 'icon'=>'image.gif'),
72 'gtar' => array ('type'=>'application/x-gtar', 'icon'=>'zip.gif'),
759bc3c8 73 'tgz' => array ('type'=>'application/g-zip', 'icon'=>'zip.gif'),
a370c895 74 'gz' => array ('type'=>'application/g-zip', 'icon'=>'zip.gif'),
75 'gzip' => array ('type'=>'application/g-zip', 'icon'=>'zip.gif'),
76 'h' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
18bf47ef 77 'hpp' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
a370c895 78 'hqx' => array ('type'=>'application/mac-binhex40', 'icon'=>'zip.gif'),
70ee2841 79 'htc' => array ('type'=>'text/x-component', 'icon'=>'text.gif'),
a370c895 80 'html' => array ('type'=>'text/html', 'icon'=>'html.gif'),
1659a998 81 'xhtml'=> array ('type'=>'application/xhtml+xml', 'icon'=>'html.gif'),
a370c895 82 'htm' => array ('type'=>'text/html', 'icon'=>'html.gif'),
08297dcb 83 'ico' => array ('type'=>'image/vnd.microsoft.icon', 'icon'=>'image.gif'),
84 'isf' => array ('type'=>'application/inspiration', 'icon'=>'isf.gif'),
85 'ist' => array ('type'=>'application/inspiration.template', 'icon'=>'isf.gif'),
18bf47ef 86 'java' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
a00420fb 87 'jcb' => array ('type'=>'text/xml', 'icon'=>'jcb.gif'),
88 'jcl' => array ('type'=>'text/xml', 'icon'=>'jcl.gif'),
89 'jcw' => array ('type'=>'text/xml', 'icon'=>'jcw.gif'),
90 'jmt' => array ('type'=>'text/xml', 'icon'=>'jmt.gif'),
91 'jmx' => array ('type'=>'text/xml', 'icon'=>'jmx.gif'),
a370c895 92 'jpe' => array ('type'=>'image/jpeg', 'icon'=>'image.gif'),
93 'jpeg' => array ('type'=>'image/jpeg', 'icon'=>'image.gif'),
94 'jpg' => array ('type'=>'image/jpeg', 'icon'=>'image.gif'),
a00420fb 95 'jqz' => array ('type'=>'text/xml', 'icon'=>'jqz.gif'),
a370c895 96 'js' => array ('type'=>'application/x-javascript', 'icon'=>'text.gif'),
97 'latex'=> array ('type'=>'application/x-latex', 'icon'=>'text.gif'),
98 'm' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
99 'mov' => array ('type'=>'video/quicktime', 'icon'=>'video.gif'),
100 'movie'=> array ('type'=>'video/x-sgi-movie', 'icon'=>'video.gif'),
101 'm3u' => array ('type'=>'audio/x-mpegurl', 'icon'=>'audio.gif'),
102 'mp3' => array ('type'=>'audio/mp3', 'icon'=>'audio.gif'),
103 'mp4' => array ('type'=>'video/mp4', 'icon'=>'video.gif'),
104 'mpeg' => array ('type'=>'video/mpeg', 'icon'=>'video.gif'),
105 'mpe' => array ('type'=>'video/mpeg', 'icon'=>'video.gif'),
106 'mpg' => array ('type'=>'video/mpeg', 'icon'=>'video.gif'),
5395334d 107
108 'odt' => array ('type'=>'application/vnd.oasis.opendocument.text', 'icon'=>'odt.gif'),
109 'ott' => array ('type'=>'application/vnd.oasis.opendocument.text-template', 'icon'=>'odt.gif'),
110 'oth' => array ('type'=>'application/vnd.oasis.opendocument.text-web', 'icon'=>'odt.gif'),
e10bc440 111 'odm' => array ('type'=>'application/vnd.oasis.opendocument.text-master', 'icon'=>'odm.gif'),
112 'odg' => array ('type'=>'application/vnd.oasis.opendocument.graphics', 'icon'=>'odg.gif'),
113 'otg' => array ('type'=>'application/vnd.oasis.opendocument.graphics-template', 'icon'=>'odg.gif'),
114 'odp' => array ('type'=>'application/vnd.oasis.opendocument.presentation', 'icon'=>'odp.gif'),
115 'otp' => array ('type'=>'application/vnd.oasis.opendocument.presentation-template', 'icon'=>'odp.gif'),
116 'ods' => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet', 'icon'=>'ods.gif'),
117 'ots' => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet-template', 'icon'=>'ods.gif'),
118 'odc' => array ('type'=>'application/vnd.oasis.opendocument.chart', 'icon'=>'odc.gif'),
119 'odf' => array ('type'=>'application/vnd.oasis.opendocument.formula', 'icon'=>'odf.gif'),
120 'odb' => array ('type'=>'application/vnd.oasis.opendocument.database', 'icon'=>'odb.gif'),
121 'odi' => array ('type'=>'application/vnd.oasis.opendocument.image', 'icon'=>'odi.gif'),
5395334d 122
a370c895 123 'pct' => array ('type'=>'image/pict', 'icon'=>'image.gif'),
124 'pdf' => array ('type'=>'application/pdf', 'icon'=>'pdf.gif'),
125 'php' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
126 'pic' => array ('type'=>'image/pict', 'icon'=>'image.gif'),
127 'pict' => array ('type'=>'image/pict', 'icon'=>'image.gif'),
128 'png' => array ('type'=>'image/png', 'icon'=>'image.gif'),
129 'pps' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'powerpoint.gif'),
130 'ppt' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'powerpoint.gif'),
68da9722 131 'pptx' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'pptx.gif'),
132 'pptm' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'pptm.gif'),
133 'potx' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'potx.gif'),
134 'potm' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'potm.gif'),
135 'ppam' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'ppam.gif'),
136 'ppsx' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'ppsx.gif'),
137 'ppsm' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'ppsm.gif'),
a370c895 138 'ps' => array ('type'=>'application/postscript', 'icon'=>'pdf.gif'),
139 'qt' => array ('type'=>'video/quicktime', 'icon'=>'video.gif'),
140 'ra' => array ('type'=>'audio/x-realaudio', 'icon'=>'audio.gif'),
141 'ram' => array ('type'=>'audio/x-pn-realaudio', 'icon'=>'audio.gif'),
a00420fb 142 'rhb' => array ('type'=>'text/xml', 'icon'=>'xml.gif'),
a370c895 143 'rm' => array ('type'=>'audio/x-pn-realaudio', 'icon'=>'audio.gif'),
144 'rtf' => array ('type'=>'text/rtf', 'icon'=>'text.gif'),
145 'rtx' => array ('type'=>'text/richtext', 'icon'=>'text.gif'),
146 'sh' => array ('type'=>'application/x-sh', 'icon'=>'text.gif'),
147 'sit' => array ('type'=>'application/x-stuffit', 'icon'=>'zip.gif'),
148 'smi' => array ('type'=>'application/smil', 'icon'=>'text.gif'),
149 'smil' => array ('type'=>'application/smil', 'icon'=>'text.gif'),
a00420fb 150 'sqt' => array ('type'=>'text/xml', 'icon'=>'xml.gif'),
4db69ffb 151 'svg' => array ('type'=>'image/svg+xml', 'icon'=>'image.gif'),
152 'svgz' => array ('type'=>'image/svg+xml', 'icon'=>'image.gif'),
a370c895 153 'swa' => array ('type'=>'application/x-director', 'icon'=>'flash.gif'),
154 'swf' => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash.gif'),
155 'swfl' => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash.gif'),
5395334d 156
157 'sxw' => array ('type'=>'application/vnd.sun.xml.writer', 'icon'=>'odt.gif'),
158 'stw' => array ('type'=>'application/vnd.sun.xml.writer.template', 'icon'=>'odt.gif'),
159 'sxc' => array ('type'=>'application/vnd.sun.xml.calc', 'icon'=>'odt.gif'),
160 'stc' => array ('type'=>'application/vnd.sun.xml.calc.template', 'icon'=>'odt.gif'),
161 'sxd' => array ('type'=>'application/vnd.sun.xml.draw', 'icon'=>'odt.gif'),
162 'std' => array ('type'=>'application/vnd.sun.xml.draw.template', 'icon'=>'odt.gif'),
163 'sxi' => array ('type'=>'application/vnd.sun.xml.impress', 'icon'=>'odt.gif'),
164 'sti' => array ('type'=>'application/vnd.sun.xml.impress.template', 'icon'=>'odt.gif'),
165 'sxg' => array ('type'=>'application/vnd.sun.xml.writer.global', 'icon'=>'odt.gif'),
166 'sxm' => array ('type'=>'application/vnd.sun.xml.math', 'icon'=>'odt.gif'),
167
a370c895 168 'tar' => array ('type'=>'application/x-tar', 'icon'=>'zip.gif'),
169 'tif' => array ('type'=>'image/tiff', 'icon'=>'image.gif'),
170 'tiff' => array ('type'=>'image/tiff', 'icon'=>'image.gif'),
171 'tex' => array ('type'=>'application/x-tex', 'icon'=>'text.gif'),
172 'texi' => array ('type'=>'application/x-texinfo', 'icon'=>'text.gif'),
173 'texinfo' => array ('type'=>'application/x-texinfo', 'icon'=>'text.gif'),
174 'tsv' => array ('type'=>'text/tab-separated-values', 'icon'=>'text.gif'),
175 'txt' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
176 'wav' => array ('type'=>'audio/wav', 'icon'=>'audio.gif'),
177 'wmv' => array ('type'=>'video/x-ms-wmv', 'icon'=>'avi.gif'),
178 'asf' => array ('type'=>'video/x-ms-asf', 'icon'=>'avi.gif'),
ee7f231d 179 'xdp' => array ('type'=>'application/pdf', 'icon'=>'pdf.gif'),
180 'xfd' => array ('type'=>'application/pdf', 'icon'=>'pdf.gif'),
181 'xfdf' => array ('type'=>'application/pdf', 'icon'=>'pdf.gif'),
a370c895 182 'xls' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'excel.gif'),
68da9722 183 'xlsx' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'xlsx.gif'),
184 'xlsm' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'xlsm.gif'),
185 'xltx' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'xltx.gif'),
186 'xltm' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'xltm.gif'),
187 'xlsb' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'xlsb.gif'),
188 'xlam' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'xlam.gif'),
a370c895 189 'xml' => array ('type'=>'application/xml', 'icon'=>'xml.gif'),
190 'xsl' => array ('type'=>'text/xml', 'icon'=>'xml.gif'),
191 'zip' => array ('type'=>'application/zip', 'icon'=>'zip.gif')
f1e0649c 192 );
3ce73b14 193}
194
76ca1ff1 195/**
3ce73b14 196 * Obtains information about a filetype based on its extension. Will
197 * use a default if no information is present about that particular
198 * extension.
76ca1ff1 199 * @param string $element Desired information (usually 'icon'
3ce73b14 200 * for icon filename or 'type' for MIME type)
76ca1ff1 201 * @param string $filename Filename we're looking up
3ce73b14 202 * @return string Requested piece of information from array
203 */
204function mimeinfo($element, $filename) {
205 static $mimeinfo;
206 $mimeinfo=get_mimetypes_array();
f1e0649c 207
a370c895 208 if (eregi('\.([a-z0-9]+)$', $filename, $match)) {
f1e0649c 209 if (isset($mimeinfo[strtolower($match[1])][$element])) {
210 return $mimeinfo[strtolower($match[1])][$element];
211 } else {
a370c895 212 return $mimeinfo['xxx'][$element]; // By default
f1e0649c 213 }
214 } else {
a370c895 215 return $mimeinfo['xxx'][$element]; // By default
f1e0649c 216 }
217}
218
76ca1ff1 219/**
3ce73b14 220 * Obtains information about a filetype based on the MIME type rather than
221 * the other way around.
222 * @param string $element Desired information (usually 'icon')
76ca1ff1 223 * @param string $mimetype MIME type we're looking up
3ce73b14 224 * @return string Requested piece of information from array
225 */
226function mimeinfo_from_type($element, $mimetype) {
227 static $mimeinfo;
228 $mimeinfo=get_mimetypes_array();
76ca1ff1 229
3ce73b14 230 foreach($mimeinfo as $values) {
231 if($values['type']==$mimetype) {
232 if(isset($values[$element])) {
233 return $values[$element];
234 }
235 break;
236 }
237 }
238 return $mimeinfo['xxx'][$element]; // Default
239}
b9709b76 240
42ead7d7 241/**
242 * Get information about a filetype based on the icon file.
243 * @param string $element Desired information (usually 'icon')
244 * @param string $icon Icon file path.
245 * @return string Requested piece of information from array
246 */
247function mimeinfo_from_icon($element, $icon) {
248 static $mimeinfo;
249 $mimeinfo=get_mimetypes_array();
250
251 if (preg_match("/\/(.*)/", $icon, $matches)) {
252 $icon = $matches[1];
253 }
254 $info = $mimeinfo['xxx'][$element]; // Default
255 foreach($mimeinfo as $values) {
256 if($values['icon']==$icon) {
257 if(isset($values[$element])) {
258 $info = $values[$element];
259 }
260 //No break, for example for 'excel.gif' we don't want 'csv'!
261 }
262 }
263 return $info;
264}
265
c0381e22 266/**
76ca1ff1 267 * Obtains descriptions for file types (e.g. 'Microsoft Word document') from the
268 * mimetypes.php language file.
c0381e22 269 * @param string $mimetype MIME type (can be obtained using the mimeinfo function)
270 * @param bool $capitalise If true, capitalises first character of result
76ca1ff1 271 * @return string Text description
c0381e22 272 */
273function get_mimetype_description($mimetype,$capitalise=false) {
274 $result=get_string($mimetype,'mimetypes');
275 // Surrounded by square brackets indicates that there isn't a string for that
276 // (maybe there is a better way to find this out?)
277 if(strpos($result,'[')===0) {
278 $result=get_string('document/unknown','mimetypes');
76ca1ff1 279 }
c0381e22 280 if($capitalise) {
281 $result=ucfirst($result);
282 }
283 return $result;
284}
285
76ca1ff1 286/**
287 * Handles the sending of file data to the user's browser, including support for
288 * byteranges etc.
ba75ad94 289 * @param string $path Path of file on disk (including real filename), or actual content of file as string
290 * @param string $filename Filename to send
291 * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
292 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
293 * @param bool $pathisstring If true (default false), $path is the content to send and not the pathname
294 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
295 * @param string $mimetype Include to specify the MIME type; leave blank to have it guess the type from $filename
b9709b76 296 */
ba75ad94 297function send_file($path, $filename, $lifetime=86400 , $filter=0, $pathisstring=false, $forcedownload=false, $mimetype='') {
60f9e36e 298 global $CFG, $COURSE;
f1e0649c 299
ba4e0b05 300 // Use given MIME type if specified, otherwise guess it using mimeinfo.
301 // IE, Konqueror and Opera open html file directly in browser from web even when directed to save it to disk :-O
302 // only Firefox saves all files locally before opening when content-disposition: attachment stated
303 $isFF = check_browser_version('Firefox', '1.5'); // only FF > 1.5 properly tested
76ca1ff1 304 $mimetype = ($forcedownload and !$isFF) ? 'application/x-forcedownload' :
ba4e0b05 305 ($mimetype ? $mimetype : mimeinfo('type', $filename));
f1e0649c 306 $lastmodified = $pathisstring ? time() : filemtime($path);
307 $filesize = $pathisstring ? strlen($path) : filesize($path);
308
ee7f231d 309 //Adobe Acrobat Reader XSS prevention
310 if ($mimetype=='application/pdf' or mimeinfo('type', $filename)=='application/pdf') {
311 //please note that it prevents opening of pdfs in browser when http referer disabled
312 //or file linked from another site; browser caching of pdfs is now disabled too
c57d8874 313 if (!empty($_SERVER['HTTP_RANGE'])) {
314 //already byteserving
76ca1ff1 315 $lifetime = 1; // >0 needed for byteserving
c57d8874 316 } else if (empty($_SERVER['HTTP_REFERER']) or strpos($_SERVER['HTTP_REFERER'], $CFG->wwwroot)!==0) {
ee7f231d 317 $mimetype = 'application/x-forcedownload';
318 $forcedownload = true;
319 $lifetime = 0;
320 } else {
76ca1ff1 321 $lifetime = 1; // >0 needed for byteserving
ee7f231d 322 }
b8806ccc 323 }
f3f7610c 324
69faecce 325 //IE compatibiltiy HACK!
4c8c65ec 326 if (ini_get('zlib.output_compression')) {
69faecce 327 ini_set('zlib.output_compression', 'Off');
328 }
329
4c8c65ec 330 //try to disable automatic sid rewrite in cookieless mode
8914cb82 331 @ini_set("session.use_trans_sid", "false");
4c8c65ec 332
333 //do not put '@' before the next header to detect incorrect moodle configurations,
334 //error should be better than "weird" empty lines for admins/users
335 //TODO: should we remove all those @ before the header()? Are all of the values supported on all servers?
336 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
337
338 if ($forcedownload) {
339 @header('Content-Disposition: attachment; filename='.$filename);
340 } else {
341 @header('Content-Disposition: inline; filename='.$filename);
342 }
343
f1e0649c 344 if ($lifetime > 0) {
4c8c65ec 345 @header('Cache-Control: max-age='.$lifetime);
346 @header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
f1e0649c 347 @header('Pragma: ');
4c8c65ec 348
349 if (empty($CFG->disablebyteserving) && !$pathisstring && $mimetype != 'text/plain' && $mimetype != 'text/html') {
350
351 @header('Accept-Ranges: bytes');
352
353 if (!empty($_SERVER['HTTP_RANGE']) && strpos($_SERVER['HTTP_RANGE'],'bytes=') !== FALSE) {
354 // byteserving stuff - for acrobat reader and download accelerators
355 // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
356 // inspired by: http://www.coneural.org/florian/papers/04_byteserving.php
357 $ranges = false;
358 if (preg_match_all('/(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER)) {
359 foreach ($ranges as $key=>$value) {
360 if ($ranges[$key][1] == '') {
361 //suffix case
362 $ranges[$key][1] = $filesize - $ranges[$key][2];
363 $ranges[$key][2] = $filesize - 1;
364 } else if ($ranges[$key][2] == '' || $ranges[$key][2] > $filesize - 1) {
365 //fix range length
366 $ranges[$key][2] = $filesize - 1;
367 }
368 if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
369 //invalid byte-range ==> ignore header
370 $ranges = false;
371 break;
372 }
373 //prepare multipart header
374 $ranges[$key][0] = "\r\n--".BYTESERVING_BOUNDARY."\r\nContent-Type: $mimetype\r\n";
375 $ranges[$key][0] .= "Content-Range: bytes {$ranges[$key][1]}-{$ranges[$key][2]}/$filesize\r\n\r\n";
376 }
377 } else {
378 $ranges = false;
379 }
380 if ($ranges) {
381 byteserving_send_file($path, $mimetype, $ranges);
382 }
383 }
384 } else {
385 /// Do not byteserve (disabled, strings, text and html files).
386 @header('Accept-Ranges: none');
387 }
388 } else { // Do not cache files in proxies and browsers
85e00626 389 if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
390 @header('Cache-Control: max-age=10');
4c8c65ec 391 @header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
85e00626 392 @header('Pragma: ');
393 } else { //normal http - prevent caching at all cost
394 @header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
4c8c65ec 395 @header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
85e00626 396 @header('Pragma: no-cache');
397 }
4c8c65ec 398 @header('Accept-Ranges: none'); // Do not allow byteserving when caching disabled
69faecce 399 }
f1e0649c 400
b9709b76 401 if (empty($filter)) {
4c8c65ec 402 if ($mimetype == 'text/html' && !empty($CFG->usesid) && empty($_COOKIE['MoodleSession'.$CFG->sessioncookie])) {
403 //cookieless mode - rewrite links
404 @header('Content-Type: text/html');
405 $path = $pathisstring ? $path : implode('', file($path));
406 $path = sid_ob_rewrite($path);
407 $filesize = strlen($path);
408 $pathisstring = true;
409 } else if ($mimetype == 'text/plain') {
810944af 410 @header('Content-Type: Text/plain; charset=utf-8'); //add encoding
f1e0649c 411 } else {
4c8c65ec 412 @header('Content-Type: '.$mimetype);
f1e0649c 413 }
4c8c65ec 414 @header('Content-Length: '.$filesize);
415 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
f1e0649c 416 if ($pathisstring) {
417 echo $path;
4c8c65ec 418 } else {
69faecce 419 readfile_chunked($path);
f1e0649c 420 }
421 } else { // Try to put the file through filters
f1e0649c 422 if ($mimetype == 'text/html') {
a17c57b5 423 $options = new object();
f1e0649c 424 $options->noclean = true;
a17c57b5 425 $options->nocache = true; // temporary workaround for MDL-5136
f1e0649c 426 $text = $pathisstring ? $path : implode('', file($path));
76ca1ff1 427
3ace5ee4 428 $text = file_modify_html_header($text);
60f9e36e 429 $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
4c8c65ec 430 if (!empty($CFG->usesid) && empty($_COOKIE['MoodleSession'.$CFG->sessioncookie])) {
431 //cookieless mode - rewrite links
432 $output = sid_ob_rewrite($output);
433 }
f1e0649c 434
4c8c65ec 435 @header('Content-Length: '.strlen($output));
436 @header('Content-Type: text/html');
437 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
f1e0649c 438 echo $output;
b9709b76 439 // only filter text if filter all files is selected
440 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
60f9e36e 441 $options = new object();
f1e0649c 442 $options->newlines = false;
443 $options->noclean = true;
444 $text = htmlentities($pathisstring ? $path : implode('', file($path)));
60f9e36e 445 $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
4c8c65ec 446 if (!empty($CFG->usesid) && empty($_COOKIE['MoodleSession'.$CFG->sessioncookie])) {
447 //cookieless mode - rewrite links
448 $output = sid_ob_rewrite($output);
449 }
f1e0649c 450
4c8c65ec 451 @header('Content-Length: '.strlen($output));
810944af 452 @header('Content-Type: text/html; charset=utf-8'); //add encoding
4c8c65ec 453 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
f1e0649c 454 echo $output;
455 } else { // Just send it out raw
4c8c65ec 456 @header('Content-Length: '.$filesize);
457 @header('Content-Type: '.$mimetype);
458 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
f1e0649c 459 if ($pathisstring) {
460 echo $path;
461 }else {
69faecce 462 readfile_chunked($path);
f1e0649c 463 }
464 }
465 }
466 die; //no more chars to output!!!
467}
468
a43b5308 469function get_records_csv($file, $table) {
599f38f9 470 global $CFG, $db;
471
472 if (!$metacolumns = $db->MetaColumns($CFG->prefix . $table)) {
473 return false;
474 }
475
a77b98eb 476 if(!($handle = @fopen($file, 'r'))) {
599f38f9 477 error('get_records_csv failed to open '.$file);
478 }
479
480 $fieldnames = fgetcsv($handle, 4096);
481 if(empty($fieldnames)) {
482 fclose($handle);
483 return false;
484 }
485
486 $columns = array();
487
488 foreach($metacolumns as $metacolumn) {
489 $ord = array_search($metacolumn->name, $fieldnames);
490 if(is_int($ord)) {
491 $columns[$metacolumn->name] = $ord;
492 }
493 }
494
495 $rows = array();
496
497 while (($data = fgetcsv($handle, 4096)) !== false) {
498 $item = new stdClass;
499 foreach($columns as $name => $ord) {
500 $item->$name = $data[$ord];
501 }
502 $rows[] = $item;
503 }
504
505 fclose($handle);
506 return $rows;
507}
508
a77b98eb 509function put_records_csv($file, $records, $table = NULL) {
510 global $CFG, $db;
511
a1e93da2 512 if (empty($records)) {
a77b98eb 513 return true;
514 }
515
516 $metacolumns = NULL;
517 if ($table !== NULL && !$metacolumns = $db->MetaColumns($CFG->prefix . $table)) {
518 return false;
519 }
520
a1e93da2 521 echo "x";
522
a77b98eb 523 if(!($fp = @fopen($CFG->dataroot.'/temp/'.$file, 'w'))) {
524 error('put_records_csv failed to open '.$file);
525 }
526
a43b5308 527 $proto = reset($records);
528 if(is_object($proto)) {
529 $fields_records = array_keys(get_object_vars($proto));
530 }
531 else if(is_array($proto)) {
532 $fields_records = array_keys($proto);
533 }
534 else {
535 return false;
536 }
a1e93da2 537 echo "x";
a77b98eb 538
539 if(!empty($metacolumns)) {
540 $fields_table = array_map(create_function('$a', 'return $a->name;'), $metacolumns);
541 $fields = array_intersect($fields_records, $fields_table);
542 }
543 else {
544 $fields = $fields_records;
545 }
546
547 fwrite($fp, implode(',', $fields));
548 fwrite($fp, "\r\n");
549
550 foreach($records as $record) {
a43b5308 551 $array = (array)$record;
a77b98eb 552 $values = array();
553 foreach($fields as $field) {
a43b5308 554 if(strpos($array[$field], ',')) {
555 $values[] = '"'.str_replace('"', '\"', $array[$field]).'"';
a77b98eb 556 }
557 else {
a43b5308 558 $values[] = $array[$field];
a77b98eb 559 }
560 }
561 fwrite($fp, implode(',', $values)."\r\n");
562 }
563
564 fclose($fp);
565 return true;
566}
567
f401cc97 568
34763a79 569/**
76ca1ff1 570 * Recursively delete the file or folder with path $location. That is,
34763a79 571 * if it is a file delete it. If it is a folder, delete all its content
76ca1ff1 572 * then delete it. If $location does not exist to start, that is not
573 * considered an error.
574 *
34763a79 575 * @param $location the path to remove.
576 */
4c8c65ec 577function fulldelete($location) {
f401cc97 578 if (is_dir($location)) {
579 $currdir = opendir($location);
580 while (false !== ($file = readdir($currdir))) {
581 if ($file <> ".." && $file <> ".") {
582 $fullfile = $location."/".$file;
4c8c65ec 583 if (is_dir($fullfile)) {
f401cc97 584 if (!fulldelete($fullfile)) {
585 return false;
586 }
587 } else {
588 if (!unlink($fullfile)) {
589 return false;
590 }
4c8c65ec 591 }
f401cc97 592 }
4c8c65ec 593 }
f401cc97 594 closedir($currdir);
595 if (! rmdir($location)) {
596 return false;
597 }
598
34763a79 599 } else if (file_exists($location)) {
f401cc97 600 if (!unlink($location)) {
601 return false;
602 }
603 }
604 return true;
605}
606
4c8c65ec 607/**
608 * Improves memory consumptions and works around buggy readfile() in PHP 5.0.4 (2MB readfile limit).
609 */
610function readfile_chunked($filename, $retbytes=true) {
611 $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
69faecce 612 $buffer = '';
76ca1ff1 613 $cnt =0;
69faecce 614 $handle = fopen($filename, 'rb');
615 if ($handle === false) {
616 return false;
617 }
20371063 618
69faecce 619 while (!feof($handle)) {
68913aec 620 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
69faecce 621 $buffer = fread($handle, $chunksize);
622 echo $buffer;
20371063 623 flush();
69faecce 624 if ($retbytes) {
4c8c65ec 625 $cnt += strlen($buffer);
626 }
69faecce 627 }
628 $status = fclose($handle);
629 if ($retbytes && $status) {
630 return $cnt; // return num. bytes delivered like readfile() does.
631 }
632 return $status;
633}
634
4c8c65ec 635/**
636 * Send requested byterange of file.
637 */
638function byteserving_send_file($filename, $mimetype, $ranges) {
639 $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
640 $handle = fopen($filename, 'rb');
641 if ($handle === false) {
642 die;
643 }
644 if (count($ranges) == 1) { //only one range requested
645 $length = $ranges[0][2] - $ranges[0][1] + 1;
646 @header('HTTP/1.1 206 Partial content');
647 @header('Content-Length: '.$length);
648 @header('Content-Range: bytes '.$ranges[0][1].'-'.$ranges[0][2].'/'.filesize($filename));
649 @header('Content-Type: '.$mimetype);
650 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
651 $buffer = '';
652 fseek($handle, $ranges[0][1]);
653 while (!feof($handle) && $length > 0) {
68913aec 654 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
4c8c65ec 655 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
656 echo $buffer;
657 flush();
658 $length -= strlen($buffer);
659 }
660 fclose($handle);
661 die;
662 } else { // multiple ranges requested - not tested much
663 $totallength = 0;
664 foreach($ranges as $range) {
aba588a7 665 $totallength += strlen($range[0]) + $range[2] - $range[1] + 1;
4c8c65ec 666 }
aba588a7 667 $totallength += strlen("\r\n--".BYTESERVING_BOUNDARY."--\r\n");
4c8c65ec 668 @header('HTTP/1.1 206 Partial content');
669 @header('Content-Length: '.$totallength);
670 @header('Content-Type: multipart/byteranges; boundary='.BYTESERVING_BOUNDARY);
671 //TODO: check if "multipart/x-byteranges" is more compatible with current readers/browsers/servers
672 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
673 foreach($ranges as $range) {
674 $length = $range[2] - $range[1] + 1;
675 echo $range[0];
676 $buffer = '';
677 fseek($handle, $range[1]);
678 while (!feof($handle) && $length > 0) {
68913aec 679 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
4c8c65ec 680 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
681 echo $buffer;
682 flush();
683 $length -= strlen($buffer);
684 }
685 }
686 echo "\r\n--".BYTESERVING_BOUNDARY."--\r\n";
687 fclose($handle);
688 die;
689 }
690}
f401cc97 691
3ace5ee4 692/**
693 * add includes (js and css) into uploaded files
694 * before returning them, useful for themes and utf.js includes
695 * @param string text - text to search and replace
696 * @return string - text with added head includes
697 */
698function file_modify_html_header($text) {
699 // first look for <head> tag
700 global $CFG;
76ca1ff1 701
3ace5ee4 702 $stylesheetshtml = '';
703 foreach ($CFG->stylesheets as $stylesheet) {
704 $stylesheetshtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
76ca1ff1 705 }
706
3ace5ee4 707 $filters = explode(",", $CFG->textfilters);
708 if (in_array('filter/mediaplugin', $filters)) {
76ca1ff1 709 // this script is needed by most media filter plugins.
710 $ufo = "\n".'<script type="text/javascript" src="'.$CFG->wwwroot.'/lib/ufo.js"></script>'."\n";
3ace5ee4 711 } else {
76ca1ff1 712 $ufo = '';
3ace5ee4 713 }
76ca1ff1 714
3ace5ee4 715 preg_match('/\<head\>|\<HEAD\>/', $text, $matches);
716 if ($matches) {
717 $replacement = '<head>'.$ufo.$stylesheetshtml;
718 $text = preg_replace('/\<head\>|\<HEAD\>/', $replacement, $text, 1);
76ca1ff1 719 return $text;
3ace5ee4 720 }
76ca1ff1 721
3ace5ee4 722 // if not, look for <html> tag, and stick <head> right after
723 preg_match('/\<html\>|\<HTML\>/', $text, $matches);
724 if ($matches) {
725 // replace <html> tag with <html><head>includes</head>
13534ef7 726 $replacement = '<html>'."\n".'<head>'.$ufo.$stylesheetshtml.'</head>';
3ace5ee4 727 $text = preg_replace('/\<html\>|\<HTML\>/', $replacement, $text, 1);
76ca1ff1 728 return $text;
3ace5ee4 729 }
76ca1ff1 730
3ace5ee4 731 // if not, look for <body> tag, and stick <head> before body
732 preg_match('/\<body\>|\<BODY\>/', $text, $matches);
733 if ($matches) {
13534ef7 734 $replacement = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".'<body>';
3ace5ee4 735 $text = preg_replace('/\<body\>|\<BODY\>/', $replacement, $text, 1);
76ca1ff1 736 return $text;
737 }
738
3ace5ee4 739 // if not, just stick a <head> tag at the beginning
740 $text = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".$text;
741 return $text;
742}
743
a77b98eb 744?>