3 require_once($CFG->libdir
.'/libcurlemu/libcurlemu.inc.php'); // might be moved to setup.php later
5 define('BYTESERVING_BOUNDARY', 's1k2o3d4a5k6s7'); //unique string constant
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) {
15 $ch = curl_init($url);
16 curl_setopt($ch, CURLOPT_RETURNTRANSFER
, true);
17 curl_setopt($ch, CURLOPT_HEADER
, false);
18 if (!empty($CFG->proxyhost
)) {
19 // don't CONNECT for non-https connections
20 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL
, false);
22 if (empty($CFG->proxyport
)) {
23 curl_setopt($ch, CURLOPT_PROXY
, $CFG->proxyhost
);
25 curl_setopt($ch, CURLOPT_PROXY
, $CFG->proxyhost
.':'.$CFG->proxyport
);
27 if(!empty($CFG->proxyuser
) and !empty($CFG->proxypassword
)) {
28 curl_setopt($ch, CURLOPT_PROXYUSERPWD
, $CFG->proxyuser
.':'.$CFG->proxypassword
);
31 $result = curl_exec($ch);
33 if (curl_errno($ch)) {
34 $curlerror = "CURL request for \"$url\" failed with: ". curl_error($ch);
35 debugging($curlerror, DEBUG_DEVELOPER
);
43 * @return List of information about file types based on extensions.
44 * Associative array of extension (lower-case) to associative array
45 * from 'element name' to data. Current element names are 'type' and 'icon'.
46 * Unknown types should use the 'xxx' entry which includes defaults.
48 function get_mimetypes_array() {
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'),
58 'asm' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
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'),
62 'c' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
63 'cct' => array ('type'=>'shockwave/director', 'icon'=>'flash.gif'),
64 'cpp' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
65 'cs' => array ('type'=>'application/x-csh', 'icon'=>'text.gif'),
66 'css' => array ('type'=>'text/css', 'icon'=>'text.gif'),
67 'csv' => array ('type'=>'text/csv', 'icon'=>'excel.gif'),
68 'dv' => array ('type'=>'video/x-dv', 'icon'=>'video.gif'),
69 'dmg' => array ('type'=>'application/octet-stream', 'icon'=>'dmg.gif'),
70 'doc' => array ('type'=>'application/msword', 'icon'=>'word.gif'),
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'),
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'),
79 'fdf' => array ('type'=>'application/pdf', 'icon'=>'pdf.gif'),
80 'flv' => array ('type'=>'video/x-flv', 'icon'=>'video.gif'),
81 'gif' => array ('type'=>'image/gif', 'icon'=>'image.gif'),
82 'gtar' => array ('type'=>'application/x-gtar', 'icon'=>'zip.gif'),
83 'tgz' => array ('type'=>'application/g-zip', 'icon'=>'zip.gif'),
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'),
87 'hpp' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
88 'hqx' => array ('type'=>'application/mac-binhex40', 'icon'=>'zip.gif'),
89 'htc' => array ('type'=>'text/x-component', 'icon'=>'text.gif'),
90 'html' => array ('type'=>'text/html', 'icon'=>'html.gif'),
91 'xhtml'=> array ('type'=>'application/xhtml+xml', 'icon'=>'html.gif'),
92 'htm' => array ('type'=>'text/html', 'icon'=>'html.gif'),
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'),
96 'java' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
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'),
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'),
105 'jqz' => array ('type'=>'text/xml', 'icon'=>'jqz.gif'),
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'),
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'),
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'),
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'),
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'),
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'),
152 'rhb' => array ('type'=>'text/xml', 'icon'=>'xml.gif'),
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'),
160 'sqt' => array ('type'=>'text/xml', 'icon'=>'xml.gif'),
161 'svg' => array ('type'=>'image/svg+xml', 'icon'=>'image.gif'),
162 'svgz' => array ('type'=>'image/svg+xml', 'icon'=>'image.gif'),
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'),
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'),
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'),
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'),
192 'xls' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'excel.gif'),
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'),
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')
206 * Obtains information about a filetype based on its extension. Will
207 * use a default if no information is present about that particular
209 * @param string $element Desired information (usually 'icon'
210 * for icon filename or 'type' for MIME type)
211 * @param string $filename Filename we're looking up
212 * @return string Requested piece of information from array
214 function mimeinfo($element, $filename) {
216 $mimeinfo=get_mimetypes_array();
218 if (eregi('\.([a-z0-9]+)$', $filename, $match)) {
219 if (isset($mimeinfo[strtolower($match[1])][$element])) {
220 return $mimeinfo[strtolower($match[1])][$element];
222 return $mimeinfo['xxx'][$element]; // By default
225 return $mimeinfo['xxx'][$element]; // By default
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')
233 * @param string $mimetype MIME type we're looking up
234 * @return string Requested piece of information from array
236 function mimeinfo_from_type($element, $mimetype) {
238 $mimeinfo=get_mimetypes_array();
240 foreach($mimeinfo as $values) {
241 if($values['type']==$mimetype) {
242 if(isset($values[$element])) {
243 return $values[$element];
248 return $mimeinfo['xxx'][$element]; // Default
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
257 function mimeinfo_from_icon($element, $icon) {
259 $mimeinfo=get_mimetypes_array();
261 if (preg_match("/\/(.*)/", $icon, $matches)) {
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];
270 //No break, for example for 'excel.gif' we don't want 'csv'!
277 * Obtains descriptions for file types (e.g. 'Microsoft Word document') from the
278 * mimetypes.php language file.
279 * @param string $mimetype MIME type (can be obtained using the mimeinfo function)
280 * @param bool $capitalise If true, capitalises first character of result
281 * @return string Text description
283 function 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');
291 $result=ucfirst($result);
297 * Handles the sending of file data to the user's browser, including support for
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
307 function send_file($path, $filename, $lifetime=86400 , $filter=0, $pathisstring=false, $forcedownload=false, $mimetype='') {
308 global $CFG, $COURSE;
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
314 $mimetype = ($forcedownload and !$isFF) ?
'application/x-forcedownload' :
315 ($mimetype ?
$mimetype : mimeinfo('type', $filename));
316 $lastmodified = $pathisstring ?
time() : filemtime($path);
317 $filesize = $pathisstring ?
strlen($path) : filesize($path);
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
323 if (!empty($_SERVER['HTTP_RANGE'])) {
324 //already byteserving
325 $lifetime = 1; // >0 needed for byteserving
326 } else if (empty($_SERVER['HTTP_REFERER']) or strpos($_SERVER['HTTP_REFERER'], $CFG->wwwroot
)!==0) {
327 $mimetype = 'application/x-forcedownload';
328 $forcedownload = true;
331 $lifetime = 1; // >0 needed for byteserving
335 //IE compatibiltiy HACK!
336 if (ini_get('zlib.output_compression')) {
337 ini_set('zlib.output_compression', 'Off');
340 //try to disable automatic sid rewrite in cookieless mode
341 @ini_set
("session.use_trans_sid", "false");
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');
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);
353 if ($forcedownload) {
354 @header
('Content-Disposition: attachment; filename='.$filename);
356 @header
('Content-Disposition: inline; filename='.$filename);
360 @header
('Cache-Control: max-age='.$lifetime);
361 @header
('Expires: '. gmdate('D, d M Y H:i:s', time() +
$lifetime) .' GMT');
364 if (empty($CFG->disablebyteserving
) && !$pathisstring && $mimetype != 'text/plain' && $mimetype != 'text/html') {
366 @header
('Accept-Ranges: bytes');
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
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] == '') {
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) {
381 $ranges[$key][2] = $filesize - 1;
383 if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
384 //invalid byte-range ==> ignore header
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";
396 byteserving_send_file($path, $mimetype, $ranges);
400 /// Do not byteserve (disabled, strings, text and html files).
401 @header
('Accept-Ranges: none');
403 } else { // Do not cache files in proxies and browsers
404 if (strpos($CFG->wwwroot
, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
405 @header
('Cache-Control: max-age=10');
406 @header
('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
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');
410 @header
('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
411 @header
('Pragma: no-cache');
413 @header
('Accept-Ranges: none'); // Do not allow byteserving when caching disabled
416 if (empty($filter)) {
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') {
425 @header
('Content-Type: Text/plain; charset=utf-8'); //add encoding
427 @header
('Content-Type: '.$mimetype);
429 @header
('Content-Length: '.$filesize);
430 while (@ob_end_flush
()); //flush the buffers - save memory and disable sid rewrite
434 readfile_chunked($path);
436 } else { // Try to put the file through filters
437 if ($mimetype == 'text/html') {
438 $options = new object();
439 $options->noclean
= true;
440 $options->nocache
= true; // temporary workaround for MDL-5136
441 $text = $pathisstring ?
$path : implode('', file($path));
443 $text = file_modify_html_header($text);
444 $output = format_text($text, FORMAT_HTML
, $options, $COURSE->id
);
445 if (!empty($CFG->usesid
) && empty($_COOKIE['MoodleSession'.$CFG->sessioncookie
])) {
446 //cookieless mode - rewrite links
447 $output = sid_ob_rewrite($output);
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
454 // only filter text if filter all files is selected
455 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
456 $options = new object();
457 $options->newlines
= false;
458 $options->noclean
= true;
459 $text = htmlentities($pathisstring ?
$path : implode('', file($path)));
460 $output = '<pre>'. format_text($text, FORMAT_MOODLE
, $options, $COURSE->id
) .'</pre>';
461 if (!empty($CFG->usesid
) && empty($_COOKIE['MoodleSession'.$CFG->sessioncookie
])) {
462 //cookieless mode - rewrite links
463 $output = sid_ob_rewrite($output);
466 @header
('Content-Length: '.strlen($output));
467 @header
('Content-Type: text/html; charset=utf-8'); //add encoding
468 while (@ob_end_flush
()); //flush the buffers - save memory and disable sid rewrite
470 } else { // Just send it out raw
471 @header
('Content-Length: '.$filesize);
472 @header
('Content-Type: '.$mimetype);
473 while (@ob_end_flush
()); //flush the buffers - save memory and disable sid rewrite
477 readfile_chunked($path);
481 die; //no more chars to output!!!
484 function get_records_csv($file, $table) {
487 if (!$metacolumns = $db->MetaColumns($CFG->prefix
. $table)) {
491 if(!($handle = @fopen
($file, 'r'))) {
492 error('get_records_csv failed to open '.$file);
495 $fieldnames = fgetcsv($handle, 4096);
496 if(empty($fieldnames)) {
503 foreach($metacolumns as $metacolumn) {
504 $ord = array_search($metacolumn->name
, $fieldnames);
506 $columns[$metacolumn->name
] = $ord;
512 while (($data = fgetcsv($handle, 4096)) !== false) {
513 $item = new stdClass
;
514 foreach($columns as $name => $ord) {
515 $item->$name = $data[$ord];
524 function put_records_csv($file, $records, $table = NULL) {
527 if (empty($records)) {
532 if ($table !== NULL && !$metacolumns = $db->MetaColumns($CFG->prefix
. $table)) {
538 if(!($fp = @fopen
($CFG->dataroot
.'/temp/'.$file, 'w'))) {
539 error('put_records_csv failed to open '.$file);
542 $proto = reset($records);
543 if(is_object($proto)) {
544 $fields_records = array_keys(get_object_vars($proto));
546 else if(is_array($proto)) {
547 $fields_records = array_keys($proto);
554 if(!empty($metacolumns)) {
555 $fields_table = array_map(create_function('$a', 'return $a->name;'), $metacolumns);
556 $fields = array_intersect($fields_records, $fields_table);
559 $fields = $fields_records;
562 fwrite($fp, implode(',', $fields));
565 foreach($records as $record) {
566 $array = (array)$record;
568 foreach($fields as $field) {
569 if(strpos($array[$field], ',')) {
570 $values[] = '"'.str_replace('"', '\"', $array[$field]).'"';
573 $values[] = $array[$field];
576 fwrite($fp, implode(',', $values)."\r\n");
585 * Recursively delete the file or folder with path $location. That is,
586 * if it is a file delete it. If it is a folder, delete all its content
587 * then delete it. If $location does not exist to start, that is not
588 * considered an error.
590 * @param $location the path to remove.
592 function fulldelete($location) {
593 if (is_dir($location)) {
594 $currdir = opendir($location);
595 while (false !== ($file = readdir($currdir))) {
596 if ($file <> ".." && $file <> ".") {
597 $fullfile = $location."/".$file;
598 if (is_dir($fullfile)) {
599 if (!fulldelete($fullfile)) {
603 if (!unlink($fullfile)) {
610 if (! rmdir($location)) {
614 } else if (file_exists($location)) {
615 if (!unlink($location)) {
623 * Improves memory consumptions and works around buggy readfile() in PHP 5.0.4 (2MB readfile limit).
625 function readfile_chunked($filename, $retbytes=true) {
626 $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
629 $handle = fopen($filename, 'rb');
630 if ($handle === false) {
634 while (!feof($handle)) {
635 @set_time_limit
(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
636 $buffer = fread($handle, $chunksize);
640 $cnt +
= strlen($buffer);
643 $status = fclose($handle);
644 if ($retbytes && $status) {
645 return $cnt; // return num. bytes delivered like readfile() does.
651 * Send requested byterange of file.
653 function 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) {
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
667 fseek($handle, $ranges[0][1]);
668 while (!feof($handle) && $length > 0) {
669 @set_time_limit
(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
670 $buffer = fread($handle, ($chunksize < $length ?
$chunksize : $length));
673 $length -= strlen($buffer);
677 } else { // multiple ranges requested - not tested much
679 foreach($ranges as $range) {
680 $totallength +
= strlen($range[0]) +
$range[2] - $range[1] +
1;
682 $totallength +
= strlen("\r\n--".BYTESERVING_BOUNDARY
."--\r\n");
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;
692 fseek($handle, $range[1]);
693 while (!feof($handle) && $length > 0) {
694 @set_time_limit
(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
695 $buffer = fread($handle, ($chunksize < $length ?
$chunksize : $length));
698 $length -= strlen($buffer);
701 echo "\r\n--".BYTESERVING_BOUNDARY
."--\r\n";
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
713 function file_modify_html_header($text) {
714 // first look for <head> tag
717 $stylesheetshtml = '';
718 foreach ($CFG->stylesheets
as $stylesheet) {
719 $stylesheetshtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
722 $filters = explode(",", $CFG->textfilters
);
723 if (in_array('filter/mediaplugin', $filters)) {
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";
730 preg_match('/\<head\>|\<HEAD\>/', $text, $matches);
732 $replacement = '<head>'.$ufo.$stylesheetshtml;
733 $text = preg_replace('/\<head\>|\<HEAD\>/', $replacement, $text, 1);
737 // if not, look for <html> tag, and stick <head> right after
738 preg_match('/\<html\>|\<HTML\>/', $text, $matches);
740 // replace <html> tag with <html><head>includes</head>
741 $replacement = '<html>'."\n".'<head>'.$ufo.$stylesheetshtml.'</head>';
742 $text = preg_replace('/\<html\>|\<HTML\>/', $replacement, $text, 1);
746 // if not, look for <body> tag, and stick <head> before body
747 preg_match('/\<body\>|\<BODY\>/', $text, $matches);
749 $replacement = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".'<body>';
750 $text = preg_replace('/\<body\>|\<BODY\>/', $replacement, $text, 1);
754 // if not, just stick a <head> tag at the beginning
755 $text = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".$text;