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) {
13 $ch = curl_init($url);
14 curl_setopt($ch, CURLOPT_RETURNTRANSFER
, true);
15 curl_setopt($ch, CURLOPT_HEADER
, false);
16 if (!empty($CFG->proxyhost
)) {
17 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL
, true);
18 if (empty($CFG->proxyport
)) {
19 curl_setopt($ch, CURLOPT_PROXY
, $CFG->proxy
);
21 curl_setopt($ch, CURLOPT_PROXY
, $CFG->proxy
.':'.$CFG->proxyport
);
23 if(!empty($CFG->proxyuser
) and !empty($CFG->proxypassword
)) {
24 curl_setopt($ch, CURLOPT_PROXYUSERPWD
, $CFG->proxyuser
.':'.$CFG->proxypassword
);
27 $result = curl_exec($ch);
33 * @return List of information about file types based on extensions.
34 * Associative array of extension (lower-case) to associative array
35 * from 'element name' to data. Current element names are 'type' and 'icon'.
36 * Unknown types should use the 'xxx' entry which includes defaults.
38 function get_mimetypes_array() {
40 'xxx' => array ('type'=>'document/unknown', 'icon'=>'unknown.gif'),
41 '3gp' => array ('type'=>'video/quicktime', 'icon'=>'video.gif'),
42 'ai' => array ('type'=>'application/postscript', 'icon'=>'image.gif'),
43 'aif' => array ('type'=>'audio/x-aiff', 'icon'=>'audio.gif'),
44 'aiff' => array ('type'=>'audio/x-aiff', 'icon'=>'audio.gif'),
45 'aifc' => array ('type'=>'audio/x-aiff', 'icon'=>'audio.gif'),
46 'applescript' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
47 'asc' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
48 'asm' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
49 'au' => array ('type'=>'audio/au', 'icon'=>'audio.gif'),
50 'avi' => array ('type'=>'video/x-ms-wm', 'icon'=>'avi.gif'),
51 'bmp' => array ('type'=>'image/bmp', 'icon'=>'image.gif'),
52 'c' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
53 'cct' => array ('type'=>'shockwave/director', 'icon'=>'flash.gif'),
54 'cpp' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
55 'cs' => array ('type'=>'application/x-csh', 'icon'=>'text.gif'),
56 'css' => array ('type'=>'text/css', 'icon'=>'text.gif'),
57 'csv' => array ('type'=>'text/csv', 'icon'=>'excel.gif'),
58 'dv' => array ('type'=>'video/x-dv', 'icon'=>'video.gif'),
59 'dmg' => array ('type'=>'application/octet-stream', 'icon'=>'dmg.gif'),
60 'doc' => array ('type'=>'application/msword', 'icon'=>'word.gif'),
61 'dcr' => array ('type'=>'application/x-director', 'icon'=>'flash.gif'),
62 'dif' => array ('type'=>'video/x-dv', 'icon'=>'video.gif'),
63 'dir' => array ('type'=>'application/x-director', 'icon'=>'flash.gif'),
64 'dxr' => array ('type'=>'application/x-director', 'icon'=>'flash.gif'),
65 'eps' => array ('type'=>'application/postscript', 'icon'=>'pdf.gif'),
66 'fdf' => array ('type'=>'application/pdf', 'icon'=>'pdf.gif'),
67 'gif' => array ('type'=>'image/gif', 'icon'=>'image.gif'),
68 'gtar' => array ('type'=>'application/x-gtar', 'icon'=>'zip.gif'),
69 'tgz' => array ('type'=>'application/g-zip', 'icon'=>'zip.gif'),
70 'gz' => array ('type'=>'application/g-zip', 'icon'=>'zip.gif'),
71 'gzip' => array ('type'=>'application/g-zip', 'icon'=>'zip.gif'),
72 'h' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
73 'hpp' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
74 'hqx' => array ('type'=>'application/mac-binhex40', 'icon'=>'zip.gif'),
75 'htc' => array ('type'=>'text/x-component', 'icon'=>'text.gif'),
76 'html' => array ('type'=>'text/html', 'icon'=>'html.gif'),
77 'xhtml'=> array ('type'=>'application/xhtml+xml', 'icon'=>'html.gif'),
78 'htm' => array ('type'=>'text/html', 'icon'=>'html.gif'),
79 'ico' => array ('type'=>'image/vnd.microsoft.icon', 'icon'=>'image.gif'),
80 'isf' => array ('type'=>'application/inspiration', 'icon'=>'isf.gif'),
81 'ist' => array ('type'=>'application/inspiration.template', 'icon'=>'isf.gif'),
82 'java' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
83 'jcb' => array ('type'=>'text/xml', 'icon'=>'jcb.gif'),
84 'jcl' => array ('type'=>'text/xml', 'icon'=>'jcl.gif'),
85 'jcw' => array ('type'=>'text/xml', 'icon'=>'jcw.gif'),
86 'jmt' => array ('type'=>'text/xml', 'icon'=>'jmt.gif'),
87 'jmx' => array ('type'=>'text/xml', 'icon'=>'jmx.gif'),
88 'jpe' => array ('type'=>'image/jpeg', 'icon'=>'image.gif'),
89 'jpeg' => array ('type'=>'image/jpeg', 'icon'=>'image.gif'),
90 'jpg' => array ('type'=>'image/jpeg', 'icon'=>'image.gif'),
91 'jqz' => array ('type'=>'text/xml', 'icon'=>'jqz.gif'),
92 'js' => array ('type'=>'application/x-javascript', 'icon'=>'text.gif'),
93 'latex'=> array ('type'=>'application/x-latex', 'icon'=>'text.gif'),
94 'm' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
95 'mov' => array ('type'=>'video/quicktime', 'icon'=>'video.gif'),
96 'movie'=> array ('type'=>'video/x-sgi-movie', 'icon'=>'video.gif'),
97 'm3u' => array ('type'=>'audio/x-mpegurl', 'icon'=>'audio.gif'),
98 'mp3' => array ('type'=>'audio/mp3', 'icon'=>'audio.gif'),
99 'mp4' => array ('type'=>'video/mp4', 'icon'=>'video.gif'),
100 'mpeg' => array ('type'=>'video/mpeg', 'icon'=>'video.gif'),
101 'mpe' => array ('type'=>'video/mpeg', 'icon'=>'video.gif'),
102 'mpg' => array ('type'=>'video/mpeg', 'icon'=>'video.gif'),
104 'odt' => array ('type'=>'application/vnd.oasis.opendocument.text', 'icon'=>'odt.gif'),
105 'ott' => array ('type'=>'application/vnd.oasis.opendocument.text-template', 'icon'=>'odt.gif'),
106 'oth' => array ('type'=>'application/vnd.oasis.opendocument.text-web', 'icon'=>'odt.gif'),
107 'odm' => array ('type'=>'application/vnd.oasis.opendocument.text-master', 'icon'=>'odm.gif'),
108 'odg' => array ('type'=>'application/vnd.oasis.opendocument.graphics', 'icon'=>'odg.gif'),
109 'otg' => array ('type'=>'application/vnd.oasis.opendocument.graphics-template', 'icon'=>'odg.gif'),
110 'odp' => array ('type'=>'application/vnd.oasis.opendocument.presentation', 'icon'=>'odp.gif'),
111 'otp' => array ('type'=>'application/vnd.oasis.opendocument.presentation-template', 'icon'=>'odp.gif'),
112 'ods' => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet', 'icon'=>'ods.gif'),
113 'ots' => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet-template', 'icon'=>'ods.gif'),
114 'odc' => array ('type'=>'application/vnd.oasis.opendocument.chart', 'icon'=>'odc.gif'),
115 'odf' => array ('type'=>'application/vnd.oasis.opendocument.formula', 'icon'=>'odf.gif'),
116 'odb' => array ('type'=>'application/vnd.oasis.opendocument.database', 'icon'=>'odb.gif'),
117 'odi' => array ('type'=>'application/vnd.oasis.opendocument.image', 'icon'=>'odi.gif'),
119 'pct' => array ('type'=>'image/pict', 'icon'=>'image.gif'),
120 'pdf' => array ('type'=>'application/pdf', 'icon'=>'pdf.gif'),
121 'php' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
122 'pic' => array ('type'=>'image/pict', 'icon'=>'image.gif'),
123 'pict' => array ('type'=>'image/pict', 'icon'=>'image.gif'),
124 'png' => array ('type'=>'image/png', 'icon'=>'image.gif'),
125 'pps' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'powerpoint.gif'),
126 'ppt' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'powerpoint.gif'),
127 'ps' => array ('type'=>'application/postscript', 'icon'=>'pdf.gif'),
128 'qt' => array ('type'=>'video/quicktime', 'icon'=>'video.gif'),
129 'ra' => array ('type'=>'audio/x-realaudio', 'icon'=>'audio.gif'),
130 'ram' => array ('type'=>'audio/x-pn-realaudio', 'icon'=>'audio.gif'),
131 'rhb' => array ('type'=>'text/xml', 'icon'=>'xml.gif'),
132 'rm' => array ('type'=>'audio/x-pn-realaudio', 'icon'=>'audio.gif'),
133 'rtf' => array ('type'=>'text/rtf', 'icon'=>'text.gif'),
134 'rtx' => array ('type'=>'text/richtext', 'icon'=>'text.gif'),
135 'sh' => array ('type'=>'application/x-sh', 'icon'=>'text.gif'),
136 'sit' => array ('type'=>'application/x-stuffit', 'icon'=>'zip.gif'),
137 'smi' => array ('type'=>'application/smil', 'icon'=>'text.gif'),
138 'smil' => array ('type'=>'application/smil', 'icon'=>'text.gif'),
139 'sqt' => array ('type'=>'text/xml', 'icon'=>'xml.gif'),
140 'svg' => array ('type'=>'image/svg+xml', 'icon'=>'image.gif'),
141 'svgz' => array ('type'=>'image/svg+xml', 'icon'=>'image.gif'),
142 'swa' => array ('type'=>'application/x-director', 'icon'=>'flash.gif'),
143 'swf' => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash.gif'),
144 'swfl' => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash.gif'),
146 'sxw' => array ('type'=>'application/vnd.sun.xml.writer', 'icon'=>'odt.gif'),
147 'stw' => array ('type'=>'application/vnd.sun.xml.writer.template', 'icon'=>'odt.gif'),
148 'sxc' => array ('type'=>'application/vnd.sun.xml.calc', 'icon'=>'odt.gif'),
149 'stc' => array ('type'=>'application/vnd.sun.xml.calc.template', 'icon'=>'odt.gif'),
150 'sxd' => array ('type'=>'application/vnd.sun.xml.draw', 'icon'=>'odt.gif'),
151 'std' => array ('type'=>'application/vnd.sun.xml.draw.template', 'icon'=>'odt.gif'),
152 'sxi' => array ('type'=>'application/vnd.sun.xml.impress', 'icon'=>'odt.gif'),
153 'sti' => array ('type'=>'application/vnd.sun.xml.impress.template', 'icon'=>'odt.gif'),
154 'sxg' => array ('type'=>'application/vnd.sun.xml.writer.global', 'icon'=>'odt.gif'),
155 'sxm' => array ('type'=>'application/vnd.sun.xml.math', 'icon'=>'odt.gif'),
157 'tar' => array ('type'=>'application/x-tar', 'icon'=>'zip.gif'),
158 'tif' => array ('type'=>'image/tiff', 'icon'=>'image.gif'),
159 'tiff' => array ('type'=>'image/tiff', 'icon'=>'image.gif'),
160 'tex' => array ('type'=>'application/x-tex', 'icon'=>'text.gif'),
161 'texi' => array ('type'=>'application/x-texinfo', 'icon'=>'text.gif'),
162 'texinfo' => array ('type'=>'application/x-texinfo', 'icon'=>'text.gif'),
163 'tsv' => array ('type'=>'text/tab-separated-values', 'icon'=>'text.gif'),
164 'txt' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
165 'wav' => array ('type'=>'audio/wav', 'icon'=>'audio.gif'),
166 'wmv' => array ('type'=>'video/x-ms-wmv', 'icon'=>'avi.gif'),
167 'asf' => array ('type'=>'video/x-ms-asf', 'icon'=>'avi.gif'),
168 'xdp' => array ('type'=>'application/pdf', 'icon'=>'pdf.gif'),
169 'xfd' => array ('type'=>'application/pdf', 'icon'=>'pdf.gif'),
170 'xfdf' => array ('type'=>'application/pdf', 'icon'=>'pdf.gif'),
171 'xls' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'excel.gif'),
172 'xml' => array ('type'=>'application/xml', 'icon'=>'xml.gif'),
173 'xsl' => array ('type'=>'text/xml', 'icon'=>'xml.gif'),
174 'zip' => array ('type'=>'application/zip', 'icon'=>'zip.gif')
179 * Obtains information about a filetype based on its extension. Will
180 * use a default if no information is present about that particular
182 * @param string $element Desired information (usually 'icon'
183 * for icon filename or 'type' for MIME type)
184 * @param string $filename Filename we're looking up
185 * @return string Requested piece of information from array
187 function mimeinfo($element, $filename) {
189 $mimeinfo=get_mimetypes_array();
191 if (eregi('\.([a-z0-9]+)$', $filename, $match)) {
192 if (isset($mimeinfo[strtolower($match[1])][$element])) {
193 return $mimeinfo[strtolower($match[1])][$element];
195 return $mimeinfo['xxx'][$element]; // By default
198 return $mimeinfo['xxx'][$element]; // By default
203 * Obtains information about a filetype based on the MIME type rather than
204 * the other way around.
205 * @param string $element Desired information (usually 'icon')
206 * @param string $mimetype MIME type we're looking up
207 * @return string Requested piece of information from array
209 function mimeinfo_from_type($element, $mimetype) {
211 $mimeinfo=get_mimetypes_array();
213 foreach($mimeinfo as $values) {
214 if($values['type']==$mimetype) {
215 if(isset($values[$element])) {
216 return $values[$element];
221 return $mimeinfo['xxx'][$element]; // Default
225 * Obtains descriptions for file types (e.g. 'Microsoft Word document') from the
226 * mimetypes.php language file.
227 * @param string $mimetype MIME type (can be obtained using the mimeinfo function)
228 * @param bool $capitalise If true, capitalises first character of result
229 * @return string Text description
231 function get_mimetype_description($mimetype,$capitalise=false) {
232 $result=get_string($mimetype,'mimetypes');
233 // Surrounded by square brackets indicates that there isn't a string for that
234 // (maybe there is a better way to find this out?)
235 if(strpos($result,'[')===0) {
236 $result=get_string('document/unknown','mimetypes');
239 $result=ucfirst($result);
245 * Handles the sending of file data to the user's browser, including support for
247 * @param string $path Path of file on disk (including real filename), or actual content of file as string
248 * @param string $filename Filename to send
249 * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
250 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
251 * @param bool $pathisstring If true (default false), $path is the content to send and not the pathname
252 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
253 * @param string $mimetype Include to specify the MIME type; leave blank to have it guess the type from $filename
255 function send_file($path, $filename, $lifetime=86400 , $filter=0, $pathisstring=false, $forcedownload=false, $mimetype='') {
256 global $CFG, $COURSE;
258 // Use given MIME type if specified, otherwise guess it using mimeinfo.
259 // IE, Konqueror and Opera open html file directly in browser from web even when directed to save it to disk :-O
260 // only Firefox saves all files locally before opening when content-disposition: attachment stated
261 $isFF = check_browser_version('Firefox', '1.5'); // only FF > 1.5 properly tested
262 $mimetype = ($forcedownload and !$isFF) ?
'application/x-forcedownload' :
263 ($mimetype ?
$mimetype : mimeinfo('type', $filename));
264 $lastmodified = $pathisstring ?
time() : filemtime($path);
265 $filesize = $pathisstring ?
strlen($path) : filesize($path);
267 //Adobe Acrobat Reader XSS prevention
268 if ($mimetype=='application/pdf' or mimeinfo('type', $filename)=='application/pdf') {
269 //please note that it prevents opening of pdfs in browser when http referer disabled
270 //or file linked from another site; browser caching of pdfs is now disabled too
271 if (!empty($_SERVER['HTTP_RANGE'])) {
272 //already byteserving
273 $lifetime = 1; // >0 needed for byteserving
274 } else if (empty($_SERVER['HTTP_REFERER']) or strpos($_SERVER['HTTP_REFERER'], $CFG->wwwroot
)!==0) {
275 $mimetype = 'application/x-forcedownload';
276 $forcedownload = true;
279 $lifetime = 1; // >0 needed for byteserving
283 //IE compatibiltiy HACK!
284 if (ini_get('zlib.output_compression')) {
285 ini_set('zlib.output_compression', 'Off');
288 //try to disable automatic sid rewrite in cookieless mode
289 @ini_set
("session.use_trans_sid", "false");
291 //do not put '@' before the next header to detect incorrect moodle configurations,
292 //error should be better than "weird" empty lines for admins/users
293 //TODO: should we remove all those @ before the header()? Are all of the values supported on all servers?
294 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
296 if ($forcedownload) {
297 @header
('Content-Disposition: attachment; filename='.$filename);
299 @header
('Content-Disposition: inline; filename='.$filename);
303 @header
('Cache-Control: max-age='.$lifetime);
304 @header
('Expires: '. gmdate('D, d M Y H:i:s', time() +
$lifetime) .' GMT');
307 if (empty($CFG->disablebyteserving
) && !$pathisstring && $mimetype != 'text/plain' && $mimetype != 'text/html') {
309 @header
('Accept-Ranges: bytes');
311 if (!empty($_SERVER['HTTP_RANGE']) && strpos($_SERVER['HTTP_RANGE'],'bytes=') !== FALSE) {
312 // byteserving stuff - for acrobat reader and download accelerators
313 // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
314 // inspired by: http://www.coneural.org/florian/papers/04_byteserving.php
316 if (preg_match_all('/(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER
)) {
317 foreach ($ranges as $key=>$value) {
318 if ($ranges[$key][1] == '') {
320 $ranges[$key][1] = $filesize - $ranges[$key][2];
321 $ranges[$key][2] = $filesize - 1;
322 } else if ($ranges[$key][2] == '' ||
$ranges[$key][2] > $filesize - 1) {
324 $ranges[$key][2] = $filesize - 1;
326 if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
327 //invalid byte-range ==> ignore header
331 //prepare multipart header
332 $ranges[$key][0] = "\r\n--".BYTESERVING_BOUNDARY
."\r\nContent-Type: $mimetype\r\n";
333 $ranges[$key][0] .= "Content-Range: bytes {$ranges[$key][1]}-{$ranges[$key][2]}/$filesize\r\n\r\n";
339 byteserving_send_file($path, $mimetype, $ranges);
343 /// Do not byteserve (disabled, strings, text and html files).
344 @header
('Accept-Ranges: none');
346 } else { // Do not cache files in proxies and browsers
347 if (strpos($CFG->wwwroot
, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
348 @header
('Cache-Control: max-age=10');
349 @header
('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
351 } else { //normal http - prevent caching at all cost
352 @header
('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
353 @header
('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
354 @header
('Pragma: no-cache');
356 @header
('Accept-Ranges: none'); // Do not allow byteserving when caching disabled
359 if (empty($filter)) {
360 if ($mimetype == 'text/html' && !empty($CFG->usesid
) && empty($_COOKIE['MoodleSession'.$CFG->sessioncookie
])) {
361 //cookieless mode - rewrite links
362 @header
('Content-Type: text/html');
363 $path = $pathisstring ?
$path : implode('', file($path));
364 $path = sid_ob_rewrite($path);
365 $filesize = strlen($path);
366 $pathisstring = true;
367 } else if ($mimetype == 'text/plain') {
368 @header
('Content-Type: Text/plain; charset=utf-8'); //add encoding
370 @header
('Content-Type: '.$mimetype);
372 @header
('Content-Length: '.$filesize);
373 while (@ob_end_flush
()); //flush the buffers - save memory and disable sid rewrite
377 readfile_chunked($path);
379 } else { // Try to put the file through filters
380 if ($mimetype == 'text/html') {
381 $options = new object();
382 $options->noclean
= true;
383 $options->nocache
= true; // temporary workaround for MDL-5136
384 $text = $pathisstring ?
$path : implode('', file($path));
385 $output = format_text($text, FORMAT_HTML
, $options, $COURSE->id
);
386 if (!empty($CFG->usesid
) && empty($_COOKIE['MoodleSession'.$CFG->sessioncookie
])) {
387 //cookieless mode - rewrite links
388 $output = sid_ob_rewrite($output);
391 @header
('Content-Length: '.strlen($output));
392 @header
('Content-Type: text/html');
393 while (@ob_end_flush
()); //flush the buffers - save memory and disable sid rewrite
395 // only filter text if filter all files is selected
396 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
397 $options = new object();
398 $options->newlines
= false;
399 $options->noclean
= true;
400 $text = htmlentities($pathisstring ?
$path : implode('', file($path)));
401 $output = '<pre>'. format_text($text, FORMAT_MOODLE
, $options, $COURSE->id
) .'</pre>';
402 if (!empty($CFG->usesid
) && empty($_COOKIE['MoodleSession'.$CFG->sessioncookie
])) {
403 //cookieless mode - rewrite links
404 $output = sid_ob_rewrite($output);
407 @header
('Content-Length: '.strlen($output));
408 @header
('Content-Type: text/html; charset=utf-8'); //add encoding
409 while (@ob_end_flush
()); //flush the buffers - save memory and disable sid rewrite
411 } else { // Just send it out raw
412 @header
('Content-Length: '.$filesize);
413 @header
('Content-Type: '.$mimetype);
414 while (@ob_end_flush
()); //flush the buffers - save memory and disable sid rewrite
418 readfile_chunked($path);
422 die; //no more chars to output!!!
425 function get_records_csv($file, $table) {
428 if (!$metacolumns = $db->MetaColumns($CFG->prefix
. $table)) {
432 if(!($handle = @fopen
($file, 'r'))) {
433 error('get_records_csv failed to open '.$file);
436 $fieldnames = fgetcsv($handle, 4096);
437 if(empty($fieldnames)) {
444 foreach($metacolumns as $metacolumn) {
445 $ord = array_search($metacolumn->name
, $fieldnames);
447 $columns[$metacolumn->name
] = $ord;
453 while (($data = fgetcsv($handle, 4096)) !== false) {
454 $item = new stdClass
;
455 foreach($columns as $name => $ord) {
456 $item->$name = $data[$ord];
465 function put_records_csv($file, $records, $table = NULL) {
468 if (empty($records)) {
473 if ($table !== NULL && !$metacolumns = $db->MetaColumns($CFG->prefix
. $table)) {
479 if(!($fp = @fopen
($CFG->dataroot
.'/temp/'.$file, 'w'))) {
480 error('put_records_csv failed to open '.$file);
483 $proto = reset($records);
484 if(is_object($proto)) {
485 $fields_records = array_keys(get_object_vars($proto));
487 else if(is_array($proto)) {
488 $fields_records = array_keys($proto);
495 if(!empty($metacolumns)) {
496 $fields_table = array_map(create_function('$a', 'return $a->name;'), $metacolumns);
497 $fields = array_intersect($fields_records, $fields_table);
500 $fields = $fields_records;
503 fwrite($fp, implode(',', $fields));
506 foreach($records as $record) {
507 $array = (array)$record;
509 foreach($fields as $field) {
510 if(strpos($array[$field], ',')) {
511 $values[] = '"'.str_replace('"', '\"', $array[$field]).'"';
514 $values[] = $array[$field];
517 fwrite($fp, implode(',', $values)."\r\n");
526 * Recursively delete the file or folder with path $location. That is,
527 * if it is a file delete it. If it is a folder, delete all its content
528 * then delete it. If $location does not exist to start, that is not
529 * considered an error.
531 * @param $location the path to remove.
533 function fulldelete($location) {
534 if (is_dir($location)) {
535 $currdir = opendir($location);
536 while (false !== ($file = readdir($currdir))) {
537 if ($file <> ".." && $file <> ".") {
538 $fullfile = $location."/".$file;
539 if (is_dir($fullfile)) {
540 if (!fulldelete($fullfile)) {
544 if (!unlink($fullfile)) {
551 if (! rmdir($location)) {
555 } else if (file_exists($location)) {
556 if (!unlink($location)) {
564 * Improves memory consumptions and works around buggy readfile() in PHP 5.0.4 (2MB readfile limit).
566 function readfile_chunked($filename, $retbytes=true) {
567 $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
569 $cnt =0;// $handle = fopen($filename, 'rb');
570 $handle = fopen($filename, 'rb');
571 if ($handle === false) {
575 while (!feof($handle)) {
576 @set_time_limit
(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
577 $buffer = fread($handle, $chunksize);
581 $cnt +
= strlen($buffer);
584 $status = fclose($handle);
585 if ($retbytes && $status) {
586 return $cnt; // return num. bytes delivered like readfile() does.
592 * Send requested byterange of file.
594 function byteserving_send_file($filename, $mimetype, $ranges) {
595 $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
596 $handle = fopen($filename, 'rb');
597 if ($handle === false) {
600 if (count($ranges) == 1) { //only one range requested
601 $length = $ranges[0][2] - $ranges[0][1] +
1;
602 @header
('HTTP/1.1 206 Partial content');
603 @header
('Content-Length: '.$length);
604 @header
('Content-Range: bytes '.$ranges[0][1].'-'.$ranges[0][2].'/'.filesize($filename));
605 @header
('Content-Type: '.$mimetype);
606 while (@ob_end_flush
()); //flush the buffers - save memory and disable sid rewrite
608 fseek($handle, $ranges[0][1]);
609 while (!feof($handle) && $length > 0) {
610 @set_time_limit
(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
611 $buffer = fread($handle, ($chunksize < $length ?
$chunksize : $length));
614 $length -= strlen($buffer);
618 } else { // multiple ranges requested - not tested much
620 foreach($ranges as $range) {
621 $totallength +
= strlen($range[0]) +
$range[2] - $range[1] +
1;
623 $totallength +
= strlen("\r\n--".BYTESERVING_BOUNDARY
."--\r\n");
624 @header
('HTTP/1.1 206 Partial content');
625 @header
('Content-Length: '.$totallength);
626 @header
('Content-Type: multipart/byteranges; boundary='.BYTESERVING_BOUNDARY
);
627 //TODO: check if "multipart/x-byteranges" is more compatible with current readers/browsers/servers
628 while (@ob_end_flush
()); //flush the buffers - save memory and disable sid rewrite
629 foreach($ranges as $range) {
630 $length = $range[2] - $range[1] +
1;
633 fseek($handle, $range[1]);
634 while (!feof($handle) && $length > 0) {
635 @set_time_limit
(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
636 $buffer = fread($handle, ($chunksize < $length ?
$chunksize : $length));
639 $length -= strlen($buffer);
642 echo "\r\n--".BYTESERVING_BOUNDARY
."--\r\n";