filelib - Added support for looking up icons via MIME type as well as via extension
[moodle.git] / lib / filelib.php
CommitLineData
599f38f9 1<?php //$Id$
2
4c8c65ec 3define('BYTESERVING_BOUNDARY', 's1k2o3d4a5k6s7'); //unique string constant
4
3ce73b14 5/**
6 * @return List of information about file types based on extensions.
7 * Associative array of extension (lower-case) to associative array
8 * from 'element name' to data. Current element names are 'type' and 'icon'.
9 * Unknown types should use the 'xxx' entry which includes defaults.
10 */
11function get_mimetypes_array() {
12 return array (
a370c895 13 'xxx' => array ('type'=>'document/unknown', 'icon'=>'unknown.gif'),
14 '3gp' => array ('type'=>'video/quicktime', 'icon'=>'video.gif'),
15 'ai' => array ('type'=>'application/postscript', 'icon'=>'image.gif'),
16 'aif' => array ('type'=>'audio/x-aiff', 'icon'=>'audio.gif'),
17 'aiff' => array ('type'=>'audio/x-aiff', 'icon'=>'audio.gif'),
18 'aifc' => array ('type'=>'audio/x-aiff', 'icon'=>'audio.gif'),
19 'applescript' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
20 'asc' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
18bf47ef 21 'asm' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
a370c895 22 'au' => array ('type'=>'audio/au', 'icon'=>'audio.gif'),
23 'avi' => array ('type'=>'video/x-ms-wm', 'icon'=>'avi.gif'),
24 'bmp' => array ('type'=>'image/bmp', 'icon'=>'image.gif'),
18bf47ef 25 'c' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
a370c895 26 'cct' => array ('type'=>'shockwave/director', 'icon'=>'flash.gif'),
18bf47ef 27 'cpp' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
a370c895 28 'cs' => array ('type'=>'application/x-csh', 'icon'=>'text.gif'),
29 'css' => array ('type'=>'text/css', 'icon'=>'text.gif'),
30 'dv' => array ('type'=>'video/x-dv', 'icon'=>'video.gif'),
609d84e3 31 'dmg' => array ('type'=>'application/octet-stream', 'icon'=>'dmg.gif'),
a370c895 32 'doc' => array ('type'=>'application/msword', 'icon'=>'word.gif'),
33 'dcr' => array ('type'=>'application/x-director', 'icon'=>'flash.gif'),
34 'dif' => array ('type'=>'video/x-dv', 'icon'=>'video.gif'),
35 'dir' => array ('type'=>'application/x-director', 'icon'=>'flash.gif'),
36 'dxr' => array ('type'=>'application/x-director', 'icon'=>'flash.gif'),
37 'eps' => array ('type'=>'application/postscript', 'icon'=>'pdf.gif'),
38 'gif' => array ('type'=>'image/gif', 'icon'=>'image.gif'),
39 'gtar' => array ('type'=>'application/x-gtar', 'icon'=>'zip.gif'),
609d84e3 40 'tgz' => array ('type'=>'application/g-zip', 'icon'=>'zip.gif'),
a370c895 41 'gz' => array ('type'=>'application/g-zip', 'icon'=>'zip.gif'),
42 'gzip' => array ('type'=>'application/g-zip', 'icon'=>'zip.gif'),
43 'h' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
18bf47ef 44 'hpp' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
a370c895 45 'hqx' => array ('type'=>'application/mac-binhex40', 'icon'=>'zip.gif'),
46 'html' => array ('type'=>'text/html', 'icon'=>'html.gif'),
47 'htm' => array ('type'=>'text/html', 'icon'=>'html.gif'),
18bf47ef 48 'java' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
a00420fb 49 'jcb' => array ('type'=>'text/xml', 'icon'=>'jcb.gif'),
50 'jcl' => array ('type'=>'text/xml', 'icon'=>'jcl.gif'),
51 'jcw' => array ('type'=>'text/xml', 'icon'=>'jcw.gif'),
52 'jmt' => array ('type'=>'text/xml', 'icon'=>'jmt.gif'),
53 'jmx' => array ('type'=>'text/xml', 'icon'=>'jmx.gif'),
a370c895 54 'jpe' => array ('type'=>'image/jpeg', 'icon'=>'image.gif'),
55 'jpeg' => array ('type'=>'image/jpeg', 'icon'=>'image.gif'),
56 'jpg' => array ('type'=>'image/jpeg', 'icon'=>'image.gif'),
a00420fb 57 'jqz' => array ('type'=>'text/xml', 'icon'=>'jqz.gif'),
a370c895 58 'js' => array ('type'=>'application/x-javascript', 'icon'=>'text.gif'),
59 'latex'=> array ('type'=>'application/x-latex', 'icon'=>'text.gif'),
60 'm' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
61 'mov' => array ('type'=>'video/quicktime', 'icon'=>'video.gif'),
62 'movie'=> array ('type'=>'video/x-sgi-movie', 'icon'=>'video.gif'),
63 'm3u' => array ('type'=>'audio/x-mpegurl', 'icon'=>'audio.gif'),
64 'mp3' => array ('type'=>'audio/mp3', 'icon'=>'audio.gif'),
65 'mp4' => array ('type'=>'video/mp4', 'icon'=>'video.gif'),
66 'mpeg' => array ('type'=>'video/mpeg', 'icon'=>'video.gif'),
67 'mpe' => array ('type'=>'video/mpeg', 'icon'=>'video.gif'),
68 'mpg' => array ('type'=>'video/mpeg', 'icon'=>'video.gif'),
5395334d 69
70 'odt' => array ('type'=>'application/vnd.oasis.opendocument.text', 'icon'=>'odt.gif'),
71 'ott' => array ('type'=>'application/vnd.oasis.opendocument.text-template', 'icon'=>'odt.gif'),
72 'oth' => array ('type'=>'application/vnd.oasis.opendocument.text-web', 'icon'=>'odt.gif'),
73 'odm' => array ('type'=>'application/vnd.oasis.opendocument.text-master', 'icon'=>'odt.gif'),
74 'odg' => array ('type'=>'application/vnd.oasis.opendocument.graphics', 'icon'=>'odt.gif'),
75 'otg' => array ('type'=>'application/vnd.oasis.opendocument.graphics-template', 'icon'=>'odt.gif'),
76 'odp' => array ('type'=>'application/vnd.oasis.opendocument.presentation', 'icon'=>'odt.gif'),
77 'otp' => array ('type'=>'application/vnd.oasis.opendocument.presentation-template', 'icon'=>'odt.gif'),
78 'ods' => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet', 'icon'=>'odt.gif'),
79 'ots' => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet-template', 'icon'=>'odt.gif'),
80 'odc' => array ('type'=>'application/vnd.oasis.opendocument.chart', 'icon'=>'odt.gif'),
81 'odf' => array ('type'=>'application/vnd.oasis.opendocument.formula', 'icon'=>'odt.gif'),
82 'odb' => array ('type'=>'application/vnd.oasis.opendocument.database', 'icon'=>'odt.gif'),
83 'odi' => array ('type'=>'application/vnd.oasis.opendocument.image', 'icon'=>'odt.gif'),
84
a370c895 85 'pct' => array ('type'=>'image/pict', 'icon'=>'image.gif'),
86 'pdf' => array ('type'=>'application/pdf', 'icon'=>'pdf.gif'),
87 'php' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
88 'pic' => array ('type'=>'image/pict', 'icon'=>'image.gif'),
89 'pict' => array ('type'=>'image/pict', 'icon'=>'image.gif'),
90 'png' => array ('type'=>'image/png', 'icon'=>'image.gif'),
91 'pps' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'powerpoint.gif'),
92 'ppt' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'powerpoint.gif'),
93 'ps' => array ('type'=>'application/postscript', 'icon'=>'pdf.gif'),
94 'qt' => array ('type'=>'video/quicktime', 'icon'=>'video.gif'),
95 'ra' => array ('type'=>'audio/x-realaudio', 'icon'=>'audio.gif'),
96 'ram' => array ('type'=>'audio/x-pn-realaudio', 'icon'=>'audio.gif'),
a00420fb 97 'rhb' => array ('type'=>'text/xml', 'icon'=>'xml.gif'),
a370c895 98 'rm' => array ('type'=>'audio/x-pn-realaudio', 'icon'=>'audio.gif'),
99 'rtf' => array ('type'=>'text/rtf', 'icon'=>'text.gif'),
100 'rtx' => array ('type'=>'text/richtext', 'icon'=>'text.gif'),
101 'sh' => array ('type'=>'application/x-sh', 'icon'=>'text.gif'),
102 'sit' => array ('type'=>'application/x-stuffit', 'icon'=>'zip.gif'),
103 'smi' => array ('type'=>'application/smil', 'icon'=>'text.gif'),
104 'smil' => array ('type'=>'application/smil', 'icon'=>'text.gif'),
a00420fb 105 'sqt' => array ('type'=>'text/xml', 'icon'=>'xml.gif'),
a370c895 106 'swa' => array ('type'=>'application/x-director', 'icon'=>'flash.gif'),
107 'swf' => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash.gif'),
108 'swfl' => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash.gif'),
5395334d 109
110 'sxw' => array ('type'=>'application/vnd.sun.xml.writer', 'icon'=>'odt.gif'),
111 'stw' => array ('type'=>'application/vnd.sun.xml.writer.template', 'icon'=>'odt.gif'),
112 'sxc' => array ('type'=>'application/vnd.sun.xml.calc', 'icon'=>'odt.gif'),
113 'stc' => array ('type'=>'application/vnd.sun.xml.calc.template', 'icon'=>'odt.gif'),
114 'sxd' => array ('type'=>'application/vnd.sun.xml.draw', 'icon'=>'odt.gif'),
115 'std' => array ('type'=>'application/vnd.sun.xml.draw.template', 'icon'=>'odt.gif'),
116 'sxi' => array ('type'=>'application/vnd.sun.xml.impress', 'icon'=>'odt.gif'),
117 'sti' => array ('type'=>'application/vnd.sun.xml.impress.template', 'icon'=>'odt.gif'),
118 'sxg' => array ('type'=>'application/vnd.sun.xml.writer.global', 'icon'=>'odt.gif'),
119 'sxm' => array ('type'=>'application/vnd.sun.xml.math', 'icon'=>'odt.gif'),
120
a370c895 121 'tar' => array ('type'=>'application/x-tar', 'icon'=>'zip.gif'),
122 'tif' => array ('type'=>'image/tiff', 'icon'=>'image.gif'),
123 'tiff' => array ('type'=>'image/tiff', 'icon'=>'image.gif'),
124 'tex' => array ('type'=>'application/x-tex', 'icon'=>'text.gif'),
125 'texi' => array ('type'=>'application/x-texinfo', 'icon'=>'text.gif'),
126 'texinfo' => array ('type'=>'application/x-texinfo', 'icon'=>'text.gif'),
127 'tsv' => array ('type'=>'text/tab-separated-values', 'icon'=>'text.gif'),
128 'txt' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
129 'wav' => array ('type'=>'audio/wav', 'icon'=>'audio.gif'),
130 'wmv' => array ('type'=>'video/x-ms-wmv', 'icon'=>'avi.gif'),
131 'asf' => array ('type'=>'video/x-ms-asf', 'icon'=>'avi.gif'),
132 'xls' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'excel.gif'),
133 'xml' => array ('type'=>'application/xml', 'icon'=>'xml.gif'),
134 'xsl' => array ('type'=>'text/xml', 'icon'=>'xml.gif'),
135 'zip' => array ('type'=>'application/zip', 'icon'=>'zip.gif')
f1e0649c 136 );
3ce73b14 137}
138
139/**
140 * Obtains information about a filetype based on its extension. Will
141 * use a default if no information is present about that particular
142 * extension.
143 * @param string $element Desired information (usually 'icon'
144 * for icon filename or 'type' for MIME type)
145 * @param string $filename Filename we're looking up
146 * @return string Requested piece of information from array
147 */
148function mimeinfo($element, $filename) {
149 static $mimeinfo;
150 $mimeinfo=get_mimetypes_array();
f1e0649c 151
a370c895 152 if (eregi('\.([a-z0-9]+)$', $filename, $match)) {
f1e0649c 153 if (isset($mimeinfo[strtolower($match[1])][$element])) {
154 return $mimeinfo[strtolower($match[1])][$element];
155 } else {
a370c895 156 return $mimeinfo['xxx'][$element]; // By default
f1e0649c 157 }
158 } else {
a370c895 159 return $mimeinfo['xxx'][$element]; // By default
f1e0649c 160 }
161}
162
3ce73b14 163/**
164 * Obtains information about a filetype based on the MIME type rather than
165 * the other way around.
166 * @param string $element Desired information (usually 'icon')
167 * @param string $mimetype MIME type we're looking up
168 * @return string Requested piece of information from array
169 */
170function mimeinfo_from_type($element, $mimetype) {
171 static $mimeinfo;
172 $mimeinfo=get_mimetypes_array();
173
174 foreach($mimeinfo as $values) {
175 if($values['type']==$mimetype) {
176 if(isset($values[$element])) {
177 return $values[$element];
178 }
179 break;
180 }
181 }
182 return $mimeinfo['xxx'][$element]; // Default
183}
b9709b76 184
185/**
186 * @PARAM $filter int 0=no filtering, 1=all files, 2=html files only
187 */
188function send_file($path, $filename, $lifetime=86400 , $filter=0, $pathisstring=false, $forcedownload=false) {
85e00626 189 global $CFG;
f1e0649c 190
9b76b451 191 $mimetype = $forcedownload ? 'application/x-forcedownload' : mimeinfo('type', $filename);
f1e0649c 192 $lastmodified = $pathisstring ? time() : filemtime($path);
193 $filesize = $pathisstring ? strlen($path) : filesize($path);
194
69faecce 195 //IE compatibiltiy HACK!
4c8c65ec 196 if (ini_get('zlib.output_compression')) {
69faecce 197 ini_set('zlib.output_compression', 'Off');
198 }
199
4c8c65ec 200 //try to disable automatic sid rewrite in cookieless mode
8914cb82 201 @ini_set("session.use_trans_sid", "false");
4c8c65ec 202
203 //do not put '@' before the next header to detect incorrect moodle configurations,
204 //error should be better than "weird" empty lines for admins/users
205 //TODO: should we remove all those @ before the header()? Are all of the values supported on all servers?
206 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
207
208 if ($forcedownload) {
209 @header('Content-Disposition: attachment; filename='.$filename);
210 } else {
211 @header('Content-Disposition: inline; filename='.$filename);
212 }
213
f1e0649c 214 if ($lifetime > 0) {
4c8c65ec 215 @header('Cache-Control: max-age='.$lifetime);
216 @header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
f1e0649c 217 @header('Pragma: ');
4c8c65ec 218
219 if (empty($CFG->disablebyteserving) && !$pathisstring && $mimetype != 'text/plain' && $mimetype != 'text/html') {
220
221 @header('Accept-Ranges: bytes');
222
223 if (!empty($_SERVER['HTTP_RANGE']) && strpos($_SERVER['HTTP_RANGE'],'bytes=') !== FALSE) {
224 // byteserving stuff - for acrobat reader and download accelerators
225 // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
226 // inspired by: http://www.coneural.org/florian/papers/04_byteserving.php
227 $ranges = false;
228 if (preg_match_all('/(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER)) {
229 foreach ($ranges as $key=>$value) {
230 if ($ranges[$key][1] == '') {
231 //suffix case
232 $ranges[$key][1] = $filesize - $ranges[$key][2];
233 $ranges[$key][2] = $filesize - 1;
234 } else if ($ranges[$key][2] == '' || $ranges[$key][2] > $filesize - 1) {
235 //fix range length
236 $ranges[$key][2] = $filesize - 1;
237 }
238 if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
239 //invalid byte-range ==> ignore header
240 $ranges = false;
241 break;
242 }
243 //prepare multipart header
244 $ranges[$key][0] = "\r\n--".BYTESERVING_BOUNDARY."\r\nContent-Type: $mimetype\r\n";
245 $ranges[$key][0] .= "Content-Range: bytes {$ranges[$key][1]}-{$ranges[$key][2]}/$filesize\r\n\r\n";
246 }
247 } else {
248 $ranges = false;
249 }
250 if ($ranges) {
251 byteserving_send_file($path, $mimetype, $ranges);
252 }
253 }
254 } else {
255 /// Do not byteserve (disabled, strings, text and html files).
256 @header('Accept-Ranges: none');
257 }
258 } else { // Do not cache files in proxies and browsers
85e00626 259 if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
260 @header('Cache-Control: max-age=10');
4c8c65ec 261 @header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
85e00626 262 @header('Pragma: ');
263 } else { //normal http - prevent caching at all cost
264 @header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
4c8c65ec 265 @header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
85e00626 266 @header('Pragma: no-cache');
267 }
4c8c65ec 268 @header('Accept-Ranges: none'); // Do not allow byteserving when caching disabled
69faecce 269 }
f1e0649c 270
b9709b76 271 if (empty($filter)) {
4c8c65ec 272 if ($mimetype == 'text/html' && !empty($CFG->usesid) && empty($_COOKIE['MoodleSession'.$CFG->sessioncookie])) {
273 //cookieless mode - rewrite links
274 @header('Content-Type: text/html');
275 $path = $pathisstring ? $path : implode('', file($path));
276 $path = sid_ob_rewrite($path);
277 $filesize = strlen($path);
278 $pathisstring = true;
279 } else if ($mimetype == 'text/plain') {
280 @header('Content-Type: Text/plain; charset='.current_charset()); //add encoding
f1e0649c 281 } else {
4c8c65ec 282 @header('Content-Type: '.$mimetype);
f1e0649c 283 }
4c8c65ec 284 @header('Content-Length: '.$filesize);
285 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
f1e0649c 286 if ($pathisstring) {
287 echo $path;
4c8c65ec 288 } else {
69faecce 289 readfile_chunked($path);
f1e0649c 290 }
291 } else { // Try to put the file through filters
a370c895 292 global $course; // HACK!
f1e0649c 293 if (!empty($course->id)) {
294 $courseid = $course->id;
295 } else {
296 $courseid = SITEID;
297 }
298 if ($mimetype == 'text/html') {
299 $options->noclean = true;
300 $text = $pathisstring ? $path : implode('', file($path));
301 $output = format_text($text, FORMAT_HTML, $options, $courseid);
4c8c65ec 302 if (!empty($CFG->usesid) && empty($_COOKIE['MoodleSession'.$CFG->sessioncookie])) {
303 //cookieless mode - rewrite links
304 $output = sid_ob_rewrite($output);
305 }
f1e0649c 306
4c8c65ec 307 @header('Content-Length: '.strlen($output));
308 @header('Content-Type: text/html');
309 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
f1e0649c 310 echo $output;
b9709b76 311 // only filter text if filter all files is selected
312 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
f1e0649c 313 $options->newlines = false;
314 $options->noclean = true;
315 $text = htmlentities($pathisstring ? $path : implode('', file($path)));
316 $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $courseid) .'</pre>';
4c8c65ec 317 if (!empty($CFG->usesid) && empty($_COOKIE['MoodleSession'.$CFG->sessioncookie])) {
318 //cookieless mode - rewrite links
319 $output = sid_ob_rewrite($output);
320 }
f1e0649c 321
4c8c65ec 322 @header('Content-Length: '.strlen($output));
323 @header('Content-Type: text/html; charset='.current_charset()); //add encoding
324 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
f1e0649c 325 echo $output;
326 } else { // Just send it out raw
4c8c65ec 327 @header('Content-Length: '.$filesize);
328 @header('Content-Type: '.$mimetype);
329 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
f1e0649c 330 if ($pathisstring) {
331 echo $path;
332 }else {
69faecce 333 readfile_chunked($path);
f1e0649c 334 }
335 }
336 }
337 die; //no more chars to output!!!
338}
339
a43b5308 340function get_records_csv($file, $table) {
599f38f9 341 global $CFG, $db;
342
343 if (!$metacolumns = $db->MetaColumns($CFG->prefix . $table)) {
344 return false;
345 }
346
a77b98eb 347 if(!($handle = @fopen($file, 'r'))) {
599f38f9 348 error('get_records_csv failed to open '.$file);
349 }
350
351 $fieldnames = fgetcsv($handle, 4096);
352 if(empty($fieldnames)) {
353 fclose($handle);
354 return false;
355 }
356
357 $columns = array();
358
359 foreach($metacolumns as $metacolumn) {
360 $ord = array_search($metacolumn->name, $fieldnames);
361 if(is_int($ord)) {
362 $columns[$metacolumn->name] = $ord;
363 }
364 }
365
366 $rows = array();
367
368 while (($data = fgetcsv($handle, 4096)) !== false) {
369 $item = new stdClass;
370 foreach($columns as $name => $ord) {
371 $item->$name = $data[$ord];
372 }
373 $rows[] = $item;
374 }
375
376 fclose($handle);
377 return $rows;
378}
379
a77b98eb 380function put_records_csv($file, $records, $table = NULL) {
381 global $CFG, $db;
382
a1e93da2 383 if (empty($records)) {
a77b98eb 384 return true;
385 }
386
387 $metacolumns = NULL;
388 if ($table !== NULL && !$metacolumns = $db->MetaColumns($CFG->prefix . $table)) {
389 return false;
390 }
391
a1e93da2 392 echo "x";
393
a77b98eb 394 if(!($fp = @fopen($CFG->dataroot.'/temp/'.$file, 'w'))) {
395 error('put_records_csv failed to open '.$file);
396 }
397
a43b5308 398 $proto = reset($records);
399 if(is_object($proto)) {
400 $fields_records = array_keys(get_object_vars($proto));
401 }
402 else if(is_array($proto)) {
403 $fields_records = array_keys($proto);
404 }
405 else {
406 return false;
407 }
a1e93da2 408 echo "x";
a77b98eb 409
410 if(!empty($metacolumns)) {
411 $fields_table = array_map(create_function('$a', 'return $a->name;'), $metacolumns);
412 $fields = array_intersect($fields_records, $fields_table);
413 }
414 else {
415 $fields = $fields_records;
416 }
417
418 fwrite($fp, implode(',', $fields));
419 fwrite($fp, "\r\n");
420
421 foreach($records as $record) {
a43b5308 422 $array = (array)$record;
a77b98eb 423 $values = array();
424 foreach($fields as $field) {
a43b5308 425 if(strpos($array[$field], ',')) {
426 $values[] = '"'.str_replace('"', '\"', $array[$field]).'"';
a77b98eb 427 }
428 else {
a43b5308 429 $values[] = $array[$field];
a77b98eb 430 }
431 }
432 fwrite($fp, implode(',', $values)."\r\n");
433 }
434
435 fclose($fp);
436 return true;
437}
438
f401cc97 439
7ab8bb71 440if (!function_exists('file_get_contents')) {
441 function file_get_contents($file) {
442 $file = file($file);
443 return !$file ? false : implode('', $file);
444 }
445}
446
f401cc97 447
34763a79 448/**
449 * Recursively delete the file or folder with path $location. That is,
450 * if it is a file delete it. If it is a folder, delete all its content
451 * then delete it. If $location does not exist to start, that is not
452 * considered an error.
453 *
454 * @param $location the path to remove.
455 */
4c8c65ec 456function fulldelete($location) {
f401cc97 457 if (is_dir($location)) {
458 $currdir = opendir($location);
459 while (false !== ($file = readdir($currdir))) {
460 if ($file <> ".." && $file <> ".") {
461 $fullfile = $location."/".$file;
4c8c65ec 462 if (is_dir($fullfile)) {
f401cc97 463 if (!fulldelete($fullfile)) {
464 return false;
465 }
466 } else {
467 if (!unlink($fullfile)) {
468 return false;
469 }
4c8c65ec 470 }
f401cc97 471 }
4c8c65ec 472 }
f401cc97 473 closedir($currdir);
474 if (! rmdir($location)) {
475 return false;
476 }
477
34763a79 478 } else if (file_exists($location)) {
f401cc97 479 if (!unlink($location)) {
480 return false;
481 }
482 }
483 return true;
484}
485
4c8c65ec 486/**
487 * Improves memory consumptions and works around buggy readfile() in PHP 5.0.4 (2MB readfile limit).
488 */
489function readfile_chunked($filename, $retbytes=true) {
490 $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
69faecce 491 $buffer = '';
492 $cnt =0;// $handle = fopen($filename, 'rb');
493 $handle = fopen($filename, 'rb');
494 if ($handle === false) {
495 return false;
496 }
20371063 497
69faecce 498 while (!feof($handle)) {
68913aec 499 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
69faecce 500 $buffer = fread($handle, $chunksize);
501 echo $buffer;
20371063 502 flush();
69faecce 503 if ($retbytes) {
4c8c65ec 504 $cnt += strlen($buffer);
505 }
69faecce 506 }
507 $status = fclose($handle);
508 if ($retbytes && $status) {
509 return $cnt; // return num. bytes delivered like readfile() does.
510 }
511 return $status;
512}
513
4c8c65ec 514/**
515 * Send requested byterange of file.
516 */
517function byteserving_send_file($filename, $mimetype, $ranges) {
518 $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
519 $handle = fopen($filename, 'rb');
520 if ($handle === false) {
521 die;
522 }
523 if (count($ranges) == 1) { //only one range requested
524 $length = $ranges[0][2] - $ranges[0][1] + 1;
525 @header('HTTP/1.1 206 Partial content');
526 @header('Content-Length: '.$length);
527 @header('Content-Range: bytes '.$ranges[0][1].'-'.$ranges[0][2].'/'.filesize($filename));
528 @header('Content-Type: '.$mimetype);
529 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
530 $buffer = '';
531 fseek($handle, $ranges[0][1]);
532 while (!feof($handle) && $length > 0) {
68913aec 533 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
4c8c65ec 534 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
535 echo $buffer;
536 flush();
537 $length -= strlen($buffer);
538 }
539 fclose($handle);
540 die;
541 } else { // multiple ranges requested - not tested much
542 $totallength = 0;
543 foreach($ranges as $range) {
544 $totallength .= strlen($range[0]) + $range[2] - $range[1] + 1;
545 }
546 $totallength .= strlen("\r\n--".BYTESERVING_BOUNDARY."--\r\n");
547 @header('HTTP/1.1 206 Partial content');
548 @header('Content-Length: '.$totallength);
549 @header('Content-Type: multipart/byteranges; boundary='.BYTESERVING_BOUNDARY);
550 //TODO: check if "multipart/x-byteranges" is more compatible with current readers/browsers/servers
551 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
552 foreach($ranges as $range) {
553 $length = $range[2] - $range[1] + 1;
554 echo $range[0];
555 $buffer = '';
556 fseek($handle, $range[1]);
557 while (!feof($handle) && $length > 0) {
68913aec 558 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
4c8c65ec 559 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
560 echo $buffer;
561 flush();
562 $length -= strlen($buffer);
563 }
564 }
565 echo "\r\n--".BYTESERVING_BOUNDARY."--\r\n";
566 fclose($handle);
567 die;
568 }
569}
f401cc97 570
a77b98eb 571?>