MDL-10898 - Option to back up only selected role assignements when backing up a cours...
[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
c0381e22 241/**
76ca1ff1 242 * Obtains descriptions for file types (e.g. 'Microsoft Word document') from the
243 * mimetypes.php language file.
c0381e22 244 * @param string $mimetype MIME type (can be obtained using the mimeinfo function)
245 * @param bool $capitalise If true, capitalises first character of result
76ca1ff1 246 * @return string Text description
c0381e22 247 */
248function get_mimetype_description($mimetype,$capitalise=false) {
249 $result=get_string($mimetype,'mimetypes');
250 // Surrounded by square brackets indicates that there isn't a string for that
251 // (maybe there is a better way to find this out?)
252 if(strpos($result,'[')===0) {
253 $result=get_string('document/unknown','mimetypes');
76ca1ff1 254 }
c0381e22 255 if($capitalise) {
256 $result=ucfirst($result);
257 }
258 return $result;
259}
260
76ca1ff1 261/**
262 * Handles the sending of file data to the user's browser, including support for
263 * byteranges etc.
ba75ad94 264 * @param string $path Path of file on disk (including real filename), or actual content of file as string
265 * @param string $filename Filename to send
266 * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
267 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
268 * @param bool $pathisstring If true (default false), $path is the content to send and not the pathname
269 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
270 * @param string $mimetype Include to specify the MIME type; leave blank to have it guess the type from $filename
b9709b76 271 */
ba75ad94 272function send_file($path, $filename, $lifetime=86400 , $filter=0, $pathisstring=false, $forcedownload=false, $mimetype='') {
60f9e36e 273 global $CFG, $COURSE;
f1e0649c 274
ba4e0b05 275 // Use given MIME type if specified, otherwise guess it using mimeinfo.
276 // IE, Konqueror and Opera open html file directly in browser from web even when directed to save it to disk :-O
277 // only Firefox saves all files locally before opening when content-disposition: attachment stated
278 $isFF = check_browser_version('Firefox', '1.5'); // only FF > 1.5 properly tested
76ca1ff1 279 $mimetype = ($forcedownload and !$isFF) ? 'application/x-forcedownload' :
ba4e0b05 280 ($mimetype ? $mimetype : mimeinfo('type', $filename));
f1e0649c 281 $lastmodified = $pathisstring ? time() : filemtime($path);
282 $filesize = $pathisstring ? strlen($path) : filesize($path);
283
ee7f231d 284 //Adobe Acrobat Reader XSS prevention
285 if ($mimetype=='application/pdf' or mimeinfo('type', $filename)=='application/pdf') {
286 //please note that it prevents opening of pdfs in browser when http referer disabled
287 //or file linked from another site; browser caching of pdfs is now disabled too
c57d8874 288 if (!empty($_SERVER['HTTP_RANGE'])) {
289 //already byteserving
76ca1ff1 290 $lifetime = 1; // >0 needed for byteserving
c57d8874 291 } else if (empty($_SERVER['HTTP_REFERER']) or strpos($_SERVER['HTTP_REFERER'], $CFG->wwwroot)!==0) {
ee7f231d 292 $mimetype = 'application/x-forcedownload';
293 $forcedownload = true;
294 $lifetime = 0;
295 } else {
76ca1ff1 296 $lifetime = 1; // >0 needed for byteserving
ee7f231d 297 }
b8806ccc 298 }
f3f7610c 299
69faecce 300 //IE compatibiltiy HACK!
4c8c65ec 301 if (ini_get('zlib.output_compression')) {
69faecce 302 ini_set('zlib.output_compression', 'Off');
303 }
304
4c8c65ec 305 //try to disable automatic sid rewrite in cookieless mode
8914cb82 306 @ini_set("session.use_trans_sid", "false");
4c8c65ec 307
308 //do not put '@' before the next header to detect incorrect moodle configurations,
309 //error should be better than "weird" empty lines for admins/users
310 //TODO: should we remove all those @ before the header()? Are all of the values supported on all servers?
311 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
312
313 if ($forcedownload) {
314 @header('Content-Disposition: attachment; filename='.$filename);
315 } else {
316 @header('Content-Disposition: inline; filename='.$filename);
317 }
318
f1e0649c 319 if ($lifetime > 0) {
4c8c65ec 320 @header('Cache-Control: max-age='.$lifetime);
321 @header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
f1e0649c 322 @header('Pragma: ');
4c8c65ec 323
324 if (empty($CFG->disablebyteserving) && !$pathisstring && $mimetype != 'text/plain' && $mimetype != 'text/html') {
325
326 @header('Accept-Ranges: bytes');
327
328 if (!empty($_SERVER['HTTP_RANGE']) && strpos($_SERVER['HTTP_RANGE'],'bytes=') !== FALSE) {
329 // byteserving stuff - for acrobat reader and download accelerators
330 // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
331 // inspired by: http://www.coneural.org/florian/papers/04_byteserving.php
332 $ranges = false;
333 if (preg_match_all('/(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER)) {
334 foreach ($ranges as $key=>$value) {
335 if ($ranges[$key][1] == '') {
336 //suffix case
337 $ranges[$key][1] = $filesize - $ranges[$key][2];
338 $ranges[$key][2] = $filesize - 1;
339 } else if ($ranges[$key][2] == '' || $ranges[$key][2] > $filesize - 1) {
340 //fix range length
341 $ranges[$key][2] = $filesize - 1;
342 }
343 if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
344 //invalid byte-range ==> ignore header
345 $ranges = false;
346 break;
347 }
348 //prepare multipart header
349 $ranges[$key][0] = "\r\n--".BYTESERVING_BOUNDARY."\r\nContent-Type: $mimetype\r\n";
350 $ranges[$key][0] .= "Content-Range: bytes {$ranges[$key][1]}-{$ranges[$key][2]}/$filesize\r\n\r\n";
351 }
352 } else {
353 $ranges = false;
354 }
355 if ($ranges) {
356 byteserving_send_file($path, $mimetype, $ranges);
357 }
358 }
359 } else {
360 /// Do not byteserve (disabled, strings, text and html files).
361 @header('Accept-Ranges: none');
362 }
363 } else { // Do not cache files in proxies and browsers
85e00626 364 if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
365 @header('Cache-Control: max-age=10');
4c8c65ec 366 @header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
85e00626 367 @header('Pragma: ');
368 } else { //normal http - prevent caching at all cost
369 @header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
4c8c65ec 370 @header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
85e00626 371 @header('Pragma: no-cache');
372 }
4c8c65ec 373 @header('Accept-Ranges: none'); // Do not allow byteserving when caching disabled
69faecce 374 }
f1e0649c 375
b9709b76 376 if (empty($filter)) {
4c8c65ec 377 if ($mimetype == 'text/html' && !empty($CFG->usesid) && empty($_COOKIE['MoodleSession'.$CFG->sessioncookie])) {
378 //cookieless mode - rewrite links
379 @header('Content-Type: text/html');
380 $path = $pathisstring ? $path : implode('', file($path));
381 $path = sid_ob_rewrite($path);
382 $filesize = strlen($path);
383 $pathisstring = true;
384 } else if ($mimetype == 'text/plain') {
810944af 385 @header('Content-Type: Text/plain; charset=utf-8'); //add encoding
f1e0649c 386 } else {
4c8c65ec 387 @header('Content-Type: '.$mimetype);
f1e0649c 388 }
4c8c65ec 389 @header('Content-Length: '.$filesize);
390 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
f1e0649c 391 if ($pathisstring) {
392 echo $path;
4c8c65ec 393 } else {
69faecce 394 readfile_chunked($path);
f1e0649c 395 }
396 } else { // Try to put the file through filters
f1e0649c 397 if ($mimetype == 'text/html') {
a17c57b5 398 $options = new object();
f1e0649c 399 $options->noclean = true;
a17c57b5 400 $options->nocache = true; // temporary workaround for MDL-5136
f1e0649c 401 $text = $pathisstring ? $path : implode('', file($path));
76ca1ff1 402
3ace5ee4 403 $text = file_modify_html_header($text);
60f9e36e 404 $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
4c8c65ec 405 if (!empty($CFG->usesid) && empty($_COOKIE['MoodleSession'.$CFG->sessioncookie])) {
406 //cookieless mode - rewrite links
407 $output = sid_ob_rewrite($output);
408 }
f1e0649c 409
4c8c65ec 410 @header('Content-Length: '.strlen($output));
411 @header('Content-Type: text/html');
412 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
f1e0649c 413 echo $output;
b9709b76 414 // only filter text if filter all files is selected
415 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
60f9e36e 416 $options = new object();
f1e0649c 417 $options->newlines = false;
418 $options->noclean = true;
419 $text = htmlentities($pathisstring ? $path : implode('', file($path)));
60f9e36e 420 $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
4c8c65ec 421 if (!empty($CFG->usesid) && empty($_COOKIE['MoodleSession'.$CFG->sessioncookie])) {
422 //cookieless mode - rewrite links
423 $output = sid_ob_rewrite($output);
424 }
f1e0649c 425
4c8c65ec 426 @header('Content-Length: '.strlen($output));
810944af 427 @header('Content-Type: text/html; charset=utf-8'); //add encoding
4c8c65ec 428 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
f1e0649c 429 echo $output;
430 } else { // Just send it out raw
4c8c65ec 431 @header('Content-Length: '.$filesize);
432 @header('Content-Type: '.$mimetype);
433 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
f1e0649c 434 if ($pathisstring) {
435 echo $path;
436 }else {
69faecce 437 readfile_chunked($path);
f1e0649c 438 }
439 }
440 }
441 die; //no more chars to output!!!
442}
443
a43b5308 444function get_records_csv($file, $table) {
599f38f9 445 global $CFG, $db;
446
447 if (!$metacolumns = $db->MetaColumns($CFG->prefix . $table)) {
448 return false;
449 }
450
a77b98eb 451 if(!($handle = @fopen($file, 'r'))) {
599f38f9 452 error('get_records_csv failed to open '.$file);
453 }
454
455 $fieldnames = fgetcsv($handle, 4096);
456 if(empty($fieldnames)) {
457 fclose($handle);
458 return false;
459 }
460
461 $columns = array();
462
463 foreach($metacolumns as $metacolumn) {
464 $ord = array_search($metacolumn->name, $fieldnames);
465 if(is_int($ord)) {
466 $columns[$metacolumn->name] = $ord;
467 }
468 }
469
470 $rows = array();
471
472 while (($data = fgetcsv($handle, 4096)) !== false) {
473 $item = new stdClass;
474 foreach($columns as $name => $ord) {
475 $item->$name = $data[$ord];
476 }
477 $rows[] = $item;
478 }
479
480 fclose($handle);
481 return $rows;
482}
483
a77b98eb 484function put_records_csv($file, $records, $table = NULL) {
485 global $CFG, $db;
486
a1e93da2 487 if (empty($records)) {
a77b98eb 488 return true;
489 }
490
491 $metacolumns = NULL;
492 if ($table !== NULL && !$metacolumns = $db->MetaColumns($CFG->prefix . $table)) {
493 return false;
494 }
495
a1e93da2 496 echo "x";
497
a77b98eb 498 if(!($fp = @fopen($CFG->dataroot.'/temp/'.$file, 'w'))) {
499 error('put_records_csv failed to open '.$file);
500 }
501
a43b5308 502 $proto = reset($records);
503 if(is_object($proto)) {
504 $fields_records = array_keys(get_object_vars($proto));
505 }
506 else if(is_array($proto)) {
507 $fields_records = array_keys($proto);
508 }
509 else {
510 return false;
511 }
a1e93da2 512 echo "x";
a77b98eb 513
514 if(!empty($metacolumns)) {
515 $fields_table = array_map(create_function('$a', 'return $a->name;'), $metacolumns);
516 $fields = array_intersect($fields_records, $fields_table);
517 }
518 else {
519 $fields = $fields_records;
520 }
521
522 fwrite($fp, implode(',', $fields));
523 fwrite($fp, "\r\n");
524
525 foreach($records as $record) {
a43b5308 526 $array = (array)$record;
a77b98eb 527 $values = array();
528 foreach($fields as $field) {
a43b5308 529 if(strpos($array[$field], ',')) {
530 $values[] = '"'.str_replace('"', '\"', $array[$field]).'"';
a77b98eb 531 }
532 else {
a43b5308 533 $values[] = $array[$field];
a77b98eb 534 }
535 }
536 fwrite($fp, implode(',', $values)."\r\n");
537 }
538
539 fclose($fp);
540 return true;
541}
542
f401cc97 543
34763a79 544/**
76ca1ff1 545 * Recursively delete the file or folder with path $location. That is,
34763a79 546 * if it is a file delete it. If it is a folder, delete all its content
76ca1ff1 547 * then delete it. If $location does not exist to start, that is not
548 * considered an error.
549 *
34763a79 550 * @param $location the path to remove.
551 */
4c8c65ec 552function fulldelete($location) {
f401cc97 553 if (is_dir($location)) {
554 $currdir = opendir($location);
555 while (false !== ($file = readdir($currdir))) {
556 if ($file <> ".." && $file <> ".") {
557 $fullfile = $location."/".$file;
4c8c65ec 558 if (is_dir($fullfile)) {
f401cc97 559 if (!fulldelete($fullfile)) {
560 return false;
561 }
562 } else {
563 if (!unlink($fullfile)) {
564 return false;
565 }
4c8c65ec 566 }
f401cc97 567 }
4c8c65ec 568 }
f401cc97 569 closedir($currdir);
570 if (! rmdir($location)) {
571 return false;
572 }
573
34763a79 574 } else if (file_exists($location)) {
f401cc97 575 if (!unlink($location)) {
576 return false;
577 }
578 }
579 return true;
580}
581
4c8c65ec 582/**
583 * Improves memory consumptions and works around buggy readfile() in PHP 5.0.4 (2MB readfile limit).
584 */
585function readfile_chunked($filename, $retbytes=true) {
586 $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
69faecce 587 $buffer = '';
76ca1ff1 588 $cnt =0;
69faecce 589 $handle = fopen($filename, 'rb');
590 if ($handle === false) {
591 return false;
592 }
20371063 593
69faecce 594 while (!feof($handle)) {
68913aec 595 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
69faecce 596 $buffer = fread($handle, $chunksize);
597 echo $buffer;
20371063 598 flush();
69faecce 599 if ($retbytes) {
4c8c65ec 600 $cnt += strlen($buffer);
601 }
69faecce 602 }
603 $status = fclose($handle);
604 if ($retbytes && $status) {
605 return $cnt; // return num. bytes delivered like readfile() does.
606 }
607 return $status;
608}
609
4c8c65ec 610/**
611 * Send requested byterange of file.
612 */
613function byteserving_send_file($filename, $mimetype, $ranges) {
614 $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
615 $handle = fopen($filename, 'rb');
616 if ($handle === false) {
617 die;
618 }
619 if (count($ranges) == 1) { //only one range requested
620 $length = $ranges[0][2] - $ranges[0][1] + 1;
621 @header('HTTP/1.1 206 Partial content');
622 @header('Content-Length: '.$length);
623 @header('Content-Range: bytes '.$ranges[0][1].'-'.$ranges[0][2].'/'.filesize($filename));
624 @header('Content-Type: '.$mimetype);
625 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
626 $buffer = '';
627 fseek($handle, $ranges[0][1]);
628 while (!feof($handle) && $length > 0) {
68913aec 629 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
4c8c65ec 630 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
631 echo $buffer;
632 flush();
633 $length -= strlen($buffer);
634 }
635 fclose($handle);
636 die;
637 } else { // multiple ranges requested - not tested much
638 $totallength = 0;
639 foreach($ranges as $range) {
aba588a7 640 $totallength += strlen($range[0]) + $range[2] - $range[1] + 1;
4c8c65ec 641 }
aba588a7 642 $totallength += strlen("\r\n--".BYTESERVING_BOUNDARY."--\r\n");
4c8c65ec 643 @header('HTTP/1.1 206 Partial content');
644 @header('Content-Length: '.$totallength);
645 @header('Content-Type: multipart/byteranges; boundary='.BYTESERVING_BOUNDARY);
646 //TODO: check if "multipart/x-byteranges" is more compatible with current readers/browsers/servers
647 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
648 foreach($ranges as $range) {
649 $length = $range[2] - $range[1] + 1;
650 echo $range[0];
651 $buffer = '';
652 fseek($handle, $range[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 }
661 echo "\r\n--".BYTESERVING_BOUNDARY."--\r\n";
662 fclose($handle);
663 die;
664 }
665}
f401cc97 666
3ace5ee4 667/**
668 * add includes (js and css) into uploaded files
669 * before returning them, useful for themes and utf.js includes
670 * @param string text - text to search and replace
671 * @return string - text with added head includes
672 */
673function file_modify_html_header($text) {
674 // first look for <head> tag
675 global $CFG;
76ca1ff1 676
3ace5ee4 677 $stylesheetshtml = '';
678 foreach ($CFG->stylesheets as $stylesheet) {
679 $stylesheetshtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
76ca1ff1 680 }
681
3ace5ee4 682 $filters = explode(",", $CFG->textfilters);
683 if (in_array('filter/mediaplugin', $filters)) {
76ca1ff1 684 // this script is needed by most media filter plugins.
685 $ufo = "\n".'<script type="text/javascript" src="'.$CFG->wwwroot.'/lib/ufo.js"></script>'."\n";
3ace5ee4 686 } else {
76ca1ff1 687 $ufo = '';
3ace5ee4 688 }
76ca1ff1 689
3ace5ee4 690 preg_match('/\<head\>|\<HEAD\>/', $text, $matches);
691 if ($matches) {
692 $replacement = '<head>'.$ufo.$stylesheetshtml;
693 $text = preg_replace('/\<head\>|\<HEAD\>/', $replacement, $text, 1);
76ca1ff1 694 return $text;
3ace5ee4 695 }
76ca1ff1 696
3ace5ee4 697 // if not, look for <html> tag, and stick <head> right after
698 preg_match('/\<html\>|\<HTML\>/', $text, $matches);
699 if ($matches) {
700 // replace <html> tag with <html><head>includes</head>
13534ef7 701 $replacement = '<html>'."\n".'<head>'.$ufo.$stylesheetshtml.'</head>';
3ace5ee4 702 $text = preg_replace('/\<html\>|\<HTML\>/', $replacement, $text, 1);
76ca1ff1 703 return $text;
3ace5ee4 704 }
76ca1ff1 705
3ace5ee4 706 // if not, look for <body> tag, and stick <head> before body
707 preg_match('/\<body\>|\<BODY\>/', $text, $matches);
708 if ($matches) {
13534ef7 709 $replacement = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".'<body>';
3ace5ee4 710 $text = preg_replace('/\<body\>|\<BODY\>/', $replacement, $text, 1);
76ca1ff1 711 return $text;
712 }
713
3ace5ee4 714 // if not, just stick a <head> tag at the beginning
715 $text = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".$text;
716 return $text;
717}
718
a77b98eb 719?>