Bug 6019: Quiz timer does not submit the form when it reaches zero. Merged from MOODL...
[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
c0381e22 185/**
186 * Obtains descriptions for file types (e.g. 'Microsoft Word document') from the
187 * mimetypes.php language file.
188 * @param string $mimetype MIME type (can be obtained using the mimeinfo function)
189 * @param bool $capitalise If true, capitalises first character of result
190 * @return string Text description
191 */
192function get_mimetype_description($mimetype,$capitalise=false) {
193 $result=get_string($mimetype,'mimetypes');
194 // Surrounded by square brackets indicates that there isn't a string for that
195 // (maybe there is a better way to find this out?)
196 if(strpos($result,'[')===0) {
197 $result=get_string('document/unknown','mimetypes');
198 }
199 if($capitalise) {
200 $result=ucfirst($result);
201 }
202 return $result;
203}
204
b9709b76 205/**
206 * @PARAM $filter int 0=no filtering, 1=all files, 2=html files only
207 */
208function send_file($path, $filename, $lifetime=86400 , $filter=0, $pathisstring=false, $forcedownload=false) {
85e00626 209 global $CFG;
f1e0649c 210
9b76b451 211 $mimetype = $forcedownload ? 'application/x-forcedownload' : mimeinfo('type', $filename);
f1e0649c 212 $lastmodified = $pathisstring ? time() : filemtime($path);
213 $filesize = $pathisstring ? strlen($path) : filesize($path);
214
69faecce 215 //IE compatibiltiy HACK!
4c8c65ec 216 if (ini_get('zlib.output_compression')) {
69faecce 217 ini_set('zlib.output_compression', 'Off');
218 }
219
4c8c65ec 220 //try to disable automatic sid rewrite in cookieless mode
8914cb82 221 @ini_set("session.use_trans_sid", "false");
4c8c65ec 222
223 //do not put '@' before the next header to detect incorrect moodle configurations,
224 //error should be better than "weird" empty lines for admins/users
225 //TODO: should we remove all those @ before the header()? Are all of the values supported on all servers?
226 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
227
228 if ($forcedownload) {
229 @header('Content-Disposition: attachment; filename='.$filename);
230 } else {
231 @header('Content-Disposition: inline; filename='.$filename);
232 }
233
f1e0649c 234 if ($lifetime > 0) {
4c8c65ec 235 @header('Cache-Control: max-age='.$lifetime);
236 @header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
f1e0649c 237 @header('Pragma: ');
4c8c65ec 238
239 if (empty($CFG->disablebyteserving) && !$pathisstring && $mimetype != 'text/plain' && $mimetype != 'text/html') {
240
241 @header('Accept-Ranges: bytes');
242
243 if (!empty($_SERVER['HTTP_RANGE']) && strpos($_SERVER['HTTP_RANGE'],'bytes=') !== FALSE) {
244 // byteserving stuff - for acrobat reader and download accelerators
245 // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
246 // inspired by: http://www.coneural.org/florian/papers/04_byteserving.php
247 $ranges = false;
248 if (preg_match_all('/(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER)) {
249 foreach ($ranges as $key=>$value) {
250 if ($ranges[$key][1] == '') {
251 //suffix case
252 $ranges[$key][1] = $filesize - $ranges[$key][2];
253 $ranges[$key][2] = $filesize - 1;
254 } else if ($ranges[$key][2] == '' || $ranges[$key][2] > $filesize - 1) {
255 //fix range length
256 $ranges[$key][2] = $filesize - 1;
257 }
258 if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
259 //invalid byte-range ==> ignore header
260 $ranges = false;
261 break;
262 }
263 //prepare multipart header
264 $ranges[$key][0] = "\r\n--".BYTESERVING_BOUNDARY."\r\nContent-Type: $mimetype\r\n";
265 $ranges[$key][0] .= "Content-Range: bytes {$ranges[$key][1]}-{$ranges[$key][2]}/$filesize\r\n\r\n";
266 }
267 } else {
268 $ranges = false;
269 }
270 if ($ranges) {
271 byteserving_send_file($path, $mimetype, $ranges);
272 }
273 }
274 } else {
275 /// Do not byteserve (disabled, strings, text and html files).
276 @header('Accept-Ranges: none');
277 }
278 } else { // Do not cache files in proxies and browsers
85e00626 279 if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
280 @header('Cache-Control: max-age=10');
4c8c65ec 281 @header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
85e00626 282 @header('Pragma: ');
283 } else { //normal http - prevent caching at all cost
284 @header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
4c8c65ec 285 @header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
85e00626 286 @header('Pragma: no-cache');
287 }
4c8c65ec 288 @header('Accept-Ranges: none'); // Do not allow byteserving when caching disabled
69faecce 289 }
f1e0649c 290
b9709b76 291 if (empty($filter)) {
4c8c65ec 292 if ($mimetype == 'text/html' && !empty($CFG->usesid) && empty($_COOKIE['MoodleSession'.$CFG->sessioncookie])) {
293 //cookieless mode - rewrite links
294 @header('Content-Type: text/html');
295 $path = $pathisstring ? $path : implode('', file($path));
296 $path = sid_ob_rewrite($path);
297 $filesize = strlen($path);
298 $pathisstring = true;
299 } else if ($mimetype == 'text/plain') {
300 @header('Content-Type: Text/plain; charset='.current_charset()); //add encoding
f1e0649c 301 } else {
4c8c65ec 302 @header('Content-Type: '.$mimetype);
f1e0649c 303 }
4c8c65ec 304 @header('Content-Length: '.$filesize);
305 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
f1e0649c 306 if ($pathisstring) {
307 echo $path;
4c8c65ec 308 } else {
69faecce 309 readfile_chunked($path);
f1e0649c 310 }
311 } else { // Try to put the file through filters
a370c895 312 global $course; // HACK!
f1e0649c 313 if (!empty($course->id)) {
314 $courseid = $course->id;
315 } else {
316 $courseid = SITEID;
317 }
318 if ($mimetype == 'text/html') {
319 $options->noclean = true;
320 $text = $pathisstring ? $path : implode('', file($path));
321 $output = format_text($text, FORMAT_HTML, $options, $courseid);
4c8c65ec 322 if (!empty($CFG->usesid) && empty($_COOKIE['MoodleSession'.$CFG->sessioncookie])) {
323 //cookieless mode - rewrite links
324 $output = sid_ob_rewrite($output);
325 }
f1e0649c 326
4c8c65ec 327 @header('Content-Length: '.strlen($output));
328 @header('Content-Type: text/html');
329 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
f1e0649c 330 echo $output;
b9709b76 331 // only filter text if filter all files is selected
332 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
f1e0649c 333 $options->newlines = false;
334 $options->noclean = true;
335 $text = htmlentities($pathisstring ? $path : implode('', file($path)));
336 $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $courseid) .'</pre>';
4c8c65ec 337 if (!empty($CFG->usesid) && empty($_COOKIE['MoodleSession'.$CFG->sessioncookie])) {
338 //cookieless mode - rewrite links
339 $output = sid_ob_rewrite($output);
340 }
f1e0649c 341
4c8c65ec 342 @header('Content-Length: '.strlen($output));
343 @header('Content-Type: text/html; charset='.current_charset()); //add encoding
344 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
f1e0649c 345 echo $output;
346 } else { // Just send it out raw
4c8c65ec 347 @header('Content-Length: '.$filesize);
348 @header('Content-Type: '.$mimetype);
349 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
f1e0649c 350 if ($pathisstring) {
351 echo $path;
352 }else {
69faecce 353 readfile_chunked($path);
f1e0649c 354 }
355 }
356 }
357 die; //no more chars to output!!!
358}
359
a43b5308 360function get_records_csv($file, $table) {
599f38f9 361 global $CFG, $db;
362
363 if (!$metacolumns = $db->MetaColumns($CFG->prefix . $table)) {
364 return false;
365 }
366
a77b98eb 367 if(!($handle = @fopen($file, 'r'))) {
599f38f9 368 error('get_records_csv failed to open '.$file);
369 }
370
371 $fieldnames = fgetcsv($handle, 4096);
372 if(empty($fieldnames)) {
373 fclose($handle);
374 return false;
375 }
376
377 $columns = array();
378
379 foreach($metacolumns as $metacolumn) {
380 $ord = array_search($metacolumn->name, $fieldnames);
381 if(is_int($ord)) {
382 $columns[$metacolumn->name] = $ord;
383 }
384 }
385
386 $rows = array();
387
388 while (($data = fgetcsv($handle, 4096)) !== false) {
389 $item = new stdClass;
390 foreach($columns as $name => $ord) {
391 $item->$name = $data[$ord];
392 }
393 $rows[] = $item;
394 }
395
396 fclose($handle);
397 return $rows;
398}
399
a77b98eb 400function put_records_csv($file, $records, $table = NULL) {
401 global $CFG, $db;
402
a1e93da2 403 if (empty($records)) {
a77b98eb 404 return true;
405 }
406
407 $metacolumns = NULL;
408 if ($table !== NULL && !$metacolumns = $db->MetaColumns($CFG->prefix . $table)) {
409 return false;
410 }
411
a1e93da2 412 echo "x";
413
a77b98eb 414 if(!($fp = @fopen($CFG->dataroot.'/temp/'.$file, 'w'))) {
415 error('put_records_csv failed to open '.$file);
416 }
417
a43b5308 418 $proto = reset($records);
419 if(is_object($proto)) {
420 $fields_records = array_keys(get_object_vars($proto));
421 }
422 else if(is_array($proto)) {
423 $fields_records = array_keys($proto);
424 }
425 else {
426 return false;
427 }
a1e93da2 428 echo "x";
a77b98eb 429
430 if(!empty($metacolumns)) {
431 $fields_table = array_map(create_function('$a', 'return $a->name;'), $metacolumns);
432 $fields = array_intersect($fields_records, $fields_table);
433 }
434 else {
435 $fields = $fields_records;
436 }
437
438 fwrite($fp, implode(',', $fields));
439 fwrite($fp, "\r\n");
440
441 foreach($records as $record) {
a43b5308 442 $array = (array)$record;
a77b98eb 443 $values = array();
444 foreach($fields as $field) {
a43b5308 445 if(strpos($array[$field], ',')) {
446 $values[] = '"'.str_replace('"', '\"', $array[$field]).'"';
a77b98eb 447 }
448 else {
a43b5308 449 $values[] = $array[$field];
a77b98eb 450 }
451 }
452 fwrite($fp, implode(',', $values)."\r\n");
453 }
454
455 fclose($fp);
456 return true;
457}
458
f401cc97 459
7ab8bb71 460if (!function_exists('file_get_contents')) {
461 function file_get_contents($file) {
462 $file = file($file);
463 return !$file ? false : implode('', $file);
464 }
465}
466
f401cc97 467
34763a79 468/**
469 * Recursively delete the file or folder with path $location. That is,
470 * if it is a file delete it. If it is a folder, delete all its content
471 * then delete it. If $location does not exist to start, that is not
472 * considered an error.
473 *
474 * @param $location the path to remove.
475 */
4c8c65ec 476function fulldelete($location) {
f401cc97 477 if (is_dir($location)) {
478 $currdir = opendir($location);
479 while (false !== ($file = readdir($currdir))) {
480 if ($file <> ".." && $file <> ".") {
481 $fullfile = $location."/".$file;
4c8c65ec 482 if (is_dir($fullfile)) {
f401cc97 483 if (!fulldelete($fullfile)) {
484 return false;
485 }
486 } else {
487 if (!unlink($fullfile)) {
488 return false;
489 }
4c8c65ec 490 }
f401cc97 491 }
4c8c65ec 492 }
f401cc97 493 closedir($currdir);
494 if (! rmdir($location)) {
495 return false;
496 }
497
34763a79 498 } else if (file_exists($location)) {
f401cc97 499 if (!unlink($location)) {
500 return false;
501 }
502 }
503 return true;
504}
505
4c8c65ec 506/**
507 * Improves memory consumptions and works around buggy readfile() in PHP 5.0.4 (2MB readfile limit).
508 */
509function readfile_chunked($filename, $retbytes=true) {
510 $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
69faecce 511 $buffer = '';
512 $cnt =0;// $handle = fopen($filename, 'rb');
513 $handle = fopen($filename, 'rb');
514 if ($handle === false) {
515 return false;
516 }
20371063 517
69faecce 518 while (!feof($handle)) {
68913aec 519 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
69faecce 520 $buffer = fread($handle, $chunksize);
521 echo $buffer;
20371063 522 flush();
69faecce 523 if ($retbytes) {
4c8c65ec 524 $cnt += strlen($buffer);
525 }
69faecce 526 }
527 $status = fclose($handle);
528 if ($retbytes && $status) {
529 return $cnt; // return num. bytes delivered like readfile() does.
530 }
531 return $status;
532}
533
4c8c65ec 534/**
535 * Send requested byterange of file.
536 */
537function byteserving_send_file($filename, $mimetype, $ranges) {
538 $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
539 $handle = fopen($filename, 'rb');
540 if ($handle === false) {
541 die;
542 }
543 if (count($ranges) == 1) { //only one range requested
544 $length = $ranges[0][2] - $ranges[0][1] + 1;
545 @header('HTTP/1.1 206 Partial content');
546 @header('Content-Length: '.$length);
547 @header('Content-Range: bytes '.$ranges[0][1].'-'.$ranges[0][2].'/'.filesize($filename));
548 @header('Content-Type: '.$mimetype);
549 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
550 $buffer = '';
551 fseek($handle, $ranges[0][1]);
552 while (!feof($handle) && $length > 0) {
68913aec 553 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
4c8c65ec 554 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
555 echo $buffer;
556 flush();
557 $length -= strlen($buffer);
558 }
559 fclose($handle);
560 die;
561 } else { // multiple ranges requested - not tested much
562 $totallength = 0;
563 foreach($ranges as $range) {
aba588a7 564 $totallength += strlen($range[0]) + $range[2] - $range[1] + 1;
4c8c65ec 565 }
aba588a7 566 $totallength += strlen("\r\n--".BYTESERVING_BOUNDARY."--\r\n");
4c8c65ec 567 @header('HTTP/1.1 206 Partial content');
568 @header('Content-Length: '.$totallength);
569 @header('Content-Type: multipart/byteranges; boundary='.BYTESERVING_BOUNDARY);
570 //TODO: check if "multipart/x-byteranges" is more compatible with current readers/browsers/servers
571 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
572 foreach($ranges as $range) {
573 $length = $range[2] - $range[1] + 1;
574 echo $range[0];
575 $buffer = '';
576 fseek($handle, $range[1]);
577 while (!feof($handle) && $length > 0) {
68913aec 578 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
4c8c65ec 579 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
580 echo $buffer;
581 flush();
582 $length -= strlen($buffer);
583 }
584 }
585 echo "\r\n--".BYTESERVING_BOUNDARY."--\r\n";
586 fclose($handle);
587 die;
588 }
589}
f401cc97 590
a77b98eb 591?>