MDL-11517 reserved word MOD used in table alias in questions backup code
[moodle-pu.git] / lib / filelib.php
blobc9a7846745f291444c89730725ffad5574c0324b
1 <?php //$Id$
3 require_once($CFG->libdir.'/libcurlemu/libcurlemu.inc.php'); // might be moved to setup.php later
5 define('BYTESERVING_BOUNDARY', 's1k2o3d4a5k6s7'); //unique string constant
7 /**
8 * Fetches content of file from Internet (using proxy if defined).
10 * @return mixed false if request failed or content of the file as string if ok.
12 function 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);
23 if(!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) {
24 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $CFG->proxyuser.':'.$CFG->proxypassword);
27 $result = curl_exec($ch);
28 curl_close($ch);
29 return $result;
32 /**
33 * @return List of information about file types based on extensions.
34 * Associative array of extension (lower-case) to associative array
35 * from 'element name' to data. Current element names are 'type' and 'icon'.
36 * Unknown types should use the 'xxx' entry which includes defaults.
38 function get_mimetypes_array() {
39 return array (
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'),
48 'asm' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
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'),
52 'c' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
53 'cct' => array ('type'=>'shockwave/director', 'icon'=>'flash.gif'),
54 'cpp' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
55 'cs' => array ('type'=>'application/x-csh', 'icon'=>'text.gif'),
56 'css' => array ('type'=>'text/css', 'icon'=>'text.gif'),
57 'csv' => array ('type'=>'text/csv', 'icon'=>'excel.gif'),
58 'dv' => array ('type'=>'video/x-dv', 'icon'=>'video.gif'),
59 'dmg' => array ('type'=>'application/octet-stream', 'icon'=>'dmg.gif'),
60 'doc' => array ('type'=>'application/msword', 'icon'=>'word.gif'),
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'),
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'),
69 'fdf' => array ('type'=>'application/pdf', 'icon'=>'pdf.gif'),
70 'flv' => array ('type'=>'video/x-flv', 'icon'=>'video.gif'),
71 'gif' => array ('type'=>'image/gif', 'icon'=>'image.gif'),
72 'gtar' => array ('type'=>'application/x-gtar', 'icon'=>'zip.gif'),
73 'tgz' => array ('type'=>'application/g-zip', 'icon'=>'zip.gif'),
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'),
77 'hpp' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
78 'hqx' => array ('type'=>'application/mac-binhex40', 'icon'=>'zip.gif'),
79 'htc' => array ('type'=>'text/x-component', 'icon'=>'text.gif'),
80 'html' => array ('type'=>'text/html', 'icon'=>'html.gif'),
81 'xhtml'=> array ('type'=>'application/xhtml+xml', 'icon'=>'html.gif'),
82 'htm' => array ('type'=>'text/html', 'icon'=>'html.gif'),
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'),
86 'java' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
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'),
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'),
95 'jqz' => array ('type'=>'text/xml', 'icon'=>'jqz.gif'),
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'),
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'),
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'),
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'),
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'),
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'),
142 'rhb' => array ('type'=>'text/xml', 'icon'=>'xml.gif'),
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'),
150 'sqt' => array ('type'=>'text/xml', 'icon'=>'xml.gif'),
151 'svg' => array ('type'=>'image/svg+xml', 'icon'=>'image.gif'),
152 'svgz' => array ('type'=>'image/svg+xml', 'icon'=>'image.gif'),
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'),
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'),
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'),
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'),
182 'xls' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'excel.gif'),
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'),
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')
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.
199 * @param string $element Desired information (usually 'icon'
200 * for icon filename or 'type' for MIME type)
201 * @param string $filename Filename we're looking up
202 * @return string Requested piece of information from array
204 function mimeinfo($element, $filename) {
205 static $mimeinfo;
206 $mimeinfo=get_mimetypes_array();
208 if (eregi('\.([a-z0-9]+)$', $filename, $match)) {
209 if (isset($mimeinfo[strtolower($match[1])][$element])) {
210 return $mimeinfo[strtolower($match[1])][$element];
211 } else {
212 return $mimeinfo['xxx'][$element]; // By default
214 } else {
215 return $mimeinfo['xxx'][$element]; // By default
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')
223 * @param string $mimetype MIME type we're looking up
224 * @return string Requested piece of information from array
226 function mimeinfo_from_type($element, $mimetype) {
227 static $mimeinfo;
228 $mimeinfo=get_mimetypes_array();
230 foreach($mimeinfo as $values) {
231 if($values['type']==$mimetype) {
232 if(isset($values[$element])) {
233 return $values[$element];
235 break;
238 return $mimeinfo['xxx'][$element]; // Default
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
247 function mimeinfo_from_icon($element, $icon) {
248 static $mimeinfo;
249 $mimeinfo=get_mimetypes_array();
251 if (preg_match("/\/(.*)/", $icon, $matches)) {
252 $icon = $matches[1];
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];
260 //No break, for example for 'excel.gif' we don't want 'csv'!
263 return $info;
267 * Obtains descriptions for file types (e.g. 'Microsoft Word document') from the
268 * mimetypes.php language file.
269 * @param string $mimetype MIME type (can be obtained using the mimeinfo function)
270 * @param bool $capitalise If true, capitalises first character of result
271 * @return string Text description
273 function 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');
280 if($capitalise) {
281 $result=ucfirst($result);
283 return $result;
287 * Handles the sending of file data to the user's browser, including support for
288 * byteranges etc.
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
297 function send_file($path, $filename, $lifetime=86400 , $filter=0, $pathisstring=false, $forcedownload=false, $mimetype='') {
298 global $CFG, $COURSE;
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
304 $mimetype = ($forcedownload and !$isFF) ? 'application/x-forcedownload' :
305 ($mimetype ? $mimetype : mimeinfo('type', $filename));
306 $lastmodified = $pathisstring ? time() : filemtime($path);
307 $filesize = $pathisstring ? strlen($path) : filesize($path);
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
313 if (!empty($_SERVER['HTTP_RANGE'])) {
314 //already byteserving
315 $lifetime = 1; // >0 needed for byteserving
316 } else if (empty($_SERVER['HTTP_REFERER']) or strpos($_SERVER['HTTP_REFERER'], $CFG->wwwroot)!==0) {
317 $mimetype = 'application/x-forcedownload';
318 $forcedownload = true;
319 $lifetime = 0;
320 } else {
321 $lifetime = 1; // >0 needed for byteserving
325 //IE compatibiltiy HACK!
326 if (ini_get('zlib.output_compression')) {
327 ini_set('zlib.output_compression', 'Off');
330 //try to disable automatic sid rewrite in cookieless mode
331 @ini_set("session.use_trans_sid", "false");
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');
338 if ($forcedownload) {
339 @header('Content-Disposition: attachment; filename='.$filename);
340 } else {
341 @header('Content-Disposition: inline; filename='.$filename);
344 if ($lifetime > 0) {
345 @header('Cache-Control: max-age='.$lifetime);
346 @header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
347 @header('Pragma: ');
349 if (empty($CFG->disablebyteserving) && !$pathisstring && $mimetype != 'text/plain' && $mimetype != 'text/html') {
351 @header('Accept-Ranges: bytes');
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;
368 if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
369 //invalid byte-range ==> ignore header
370 $ranges = false;
371 break;
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";
377 } else {
378 $ranges = false;
380 if ($ranges) {
381 byteserving_send_file($path, $mimetype, $ranges);
384 } else {
385 /// Do not byteserve (disabled, strings, text and html files).
386 @header('Accept-Ranges: none');
388 } else { // Do not cache files in proxies and browsers
389 if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
390 @header('Cache-Control: max-age=10');
391 @header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
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');
395 @header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
396 @header('Pragma: no-cache');
398 @header('Accept-Ranges: none'); // Do not allow byteserving when caching disabled
401 if (empty($filter)) {
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') {
410 @header('Content-Type: Text/plain; charset=utf-8'); //add encoding
411 } else {
412 @header('Content-Type: '.$mimetype);
414 @header('Content-Length: '.$filesize);
415 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
416 if ($pathisstring) {
417 echo $path;
418 } else {
419 readfile_chunked($path);
421 } else { // Try to put the file through filters
422 if ($mimetype == 'text/html') {
423 $options = new object();
424 $options->noclean = true;
425 $options->nocache = true; // temporary workaround for MDL-5136
426 $text = $pathisstring ? $path : implode('', file($path));
428 $text = file_modify_html_header($text);
429 $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
430 if (!empty($CFG->usesid) && empty($_COOKIE['MoodleSession'.$CFG->sessioncookie])) {
431 //cookieless mode - rewrite links
432 $output = sid_ob_rewrite($output);
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
438 echo $output;
439 // only filter text if filter all files is selected
440 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
441 $options = new object();
442 $options->newlines = false;
443 $options->noclean = true;
444 $text = htmlentities($pathisstring ? $path : implode('', file($path)));
445 $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
446 if (!empty($CFG->usesid) && empty($_COOKIE['MoodleSession'.$CFG->sessioncookie])) {
447 //cookieless mode - rewrite links
448 $output = sid_ob_rewrite($output);
451 @header('Content-Length: '.strlen($output));
452 @header('Content-Type: text/html; charset=utf-8'); //add encoding
453 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
454 echo $output;
455 } else { // Just send it out raw
456 @header('Content-Length: '.$filesize);
457 @header('Content-Type: '.$mimetype);
458 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
459 if ($pathisstring) {
460 echo $path;
461 }else {
462 readfile_chunked($path);
466 die; //no more chars to output!!!
469 function get_records_csv($file, $table) {
470 global $CFG, $db;
472 if (!$metacolumns = $db->MetaColumns($CFG->prefix . $table)) {
473 return false;
476 if(!($handle = @fopen($file, 'r'))) {
477 error('get_records_csv failed to open '.$file);
480 $fieldnames = fgetcsv($handle, 4096);
481 if(empty($fieldnames)) {
482 fclose($handle);
483 return false;
486 $columns = array();
488 foreach($metacolumns as $metacolumn) {
489 $ord = array_search($metacolumn->name, $fieldnames);
490 if(is_int($ord)) {
491 $columns[$metacolumn->name] = $ord;
495 $rows = array();
497 while (($data = fgetcsv($handle, 4096)) !== false) {
498 $item = new stdClass;
499 foreach($columns as $name => $ord) {
500 $item->$name = $data[$ord];
502 $rows[] = $item;
505 fclose($handle);
506 return $rows;
509 function put_records_csv($file, $records, $table = NULL) {
510 global $CFG, $db;
512 if (empty($records)) {
513 return true;
516 $metacolumns = NULL;
517 if ($table !== NULL && !$metacolumns = $db->MetaColumns($CFG->prefix . $table)) {
518 return false;
521 echo "x";
523 if(!($fp = @fopen($CFG->dataroot.'/temp/'.$file, 'w'))) {
524 error('put_records_csv failed to open '.$file);
527 $proto = reset($records);
528 if(is_object($proto)) {
529 $fields_records = array_keys(get_object_vars($proto));
531 else if(is_array($proto)) {
532 $fields_records = array_keys($proto);
534 else {
535 return false;
537 echo "x";
539 if(!empty($metacolumns)) {
540 $fields_table = array_map(create_function('$a', 'return $a->name;'), $metacolumns);
541 $fields = array_intersect($fields_records, $fields_table);
543 else {
544 $fields = $fields_records;
547 fwrite($fp, implode(',', $fields));
548 fwrite($fp, "\r\n");
550 foreach($records as $record) {
551 $array = (array)$record;
552 $values = array();
553 foreach($fields as $field) {
554 if(strpos($array[$field], ',')) {
555 $values[] = '"'.str_replace('"', '\"', $array[$field]).'"';
557 else {
558 $values[] = $array[$field];
561 fwrite($fp, implode(',', $values)."\r\n");
564 fclose($fp);
565 return true;
570 * Recursively delete the file or folder with path $location. That is,
571 * if it is a file delete it. If it is a folder, delete all its content
572 * then delete it. If $location does not exist to start, that is not
573 * considered an error.
575 * @param $location the path to remove.
577 function fulldelete($location) {
578 if (is_dir($location)) {
579 $currdir = opendir($location);
580 while (false !== ($file = readdir($currdir))) {
581 if ($file <> ".." && $file <> ".") {
582 $fullfile = $location."/".$file;
583 if (is_dir($fullfile)) {
584 if (!fulldelete($fullfile)) {
585 return false;
587 } else {
588 if (!unlink($fullfile)) {
589 return false;
594 closedir($currdir);
595 if (! rmdir($location)) {
596 return false;
599 } else if (file_exists($location)) {
600 if (!unlink($location)) {
601 return false;
604 return true;
608 * Improves memory consumptions and works around buggy readfile() in PHP 5.0.4 (2MB readfile limit).
610 function readfile_chunked($filename, $retbytes=true) {
611 $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
612 $buffer = '';
613 $cnt =0;
614 $handle = fopen($filename, 'rb');
615 if ($handle === false) {
616 return false;
619 while (!feof($handle)) {
620 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
621 $buffer = fread($handle, $chunksize);
622 echo $buffer;
623 flush();
624 if ($retbytes) {
625 $cnt += strlen($buffer);
628 $status = fclose($handle);
629 if ($retbytes && $status) {
630 return $cnt; // return num. bytes delivered like readfile() does.
632 return $status;
636 * Send requested byterange of file.
638 function 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;
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) {
654 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
655 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
656 echo $buffer;
657 flush();
658 $length -= strlen($buffer);
660 fclose($handle);
661 die;
662 } else { // multiple ranges requested - not tested much
663 $totallength = 0;
664 foreach($ranges as $range) {
665 $totallength += strlen($range[0]) + $range[2] - $range[1] + 1;
667 $totallength += strlen("\r\n--".BYTESERVING_BOUNDARY."--\r\n");
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) {
679 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
680 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
681 echo $buffer;
682 flush();
683 $length -= strlen($buffer);
686 echo "\r\n--".BYTESERVING_BOUNDARY."--\r\n";
687 fclose($handle);
688 die;
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
698 function file_modify_html_header($text) {
699 // first look for <head> tag
700 global $CFG;
702 $stylesheetshtml = '';
703 foreach ($CFG->stylesheets as $stylesheet) {
704 $stylesheetshtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
707 $filters = explode(",", $CFG->textfilters);
708 if (in_array('filter/mediaplugin', $filters)) {
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";
711 } else {
712 $ufo = '';
715 preg_match('/\<head\>|\<HEAD\>/', $text, $matches);
716 if ($matches) {
717 $replacement = '<head>'.$ufo.$stylesheetshtml;
718 $text = preg_replace('/\<head\>|\<HEAD\>/', $replacement, $text, 1);
719 return $text;
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>
726 $replacement = '<html>'."\n".'<head>'.$ufo.$stylesheetshtml.'</head>';
727 $text = preg_replace('/\<html\>|\<HTML\>/', $replacement, $text, 1);
728 return $text;
731 // if not, look for <body> tag, and stick <head> before body
732 preg_match('/\<body\>|\<BODY\>/', $text, $matches);
733 if ($matches) {
734 $replacement = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".'<body>';
735 $text = preg_replace('/\<body\>|\<BODY\>/', $replacement, $text, 1);
736 return $text;
739 // if not, just stick a <head> tag at the beginning
740 $text = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".$text;
741 return $text;