calendar/lib: calendar_set_filters() use pre-fetched context and course recs
[moodle-pu.git] / lib / filelib.php
blob0feb39abf995ce363c3760056c40f3390207cfe1
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 * Obtains descriptions for file types (e.g. 'Microsoft Word document') from the
243 * mimetypes.php language file.
244 * @param string $mimetype MIME type (can be obtained using the mimeinfo function)
245 * @param bool $capitalise If true, capitalises first character of result
246 * @return string Text description
248 function 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');
255 if($capitalise) {
256 $result=ucfirst($result);
258 return $result;
262 * Handles the sending of file data to the user's browser, including support for
263 * byteranges etc.
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
272 function send_file($path, $filename, $lifetime=86400 , $filter=0, $pathisstring=false, $forcedownload=false, $mimetype='') {
273 global $CFG, $COURSE;
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
279 $mimetype = ($forcedownload and !$isFF) ? 'application/x-forcedownload' :
280 ($mimetype ? $mimetype : mimeinfo('type', $filename));
281 $lastmodified = $pathisstring ? time() : filemtime($path);
282 $filesize = $pathisstring ? strlen($path) : filesize($path);
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
288 if (!empty($_SERVER['HTTP_RANGE'])) {
289 //already byteserving
290 $lifetime = 1; // >0 needed for byteserving
291 } else if (empty($_SERVER['HTTP_REFERER']) or strpos($_SERVER['HTTP_REFERER'], $CFG->wwwroot)!==0) {
292 $mimetype = 'application/x-forcedownload';
293 $forcedownload = true;
294 $lifetime = 0;
295 } else {
296 $lifetime = 1; // >0 needed for byteserving
300 //IE compatibiltiy HACK!
301 if (ini_get('zlib.output_compression')) {
302 ini_set('zlib.output_compression', 'Off');
305 //try to disable automatic sid rewrite in cookieless mode
306 @ini_set("session.use_trans_sid", "false");
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');
313 if ($forcedownload) {
314 @header('Content-Disposition: attachment; filename='.$filename);
315 } else {
316 @header('Content-Disposition: inline; filename='.$filename);
319 if ($lifetime > 0) {
320 @header('Cache-Control: max-age='.$lifetime);
321 @header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
322 @header('Pragma: ');
324 if (empty($CFG->disablebyteserving) && !$pathisstring && $mimetype != 'text/plain' && $mimetype != 'text/html') {
326 @header('Accept-Ranges: bytes');
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;
343 if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
344 //invalid byte-range ==> ignore header
345 $ranges = false;
346 break;
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";
352 } else {
353 $ranges = false;
355 if ($ranges) {
356 byteserving_send_file($path, $mimetype, $ranges);
359 } else {
360 /// Do not byteserve (disabled, strings, text and html files).
361 @header('Accept-Ranges: none');
363 } else { // Do not cache files in proxies and browsers
364 if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
365 @header('Cache-Control: max-age=10');
366 @header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
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');
370 @header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
371 @header('Pragma: no-cache');
373 @header('Accept-Ranges: none'); // Do not allow byteserving when caching disabled
376 if (empty($filter)) {
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') {
385 @header('Content-Type: Text/plain; charset=utf-8'); //add encoding
386 } else {
387 @header('Content-Type: '.$mimetype);
389 @header('Content-Length: '.$filesize);
390 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
391 if ($pathisstring) {
392 echo $path;
393 } else {
394 readfile_chunked($path);
396 } else { // Try to put the file through filters
397 if ($mimetype == 'text/html') {
398 $options = new object();
399 $options->noclean = true;
400 $options->nocache = true; // temporary workaround for MDL-5136
401 $text = $pathisstring ? $path : implode('', file($path));
403 $text = file_modify_html_header($text);
404 $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
405 if (!empty($CFG->usesid) && empty($_COOKIE['MoodleSession'.$CFG->sessioncookie])) {
406 //cookieless mode - rewrite links
407 $output = sid_ob_rewrite($output);
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
413 echo $output;
414 // only filter text if filter all files is selected
415 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
416 $options = new object();
417 $options->newlines = false;
418 $options->noclean = true;
419 $text = htmlentities($pathisstring ? $path : implode('', file($path)));
420 $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
421 if (!empty($CFG->usesid) && empty($_COOKIE['MoodleSession'.$CFG->sessioncookie])) {
422 //cookieless mode - rewrite links
423 $output = sid_ob_rewrite($output);
426 @header('Content-Length: '.strlen($output));
427 @header('Content-Type: text/html; charset=utf-8'); //add encoding
428 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
429 echo $output;
430 } else { // Just send it out raw
431 @header('Content-Length: '.$filesize);
432 @header('Content-Type: '.$mimetype);
433 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
434 if ($pathisstring) {
435 echo $path;
436 }else {
437 readfile_chunked($path);
441 die; //no more chars to output!!!
444 function get_records_csv($file, $table) {
445 global $CFG, $db;
447 if (!$metacolumns = $db->MetaColumns($CFG->prefix . $table)) {
448 return false;
451 if(!($handle = @fopen($file, 'r'))) {
452 error('get_records_csv failed to open '.$file);
455 $fieldnames = fgetcsv($handle, 4096);
456 if(empty($fieldnames)) {
457 fclose($handle);
458 return false;
461 $columns = array();
463 foreach($metacolumns as $metacolumn) {
464 $ord = array_search($metacolumn->name, $fieldnames);
465 if(is_int($ord)) {
466 $columns[$metacolumn->name] = $ord;
470 $rows = array();
472 while (($data = fgetcsv($handle, 4096)) !== false) {
473 $item = new stdClass;
474 foreach($columns as $name => $ord) {
475 $item->$name = $data[$ord];
477 $rows[] = $item;
480 fclose($handle);
481 return $rows;
484 function put_records_csv($file, $records, $table = NULL) {
485 global $CFG, $db;
487 if (empty($records)) {
488 return true;
491 $metacolumns = NULL;
492 if ($table !== NULL && !$metacolumns = $db->MetaColumns($CFG->prefix . $table)) {
493 return false;
496 echo "x";
498 if(!($fp = @fopen($CFG->dataroot.'/temp/'.$file, 'w'))) {
499 error('put_records_csv failed to open '.$file);
502 $proto = reset($records);
503 if(is_object($proto)) {
504 $fields_records = array_keys(get_object_vars($proto));
506 else if(is_array($proto)) {
507 $fields_records = array_keys($proto);
509 else {
510 return false;
512 echo "x";
514 if(!empty($metacolumns)) {
515 $fields_table = array_map(create_function('$a', 'return $a->name;'), $metacolumns);
516 $fields = array_intersect($fields_records, $fields_table);
518 else {
519 $fields = $fields_records;
522 fwrite($fp, implode(',', $fields));
523 fwrite($fp, "\r\n");
525 foreach($records as $record) {
526 $array = (array)$record;
527 $values = array();
528 foreach($fields as $field) {
529 if(strpos($array[$field], ',')) {
530 $values[] = '"'.str_replace('"', '\"', $array[$field]).'"';
532 else {
533 $values[] = $array[$field];
536 fwrite($fp, implode(',', $values)."\r\n");
539 fclose($fp);
540 return true;
545 * Recursively delete the file or folder with path $location. That is,
546 * if it is a file delete it. If it is a folder, delete all its content
547 * then delete it. If $location does not exist to start, that is not
548 * considered an error.
550 * @param $location the path to remove.
552 function fulldelete($location) {
553 if (is_dir($location)) {
554 $currdir = opendir($location);
555 while (false !== ($file = readdir($currdir))) {
556 if ($file <> ".." && $file <> ".") {
557 $fullfile = $location."/".$file;
558 if (is_dir($fullfile)) {
559 if (!fulldelete($fullfile)) {
560 return false;
562 } else {
563 if (!unlink($fullfile)) {
564 return false;
569 closedir($currdir);
570 if (! rmdir($location)) {
571 return false;
574 } else if (file_exists($location)) {
575 if (!unlink($location)) {
576 return false;
579 return true;
583 * Improves memory consumptions and works around buggy readfile() in PHP 5.0.4 (2MB readfile limit).
585 function readfile_chunked($filename, $retbytes=true) {
586 $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
587 $buffer = '';
588 $cnt =0;
589 $handle = fopen($filename, 'rb');
590 if ($handle === false) {
591 return false;
594 while (!feof($handle)) {
595 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
596 $buffer = fread($handle, $chunksize);
597 echo $buffer;
598 flush();
599 if ($retbytes) {
600 $cnt += strlen($buffer);
603 $status = fclose($handle);
604 if ($retbytes && $status) {
605 return $cnt; // return num. bytes delivered like readfile() does.
607 return $status;
611 * Send requested byterange of file.
613 function 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;
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) {
629 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
630 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
631 echo $buffer;
632 flush();
633 $length -= strlen($buffer);
635 fclose($handle);
636 die;
637 } else { // multiple ranges requested - not tested much
638 $totallength = 0;
639 foreach($ranges as $range) {
640 $totallength += strlen($range[0]) + $range[2] - $range[1] + 1;
642 $totallength += strlen("\r\n--".BYTESERVING_BOUNDARY."--\r\n");
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) {
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);
661 echo "\r\n--".BYTESERVING_BOUNDARY."--\r\n";
662 fclose($handle);
663 die;
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
673 function file_modify_html_header($text) {
674 // first look for <head> tag
675 global $CFG;
677 $stylesheetshtml = '';
678 foreach ($CFG->stylesheets as $stylesheet) {
679 $stylesheetshtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
682 $filters = explode(",", $CFG->textfilters);
683 if (in_array('filter/mediaplugin', $filters)) {
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";
686 } else {
687 $ufo = '';
690 preg_match('/\<head\>|\<HEAD\>/', $text, $matches);
691 if ($matches) {
692 $replacement = '<head>'.$ufo.$stylesheetshtml;
693 $text = preg_replace('/\<head\>|\<HEAD\>/', $replacement, $text, 1);
694 return $text;
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>
701 $replacement = '<html>'."\n".'<head>'.$ufo.$stylesheetshtml.'</head>';
702 $text = preg_replace('/\<html\>|\<HTML\>/', $replacement, $text, 1);
703 return $text;
706 // if not, look for <body> tag, and stick <head> before body
707 preg_match('/\<body\>|\<BODY\>/', $text, $matches);
708 if ($matches) {
709 $replacement = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".'<body>';
710 $text = preg_replace('/\<body\>|\<BODY\>/', $replacement, $text, 1);
711 return $text;
714 // if not, just stick a <head> tag at the beginning
715 $text = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".$text;
716 return $text;