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