MDL-26502 check browser - fix for Symbian (backported)
[moodle.git] / lib / filelib.php
blobea150e2deeab4455fd18a3c72add2497fa39b6a1
1 <?php //$Id$
3 define('BYTESERVING_BOUNDARY', 's1k2o3d4a5k6s7'); //unique string constant
5 function get_file_url($path, $options=null, $type='coursefile') {
6 global $CFG, $HTTPSPAGEREQUIRED;
8 $path = str_replace('//', '/', $path);
9 $path = trim($path, '/'); // no leading and trailing slashes
11 // type of file
12 switch ($type) {
13 case 'questionfile':
14 $url = $CFG->wwwroot."/question/exportfile.php";
15 break;
16 case 'rssfile':
17 $url = $CFG->wwwroot."/rss/file.php";
18 break;
19 case 'user':
20 if (!empty($HTTPSPAGEREQUIRED)) {
21 $wwwroot = $CFG->httpswwwroot;
23 else {
24 $wwwroot = $CFG->wwwroot;
26 $url = $wwwroot."/user/pix.php";
27 break;
28 case 'usergroup':
29 $url = $CFG->wwwroot."/user/pixgroup.php";
30 break;
31 case 'httpscoursefile':
32 $url = $CFG->httpswwwroot."/file.php";
33 break;
34 case 'coursefile':
35 default:
36 $url = $CFG->wwwroot."/file.php";
39 if ($CFG->slasharguments) {
40 $parts = explode('/', $path);
41 foreach ($parts as $key => $part) {
42 /// anchor dash character should not be encoded
43 $subparts = explode('#', $part);
44 $subparts = array_map('rawurlencode', $subparts);
45 $parts[$key] = implode('#', $subparts);
47 $path = implode('/', $parts);
48 $ffurl = $url.'/'.$path;
49 $separator = '?';
50 } else {
51 $path = rawurlencode('/'.$path);
52 $ffurl = $url.'?file='.$path;
53 $separator = '&amp;';
56 if ($options) {
57 foreach ($options as $name=>$value) {
58 $ffurl = $ffurl.$separator.$name.'='.$value;
59 $separator = '&amp;';
63 return $ffurl;
66 /**
67 * Fetches content of file from Internet (using proxy if defined). Uses cURL extension if present.
68 * Due to security concerns only downloads from http(s) sources are supported.
70 * @param string $url file url starting with http(s)://
71 * @param array $headers http headers, null if none. If set, should be an
72 * associative array of header name => value pairs.
73 * @param array $postdata array means use POST request with given parameters
74 * @param bool $fullresponse return headers, responses, etc in a similar way snoopy does
75 * (if false, just returns content)
76 * @param int $timeout timeout for complete download process including all file transfer
77 * (default 5 minutes)
78 * @param int $connecttimeout timeout for connection to server; this is the timeout that
79 * usually happens if the remote server is completely down (default 20 seconds);
80 * may not work when using proxy
81 * @param bool $skipcertverify If true, the peer's SSL certificate will not be checked. Only use this when already in a trusted location.
82 * @return mixed false if request failed or content of the file as string if ok.
84 function download_file_content($url, $headers=null, $postdata=null, $fullresponse=false, $timeout=300, $connecttimeout=20, $skipcertverify=false) {
85 global $CFG;
87 // some extra security
88 $newlines = array("\r", "\n");
89 if (is_array($headers) ) {
90 foreach ($headers as $key => $value) {
91 $headers[$key] = str_replace($newlines, '', $value);
94 $url = str_replace($newlines, '', $url);
95 if (!preg_match('|^https?://|i', $url)) {
96 if ($fullresponse) {
97 $response = new object();
98 $response->status = 0;
99 $response->headers = array();
100 $response->response_code = 'Invalid protocol specified in url';
101 $response->results = '';
102 $response->error = 'Invalid protocol specified in url';
103 return $response;
104 } else {
105 return false;
110 if (!extension_loaded('curl') or ($ch = curl_init($url)) === false) {
111 require_once($CFG->libdir.'/snoopy/Snoopy.class.inc');
112 $snoopy = new Snoopy();
113 $snoopy->read_timeout = $timeout;
114 $snoopy->_fp_timeout = $connecttimeout;
115 $snoopy->proxy_host = $CFG->proxyhost;
116 $snoopy->proxy_port = $CFG->proxyport;
117 if (!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) {
118 // this will probably fail, but let's try it anyway
119 $snoopy->proxy_user = $CFG->proxyuser;
120 $snoopy->proxy_password = $CFG->proxypassword;
122 if (is_array($headers) ) {
123 $client->rawheaders = $headers;
126 if (is_array($postdata)) {
127 $fetch = @$snoopy->fetch($url, $postdata); // use more specific debug code bellow
128 } else {
129 $fetch = @$snoopy->fetch($url); // use more specific debug code bellow
132 if ($fetch) {
133 if ($fullresponse) {
134 //fix header line endings
135 foreach ($snoopy->headers as $key=>$unused) {
136 $snoopy->headers[$key] = trim($snoopy->headers[$key]);
138 $response = new object();
139 $response->status = $snoopy->status;
140 $response->headers = $snoopy->headers;
141 $response->response_code = trim($snoopy->response_code);
142 $response->results = $snoopy->results;
143 $response->error = $snoopy->error;
144 return $response;
146 } else if ($snoopy->status != 200) {
147 debugging("Snoopy request for \"$url\" failed, http response code: ".$snoopy->response_code, DEBUG_ALL);
148 return false;
150 } else {
151 return $snoopy->results;
153 } else {
154 if ($fullresponse) {
155 $response = new object();
156 $response->status = $snoopy->status;
157 $response->headers = array();
158 $response->response_code = $snoopy->response_code;
159 $response->results = '';
160 $response->error = $snoopy->error;
161 return $response;
162 } else {
163 debugging("Snoopy request for \"$url\" failed with: ".$snoopy->error, DEBUG_ALL);
164 return false;
169 // set extra headers
170 if (is_array($headers) ) {
171 $headers2 = array();
172 foreach ($headers as $key => $value) {
173 $headers2[] = "$key: $value";
175 curl_setopt($ch, CURLOPT_HTTPHEADER, $headers2);
178 if ($skipcertverify) {
179 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
182 // use POST if requested
183 if (is_array($postdata)) {
184 foreach ($postdata as $k=>$v) {
185 $postdata[$k] = urlencode($k).'='.urlencode($v);
187 $postdata = implode('&', $postdata);
188 curl_setopt($ch, CURLOPT_POST, true);
189 curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
192 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
193 curl_setopt($ch, CURLOPT_HEADER, true);
194 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $connecttimeout);
195 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
196 if (!ini_get('open_basedir') and !ini_get('safe_mode')) {
197 // TODO: add version test for '7.10.5'
198 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
199 curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
202 if (!empty($CFG->proxyhost)) {
203 // SOCKS supported in PHP5 only
204 if (!empty($CFG->proxytype) and ($CFG->proxytype == 'SOCKS5')) {
205 if (defined('CURLPROXY_SOCKS5')) {
206 curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
207 } else {
208 curl_close($ch);
209 if ($fullresponse) {
210 $response = new object();
211 $response->status = '0';
212 $response->headers = array();
213 $response->response_code = 'SOCKS5 proxy is not supported in PHP4';
214 $response->results = '';
215 $response->error = 'SOCKS5 proxy is not supported in PHP4';
216 return $response;
217 } else {
218 debugging("SOCKS5 proxy is not supported in PHP4.", DEBUG_ALL);
219 return false;
224 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, false);
226 if (empty($CFG->proxyport)) {
227 curl_setopt($ch, CURLOPT_PROXY, $CFG->proxyhost);
228 } else {
229 curl_setopt($ch, CURLOPT_PROXY, $CFG->proxyhost.':'.$CFG->proxyport);
232 if (!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) {
233 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $CFG->proxyuser.':'.$CFG->proxypassword);
234 if (defined('CURLOPT_PROXYAUTH')) {
235 // any proxy authentication if PHP 5.1
236 curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_BASIC | CURLAUTH_NTLM);
241 $data = curl_exec($ch);
243 // try to detect encoding problems
244 if ((curl_errno($ch) == 23 or curl_errno($ch) == 61) and defined('CURLOPT_ENCODING')) {
245 curl_setopt($ch, CURLOPT_ENCODING, 'none');
246 $data = curl_exec($ch);
249 if (curl_errno($ch)) {
250 $error = curl_error($ch);
251 $error_no = curl_errno($ch);
252 curl_close($ch);
254 if ($fullresponse) {
255 $response = new object();
256 if ($error_no == 28) {
257 $response->status = '-100'; // mimic snoopy
258 } else {
259 $response->status = '0';
261 $response->headers = array();
262 $response->response_code = $error;
263 $response->results = '';
264 $response->error = $error;
265 return $response;
266 } else {
267 debugging("cURL request for \"$url\" failed with: $error ($error_no)", DEBUG_ALL);
268 return false;
271 } else {
272 $info = curl_getinfo($ch);
273 curl_close($ch);
275 if (empty($info['http_code'])) {
276 // for security reasons we support only true http connections (Location: file:// exploit prevention)
277 $response = new object();
278 $response->status = '0';
279 $response->headers = array();
280 $response->response_code = 'Unknown cURL error';
281 $response->results = ''; // do NOT change this!
282 $response->error = 'Unknown cURL error';
284 } else {
285 // strip redirect headers and get headers array and content
286 $data = explode("\r\n\r\n", $data, $info['redirect_count'] + 2);
287 $results = array_pop($data);
288 $headers = array_pop($data);
289 $headers = explode("\r\n", trim($headers));
291 $response = new object();;
292 $response->status = (string)$info['http_code'];
293 $response->headers = $headers;
294 $response->response_code = $headers[0];
295 $response->results = $results;
296 $response->error = '';
299 if ($fullresponse) {
300 return $response;
301 } else if ($info['http_code'] != 200) {
302 debugging("cURL request for \"$url\" failed, HTTP response code: ".$response->response_code, DEBUG_ALL);
303 return false;
304 } else {
305 return $response->results;
311 * @return List of information about file types based on extensions.
312 * Associative array of extension (lower-case) to associative array
313 * from 'element name' to data. Current element names are 'type' and 'icon'.
314 * Unknown types should use the 'xxx' entry which includes defaults.
316 function get_mimetypes_array() {
317 return array (
318 'xxx' => array ('type'=>'document/unknown', 'icon'=>'unknown.gif'),
319 '3gp' => array ('type'=>'video/quicktime', 'icon'=>'video.gif'),
320 'ai' => array ('type'=>'application/postscript', 'icon'=>'image.gif'),
321 'aif' => array ('type'=>'audio/x-aiff', 'icon'=>'audio.gif'),
322 'aiff' => array ('type'=>'audio/x-aiff', 'icon'=>'audio.gif'),
323 'aifc' => array ('type'=>'audio/x-aiff', 'icon'=>'audio.gif'),
324 'applescript' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
325 'asc' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
326 'asm' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
327 'au' => array ('type'=>'audio/au', 'icon'=>'audio.gif'),
328 'avi' => array ('type'=>'video/x-ms-wm', 'icon'=>'avi.gif'),
329 'bmp' => array ('type'=>'image/bmp', 'icon'=>'image.gif'),
330 'c' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
331 'cct' => array ('type'=>'shockwave/director', 'icon'=>'flash.gif'),
332 'cpp' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
333 'cs' => array ('type'=>'application/x-csh', 'icon'=>'text.gif'),
334 'css' => array ('type'=>'text/css', 'icon'=>'text.gif'),
335 'csv' => array ('type'=>'text/csv', 'icon'=>'excel.gif'),
336 'dv' => array ('type'=>'video/x-dv', 'icon'=>'video.gif'),
337 'dmg' => array ('type'=>'application/octet-stream', 'icon'=>'dmg.gif'),
339 'doc' => array ('type'=>'application/msword', 'icon'=>'word.gif'),
340 'docx' => array ('type'=>'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'icon'=>'docx.gif'),
341 'docm' => array ('type'=>'application/vnd.ms-word.document.macroEnabled.12', 'icon'=>'docm.gif'),
342 'dotx' => array ('type'=>'application/vnd.openxmlformats-officedocument.wordprocessingml.template', 'icon'=>'dotx.gif'),
343 'dotm' => array ('type'=>'application/vnd.ms-word.template.macroEnabled.12', 'icon'=>'dotm.gif'),
345 'dcr' => array ('type'=>'application/x-director', 'icon'=>'flash.gif'),
346 'dif' => array ('type'=>'video/x-dv', 'icon'=>'video.gif'),
347 'dir' => array ('type'=>'application/x-director', 'icon'=>'flash.gif'),
348 'dxr' => array ('type'=>'application/x-director', 'icon'=>'flash.gif'),
349 'eps' => array ('type'=>'application/postscript', 'icon'=>'pdf.gif'),
350 'fdf' => array ('type'=>'application/pdf', 'icon'=>'pdf.gif'),
351 'flv' => array ('type'=>'video/x-flv', 'icon'=>'video.gif'),
352 'gif' => array ('type'=>'image/gif', 'icon'=>'image.gif'),
353 'gtar' => array ('type'=>'application/x-gtar', 'icon'=>'zip.gif'),
354 'tgz' => array ('type'=>'application/g-zip', 'icon'=>'zip.gif'),
355 'gz' => array ('type'=>'application/g-zip', 'icon'=>'zip.gif'),
356 'gzip' => array ('type'=>'application/g-zip', 'icon'=>'zip.gif'),
357 'h' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
358 'hpp' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
359 'hqx' => array ('type'=>'application/mac-binhex40', 'icon'=>'zip.gif'),
360 'htc' => array ('type'=>'text/x-component', 'icon'=>'text.gif'),
361 'html' => array ('type'=>'text/html', 'icon'=>'html.gif'),
362 'xhtml'=> array ('type'=>'application/xhtml+xml', 'icon'=>'html.gif'),
363 'htm' => array ('type'=>'text/html', 'icon'=>'html.gif'),
364 'ico' => array ('type'=>'image/vnd.microsoft.icon', 'icon'=>'image.gif'),
365 'ics' => array ('type'=>'text/calendar', 'icon'=>'text.gif'),
366 'isf' => array ('type'=>'application/inspiration', 'icon'=>'isf.gif'),
367 'ist' => array ('type'=>'application/inspiration.template', 'icon'=>'isf.gif'),
368 'java' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
369 'jcb' => array ('type'=>'text/xml', 'icon'=>'jcb.gif'),
370 'jcl' => array ('type'=>'text/xml', 'icon'=>'jcl.gif'),
371 'jcw' => array ('type'=>'text/xml', 'icon'=>'jcw.gif'),
372 'jmt' => array ('type'=>'text/xml', 'icon'=>'jmt.gif'),
373 'jmx' => array ('type'=>'text/xml', 'icon'=>'jmx.gif'),
374 'jpe' => array ('type'=>'image/jpeg', 'icon'=>'image.gif'),
375 'jpeg' => array ('type'=>'image/jpeg', 'icon'=>'image.gif'),
376 'jpg' => array ('type'=>'image/jpeg', 'icon'=>'image.gif'),
377 'jqz' => array ('type'=>'text/xml', 'icon'=>'jqz.gif'),
378 'js' => array ('type'=>'application/x-javascript', 'icon'=>'text.gif'),
379 'latex'=> array ('type'=>'application/x-latex', 'icon'=>'text.gif'),
380 'm' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
381 'mov' => array ('type'=>'video/quicktime', 'icon'=>'video.gif'),
382 'movie'=> array ('type'=>'video/x-sgi-movie', 'icon'=>'video.gif'),
383 'm3u' => array ('type'=>'audio/x-mpegurl', 'icon'=>'audio.gif'),
384 'mp3' => array ('type'=>'audio/mp3', 'icon'=>'audio.gif'),
385 'mp4' => array ('type'=>'video/mp4', 'icon'=>'video.gif'),
386 'm4v' => array ('type'=>'video/mp4', 'icon'=>'video.gif'),
387 'm4a' => array ('type'=>'audio/mp4', 'icon'=>'audio.gif'),
388 'mpeg' => array ('type'=>'video/mpeg', 'icon'=>'video.gif'),
389 'mpe' => array ('type'=>'video/mpeg', 'icon'=>'video.gif'),
390 'mpg' => array ('type'=>'video/mpeg', 'icon'=>'video.gif'),
392 'odt' => array ('type'=>'application/vnd.oasis.opendocument.text', 'icon'=>'odt.gif'),
393 'ott' => array ('type'=>'application/vnd.oasis.opendocument.text-template', 'icon'=>'odt.gif'),
394 'oth' => array ('type'=>'application/vnd.oasis.opendocument.text-web', 'icon'=>'odt.gif'),
395 'odm' => array ('type'=>'application/vnd.oasis.opendocument.text-master', 'icon'=>'odm.gif'),
396 'odg' => array ('type'=>'application/vnd.oasis.opendocument.graphics', 'icon'=>'odg.gif'),
397 'otg' => array ('type'=>'application/vnd.oasis.opendocument.graphics-template', 'icon'=>'odg.gif'),
398 'odp' => array ('type'=>'application/vnd.oasis.opendocument.presentation', 'icon'=>'odp.gif'),
399 'otp' => array ('type'=>'application/vnd.oasis.opendocument.presentation-template', 'icon'=>'odp.gif'),
400 'ods' => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet', 'icon'=>'ods.gif'),
401 'ots' => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet-template', 'icon'=>'ods.gif'),
402 'odc' => array ('type'=>'application/vnd.oasis.opendocument.chart', 'icon'=>'odc.gif'),
403 'odf' => array ('type'=>'application/vnd.oasis.opendocument.formula', 'icon'=>'odf.gif'),
404 'odb' => array ('type'=>'application/vnd.oasis.opendocument.database', 'icon'=>'odb.gif'),
405 'odi' => array ('type'=>'application/vnd.oasis.opendocument.image', 'icon'=>'odi.gif'),
406 'ogg' => array ('type'=>'audio/ogg', 'icon'=>'audio.gif'),
407 'ogv' => array ('type'=>'video/ogg', 'icon'=>'video.gif'),
409 'pct' => array ('type'=>'image/pict', 'icon'=>'image.gif'),
410 'pdf' => array ('type'=>'application/pdf', 'icon'=>'pdf.gif'),
411 'php' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
412 'pic' => array ('type'=>'image/pict', 'icon'=>'image.gif'),
413 'pict' => array ('type'=>'image/pict', 'icon'=>'image.gif'),
414 'png' => array ('type'=>'image/png', 'icon'=>'image.gif'),
416 'pps' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'powerpoint.gif'),
417 'ppt' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'powerpoint.gif'),
418 'pptx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'icon'=>'pptx.gif'),
419 'pptm' => array ('type'=>'application/vnd.ms-powerpoint.presentation.macroEnabled.12', 'icon'=>'pptm.gif'),
420 'potx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.template', 'icon'=>'potx.gif'),
421 'potm' => array ('type'=>'application/vnd.ms-powerpoint.template.macroEnabled.12', 'icon'=>'potm.gif'),
422 'ppam' => array ('type'=>'application/vnd.ms-powerpoint.addin.macroEnabled.12', 'icon'=>'ppam.gif'),
423 'ppsx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.slideshow', 'icon'=>'ppsx.gif'),
424 'ppsm' => array ('type'=>'application/vnd.ms-powerpoint.slideshow.macroEnabled.12', 'icon'=>'ppsm.gif'),
426 'ps' => array ('type'=>'application/postscript', 'icon'=>'pdf.gif'),
427 'qt' => array ('type'=>'video/quicktime', 'icon'=>'video.gif'),
428 'ra' => array ('type'=>'audio/x-realaudio-plugin', 'icon'=>'audio.gif'),
429 'ram' => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'audio.gif'),
430 'rhb' => array ('type'=>'text/xml', 'icon'=>'xml.gif'),
431 'rm' => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'audio.gif'),
432 'rtf' => array ('type'=>'text/rtf', 'icon'=>'text.gif'),
433 'rtx' => array ('type'=>'text/richtext', 'icon'=>'text.gif'),
434 'sh' => array ('type'=>'application/x-sh', 'icon'=>'text.gif'),
435 'sit' => array ('type'=>'application/x-stuffit', 'icon'=>'zip.gif'),
436 'smi' => array ('type'=>'application/smil', 'icon'=>'text.gif'),
437 'smil' => array ('type'=>'application/smil', 'icon'=>'text.gif'),
438 'sqt' => array ('type'=>'text/xml', 'icon'=>'xml.gif'),
439 'svg' => array ('type'=>'image/svg+xml', 'icon'=>'image.gif'),
440 'svgz' => array ('type'=>'image/svg+xml', 'icon'=>'image.gif'),
441 'swa' => array ('type'=>'application/x-director', 'icon'=>'flash.gif'),
442 'swf' => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash.gif'),
443 'swfl' => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash.gif'),
445 'sxw' => array ('type'=>'application/vnd.sun.xml.writer', 'icon'=>'odt.gif'),
446 'stw' => array ('type'=>'application/vnd.sun.xml.writer.template', 'icon'=>'odt.gif'),
447 'sxc' => array ('type'=>'application/vnd.sun.xml.calc', 'icon'=>'odt.gif'),
448 'stc' => array ('type'=>'application/vnd.sun.xml.calc.template', 'icon'=>'odt.gif'),
449 'sxd' => array ('type'=>'application/vnd.sun.xml.draw', 'icon'=>'odt.gif'),
450 'std' => array ('type'=>'application/vnd.sun.xml.draw.template', 'icon'=>'odt.gif'),
451 'sxi' => array ('type'=>'application/vnd.sun.xml.impress', 'icon'=>'odt.gif'),
452 'sti' => array ('type'=>'application/vnd.sun.xml.impress.template', 'icon'=>'odt.gif'),
453 'sxg' => array ('type'=>'application/vnd.sun.xml.writer.global', 'icon'=>'odt.gif'),
454 'sxm' => array ('type'=>'application/vnd.sun.xml.math', 'icon'=>'odt.gif'),
456 'tar' => array ('type'=>'application/x-tar', 'icon'=>'zip.gif'),
457 'tif' => array ('type'=>'image/tiff', 'icon'=>'image.gif'),
458 'tiff' => array ('type'=>'image/tiff', 'icon'=>'image.gif'),
459 'tex' => array ('type'=>'application/x-tex', 'icon'=>'text.gif'),
460 'texi' => array ('type'=>'application/x-texinfo', 'icon'=>'text.gif'),
461 'texinfo' => array ('type'=>'application/x-texinfo', 'icon'=>'text.gif'),
462 'tsv' => array ('type'=>'text/tab-separated-values', 'icon'=>'text.gif'),
463 'txt' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
464 'wav' => array ('type'=>'audio/wav', 'icon'=>'audio.gif'),
465 'wmv' => array ('type'=>'video/x-ms-wmv', 'icon'=>'avi.gif'),
466 'asf' => array ('type'=>'video/x-ms-asf', 'icon'=>'avi.gif'),
467 'xdp' => array ('type'=>'application/pdf', 'icon'=>'pdf.gif'),
468 'xfd' => array ('type'=>'application/pdf', 'icon'=>'pdf.gif'),
469 'xfdf' => array ('type'=>'application/pdf', 'icon'=>'pdf.gif'),
471 'xls' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'excel.gif'),
472 'xlsx' => array ('type'=>'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'icon'=>'xlsx.gif'),
473 'xlsm' => array ('type'=>'application/vnd.ms-excel.sheet.macroEnabled.12', 'icon'=>'xlsm.gif'),
474 'xltx' => array ('type'=>'application/vnd.openxmlformats-officedocument.spreadsheetml.template', 'icon'=>'xltx.gif'),
475 'xltm' => array ('type'=>'application/vnd.ms-excel.template.macroEnabled.12', 'icon'=>'xltm.gif'),
476 'xlsb' => array ('type'=>'application/vnd.ms-excel.sheet.binary.macroEnabled.12', 'icon'=>'xlsb.gif'),
477 'xlam' => array ('type'=>'application/vnd.ms-excel.addin.macroEnabled.12', 'icon'=>'xlam.gif'),
479 'xml' => array ('type'=>'application/xml', 'icon'=>'xml.gif'),
480 'xsl' => array ('type'=>'text/xml', 'icon'=>'xml.gif'),
481 'zip' => array ('type'=>'application/zip', 'icon'=>'zip.gif')
486 * Obtains information about a filetype based on its extension. Will
487 * use a default if no information is present about that particular
488 * extension.
489 * @param string $element Desired information (usually 'icon'
490 * for icon filename or 'type' for MIME type)
491 * @param string $filename Filename we're looking up
492 * @return string Requested piece of information from array
494 function mimeinfo($element, $filename) {
495 static $mimeinfo = null;
496 if (is_null($mimeinfo)) {
497 $mimeinfo = get_mimetypes_array();
500 if (preg_match('/\.([a-zA-Z0-9]+)$/', $filename, $match)) {
501 if (isset($mimeinfo[strtolower($match[1])][$element])) {
502 return $mimeinfo[strtolower($match[1])][$element];
503 } else {
504 return $mimeinfo['xxx'][$element]; // By default
506 } else {
507 return $mimeinfo['xxx'][$element]; // By default
512 * Obtains information about a filetype based on the MIME type rather than
513 * the other way around.
514 * @param string $element Desired information (usually 'icon')
515 * @param string $mimetype MIME type we're looking up
516 * @return string Requested piece of information from array
518 function mimeinfo_from_type($element, $mimetype) {
519 static $mimeinfo;
520 $mimeinfo=get_mimetypes_array();
522 foreach($mimeinfo as $values) {
523 if($values['type']==$mimetype) {
524 if(isset($values[$element])) {
525 return $values[$element];
527 break;
530 return $mimeinfo['xxx'][$element]; // Default
534 * Get information about a filetype based on the icon file.
535 * @param string $element Desired information (usually 'icon')
536 * @param string $icon Icon file path.
537 * @return string Requested piece of information from array
539 function mimeinfo_from_icon($element, $icon) {
540 static $mimeinfo;
541 $mimeinfo=get_mimetypes_array();
543 if (preg_match("/\/(.*)/", $icon, $matches)) {
544 $icon = $matches[1];
546 $info = $mimeinfo['xxx'][$element]; // Default
547 foreach($mimeinfo as $values) {
548 if($values['icon']==$icon) {
549 if(isset($values[$element])) {
550 $info = $values[$element];
552 //No break, for example for 'excel.gif' we don't want 'csv'!
555 return $info;
559 * Obtains descriptions for file types (e.g. 'Microsoft Word document') from the
560 * mimetypes.php language file.
561 * @param string $mimetype MIME type (can be obtained using the mimeinfo function)
562 * @param bool $capitalise If true, capitalises first character of result
563 * @return string Text description
565 function get_mimetype_description($mimetype,$capitalise=false) {
566 $result=get_string($mimetype,'mimetypes');
567 // Surrounded by square brackets indicates that there isn't a string for that
568 // (maybe there is a better way to find this out?)
569 if(strpos($result,'[')===0) {
570 $result=get_string('document/unknown','mimetypes');
572 if($capitalise) {
573 $result=ucfirst($result);
575 return $result;
579 * Handles the sending of temporary file to user, download is forced.
580 * File is deleted after abort or succesful sending.
581 * @param string $path path to file, preferably from moodledata/temp/something; or content of file itself
582 * @param string $filename proposed file name when saving file
583 * @param bool $path is content of file
585 function send_temp_file($path, $filename, $pathisstring=false) {
586 global $CFG;
588 // close session - not needed anymore
589 @session_write_close();
591 if (!$pathisstring) {
592 if (!file_exists($path)) {
593 header('HTTP/1.0 404 not found');
594 error(get_string('filenotfound', 'error'), $CFG->wwwroot.'/');
596 // executed after normal finish or abort
597 @register_shutdown_function('send_temp_file_finished', $path);
600 //IE compatibiltiy HACK!
601 if (ini_get('zlib.output_compression')) {
602 ini_set('zlib.output_compression', 'Off');
605 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
606 if (check_browser_version('MSIE')) {
607 $filename = urlencode($filename);
610 $filesize = $pathisstring ? strlen($path) : filesize($path);
612 @header('Content-Disposition: attachment; filename='.$filename);
613 @header('Content-Length: '.$filesize);
614 if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
615 @header('Cache-Control: max-age=10');
616 @header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
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');
620 @header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
621 @header('Pragma: no-cache');
623 @header('Accept-Ranges: none'); // Do not allow byteserving
625 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
626 if ($pathisstring) {
627 echo $path;
628 } else {
629 readfile_chunked($path);
632 die; //no more chars to output
636 * Internal callnack function used by send_temp_file()
638 function send_temp_file_finished($path) {
639 if (file_exists($path)) {
640 @unlink($path);
645 * Handles the sending of file data to the user's browser, including support for
646 * byteranges etc.
647 * @param string $path Path of file on disk (including real filename), or actual content of file as string
648 * @param string $filename Filename to send
649 * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
650 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
651 * @param bool $pathisstring If true (default false), $path is the content to send and not the pathname
652 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
653 * @param string $mimetype Include to specify the MIME type; leave blank to have it guess the type from $filename
655 function send_file($path, $filename, $lifetime = 'default' , $filter=0, $pathisstring=false, $forcedownload=false, $mimetype='') {
656 global $CFG, $COURSE, $SESSION;
658 // MDL-11789, apply $CFG->filelifetime here
659 if ($lifetime === 'default') {
660 if (!empty($CFG->filelifetime)) {
661 $lifetime = $CFG->filelifetime;
662 } else {
663 $lifetime = 86400;
667 // Use given MIME type if specified, otherwise guess it using mimeinfo.
668 // IE, Konqueror and Opera open html file directly in browser from web even when directed to save it to disk :-O
669 // only Firefox saves all files locally before opening when content-disposition: attachment stated
670 $isFF = check_browser_version('Firefox', '1.5'); // only FF > 1.5 properly tested
671 $mimetype = ($forcedownload and !$isFF) ? 'application/x-forcedownload' :
672 ($mimetype ? $mimetype : mimeinfo('type', $filename));
674 // If the file is a Flash file and that the user flash player is outdated return a flash upgrader MDL-20841
675 if (!empty($CFG->excludeoldflashclients) && $mimetype == 'application/x-shockwave-flash'&& !empty($SESSION->flashversion)) {
676 $userplayerversion = explode('.', $SESSION->flashversion);
677 $requiredplayerversion = explode('.', $CFG->excludeoldflashclients);
678 if (($userplayerversion[0] < $requiredplayerversion[0]) ||
679 ($userplayerversion[0] == $requiredplayerversion[0] && $userplayerversion[1] < $requiredplayerversion[1]) ||
680 ($userplayerversion[0] == $requiredplayerversion[0] && $userplayerversion[1] == $requiredplayerversion[1]
681 && $userplayerversion[2] < $requiredplayerversion[2])) {
682 $path = $CFG->dirroot."/lib/flashdetect/flashupgrade.swf"; // Alternate content asking user to upgrade Flash
683 $filename = "flashupgrade.swf";
684 $lifetime = 0; // Do not cache
688 $lastmodified = $pathisstring ? time() : filemtime($path);
689 $filesize = $pathisstring ? strlen($path) : filesize($path);
691 /* - MDL-13949
692 //Adobe Acrobat Reader XSS prevention
693 if ($mimetype=='application/pdf' or mimeinfo('type', $filename)=='application/pdf') {
694 //please note that it prevents opening of pdfs in browser when http referer disabled
695 //or file linked from another site; browser caching of pdfs is now disabled too
696 if (!empty($_SERVER['HTTP_RANGE'])) {
697 //already byteserving
698 $lifetime = 1; // >0 needed for byteserving
699 } else if (empty($_SERVER['HTTP_REFERER']) or strpos($_SERVER['HTTP_REFERER'], $CFG->wwwroot)!==0) {
700 $mimetype = 'application/x-forcedownload';
701 $forcedownload = true;
702 $lifetime = 0;
703 } else {
704 $lifetime = 1; // >0 needed for byteserving
709 //IE compatibiltiy HACK!
710 if (ini_get('zlib.output_compression')) {
711 ini_set('zlib.output_compression', 'Off');
714 //try to disable automatic sid rewrite in cookieless mode
715 @ini_set("session.use_trans_sid", "false");
717 //do not put '@' before the next header to detect incorrect moodle configurations,
718 //error should be better than "weird" empty lines for admins/users
719 //TODO: should we remove all those @ before the header()? Are all of the values supported on all servers?
720 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
722 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
723 if (check_browser_version('MSIE')) {
724 $filename = rawurlencode($filename);
727 if ($forcedownload) {
728 @header('Content-Disposition: attachment; filename="'.$filename.'"');
729 } else {
730 @header('Content-Disposition: inline; filename="'.$filename.'"');
733 if ($lifetime > 0) {
734 @header('Cache-Control: max-age='.$lifetime);
735 @header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
736 @header('Pragma: ');
738 if (empty($CFG->disablebyteserving) && !$pathisstring && $mimetype != 'text/plain' && $mimetype != 'text/html') {
740 @header('Accept-Ranges: bytes');
742 if (!empty($_SERVER['HTTP_RANGE']) && strpos($_SERVER['HTTP_RANGE'],'bytes=') !== FALSE) {
743 // byteserving stuff - for acrobat reader and download accelerators
744 // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
745 // inspired by: http://www.coneural.org/florian/papers/04_byteserving.php
746 $ranges = false;
747 if (preg_match_all('/(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER)) {
748 foreach ($ranges as $key=>$value) {
749 if ($ranges[$key][1] == '') {
750 //suffix case
751 $ranges[$key][1] = $filesize - $ranges[$key][2];
752 $ranges[$key][2] = $filesize - 1;
753 } else if ($ranges[$key][2] == '' || $ranges[$key][2] > $filesize - 1) {
754 //fix range length
755 $ranges[$key][2] = $filesize - 1;
757 if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
758 //invalid byte-range ==> ignore header
759 $ranges = false;
760 break;
762 //prepare multipart header
763 $ranges[$key][0] = "\r\n--".BYTESERVING_BOUNDARY."\r\nContent-Type: $mimetype\r\n";
764 $ranges[$key][0] .= "Content-Range: bytes {$ranges[$key][1]}-{$ranges[$key][2]}/$filesize\r\n\r\n";
766 } else {
767 $ranges = false;
769 if ($ranges) {
770 byteserving_send_file($path, $mimetype, $ranges);
773 } else {
774 /// Do not byteserve (disabled, strings, text and html files).
775 @header('Accept-Ranges: none');
777 } else { // Do not cache files in proxies and browsers
778 if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
779 @header('Cache-Control: max-age=10');
780 @header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
781 @header('Pragma: ');
782 } else { //normal http - prevent caching at all cost
783 @header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
784 @header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
785 @header('Pragma: no-cache');
787 @header('Accept-Ranges: none'); // Do not allow byteserving when caching disabled
790 if (empty($filter)) {
791 if ($mimetype == 'text/html' && !empty($CFG->usesid) && empty($_COOKIE['MoodleSession'.$CFG->sessioncookie])) {
792 //cookieless mode - rewrite links
793 @header('Content-Type: text/html');
794 $path = $pathisstring ? $path : implode('', file($path));
795 $path = sid_ob_rewrite($path);
796 $filesize = strlen($path);
797 $pathisstring = true;
798 } else if ($mimetype == 'text/plain') {
799 @header('Content-Type: Text/plain; charset=utf-8'); //add encoding
800 } else {
801 @header('Content-Type: '.$mimetype);
803 @header('Content-Length: '.$filesize);
804 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
805 if ($pathisstring) {
806 echo $path;
807 } else {
808 readfile_chunked($path);
810 } else { // Try to put the file through filters
811 if ($mimetype == 'text/html') {
812 $options = new object();
813 $options->noclean = true;
814 $options->nocache = true; // temporary workaround for MDL-5136
815 $text = $pathisstring ? $path : implode('', file($path));
817 $text = file_modify_html_header($text);
818 $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
819 if (!empty($CFG->usesid) && empty($_COOKIE['MoodleSession'.$CFG->sessioncookie])) {
820 //cookieless mode - rewrite links
821 $output = sid_ob_rewrite($output);
824 @header('Content-Length: '.strlen($output));
825 @header('Content-Type: text/html');
826 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
827 echo $output;
828 // only filter text if filter all files is selected
829 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
830 $options = new object();
831 $options->newlines = false;
832 $options->noclean = true;
833 $text = htmlentities($pathisstring ? $path : implode('', file($path)));
834 $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
835 if (!empty($CFG->usesid) && empty($_COOKIE['MoodleSession'.$CFG->sessioncookie])) {
836 //cookieless mode - rewrite links
837 $output = sid_ob_rewrite($output);
840 @header('Content-Length: '.strlen($output));
841 @header('Content-Type: text/html; charset=utf-8'); //add encoding
842 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
843 echo $output;
844 } else { // Just send it out raw
845 @header('Content-Length: '.$filesize);
846 @header('Content-Type: '.$mimetype);
847 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
848 if ($pathisstring) {
849 echo $path;
850 }else {
851 readfile_chunked($path);
855 die; //no more chars to output!!!
858 function get_records_csv($file, $table) {
859 global $CFG, $db;
861 if (!$metacolumns = $db->MetaColumns($CFG->prefix . $table)) {
862 return false;
865 if(!($handle = @fopen($file, 'r'))) {
866 error('get_records_csv failed to open '.$file);
869 $fieldnames = fgetcsv($handle, 4096);
870 if(empty($fieldnames)) {
871 fclose($handle);
872 return false;
875 $columns = array();
877 foreach($metacolumns as $metacolumn) {
878 $ord = array_search($metacolumn->name, $fieldnames);
879 if(is_int($ord)) {
880 $columns[$metacolumn->name] = $ord;
884 $rows = array();
886 while (($data = fgetcsv($handle, 4096)) !== false) {
887 $item = new stdClass;
888 foreach($columns as $name => $ord) {
889 $item->$name = $data[$ord];
891 $rows[] = $item;
894 fclose($handle);
895 return $rows;
898 function put_records_csv($file, $records, $table = NULL) {
899 global $CFG, $db;
901 if (empty($records)) {
902 return true;
905 $metacolumns = NULL;
906 if ($table !== NULL && !$metacolumns = $db->MetaColumns($CFG->prefix . $table)) {
907 return false;
910 echo "x";
912 if(!($fp = @fopen($CFG->dataroot.'/temp/'.$file, 'w'))) {
913 error('put_records_csv failed to open '.$file);
916 $proto = reset($records);
917 if(is_object($proto)) {
918 $fields_records = array_keys(get_object_vars($proto));
920 else if(is_array($proto)) {
921 $fields_records = array_keys($proto);
923 else {
924 return false;
926 echo "x";
928 if(!empty($metacolumns)) {
929 $fields_table = array_map(create_function('$a', 'return $a->name;'), $metacolumns);
930 $fields = array_intersect($fields_records, $fields_table);
932 else {
933 $fields = $fields_records;
936 fwrite($fp, implode(',', $fields));
937 fwrite($fp, "\r\n");
939 foreach($records as $record) {
940 $array = (array)$record;
941 $values = array();
942 foreach($fields as $field) {
943 if(strpos($array[$field], ',')) {
944 $values[] = '"'.str_replace('"', '\"', $array[$field]).'"';
946 else {
947 $values[] = $array[$field];
950 fwrite($fp, implode(',', $values)."\r\n");
953 fclose($fp);
954 return true;
959 * Recursively delete the file or folder with path $location. That is,
960 * if it is a file delete it. If it is a folder, delete all its content
961 * then delete it. If $location does not exist to start, that is not
962 * considered an error.
964 * @param $location the path to remove.
966 function fulldelete($location) {
967 if (is_dir($location) and !is_link($location)) {
968 $currdir = opendir($location);
969 while (false !== ($file = readdir($currdir))) {
970 if ($file <> ".." && $file <> ".") {
971 $fullfile = $location."/".$file;
972 if (is_dir($fullfile)) {
973 if (!fulldelete($fullfile)) {
974 return false;
976 } else {
977 if (!unlink($fullfile)) {
978 return false;
983 closedir($currdir);
984 if (! rmdir($location)) {
985 return false;
988 } else if (file_exists($location)) {
989 if (!unlink($location)) {
990 return false;
993 return true;
997 * Improves memory consumptions and works around buggy readfile() in PHP 5.0.4 (2MB readfile limit).
999 function readfile_chunked($filename, $retbytes=true) {
1000 $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
1001 $buffer = '';
1002 $cnt =0;
1003 $handle = fopen($filename, 'rb');
1004 if ($handle === false) {
1005 return false;
1008 while (!feof($handle)) {
1009 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
1010 $buffer = fread($handle, $chunksize);
1011 echo $buffer;
1012 flush();
1013 if ($retbytes) {
1014 $cnt += strlen($buffer);
1017 $status = fclose($handle);
1018 if ($retbytes && $status) {
1019 return $cnt; // return num. bytes delivered like readfile() does.
1021 return $status;
1025 * Send requested byterange of file.
1027 function byteserving_send_file($filename, $mimetype, $ranges) {
1028 $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
1029 $handle = fopen($filename, 'rb');
1030 if ($handle === false) {
1031 die;
1033 if (count($ranges) == 1) { //only one range requested
1034 $length = $ranges[0][2] - $ranges[0][1] + 1;
1035 @header('HTTP/1.1 206 Partial content');
1036 @header('Content-Length: '.$length);
1037 @header('Content-Range: bytes '.$ranges[0][1].'-'.$ranges[0][2].'/'.filesize($filename));
1038 @header('Content-Type: '.$mimetype);
1039 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
1040 $buffer = '';
1041 fseek($handle, $ranges[0][1]);
1042 while (!feof($handle) && $length > 0) {
1043 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
1044 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
1045 echo $buffer;
1046 flush();
1047 $length -= strlen($buffer);
1049 fclose($handle);
1050 die;
1051 } else { // multiple ranges requested - not tested much
1052 $totallength = 0;
1053 foreach($ranges as $range) {
1054 $totallength += strlen($range[0]) + $range[2] - $range[1] + 1;
1056 $totallength += strlen("\r\n--".BYTESERVING_BOUNDARY."--\r\n");
1057 @header('HTTP/1.1 206 Partial content');
1058 @header('Content-Length: '.$totallength);
1059 @header('Content-Type: multipart/byteranges; boundary='.BYTESERVING_BOUNDARY);
1060 //TODO: check if "multipart/x-byteranges" is more compatible with current readers/browsers/servers
1061 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
1062 foreach($ranges as $range) {
1063 $length = $range[2] - $range[1] + 1;
1064 echo $range[0];
1065 $buffer = '';
1066 fseek($handle, $range[1]);
1067 while (!feof($handle) && $length > 0) {
1068 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
1069 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
1070 echo $buffer;
1071 flush();
1072 $length -= strlen($buffer);
1075 echo "\r\n--".BYTESERVING_BOUNDARY."--\r\n";
1076 fclose($handle);
1077 die;
1082 * add includes (js and css) into uploaded files
1083 * before returning them, useful for themes and utf.js includes
1084 * @param string text - text to search and replace
1085 * @return string - text with added head includes
1087 function file_modify_html_header($text) {
1088 // first look for <head> tag
1089 global $CFG;
1091 $stylesheetshtml = '';
1092 foreach ($CFG->stylesheets as $stylesheet) {
1093 $stylesheetshtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
1096 $filters = explode(",", $CFG->textfilters);
1097 if (in_array('filter/mediaplugin', $filters)) {
1098 // this script is needed by most media filter plugins.
1099 $ufo = "\n".'<script type="text/javascript" src="'.$CFG->wwwroot.'/lib/ufo.js"></script>'."\n";
1100 } else {
1101 $ufo = '';
1104 preg_match('/\<head\>|\<HEAD\>/', $text, $matches);
1105 if ($matches) {
1106 $replacement = '<head>'.$ufo.$stylesheetshtml;
1107 $text = preg_replace('/\<head\>|\<HEAD\>/', $replacement, $text, 1);
1108 return $text;
1111 // if not, look for <html> tag, and stick <head> right after
1112 preg_match('/\<html\>|\<HTML\>/', $text, $matches);
1113 if ($matches) {
1114 // replace <html> tag with <html><head>includes</head>
1115 $replacement = '<html>'."\n".'<head>'.$ufo.$stylesheetshtml.'</head>';
1116 $text = preg_replace('/\<html\>|\<HTML\>/', $replacement, $text, 1);
1117 return $text;
1120 // if not, look for <body> tag, and stick <head> before body
1121 preg_match('/\<body\>|\<BODY\>/', $text, $matches);
1122 if ($matches) {
1123 $replacement = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".'<body>';
1124 $text = preg_replace('/\<body\>|\<BODY\>/', $replacement, $text, 1);
1125 return $text;
1128 // if not, just stick a <head> tag at the beginning
1129 $text = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".$text;
1130 return $text;