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