Updated the HEAD build version to 20080408
[moodle.git] / lib / filelib.php
CommitLineData
599f38f9 1<?php //$Id$
2
4c8c65ec 3define('BYTESERVING_BOUNDARY', 's1k2o3d4a5k6s7'); //unique string constant
4
8ee88311 5/**
5f8bdc17 6 * Fetches content of file from Internet (using proxy if defined). Uses cURL extension if present.
599f06cf 7 * Due to security concerns only downloads from http(s) sources are supported.
8 *
9 * @param string $url file url starting with http(s)://
6bf55889 10 * @param array $headers http headers, null if none
11 * @param array $postdata array means use POST request with given parameters
12 * @param bool $fullresponse return headers, responses, etc in a similar way snoopy does
44e02d79 13 * @param int $timeout timeout for complete download process including all file transfer
14 * (default 5 minutes)
15 * @param int $connecttimeout timeout for connection to server; this is the timeout that
16 * usually happens if the remote server is completely down (default 20 seconds);
17 * may not work when using proxy
83947a36 18 * @param bool $skipcertverify If true, the peer's SSL certificate will not be checked. Only use this when already in a trusted location.
8ee88311 19 * @return mixed false if request failed or content of the file as string if ok.
20 */
83947a36 21function download_file_content($url, $headers=null, $postdata=null, $fullresponse=false, $timeout=300, $connecttimeout=20, $skipcertverify=false) {
e27f0765 22 global $CFG;
23
599f06cf 24 // some extra security
25 $newlines = array("\r", "\n");
26 if (is_array($headers) ) {
27 foreach ($headers as $key => $value) {
28 $headers[$key] = str_replace($newlines, '', $value);
29 }
30 }
31 $url = str_replace($newlines, '', $url);
32 if (!preg_match('|^https?://|i', $url)) {
33 if ($fullresponse) {
34 $response = new object();
35 $response->status = 0;
36 $response->headers = array();
37 $response->response_code = 'Invalid protocol specified in url';
38 $response->results = '';
39 $response->error = 'Invalid protocol specified in url';
40 return $response;
41 } else {
42 return false;
43 }
44 }
45
46
6bf55889 47 if (!extension_loaded('curl') or ($ch = curl_init($url)) === false) {
5f8bdc17 48 require_once($CFG->libdir.'/snoopy/Snoopy.class.inc');
49 $snoopy = new Snoopy();
6bf55889 50 $snoopy->read_timeout = $timeout;
44e02d79 51 $snoopy->_fp_timeout = $connecttimeout;
6bf55889 52 $snoopy->proxy_host = $CFG->proxyhost;
53 $snoopy->proxy_port = $CFG->proxyport;
5f8bdc17 54 if (!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) {
55 // this will probably fail, but let's try it anyway
56 $snoopy->proxy_user = $CFG->proxyuser;
57 $snoopy->proxy_password = $CFG->proxypassword;
58 }
6bf55889 59 if (is_array($headers) ) {
60 $client->rawheaders = $headers;
61 }
62
63 if (is_array($postdata)) {
64 $fetch = @$snoopy->fetch($url, $postdata); // use more specific debug code bellow
65 } else {
66 $fetch = @$snoopy->fetch($url); // use more specific debug code bellow
67 }
68
69 if ($fetch) {
70 if ($fullresponse) {
71 //fix header line endings
72 foreach ($snoopy->headers as $key=>$unused) {
73 $snoopy->headers[$key] = trim($snoopy->headers[$key]);
74 }
75 $response = new object();
76 $response->status = $snoopy->status;
77 $response->headers = $snoopy->headers;
78 $response->response_code = trim($snoopy->response_code);
79 $response->results = $snoopy->results;
80 $response->error = $snoopy->error;
81 return $response;
82
83 } else if ($snoopy->status != 200) {
5f8bdc17 84 debugging("Snoopy request for \"$url\" failed, http response code: ".$snoopy->response_code, DEBUG_ALL);
85 return false;
6bf55889 86
5f8bdc17 87 } else {
88 return $snoopy->results;
89 }
90 } else {
6bf55889 91 if ($fullresponse) {
92 $response = new object();
93 $response->status = $snoopy->status;
94 $response->headers = array();
95 $response->response_code = $snoopy->response_code;
96 $response->results = '';
97 $response->error = $snoopy->error;
98 return $response;
99 } else {
100 debugging("Snoopy request for \"$url\" failed with: ".$snoopy->error, DEBUG_ALL);
101 return false;
102 }
103 }
104 }
105
599f06cf 106 // set extra headers
6bf55889 107 if (is_array($headers) ) {
108 $headers2 = array();
109 foreach ($headers as $key => $value) {
6bf55889 110 $headers2[] = "$key: $value";
111 }
112 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers2);
113 }
114
83947a36 115
116 if ($skipcertverify) {
117 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
118 }
119
6bf55889 120 // use POST if requested
121 if (is_array($postdata)) {
122 foreach ($postdata as $k=>$v) {
123 $postdata[$k] = urlencode($k).'='.urlencode($v);
5f8bdc17 124 }
6bf55889 125 $postdata = implode('&', $postdata);
126 curl_setopt($ch, CURLOPT_POST, true);
127 curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
5f8bdc17 128 }
129
8ee88311 130 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
6bf55889 131 curl_setopt($ch, CURLOPT_HEADER, true);
44e02d79 132 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $connecttimeout);
133 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
6bf55889 134 if (!ini_get('open_basedir') and !ini_get('safe_mode')) {
599f06cf 135 // TODO: add version test for '7.10.5'
6bf55889 136 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
137 curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
138 }
139
8ee88311 140 if (!empty($CFG->proxyhost)) {
5f8bdc17 141 // SOCKS supported in PHP5 only
142 if (!empty($CFG->proxytype) and ($CFG->proxytype == 'SOCKS5')) {
143 if (defined('CURLPROXY_SOCKS5')) {
144 curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
145 } else {
5f8bdc17 146 curl_close($ch);
599f06cf 147 if ($fullresponse) {
148 $response = new object();
149 $response->status = '0';
150 $response->headers = array();
151 $response->response_code = 'SOCKS5 proxy is not supported in PHP4';
152 $response->results = '';
153 $response->error = 'SOCKS5 proxy is not supported in PHP4';
154 return $response;
155 } else {
156 debugging("SOCKS5 proxy is not supported in PHP4.", DEBUG_ALL);
157 return false;
158 }
5f8bdc17 159 }
160 }
161
08ec989f 162 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, false);
163
8ee88311 164 if (empty($CFG->proxyport)) {
e27f0765 165 curl_setopt($ch, CURLOPT_PROXY, $CFG->proxyhost);
8ee88311 166 } else {
e27f0765 167 curl_setopt($ch, CURLOPT_PROXY, $CFG->proxyhost.':'.$CFG->proxyport);
8ee88311 168 }
5f8bdc17 169
170 if (!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) {
8ee88311 171 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $CFG->proxyuser.':'.$CFG->proxypassword);
5f8bdc17 172 if (defined('CURLOPT_PROXYAUTH')) {
173 // any proxy authentication if PHP 5.1
174 curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_BASIC | CURLAUTH_NTLM);
175 }
8ee88311 176 }
177 }
6bf55889 178
599f06cf 179 $data = curl_exec($ch);
08ec989f 180
599f06cf 181 // try to detect encoding problems
6bf55889 182 if ((curl_errno($ch) == 23 or curl_errno($ch) == 61) and defined('CURLOPT_ENCODING')) {
183 curl_setopt($ch, CURLOPT_ENCODING, 'none');
599f06cf 184 $data = curl_exec($ch);
6bf55889 185 }
186
08ec989f 187 if (curl_errno($ch)) {
6bf55889 188 $error = curl_error($ch);
189 $error_no = curl_errno($ch);
190 curl_close($ch);
191
192 if ($fullresponse) {
193 $response = new object();
194 if ($error_no == 28) {
195 $response->status = '-100'; // mimic snoopy
196 } else {
197 $response->status = '0';
198 }
199 $response->headers = array();
200 $response->response_code = $error;
201 $response->results = '';
202 $response->error = $error;
203 return $response;
204 } else {
599f06cf 205 debugging("cURL request for \"$url\" failed with: $error ($error_no)", DEBUG_ALL);
6bf55889 206 return false;
207 }
5f8bdc17 208
209 } else {
6bf55889 210 $info = curl_getinfo($ch);
211 curl_close($ch);
599f06cf 212
213 if (empty($info['http_code'])) {
214 // for security reasons we support only true http connections (Location: file:// exploit prevention)
215 $response = new object();
216 $response->status = '0';
217 $response->headers = array();
218 $response->response_code = 'Unknown cURL error';
219 $response->results = ''; // do NOT change this!
220 $response->error = 'Unknown cURL error';
221
222 } else {
223 // strip redirect headers and get headers array and content
224 $data = explode("\r\n\r\n", $data, $info['redirect_count'] + 2);
225 $results = array_pop($data);
226 $headers = array_pop($data);
227 $headers = explode("\r\n", trim($headers));
228
229 $response = new object();;
230 $response->status = (string)$info['http_code'];
231 $response->headers = $headers;
232 $response->response_code = $headers[0];
233 $response->results = $results;
234 $response->error = '';
235 }
6bf55889 236
237 if ($fullresponse) {
238 return $response;
239 } else if ($info['http_code'] != 200) {
599f06cf 240 debugging("cURL request for \"$url\" failed, HTTP response code: ".$response->response_code, DEBUG_ALL);
6bf55889 241 return false;
242 } else {
243 return $response->results;
5f8bdc17 244 }
08ec989f 245 }
8ee88311 246}
247
3ce73b14 248/**
76ca1ff1 249 * @return List of information about file types based on extensions.
3ce73b14 250 * Associative array of extension (lower-case) to associative array
251 * from 'element name' to data. Current element names are 'type' and 'icon'.
76ca1ff1 252 * Unknown types should use the 'xxx' entry which includes defaults.
3ce73b14 253 */
254function get_mimetypes_array() {
255 return array (
a370c895 256 'xxx' => array ('type'=>'document/unknown', 'icon'=>'unknown.gif'),
257 '3gp' => array ('type'=>'video/quicktime', 'icon'=>'video.gif'),
258 'ai' => array ('type'=>'application/postscript', 'icon'=>'image.gif'),
259 'aif' => array ('type'=>'audio/x-aiff', 'icon'=>'audio.gif'),
260 'aiff' => array ('type'=>'audio/x-aiff', 'icon'=>'audio.gif'),
261 'aifc' => array ('type'=>'audio/x-aiff', 'icon'=>'audio.gif'),
262 'applescript' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
263 'asc' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
18bf47ef 264 'asm' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
a370c895 265 'au' => array ('type'=>'audio/au', 'icon'=>'audio.gif'),
266 'avi' => array ('type'=>'video/x-ms-wm', 'icon'=>'avi.gif'),
267 'bmp' => array ('type'=>'image/bmp', 'icon'=>'image.gif'),
18bf47ef 268 'c' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
a370c895 269 'cct' => array ('type'=>'shockwave/director', 'icon'=>'flash.gif'),
18bf47ef 270 'cpp' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
a370c895 271 'cs' => array ('type'=>'application/x-csh', 'icon'=>'text.gif'),
76ca1ff1 272 'css' => array ('type'=>'text/css', 'icon'=>'text.gif'),
6ae5e482 273 'csv' => array ('type'=>'text/csv', 'icon'=>'excel.gif'),
a370c895 274 'dv' => array ('type'=>'video/x-dv', 'icon'=>'video.gif'),
609d84e3 275 'dmg' => array ('type'=>'application/octet-stream', 'icon'=>'dmg.gif'),
a370c895 276 'doc' => array ('type'=>'application/msword', 'icon'=>'word.gif'),
68da9722 277 'docx' => array ('type'=>'application/msword', 'icon'=>'docx.gif'),
278 'docm' => array ('type'=>'application/msword', 'icon'=>'docm.gif'),
279 'dotx' => array ('type'=>'application/msword', 'icon'=>'dotx.gif'),
a370c895 280 'dcr' => array ('type'=>'application/x-director', 'icon'=>'flash.gif'),
281 'dif' => array ('type'=>'video/x-dv', 'icon'=>'video.gif'),
282 'dir' => array ('type'=>'application/x-director', 'icon'=>'flash.gif'),
283 'dxr' => array ('type'=>'application/x-director', 'icon'=>'flash.gif'),
284 'eps' => array ('type'=>'application/postscript', 'icon'=>'pdf.gif'),
ee7f231d 285 'fdf' => array ('type'=>'application/pdf', 'icon'=>'pdf.gif'),
759bc3c8 286 'flv' => array ('type'=>'video/x-flv', 'icon'=>'video.gif'),
a370c895 287 'gif' => array ('type'=>'image/gif', 'icon'=>'image.gif'),
288 'gtar' => array ('type'=>'application/x-gtar', 'icon'=>'zip.gif'),
759bc3c8 289 'tgz' => array ('type'=>'application/g-zip', 'icon'=>'zip.gif'),
a370c895 290 'gz' => array ('type'=>'application/g-zip', 'icon'=>'zip.gif'),
291 'gzip' => array ('type'=>'application/g-zip', 'icon'=>'zip.gif'),
292 'h' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
18bf47ef 293 'hpp' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
a370c895 294 'hqx' => array ('type'=>'application/mac-binhex40', 'icon'=>'zip.gif'),
70ee2841 295 'htc' => array ('type'=>'text/x-component', 'icon'=>'text.gif'),
a370c895 296 'html' => array ('type'=>'text/html', 'icon'=>'html.gif'),
1659a998 297 'xhtml'=> array ('type'=>'application/xhtml+xml', 'icon'=>'html.gif'),
a370c895 298 'htm' => array ('type'=>'text/html', 'icon'=>'html.gif'),
08297dcb 299 'ico' => array ('type'=>'image/vnd.microsoft.icon', 'icon'=>'image.gif'),
300 'isf' => array ('type'=>'application/inspiration', 'icon'=>'isf.gif'),
301 'ist' => array ('type'=>'application/inspiration.template', 'icon'=>'isf.gif'),
18bf47ef 302 'java' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
a00420fb 303 'jcb' => array ('type'=>'text/xml', 'icon'=>'jcb.gif'),
304 'jcl' => array ('type'=>'text/xml', 'icon'=>'jcl.gif'),
305 'jcw' => array ('type'=>'text/xml', 'icon'=>'jcw.gif'),
306 'jmt' => array ('type'=>'text/xml', 'icon'=>'jmt.gif'),
307 'jmx' => array ('type'=>'text/xml', 'icon'=>'jmx.gif'),
a370c895 308 'jpe' => array ('type'=>'image/jpeg', 'icon'=>'image.gif'),
309 'jpeg' => array ('type'=>'image/jpeg', 'icon'=>'image.gif'),
310 'jpg' => array ('type'=>'image/jpeg', 'icon'=>'image.gif'),
a00420fb 311 'jqz' => array ('type'=>'text/xml', 'icon'=>'jqz.gif'),
a370c895 312 'js' => array ('type'=>'application/x-javascript', 'icon'=>'text.gif'),
313 'latex'=> array ('type'=>'application/x-latex', 'icon'=>'text.gif'),
314 'm' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
315 'mov' => array ('type'=>'video/quicktime', 'icon'=>'video.gif'),
316 'movie'=> array ('type'=>'video/x-sgi-movie', 'icon'=>'video.gif'),
317 'm3u' => array ('type'=>'audio/x-mpegurl', 'icon'=>'audio.gif'),
318 'mp3' => array ('type'=>'audio/mp3', 'icon'=>'audio.gif'),
319 'mp4' => array ('type'=>'video/mp4', 'icon'=>'video.gif'),
320 'mpeg' => array ('type'=>'video/mpeg', 'icon'=>'video.gif'),
321 'mpe' => array ('type'=>'video/mpeg', 'icon'=>'video.gif'),
322 'mpg' => array ('type'=>'video/mpeg', 'icon'=>'video.gif'),
5395334d 323
324 'odt' => array ('type'=>'application/vnd.oasis.opendocument.text', 'icon'=>'odt.gif'),
325 'ott' => array ('type'=>'application/vnd.oasis.opendocument.text-template', 'icon'=>'odt.gif'),
326 'oth' => array ('type'=>'application/vnd.oasis.opendocument.text-web', 'icon'=>'odt.gif'),
e10bc440 327 'odm' => array ('type'=>'application/vnd.oasis.opendocument.text-master', 'icon'=>'odm.gif'),
328 'odg' => array ('type'=>'application/vnd.oasis.opendocument.graphics', 'icon'=>'odg.gif'),
329 'otg' => array ('type'=>'application/vnd.oasis.opendocument.graphics-template', 'icon'=>'odg.gif'),
330 'odp' => array ('type'=>'application/vnd.oasis.opendocument.presentation', 'icon'=>'odp.gif'),
331 'otp' => array ('type'=>'application/vnd.oasis.opendocument.presentation-template', 'icon'=>'odp.gif'),
332 'ods' => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet', 'icon'=>'ods.gif'),
333 'ots' => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet-template', 'icon'=>'ods.gif'),
334 'odc' => array ('type'=>'application/vnd.oasis.opendocument.chart', 'icon'=>'odc.gif'),
335 'odf' => array ('type'=>'application/vnd.oasis.opendocument.formula', 'icon'=>'odf.gif'),
336 'odb' => array ('type'=>'application/vnd.oasis.opendocument.database', 'icon'=>'odb.gif'),
337 'odi' => array ('type'=>'application/vnd.oasis.opendocument.image', 'icon'=>'odi.gif'),
5395334d 338
a370c895 339 'pct' => array ('type'=>'image/pict', 'icon'=>'image.gif'),
340 'pdf' => array ('type'=>'application/pdf', 'icon'=>'pdf.gif'),
341 'php' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
342 'pic' => array ('type'=>'image/pict', 'icon'=>'image.gif'),
343 'pict' => array ('type'=>'image/pict', 'icon'=>'image.gif'),
344 'png' => array ('type'=>'image/png', 'icon'=>'image.gif'),
345 'pps' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'powerpoint.gif'),
346 'ppt' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'powerpoint.gif'),
68da9722 347 'pptx' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'pptx.gif'),
348 'pptm' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'pptm.gif'),
349 'potx' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'potx.gif'),
350 'potm' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'potm.gif'),
351 'ppam' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'ppam.gif'),
352 'ppsx' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'ppsx.gif'),
353 'ppsm' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'ppsm.gif'),
a370c895 354 'ps' => array ('type'=>'application/postscript', 'icon'=>'pdf.gif'),
355 'qt' => array ('type'=>'video/quicktime', 'icon'=>'video.gif'),
356 'ra' => array ('type'=>'audio/x-realaudio', 'icon'=>'audio.gif'),
357 'ram' => array ('type'=>'audio/x-pn-realaudio', 'icon'=>'audio.gif'),
a00420fb 358 'rhb' => array ('type'=>'text/xml', 'icon'=>'xml.gif'),
a370c895 359 'rm' => array ('type'=>'audio/x-pn-realaudio', 'icon'=>'audio.gif'),
360 'rtf' => array ('type'=>'text/rtf', 'icon'=>'text.gif'),
361 'rtx' => array ('type'=>'text/richtext', 'icon'=>'text.gif'),
362 'sh' => array ('type'=>'application/x-sh', 'icon'=>'text.gif'),
363 'sit' => array ('type'=>'application/x-stuffit', 'icon'=>'zip.gif'),
364 'smi' => array ('type'=>'application/smil', 'icon'=>'text.gif'),
365 'smil' => array ('type'=>'application/smil', 'icon'=>'text.gif'),
a00420fb 366 'sqt' => array ('type'=>'text/xml', 'icon'=>'xml.gif'),
4db69ffb 367 'svg' => array ('type'=>'image/svg+xml', 'icon'=>'image.gif'),
368 'svgz' => array ('type'=>'image/svg+xml', 'icon'=>'image.gif'),
a370c895 369 'swa' => array ('type'=>'application/x-director', 'icon'=>'flash.gif'),
370 'swf' => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash.gif'),
371 'swfl' => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash.gif'),
5395334d 372
373 'sxw' => array ('type'=>'application/vnd.sun.xml.writer', 'icon'=>'odt.gif'),
374 'stw' => array ('type'=>'application/vnd.sun.xml.writer.template', 'icon'=>'odt.gif'),
375 'sxc' => array ('type'=>'application/vnd.sun.xml.calc', 'icon'=>'odt.gif'),
376 'stc' => array ('type'=>'application/vnd.sun.xml.calc.template', 'icon'=>'odt.gif'),
377 'sxd' => array ('type'=>'application/vnd.sun.xml.draw', 'icon'=>'odt.gif'),
378 'std' => array ('type'=>'application/vnd.sun.xml.draw.template', 'icon'=>'odt.gif'),
379 'sxi' => array ('type'=>'application/vnd.sun.xml.impress', 'icon'=>'odt.gif'),
380 'sti' => array ('type'=>'application/vnd.sun.xml.impress.template', 'icon'=>'odt.gif'),
381 'sxg' => array ('type'=>'application/vnd.sun.xml.writer.global', 'icon'=>'odt.gif'),
382 'sxm' => array ('type'=>'application/vnd.sun.xml.math', 'icon'=>'odt.gif'),
383
a370c895 384 'tar' => array ('type'=>'application/x-tar', 'icon'=>'zip.gif'),
385 'tif' => array ('type'=>'image/tiff', 'icon'=>'image.gif'),
386 'tiff' => array ('type'=>'image/tiff', 'icon'=>'image.gif'),
387 'tex' => array ('type'=>'application/x-tex', 'icon'=>'text.gif'),
388 'texi' => array ('type'=>'application/x-texinfo', 'icon'=>'text.gif'),
389 'texinfo' => array ('type'=>'application/x-texinfo', 'icon'=>'text.gif'),
390 'tsv' => array ('type'=>'text/tab-separated-values', 'icon'=>'text.gif'),
391 'txt' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
392 'wav' => array ('type'=>'audio/wav', 'icon'=>'audio.gif'),
393 'wmv' => array ('type'=>'video/x-ms-wmv', 'icon'=>'avi.gif'),
394 'asf' => array ('type'=>'video/x-ms-asf', 'icon'=>'avi.gif'),
ee7f231d 395 'xdp' => array ('type'=>'application/pdf', 'icon'=>'pdf.gif'),
396 'xfd' => array ('type'=>'application/pdf', 'icon'=>'pdf.gif'),
397 'xfdf' => array ('type'=>'application/pdf', 'icon'=>'pdf.gif'),
a370c895 398 'xls' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'excel.gif'),
68da9722 399 'xlsx' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'xlsx.gif'),
400 'xlsm' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'xlsm.gif'),
401 'xltx' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'xltx.gif'),
402 'xltm' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'xltm.gif'),
403 'xlsb' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'xlsb.gif'),
404 'xlam' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'xlam.gif'),
a370c895 405 'xml' => array ('type'=>'application/xml', 'icon'=>'xml.gif'),
406 'xsl' => array ('type'=>'text/xml', 'icon'=>'xml.gif'),
407 'zip' => array ('type'=>'application/zip', 'icon'=>'zip.gif')
f1e0649c 408 );
3ce73b14 409}
410
76ca1ff1 411/**
3ce73b14 412 * Obtains information about a filetype based on its extension. Will
413 * use a default if no information is present about that particular
414 * extension.
76ca1ff1 415 * @param string $element Desired information (usually 'icon'
3ce73b14 416 * for icon filename or 'type' for MIME type)
76ca1ff1 417 * @param string $filename Filename we're looking up
3ce73b14 418 * @return string Requested piece of information from array
419 */
420function mimeinfo($element, $filename) {
f36cbf1d 421 static $mimeinfo = null;
422 if (is_null($mimeinfo)) {
423 $mimeinfo = get_mimetypes_array();
424 }
f1e0649c 425
a370c895 426 if (eregi('\.([a-z0-9]+)$', $filename, $match)) {
f1e0649c 427 if (isset($mimeinfo[strtolower($match[1])][$element])) {
428 return $mimeinfo[strtolower($match[1])][$element];
429 } else {
a370c895 430 return $mimeinfo['xxx'][$element]; // By default
f1e0649c 431 }
432 } else {
a370c895 433 return $mimeinfo['xxx'][$element]; // By default
f1e0649c 434 }
435}
436
76ca1ff1 437/**
3ce73b14 438 * Obtains information about a filetype based on the MIME type rather than
439 * the other way around.
440 * @param string $element Desired information (usually 'icon')
76ca1ff1 441 * @param string $mimetype MIME type we're looking up
3ce73b14 442 * @return string Requested piece of information from array
443 */
444function mimeinfo_from_type($element, $mimetype) {
445 static $mimeinfo;
446 $mimeinfo=get_mimetypes_array();
76ca1ff1 447
3ce73b14 448 foreach($mimeinfo as $values) {
449 if($values['type']==$mimetype) {
450 if(isset($values[$element])) {
451 return $values[$element];
452 }
453 break;
454 }
455 }
456 return $mimeinfo['xxx'][$element]; // Default
457}
b9709b76 458
42ead7d7 459/**
460 * Get information about a filetype based on the icon file.
461 * @param string $element Desired information (usually 'icon')
462 * @param string $icon Icon file path.
463 * @return string Requested piece of information from array
464 */
465function mimeinfo_from_icon($element, $icon) {
466 static $mimeinfo;
467 $mimeinfo=get_mimetypes_array();
468
469 if (preg_match("/\/(.*)/", $icon, $matches)) {
470 $icon = $matches[1];
471 }
472 $info = $mimeinfo['xxx'][$element]; // Default
473 foreach($mimeinfo as $values) {
474 if($values['icon']==$icon) {
475 if(isset($values[$element])) {
476 $info = $values[$element];
477 }
478 //No break, for example for 'excel.gif' we don't want 'csv'!
479 }
480 }
481 return $info;
482}
483
c0381e22 484/**
76ca1ff1 485 * Obtains descriptions for file types (e.g. 'Microsoft Word document') from the
486 * mimetypes.php language file.
c0381e22 487 * @param string $mimetype MIME type (can be obtained using the mimeinfo function)
488 * @param bool $capitalise If true, capitalises first character of result
76ca1ff1 489 * @return string Text description
c0381e22 490 */
491function get_mimetype_description($mimetype,$capitalise=false) {
492 $result=get_string($mimetype,'mimetypes');
493 // Surrounded by square brackets indicates that there isn't a string for that
494 // (maybe there is a better way to find this out?)
495 if(strpos($result,'[')===0) {
496 $result=get_string('document/unknown','mimetypes');
76ca1ff1 497 }
c0381e22 498 if($capitalise) {
499 $result=ucfirst($result);
500 }
501 return $result;
502}
503
76ca1ff1 504/**
505 * Handles the sending of file data to the user's browser, including support for
506 * byteranges etc.
ba75ad94 507 * @param string $path Path of file on disk (including real filename), or actual content of file as string
508 * @param string $filename Filename to send
509 * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
510 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
511 * @param bool $pathisstring If true (default false), $path is the content to send and not the pathname
512 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
513 * @param string $mimetype Include to specify the MIME type; leave blank to have it guess the type from $filename
b9709b76 514 */
ba75ad94 515function send_file($path, $filename, $lifetime=86400 , $filter=0, $pathisstring=false, $forcedownload=false, $mimetype='') {
60f9e36e 516 global $CFG, $COURSE;
f1e0649c 517
ba4e0b05 518 // Use given MIME type if specified, otherwise guess it using mimeinfo.
519 // IE, Konqueror and Opera open html file directly in browser from web even when directed to save it to disk :-O
520 // only Firefox saves all files locally before opening when content-disposition: attachment stated
521 $isFF = check_browser_version('Firefox', '1.5'); // only FF > 1.5 properly tested
76ca1ff1 522 $mimetype = ($forcedownload and !$isFF) ? 'application/x-forcedownload' :
ba4e0b05 523 ($mimetype ? $mimetype : mimeinfo('type', $filename));
f1e0649c 524 $lastmodified = $pathisstring ? time() : filemtime($path);
525 $filesize = $pathisstring ? strlen($path) : filesize($path);
526
36bddcf5 527/* - MDL-13949
ee7f231d 528 //Adobe Acrobat Reader XSS prevention
529 if ($mimetype=='application/pdf' or mimeinfo('type', $filename)=='application/pdf') {
530 //please note that it prevents opening of pdfs in browser when http referer disabled
531 //or file linked from another site; browser caching of pdfs is now disabled too
c57d8874 532 if (!empty($_SERVER['HTTP_RANGE'])) {
533 //already byteserving
76ca1ff1 534 $lifetime = 1; // >0 needed for byteserving
c57d8874 535 } else if (empty($_SERVER['HTTP_REFERER']) or strpos($_SERVER['HTTP_REFERER'], $CFG->wwwroot)!==0) {
ee7f231d 536 $mimetype = 'application/x-forcedownload';
537 $forcedownload = true;
538 $lifetime = 0;
539 } else {
76ca1ff1 540 $lifetime = 1; // >0 needed for byteserving
ee7f231d 541 }
b8806ccc 542 }
36bddcf5 543*/
f3f7610c 544
69faecce 545 //IE compatibiltiy HACK!
4c8c65ec 546 if (ini_get('zlib.output_compression')) {
69faecce 547 ini_set('zlib.output_compression', 'Off');
548 }
549
4c8c65ec 550 //try to disable automatic sid rewrite in cookieless mode
8914cb82 551 @ini_set("session.use_trans_sid", "false");
4c8c65ec 552
553 //do not put '@' before the next header to detect incorrect moodle configurations,
554 //error should be better than "weird" empty lines for admins/users
555 //TODO: should we remove all those @ before the header()? Are all of the values supported on all servers?
556 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
557
4f047de2 558 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
559 if (check_browser_version('MSIE')) {
5f8bdc17 560 $filename = urlencode($filename);
4f047de2 561 }
562
4c8c65ec 563 if ($forcedownload) {
564 @header('Content-Disposition: attachment; filename='.$filename);
565 } else {
566 @header('Content-Disposition: inline; filename='.$filename);
567 }
568
f1e0649c 569 if ($lifetime > 0) {
4c8c65ec 570 @header('Cache-Control: max-age='.$lifetime);
571 @header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
f1e0649c 572 @header('Pragma: ');
4c8c65ec 573
574 if (empty($CFG->disablebyteserving) && !$pathisstring && $mimetype != 'text/plain' && $mimetype != 'text/html') {
575
576 @header('Accept-Ranges: bytes');
577
578 if (!empty($_SERVER['HTTP_RANGE']) && strpos($_SERVER['HTTP_RANGE'],'bytes=') !== FALSE) {
579 // byteserving stuff - for acrobat reader and download accelerators
580 // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
581 // inspired by: http://www.coneural.org/florian/papers/04_byteserving.php
582 $ranges = false;
583 if (preg_match_all('/(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER)) {
584 foreach ($ranges as $key=>$value) {
585 if ($ranges[$key][1] == '') {
586 //suffix case
587 $ranges[$key][1] = $filesize - $ranges[$key][2];
588 $ranges[$key][2] = $filesize - 1;
589 } else if ($ranges[$key][2] == '' || $ranges[$key][2] > $filesize - 1) {
590 //fix range length
591 $ranges[$key][2] = $filesize - 1;
592 }
593 if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
594 //invalid byte-range ==> ignore header
595 $ranges = false;
596 break;
597 }
598 //prepare multipart header
599 $ranges[$key][0] = "\r\n--".BYTESERVING_BOUNDARY."\r\nContent-Type: $mimetype\r\n";
600 $ranges[$key][0] .= "Content-Range: bytes {$ranges[$key][1]}-{$ranges[$key][2]}/$filesize\r\n\r\n";
601 }
602 } else {
603 $ranges = false;
604 }
605 if ($ranges) {
606 byteserving_send_file($path, $mimetype, $ranges);
607 }
608 }
609 } else {
610 /// Do not byteserve (disabled, strings, text and html files).
611 @header('Accept-Ranges: none');
612 }
613 } else { // Do not cache files in proxies and browsers
85e00626 614 if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
615 @header('Cache-Control: max-age=10');
4c8c65ec 616 @header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
85e00626 617 @header('Pragma: ');
618 } else { //normal http - prevent caching at all cost
619 @header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
4c8c65ec 620 @header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
85e00626 621 @header('Pragma: no-cache');
622 }
4c8c65ec 623 @header('Accept-Ranges: none'); // Do not allow byteserving when caching disabled
69faecce 624 }
f1e0649c 625
b9709b76 626 if (empty($filter)) {
4c8c65ec 627 if ($mimetype == 'text/html' && !empty($CFG->usesid) && empty($_COOKIE['MoodleSession'.$CFG->sessioncookie])) {
628 //cookieless mode - rewrite links
629 @header('Content-Type: text/html');
630 $path = $pathisstring ? $path : implode('', file($path));
631 $path = sid_ob_rewrite($path);
632 $filesize = strlen($path);
633 $pathisstring = true;
634 } else if ($mimetype == 'text/plain') {
810944af 635 @header('Content-Type: Text/plain; charset=utf-8'); //add encoding
f1e0649c 636 } else {
4c8c65ec 637 @header('Content-Type: '.$mimetype);
f1e0649c 638 }
4c8c65ec 639 @header('Content-Length: '.$filesize);
640 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
f1e0649c 641 if ($pathisstring) {
642 echo $path;
4c8c65ec 643 } else {
69faecce 644 readfile_chunked($path);
f1e0649c 645 }
646 } else { // Try to put the file through filters
f1e0649c 647 if ($mimetype == 'text/html') {
a17c57b5 648 $options = new object();
f1e0649c 649 $options->noclean = true;
a17c57b5 650 $options->nocache = true; // temporary workaround for MDL-5136
f1e0649c 651 $text = $pathisstring ? $path : implode('', file($path));
76ca1ff1 652
3ace5ee4 653 $text = file_modify_html_header($text);
60f9e36e 654 $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
4c8c65ec 655 if (!empty($CFG->usesid) && empty($_COOKIE['MoodleSession'.$CFG->sessioncookie])) {
656 //cookieless mode - rewrite links
657 $output = sid_ob_rewrite($output);
658 }
f1e0649c 659
4c8c65ec 660 @header('Content-Length: '.strlen($output));
661 @header('Content-Type: text/html');
662 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
f1e0649c 663 echo $output;
b9709b76 664 // only filter text if filter all files is selected
665 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
60f9e36e 666 $options = new object();
f1e0649c 667 $options->newlines = false;
668 $options->noclean = true;
669 $text = htmlentities($pathisstring ? $path : implode('', file($path)));
60f9e36e 670 $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
4c8c65ec 671 if (!empty($CFG->usesid) && empty($_COOKIE['MoodleSession'.$CFG->sessioncookie])) {
672 //cookieless mode - rewrite links
673 $output = sid_ob_rewrite($output);
674 }
f1e0649c 675
4c8c65ec 676 @header('Content-Length: '.strlen($output));
810944af 677 @header('Content-Type: text/html; charset=utf-8'); //add encoding
4c8c65ec 678 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
f1e0649c 679 echo $output;
680 } else { // Just send it out raw
4c8c65ec 681 @header('Content-Length: '.$filesize);
682 @header('Content-Type: '.$mimetype);
683 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
f1e0649c 684 if ($pathisstring) {
685 echo $path;
686 }else {
69faecce 687 readfile_chunked($path);
f1e0649c 688 }
689 }
690 }
691 die; //no more chars to output!!!
692}
693
a43b5308 694function get_records_csv($file, $table) {
599f38f9 695 global $CFG, $db;
696
697 if (!$metacolumns = $db->MetaColumns($CFG->prefix . $table)) {
698 return false;
699 }
700
a77b98eb 701 if(!($handle = @fopen($file, 'r'))) {
5a2a5331 702 print_error('get_records_csv failed to open '.$file);
599f38f9 703 }
704
705 $fieldnames = fgetcsv($handle, 4096);
706 if(empty($fieldnames)) {
707 fclose($handle);
708 return false;
709 }
710
711 $columns = array();
712
713 foreach($metacolumns as $metacolumn) {
714 $ord = array_search($metacolumn->name, $fieldnames);
715 if(is_int($ord)) {
716 $columns[$metacolumn->name] = $ord;
717 }
718 }
719
720 $rows = array();
721
722 while (($data = fgetcsv($handle, 4096)) !== false) {
723 $item = new stdClass;
724 foreach($columns as $name => $ord) {
725 $item->$name = $data[$ord];
726 }
727 $rows[] = $item;
728 }
729
730 fclose($handle);
731 return $rows;
732}
733
a77b98eb 734function put_records_csv($file, $records, $table = NULL) {
735 global $CFG, $db;
736
a1e93da2 737 if (empty($records)) {
a77b98eb 738 return true;
739 }
740
741 $metacolumns = NULL;
742 if ($table !== NULL && !$metacolumns = $db->MetaColumns($CFG->prefix . $table)) {
743 return false;
744 }
745
a1e93da2 746 echo "x";
747
a77b98eb 748 if(!($fp = @fopen($CFG->dataroot.'/temp/'.$file, 'w'))) {
5a2a5331 749 print_error('put_records_csv failed to open '.$file);
a77b98eb 750 }
751
a43b5308 752 $proto = reset($records);
753 if(is_object($proto)) {
754 $fields_records = array_keys(get_object_vars($proto));
755 }
756 else if(is_array($proto)) {
757 $fields_records = array_keys($proto);
758 }
759 else {
760 return false;
761 }
a1e93da2 762 echo "x";
a77b98eb 763
764 if(!empty($metacolumns)) {
765 $fields_table = array_map(create_function('$a', 'return $a->name;'), $metacolumns);
766 $fields = array_intersect($fields_records, $fields_table);
767 }
768 else {
769 $fields = $fields_records;
770 }
771
772 fwrite($fp, implode(',', $fields));
773 fwrite($fp, "\r\n");
774
775 foreach($records as $record) {
a43b5308 776 $array = (array)$record;
a77b98eb 777 $values = array();
778 foreach($fields as $field) {
a43b5308 779 if(strpos($array[$field], ',')) {
780 $values[] = '"'.str_replace('"', '\"', $array[$field]).'"';
a77b98eb 781 }
782 else {
a43b5308 783 $values[] = $array[$field];
a77b98eb 784 }
785 }
786 fwrite($fp, implode(',', $values)."\r\n");
787 }
788
789 fclose($fp);
790 return true;
791}
792
f401cc97 793
34763a79 794/**
76ca1ff1 795 * Recursively delete the file or folder with path $location. That is,
34763a79 796 * if it is a file delete it. If it is a folder, delete all its content
76ca1ff1 797 * then delete it. If $location does not exist to start, that is not
798 * considered an error.
799 *
34763a79 800 * @param $location the path to remove.
801 */
4c8c65ec 802function fulldelete($location) {
f401cc97 803 if (is_dir($location)) {
804 $currdir = opendir($location);
805 while (false !== ($file = readdir($currdir))) {
806 if ($file <> ".." && $file <> ".") {
807 $fullfile = $location."/".$file;
4c8c65ec 808 if (is_dir($fullfile)) {
f401cc97 809 if (!fulldelete($fullfile)) {
810 return false;
811 }
812 } else {
813 if (!unlink($fullfile)) {
814 return false;
815 }
4c8c65ec 816 }
f401cc97 817 }
4c8c65ec 818 }
f401cc97 819 closedir($currdir);
820 if (! rmdir($location)) {
821 return false;
822 }
823
34763a79 824 } else if (file_exists($location)) {
f401cc97 825 if (!unlink($location)) {
826 return false;
827 }
828 }
829 return true;
830}
831
4c8c65ec 832/**
833 * Improves memory consumptions and works around buggy readfile() in PHP 5.0.4 (2MB readfile limit).
834 */
835function readfile_chunked($filename, $retbytes=true) {
836 $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
69faecce 837 $buffer = '';
76ca1ff1 838 $cnt =0;
69faecce 839 $handle = fopen($filename, 'rb');
840 if ($handle === false) {
841 return false;
842 }
20371063 843
69faecce 844 while (!feof($handle)) {
68913aec 845 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
69faecce 846 $buffer = fread($handle, $chunksize);
847 echo $buffer;
20371063 848 flush();
69faecce 849 if ($retbytes) {
4c8c65ec 850 $cnt += strlen($buffer);
851 }
69faecce 852 }
853 $status = fclose($handle);
854 if ($retbytes && $status) {
855 return $cnt; // return num. bytes delivered like readfile() does.
856 }
857 return $status;
858}
859
4c8c65ec 860/**
861 * Send requested byterange of file.
862 */
863function byteserving_send_file($filename, $mimetype, $ranges) {
864 $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
865 $handle = fopen($filename, 'rb');
866 if ($handle === false) {
867 die;
868 }
869 if (count($ranges) == 1) { //only one range requested
870 $length = $ranges[0][2] - $ranges[0][1] + 1;
871 @header('HTTP/1.1 206 Partial content');
872 @header('Content-Length: '.$length);
873 @header('Content-Range: bytes '.$ranges[0][1].'-'.$ranges[0][2].'/'.filesize($filename));
874 @header('Content-Type: '.$mimetype);
875 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
876 $buffer = '';
877 fseek($handle, $ranges[0][1]);
878 while (!feof($handle) && $length > 0) {
68913aec 879 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
4c8c65ec 880 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
881 echo $buffer;
882 flush();
883 $length -= strlen($buffer);
884 }
885 fclose($handle);
886 die;
887 } else { // multiple ranges requested - not tested much
888 $totallength = 0;
889 foreach($ranges as $range) {
aba588a7 890 $totallength += strlen($range[0]) + $range[2] - $range[1] + 1;
4c8c65ec 891 }
aba588a7 892 $totallength += strlen("\r\n--".BYTESERVING_BOUNDARY."--\r\n");
4c8c65ec 893 @header('HTTP/1.1 206 Partial content');
894 @header('Content-Length: '.$totallength);
895 @header('Content-Type: multipart/byteranges; boundary='.BYTESERVING_BOUNDARY);
896 //TODO: check if "multipart/x-byteranges" is more compatible with current readers/browsers/servers
897 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
898 foreach($ranges as $range) {
899 $length = $range[2] - $range[1] + 1;
900 echo $range[0];
901 $buffer = '';
902 fseek($handle, $range[1]);
903 while (!feof($handle) && $length > 0) {
68913aec 904 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
4c8c65ec 905 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
906 echo $buffer;
907 flush();
908 $length -= strlen($buffer);
909 }
910 }
911 echo "\r\n--".BYTESERVING_BOUNDARY."--\r\n";
912 fclose($handle);
913 die;
914 }
915}
f401cc97 916
3ace5ee4 917/**
918 * add includes (js and css) into uploaded files
919 * before returning them, useful for themes and utf.js includes
920 * @param string text - text to search and replace
921 * @return string - text with added head includes
922 */
923function file_modify_html_header($text) {
924 // first look for <head> tag
925 global $CFG;
76ca1ff1 926
3ace5ee4 927 $stylesheetshtml = '';
928 foreach ($CFG->stylesheets as $stylesheet) {
929 $stylesheetshtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
76ca1ff1 930 }
931
3ace5ee4 932 $filters = explode(",", $CFG->textfilters);
933 if (in_array('filter/mediaplugin', $filters)) {
76ca1ff1 934 // this script is needed by most media filter plugins.
935 $ufo = "\n".'<script type="text/javascript" src="'.$CFG->wwwroot.'/lib/ufo.js"></script>'."\n";
3ace5ee4 936 } else {
76ca1ff1 937 $ufo = '';
3ace5ee4 938 }
76ca1ff1 939
3ace5ee4 940 preg_match('/\<head\>|\<HEAD\>/', $text, $matches);
941 if ($matches) {
942 $replacement = '<head>'.$ufo.$stylesheetshtml;
943 $text = preg_replace('/\<head\>|\<HEAD\>/', $replacement, $text, 1);
76ca1ff1 944 return $text;
3ace5ee4 945 }
76ca1ff1 946
3ace5ee4 947 // if not, look for <html> tag, and stick <head> right after
948 preg_match('/\<html\>|\<HTML\>/', $text, $matches);
949 if ($matches) {
950 // replace <html> tag with <html><head>includes</head>
13534ef7 951 $replacement = '<html>'."\n".'<head>'.$ufo.$stylesheetshtml.'</head>';
3ace5ee4 952 $text = preg_replace('/\<html\>|\<HTML\>/', $replacement, $text, 1);
76ca1ff1 953 return $text;
3ace5ee4 954 }
76ca1ff1 955
3ace5ee4 956 // if not, look for <body> tag, and stick <head> before body
957 preg_match('/\<body\>|\<BODY\>/', $text, $matches);
958 if ($matches) {
13534ef7 959 $replacement = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".'<body>';
3ace5ee4 960 $text = preg_replace('/\<body\>|\<BODY\>/', $replacement, $text, 1);
76ca1ff1 961 return $text;
962 }
963
3ace5ee4 964 // if not, just stick a <head> tag at the beginning
965 $text = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".$text;
966 return $text;
967}
968
a77b98eb 969?>