MDL-23726 fixed phpdocs - credit goes to Henning Bostelmann
[moodle.git] / lib / filelib.php
blobf12def11a379525713111c878a48249d23749484
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);
179 if ($skipcertverify) {
180 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
183 // use POST if requested
184 if (is_array($postdata)) {
185 foreach ($postdata as $k=>$v) {
186 $postdata[$k] = urlencode($k).'='.urlencode($v);
188 $postdata = implode('&', $postdata);
189 curl_setopt($ch, CURLOPT_POST, true);
190 curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
193 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
194 curl_setopt($ch, CURLOPT_HEADER, true);
195 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $connecttimeout);
196 curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
197 if (!ini_get('open_basedir') and !ini_get('safe_mode')) {
198 // TODO: add version test for '7.10.5'
199 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
200 curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
203 if (!empty($CFG->proxyhost)) {
204 // SOCKS supported in PHP5 only
205 if (!empty($CFG->proxytype) and ($CFG->proxytype == 'SOCKS5')) {
206 if (defined('CURLPROXY_SOCKS5')) {
207 curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
208 } else {
209 curl_close($ch);
210 if ($fullresponse) {
211 $response = new object();
212 $response->status = '0';
213 $response->headers = array();
214 $response->response_code = 'SOCKS5 proxy is not supported in PHP4';
215 $response->results = '';
216 $response->error = 'SOCKS5 proxy is not supported in PHP4';
217 return $response;
218 } else {
219 debugging("SOCKS5 proxy is not supported in PHP4.", DEBUG_ALL);
220 return false;
225 curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, false);
227 if (empty($CFG->proxyport)) {
228 curl_setopt($ch, CURLOPT_PROXY, $CFG->proxyhost);
229 } else {
230 curl_setopt($ch, CURLOPT_PROXY, $CFG->proxyhost.':'.$CFG->proxyport);
233 if (!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) {
234 curl_setopt($ch, CURLOPT_PROXYUSERPWD, $CFG->proxyuser.':'.$CFG->proxypassword);
235 if (defined('CURLOPT_PROXYAUTH')) {
236 // any proxy authentication if PHP 5.1
237 curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_BASIC | CURLAUTH_NTLM);
242 $data = curl_exec($ch);
244 // try to detect encoding problems
245 if ((curl_errno($ch) == 23 or curl_errno($ch) == 61) and defined('CURLOPT_ENCODING')) {
246 curl_setopt($ch, CURLOPT_ENCODING, 'none');
247 $data = curl_exec($ch);
250 if (curl_errno($ch)) {
251 $error = curl_error($ch);
252 $error_no = curl_errno($ch);
253 curl_close($ch);
255 if ($fullresponse) {
256 $response = new object();
257 if ($error_no == 28) {
258 $response->status = '-100'; // mimic snoopy
259 } else {
260 $response->status = '0';
262 $response->headers = array();
263 $response->response_code = $error;
264 $response->results = '';
265 $response->error = $error;
266 return $response;
267 } else {
268 debugging("cURL request for \"$url\" failed with: $error ($error_no)", DEBUG_ALL);
269 return false;
272 } else {
273 $info = curl_getinfo($ch);
274 curl_close($ch);
276 if (empty($info['http_code'])) {
277 // for security reasons we support only true http connections (Location: file:// exploit prevention)
278 $response = new object();
279 $response->status = '0';
280 $response->headers = array();
281 $response->response_code = 'Unknown cURL error';
282 $response->results = ''; // do NOT change this!
283 $response->error = 'Unknown cURL error';
285 } else {
286 // strip redirect headers and get headers array and content
287 $data = explode("\r\n\r\n", $data, $info['redirect_count'] + 2);
288 $results = array_pop($data);
289 $headers = array_pop($data);
290 $headers = explode("\r\n", trim($headers));
292 $response = new object();;
293 $response->status = (string)$info['http_code'];
294 $response->headers = $headers;
295 $response->response_code = $headers[0];
296 $response->results = $results;
297 $response->error = '';
300 if ($fullresponse) {
301 return $response;
302 } else if ($info['http_code'] != 200) {
303 debugging("cURL request for \"$url\" failed, HTTP response code: ".$response->response_code, DEBUG_ALL);
304 return false;
305 } else {
306 return $response->results;
312 * @return List of information about file types based on extensions.
313 * Associative array of extension (lower-case) to associative array
314 * from 'element name' to data. Current element names are 'type' and 'icon'.
315 * Unknown types should use the 'xxx' entry which includes defaults.
317 function get_mimetypes_array() {
318 return array (
319 'xxx' => array ('type'=>'document/unknown', 'icon'=>'unknown.gif'),
320 '3gp' => array ('type'=>'video/quicktime', 'icon'=>'video.gif'),
321 'ai' => array ('type'=>'application/postscript', 'icon'=>'image.gif'),
322 'aif' => array ('type'=>'audio/x-aiff', 'icon'=>'audio.gif'),
323 'aiff' => array ('type'=>'audio/x-aiff', 'icon'=>'audio.gif'),
324 'aifc' => array ('type'=>'audio/x-aiff', 'icon'=>'audio.gif'),
325 'applescript' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
326 'asc' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
327 'asm' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
328 'au' => array ('type'=>'audio/au', 'icon'=>'audio.gif'),
329 'avi' => array ('type'=>'video/x-ms-wm', 'icon'=>'avi.gif'),
330 'bmp' => array ('type'=>'image/bmp', 'icon'=>'image.gif'),
331 'c' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
332 'cct' => array ('type'=>'shockwave/director', 'icon'=>'flash.gif'),
333 'cpp' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
334 'cs' => array ('type'=>'application/x-csh', 'icon'=>'text.gif'),
335 'css' => array ('type'=>'text/css', 'icon'=>'text.gif'),
336 'csv' => array ('type'=>'text/csv', 'icon'=>'excel.gif'),
337 'dv' => array ('type'=>'video/x-dv', 'icon'=>'video.gif'),
338 'dmg' => array ('type'=>'application/octet-stream', 'icon'=>'dmg.gif'),
340 'doc' => array ('type'=>'application/msword', 'icon'=>'word.gif'),
341 'docx' => array ('type'=>'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'icon'=>'docx.gif'),
342 'docm' => array ('type'=>'application/vnd.ms-word.document.macroEnabled.12', 'icon'=>'docm.gif'),
343 'dotx' => array ('type'=>'application/vnd.openxmlformats-officedocument.wordprocessingml.template', 'icon'=>'dotx.gif'),
344 'dotm' => array ('type'=>'application/vnd.ms-word.template.macroEnabled.12', 'icon'=>'dotm.gif'),
346 'dcr' => array ('type'=>'application/x-director', 'icon'=>'flash.gif'),
347 'dif' => array ('type'=>'video/x-dv', 'icon'=>'video.gif'),
348 'dir' => array ('type'=>'application/x-director', 'icon'=>'flash.gif'),
349 'dxr' => array ('type'=>'application/x-director', 'icon'=>'flash.gif'),
350 'eps' => array ('type'=>'application/postscript', 'icon'=>'pdf.gif'),
351 'fdf' => array ('type'=>'application/pdf', 'icon'=>'pdf.gif'),
352 'flv' => array ('type'=>'video/x-flv', 'icon'=>'video.gif'),
353 'gif' => array ('type'=>'image/gif', 'icon'=>'image.gif'),
354 'gtar' => array ('type'=>'application/x-gtar', 'icon'=>'zip.gif'),
355 'tgz' => array ('type'=>'application/g-zip', 'icon'=>'zip.gif'),
356 'gz' => array ('type'=>'application/g-zip', 'icon'=>'zip.gif'),
357 'gzip' => array ('type'=>'application/g-zip', 'icon'=>'zip.gif'),
358 'h' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
359 'hpp' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
360 'hqx' => array ('type'=>'application/mac-binhex40', 'icon'=>'zip.gif'),
361 'htc' => array ('type'=>'text/x-component', 'icon'=>'text.gif'),
362 'html' => array ('type'=>'text/html', 'icon'=>'html.gif'),
363 'xhtml'=> array ('type'=>'application/xhtml+xml', 'icon'=>'html.gif'),
364 'htm' => array ('type'=>'text/html', 'icon'=>'html.gif'),
365 'ico' => array ('type'=>'image/vnd.microsoft.icon', 'icon'=>'image.gif'),
366 'ics' => array ('type'=>'text/calendar', 'icon'=>'text.gif'),
367 'isf' => array ('type'=>'application/inspiration', 'icon'=>'isf.gif'),
368 'ist' => array ('type'=>'application/inspiration.template', 'icon'=>'isf.gif'),
369 'java' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
370 'jcb' => array ('type'=>'text/xml', 'icon'=>'jcb.gif'),
371 'jcl' => array ('type'=>'text/xml', 'icon'=>'jcl.gif'),
372 'jcw' => array ('type'=>'text/xml', 'icon'=>'jcw.gif'),
373 'jmt' => array ('type'=>'text/xml', 'icon'=>'jmt.gif'),
374 'jmx' => array ('type'=>'text/xml', 'icon'=>'jmx.gif'),
375 'jpe' => array ('type'=>'image/jpeg', 'icon'=>'image.gif'),
376 'jpeg' => array ('type'=>'image/jpeg', 'icon'=>'image.gif'),
377 'jpg' => array ('type'=>'image/jpeg', 'icon'=>'image.gif'),
378 'jqz' => array ('type'=>'text/xml', 'icon'=>'jqz.gif'),
379 'js' => array ('type'=>'application/x-javascript', 'icon'=>'text.gif'),
380 'latex'=> array ('type'=>'application/x-latex', 'icon'=>'text.gif'),
381 'm' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
382 'mov' => array ('type'=>'video/quicktime', 'icon'=>'video.gif'),
383 'movie'=> array ('type'=>'video/x-sgi-movie', 'icon'=>'video.gif'),
384 'm3u' => array ('type'=>'audio/x-mpegurl', 'icon'=>'audio.gif'),
385 'mp3' => array ('type'=>'audio/mp3', 'icon'=>'audio.gif'),
386 'mp4' => array ('type'=>'video/mp4', 'icon'=>'video.gif'),
387 'm4v' => array ('type'=>'video/mp4', 'icon'=>'video.gif'),
388 'm4a' => array ('type'=>'audio/mp4', 'icon'=>'audio.gif'),
389 'mpeg' => array ('type'=>'video/mpeg', 'icon'=>'video.gif'),
390 'mpe' => array ('type'=>'video/mpeg', 'icon'=>'video.gif'),
391 'mpg' => array ('type'=>'video/mpeg', 'icon'=>'video.gif'),
393 'odt' => array ('type'=>'application/vnd.oasis.opendocument.text', 'icon'=>'odt.gif'),
394 'ott' => array ('type'=>'application/vnd.oasis.opendocument.text-template', 'icon'=>'odt.gif'),
395 'oth' => array ('type'=>'application/vnd.oasis.opendocument.text-web', 'icon'=>'odt.gif'),
396 'odm' => array ('type'=>'application/vnd.oasis.opendocument.text-master', 'icon'=>'odm.gif'),
397 'odg' => array ('type'=>'application/vnd.oasis.opendocument.graphics', 'icon'=>'odg.gif'),
398 'otg' => array ('type'=>'application/vnd.oasis.opendocument.graphics-template', 'icon'=>'odg.gif'),
399 'odp' => array ('type'=>'application/vnd.oasis.opendocument.presentation', 'icon'=>'odp.gif'),
400 'otp' => array ('type'=>'application/vnd.oasis.opendocument.presentation-template', 'icon'=>'odp.gif'),
401 'ods' => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet', 'icon'=>'ods.gif'),
402 'ots' => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet-template', 'icon'=>'ods.gif'),
403 'odc' => array ('type'=>'application/vnd.oasis.opendocument.chart', 'icon'=>'odc.gif'),
404 'odf' => array ('type'=>'application/vnd.oasis.opendocument.formula', 'icon'=>'odf.gif'),
405 'odb' => array ('type'=>'application/vnd.oasis.opendocument.database', 'icon'=>'odb.gif'),
406 'odi' => array ('type'=>'application/vnd.oasis.opendocument.image', 'icon'=>'odi.gif'),
408 'pct' => array ('type'=>'image/pict', 'icon'=>'image.gif'),
409 'pdf' => array ('type'=>'application/pdf', 'icon'=>'pdf.gif'),
410 'php' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
411 'pic' => array ('type'=>'image/pict', 'icon'=>'image.gif'),
412 'pict' => array ('type'=>'image/pict', 'icon'=>'image.gif'),
413 'png' => array ('type'=>'image/png', 'icon'=>'image.gif'),
415 'pps' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'powerpoint.gif'),
416 'ppt' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'powerpoint.gif'),
417 'pptx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.presentation', 'icon'=>'pptx.gif'),
418 'pptm' => array ('type'=>'application/vnd.ms-powerpoint.presentation.macroEnabled.12', 'icon'=>'pptm.gif'),
419 'potx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.template', 'icon'=>'potx.gif'),
420 'potm' => array ('type'=>'application/vnd.ms-powerpoint.template.macroEnabled.12', 'icon'=>'potm.gif'),
421 'ppam' => array ('type'=>'application/vnd.ms-powerpoint.addin.macroEnabled.12', 'icon'=>'ppam.gif'),
422 'ppsx' => array ('type'=>'application/vnd.openxmlformats-officedocument.presentationml.slideshow', 'icon'=>'ppsx.gif'),
423 'ppsm' => array ('type'=>'application/vnd.ms-powerpoint.slideshow.macroEnabled.12', 'icon'=>'ppsm.gif'),
425 'ps' => array ('type'=>'application/postscript', 'icon'=>'pdf.gif'),
426 'qt' => array ('type'=>'video/quicktime', 'icon'=>'video.gif'),
427 'ra' => array ('type'=>'audio/x-realaudio-plugin', 'icon'=>'audio.gif'),
428 'ram' => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'audio.gif'),
429 'rhb' => array ('type'=>'text/xml', 'icon'=>'xml.gif'),
430 'rm' => array ('type'=>'audio/x-pn-realaudio-plugin', 'icon'=>'audio.gif'),
431 'rtf' => array ('type'=>'text/rtf', 'icon'=>'text.gif'),
432 'rtx' => array ('type'=>'text/richtext', 'icon'=>'text.gif'),
433 'sh' => array ('type'=>'application/x-sh', 'icon'=>'text.gif'),
434 'sit' => array ('type'=>'application/x-stuffit', 'icon'=>'zip.gif'),
435 'smi' => array ('type'=>'application/smil', 'icon'=>'text.gif'),
436 'smil' => array ('type'=>'application/smil', 'icon'=>'text.gif'),
437 'sqt' => array ('type'=>'text/xml', 'icon'=>'xml.gif'),
438 'svg' => array ('type'=>'image/svg+xml', 'icon'=>'image.gif'),
439 'svgz' => array ('type'=>'image/svg+xml', 'icon'=>'image.gif'),
440 'swa' => array ('type'=>'application/x-director', 'icon'=>'flash.gif'),
441 'swf' => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash.gif'),
442 'swfl' => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash.gif'),
444 'sxw' => array ('type'=>'application/vnd.sun.xml.writer', 'icon'=>'odt.gif'),
445 'stw' => array ('type'=>'application/vnd.sun.xml.writer.template', 'icon'=>'odt.gif'),
446 'sxc' => array ('type'=>'application/vnd.sun.xml.calc', 'icon'=>'odt.gif'),
447 'stc' => array ('type'=>'application/vnd.sun.xml.calc.template', 'icon'=>'odt.gif'),
448 'sxd' => array ('type'=>'application/vnd.sun.xml.draw', 'icon'=>'odt.gif'),
449 'std' => array ('type'=>'application/vnd.sun.xml.draw.template', 'icon'=>'odt.gif'),
450 'sxi' => array ('type'=>'application/vnd.sun.xml.impress', 'icon'=>'odt.gif'),
451 'sti' => array ('type'=>'application/vnd.sun.xml.impress.template', 'icon'=>'odt.gif'),
452 'sxg' => array ('type'=>'application/vnd.sun.xml.writer.global', 'icon'=>'odt.gif'),
453 'sxm' => array ('type'=>'application/vnd.sun.xml.math', 'icon'=>'odt.gif'),
455 'tar' => array ('type'=>'application/x-tar', 'icon'=>'zip.gif'),
456 'tif' => array ('type'=>'image/tiff', 'icon'=>'image.gif'),
457 'tiff' => array ('type'=>'image/tiff', 'icon'=>'image.gif'),
458 'tex' => array ('type'=>'application/x-tex', 'icon'=>'text.gif'),
459 'texi' => array ('type'=>'application/x-texinfo', 'icon'=>'text.gif'),
460 'texinfo' => array ('type'=>'application/x-texinfo', 'icon'=>'text.gif'),
461 'tsv' => array ('type'=>'text/tab-separated-values', 'icon'=>'text.gif'),
462 'txt' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
463 'wav' => array ('type'=>'audio/wav', 'icon'=>'audio.gif'),
464 'wmv' => array ('type'=>'video/x-ms-wmv', 'icon'=>'avi.gif'),
465 'asf' => array ('type'=>'video/x-ms-asf', 'icon'=>'avi.gif'),
466 'xdp' => array ('type'=>'application/pdf', 'icon'=>'pdf.gif'),
467 'xfd' => array ('type'=>'application/pdf', 'icon'=>'pdf.gif'),
468 'xfdf' => array ('type'=>'application/pdf', 'icon'=>'pdf.gif'),
470 'xls' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'excel.gif'),
471 'xlsx' => array ('type'=>'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'icon'=>'xlsx.gif'),
472 'xlsm' => array ('type'=>'application/vnd.ms-excel.sheet.macroEnabled.12', 'icon'=>'xlsm.gif'),
473 'xltx' => array ('type'=>'application/vnd.openxmlformats-officedocument.spreadsheetml.template', 'icon'=>'xltx.gif'),
474 'xltm' => array ('type'=>'application/vnd.ms-excel.template.macroEnabled.12', 'icon'=>'xltm.gif'),
475 'xlsb' => array ('type'=>'application/vnd.ms-excel.sheet.binary.macroEnabled.12', 'icon'=>'xlsb.gif'),
476 'xlam' => array ('type'=>'application/vnd.ms-excel.addin.macroEnabled.12', 'icon'=>'xlam.gif'),
478 'xml' => array ('type'=>'application/xml', 'icon'=>'xml.gif'),
479 'xsl' => array ('type'=>'text/xml', 'icon'=>'xml.gif'),
480 'zip' => array ('type'=>'application/zip', 'icon'=>'zip.gif')
485 * Obtains information about a filetype based on its extension. Will
486 * use a default if no information is present about that particular
487 * extension.
488 * @param string $element Desired information (usually 'icon'
489 * for icon filename or 'type' for MIME type)
490 * @param string $filename Filename we're looking up
491 * @return string Requested piece of information from array
493 function mimeinfo($element, $filename) {
494 static $mimeinfo = null;
495 if (is_null($mimeinfo)) {
496 $mimeinfo = get_mimetypes_array();
499 if (preg_match('/\.([a-zA-Z0-9]+)$/', $filename, $match)) {
500 if (isset($mimeinfo[strtolower($match[1])][$element])) {
501 return $mimeinfo[strtolower($match[1])][$element];
502 } else {
503 return $mimeinfo['xxx'][$element]; // By default
505 } else {
506 return $mimeinfo['xxx'][$element]; // By default
511 * Obtains information about a filetype based on the MIME type rather than
512 * the other way around.
513 * @param string $element Desired information (usually 'icon')
514 * @param string $mimetype MIME type we're looking up
515 * @return string Requested piece of information from array
517 function mimeinfo_from_type($element, $mimetype) {
518 static $mimeinfo;
519 $mimeinfo=get_mimetypes_array();
521 foreach($mimeinfo as $values) {
522 if($values['type']==$mimetype) {
523 if(isset($values[$element])) {
524 return $values[$element];
526 break;
529 return $mimeinfo['xxx'][$element]; // Default
533 * Get information about a filetype based on the icon file.
534 * @param string $element Desired information (usually 'icon')
535 * @param string $icon Icon file path.
536 * @return string Requested piece of information from array
538 function mimeinfo_from_icon($element, $icon) {
539 static $mimeinfo;
540 $mimeinfo=get_mimetypes_array();
542 if (preg_match("/\/(.*)/", $icon, $matches)) {
543 $icon = $matches[1];
545 $info = $mimeinfo['xxx'][$element]; // Default
546 foreach($mimeinfo as $values) {
547 if($values['icon']==$icon) {
548 if(isset($values[$element])) {
549 $info = $values[$element];
551 //No break, for example for 'excel.gif' we don't want 'csv'!
554 return $info;
558 * Obtains descriptions for file types (e.g. 'Microsoft Word document') from the
559 * mimetypes.php language file.
560 * @param string $mimetype MIME type (can be obtained using the mimeinfo function)
561 * @param bool $capitalise If true, capitalises first character of result
562 * @return string Text description
564 function get_mimetype_description($mimetype,$capitalise=false) {
565 $result=get_string($mimetype,'mimetypes');
566 // Surrounded by square brackets indicates that there isn't a string for that
567 // (maybe there is a better way to find this out?)
568 if(strpos($result,'[')===0) {
569 $result=get_string('document/unknown','mimetypes');
571 if($capitalise) {
572 $result=ucfirst($result);
574 return $result;
578 * Handles the sending of temporary file to user, download is forced.
579 * File is deleted after abort or succesful sending.
580 * @param string $path path to file, preferably from moodledata/temp/something; or content of file itself
581 * @param string $filename proposed file name when saving file
582 * @param bool $path is content of file
584 function send_temp_file($path, $filename, $pathisstring=false) {
585 global $CFG;
587 // close session - not needed anymore
588 @session_write_close();
590 if (!$pathisstring) {
591 if (!file_exists($path)) {
592 header('HTTP/1.0 404 not found');
593 error(get_string('filenotfound', 'error'), $CFG->wwwroot.'/');
595 // executed after normal finish or abort
596 @register_shutdown_function('send_temp_file_finished', $path);
599 //IE compatibiltiy HACK!
600 if (ini_get('zlib.output_compression')) {
601 ini_set('zlib.output_compression', 'Off');
604 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
605 if (check_browser_version('MSIE')) {
606 $filename = urlencode($filename);
609 $filesize = $pathisstring ? strlen($path) : filesize($path);
611 @header('Content-Disposition: attachment; filename='.$filename);
612 @header('Content-Length: '.$filesize);
613 if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
614 @header('Cache-Control: max-age=10');
615 @header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
616 @header('Pragma: ');
617 } else { //normal http - prevent caching at all cost
618 @header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
619 @header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
620 @header('Pragma: no-cache');
622 @header('Accept-Ranges: none'); // Do not allow byteserving
624 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
625 if ($pathisstring) {
626 echo $path;
627 } else {
628 readfile_chunked($path);
631 die; //no more chars to output
635 * Internal callnack function used by send_temp_file()
637 function send_temp_file_finished($path) {
638 if (file_exists($path)) {
639 @unlink($path);
644 * Handles the sending of file data to the user's browser, including support for
645 * byteranges etc.
646 * @param string $path Path of file on disk (including real filename), or actual content of file as string
647 * @param string $filename Filename to send
648 * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
649 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
650 * @param bool $pathisstring If true (default false), $path is the content to send and not the pathname
651 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
652 * @param string $mimetype Include to specify the MIME type; leave blank to have it guess the type from $filename
654 function send_file($path, $filename, $lifetime = 'default' , $filter=0, $pathisstring=false, $forcedownload=false, $mimetype='') {
655 global $CFG, $COURSE, $SESSION;
657 // MDL-11789, apply $CFG->filelifetime here
658 if ($lifetime === 'default') {
659 if (!empty($CFG->filelifetime)) {
660 $lifetime = $CFG->filelifetime;
661 } else {
662 $lifetime = 86400;
666 // Use given MIME type if specified, otherwise guess it using mimeinfo.
667 // IE, Konqueror and Opera open html file directly in browser from web even when directed to save it to disk :-O
668 // only Firefox saves all files locally before opening when content-disposition: attachment stated
669 $isFF = check_browser_version('Firefox', '1.5'); // only FF > 1.5 properly tested
670 $mimetype = ($forcedownload and !$isFF) ? 'application/x-forcedownload' :
671 ($mimetype ? $mimetype : mimeinfo('type', $filename));
673 // If the file is a Flash file and that the user flash player is outdated return a flash upgrader MDL-20841
674 if (!empty($CFG->excludeoldflashclients) && $mimetype == 'application/x-shockwave-flash'&& !empty($SESSION->flashversion)) {
675 $userplayerversion = explode('.', $SESSION->flashversion);
676 $requiredplayerversion = explode('.', $CFG->excludeoldflashclients);
677 if (($userplayerversion[0] < $requiredplayerversion[0]) ||
678 ($userplayerversion[0] == $requiredplayerversion[0] && $userplayerversion[1] < $requiredplayerversion[1]) ||
679 ($userplayerversion[0] == $requiredplayerversion[0] && $userplayerversion[1] == $requiredplayerversion[1]
680 && $userplayerversion[2] < $requiredplayerversion[2])) {
681 $path = $CFG->dirroot."/lib/flashdetect/flashupgrade.swf"; // Alternate content asking user to upgrade Flash
682 $filename = "flashupgrade.swf";
683 $lifetime = 0; // Do not cache
687 $lastmodified = $pathisstring ? time() : filemtime($path);
688 $filesize = $pathisstring ? strlen($path) : filesize($path);
690 /* - MDL-13949
691 //Adobe Acrobat Reader XSS prevention
692 if ($mimetype=='application/pdf' or mimeinfo('type', $filename)=='application/pdf') {
693 //please note that it prevents opening of pdfs in browser when http referer disabled
694 //or file linked from another site; browser caching of pdfs is now disabled too
695 if (!empty($_SERVER['HTTP_RANGE'])) {
696 //already byteserving
697 $lifetime = 1; // >0 needed for byteserving
698 } else if (empty($_SERVER['HTTP_REFERER']) or strpos($_SERVER['HTTP_REFERER'], $CFG->wwwroot)!==0) {
699 $mimetype = 'application/x-forcedownload';
700 $forcedownload = true;
701 $lifetime = 0;
702 } else {
703 $lifetime = 1; // >0 needed for byteserving
708 //IE compatibiltiy HACK!
709 if (ini_get('zlib.output_compression')) {
710 ini_set('zlib.output_compression', 'Off');
713 //try to disable automatic sid rewrite in cookieless mode
714 @ini_set("session.use_trans_sid", "false");
716 //do not put '@' before the next header to detect incorrect moodle configurations,
717 //error should be better than "weird" empty lines for admins/users
718 //TODO: should we remove all those @ before the header()? Are all of the values supported on all servers?
719 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
721 // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
722 if (check_browser_version('MSIE')) {
723 $filename = rawurlencode($filename);
726 if ($forcedownload) {
727 @header('Content-Disposition: attachment; filename="'.$filename.'"');
728 } else {
729 @header('Content-Disposition: inline; filename="'.$filename.'"');
732 if ($lifetime > 0) {
733 @header('Cache-Control: max-age='.$lifetime);
734 @header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
735 @header('Pragma: ');
737 if (empty($CFG->disablebyteserving) && !$pathisstring && $mimetype != 'text/plain' && $mimetype != 'text/html') {
739 @header('Accept-Ranges: bytes');
741 if (!empty($_SERVER['HTTP_RANGE']) && strpos($_SERVER['HTTP_RANGE'],'bytes=') !== FALSE) {
742 // byteserving stuff - for acrobat reader and download accelerators
743 // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
744 // inspired by: http://www.coneural.org/florian/papers/04_byteserving.php
745 $ranges = false;
746 if (preg_match_all('/(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER)) {
747 foreach ($ranges as $key=>$value) {
748 if ($ranges[$key][1] == '') {
749 //suffix case
750 $ranges[$key][1] = $filesize - $ranges[$key][2];
751 $ranges[$key][2] = $filesize - 1;
752 } else if ($ranges[$key][2] == '' || $ranges[$key][2] > $filesize - 1) {
753 //fix range length
754 $ranges[$key][2] = $filesize - 1;
756 if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
757 //invalid byte-range ==> ignore header
758 $ranges = false;
759 break;
761 //prepare multipart header
762 $ranges[$key][0] = "\r\n--".BYTESERVING_BOUNDARY."\r\nContent-Type: $mimetype\r\n";
763 $ranges[$key][0] .= "Content-Range: bytes {$ranges[$key][1]}-{$ranges[$key][2]}/$filesize\r\n\r\n";
765 } else {
766 $ranges = false;
768 if ($ranges) {
769 byteserving_send_file($path, $mimetype, $ranges);
772 } else {
773 /// Do not byteserve (disabled, strings, text and html files).
774 @header('Accept-Ranges: none');
776 } else { // Do not cache files in proxies and browsers
777 if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
778 @header('Cache-Control: max-age=10');
779 @header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
780 @header('Pragma: ');
781 } else { //normal http - prevent caching at all cost
782 @header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
783 @header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
784 @header('Pragma: no-cache');
786 @header('Accept-Ranges: none'); // Do not allow byteserving when caching disabled
789 if (empty($filter)) {
790 if ($mimetype == 'text/html' && !empty($CFG->usesid) && empty($_COOKIE['MoodleSession'.$CFG->sessioncookie])) {
791 //cookieless mode - rewrite links
792 @header('Content-Type: text/html');
793 $path = $pathisstring ? $path : implode('', file($path));
794 $path = sid_ob_rewrite($path);
795 $filesize = strlen($path);
796 $pathisstring = true;
797 } else if ($mimetype == 'text/plain') {
798 @header('Content-Type: Text/plain; charset=utf-8'); //add encoding
799 } else {
800 @header('Content-Type: '.$mimetype);
802 @header('Content-Length: '.$filesize);
803 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
804 if ($pathisstring) {
805 echo $path;
806 } else {
807 readfile_chunked($path);
809 } else { // Try to put the file through filters
810 if ($mimetype == 'text/html') {
811 $options = new object();
812 $options->noclean = true;
813 $options->nocache = true; // temporary workaround for MDL-5136
814 $text = $pathisstring ? $path : implode('', file($path));
816 $text = file_modify_html_header($text);
817 $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
818 if (!empty($CFG->usesid) && empty($_COOKIE['MoodleSession'.$CFG->sessioncookie])) {
819 //cookieless mode - rewrite links
820 $output = sid_ob_rewrite($output);
823 @header('Content-Length: '.strlen($output));
824 @header('Content-Type: text/html');
825 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
826 echo $output;
827 // only filter text if filter all files is selected
828 } else if (($mimetype == 'text/plain') and ($filter == 1)) {
829 $options = new object();
830 $options->newlines = false;
831 $options->noclean = true;
832 $text = htmlentities($pathisstring ? $path : implode('', file($path)));
833 $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
834 if (!empty($CFG->usesid) && empty($_COOKIE['MoodleSession'.$CFG->sessioncookie])) {
835 //cookieless mode - rewrite links
836 $output = sid_ob_rewrite($output);
839 @header('Content-Length: '.strlen($output));
840 @header('Content-Type: text/html; charset=utf-8'); //add encoding
841 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
842 echo $output;
843 } else { // Just send it out raw
844 @header('Content-Length: '.$filesize);
845 @header('Content-Type: '.$mimetype);
846 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
847 if ($pathisstring) {
848 echo $path;
849 }else {
850 readfile_chunked($path);
854 die; //no more chars to output!!!
857 function get_records_csv($file, $table) {
858 global $CFG, $db;
860 if (!$metacolumns = $db->MetaColumns($CFG->prefix . $table)) {
861 return false;
864 if(!($handle = @fopen($file, 'r'))) {
865 error('get_records_csv failed to open '.$file);
868 $fieldnames = fgetcsv($handle, 4096);
869 if(empty($fieldnames)) {
870 fclose($handle);
871 return false;
874 $columns = array();
876 foreach($metacolumns as $metacolumn) {
877 $ord = array_search($metacolumn->name, $fieldnames);
878 if(is_int($ord)) {
879 $columns[$metacolumn->name] = $ord;
883 $rows = array();
885 while (($data = fgetcsv($handle, 4096)) !== false) {
886 $item = new stdClass;
887 foreach($columns as $name => $ord) {
888 $item->$name = $data[$ord];
890 $rows[] = $item;
893 fclose($handle);
894 return $rows;
897 function put_records_csv($file, $records, $table = NULL) {
898 global $CFG, $db;
900 if (empty($records)) {
901 return true;
904 $metacolumns = NULL;
905 if ($table !== NULL && !$metacolumns = $db->MetaColumns($CFG->prefix . $table)) {
906 return false;
909 echo "x";
911 if(!($fp = @fopen($CFG->dataroot.'/temp/'.$file, 'w'))) {
912 error('put_records_csv failed to open '.$file);
915 $proto = reset($records);
916 if(is_object($proto)) {
917 $fields_records = array_keys(get_object_vars($proto));
919 else if(is_array($proto)) {
920 $fields_records = array_keys($proto);
922 else {
923 return false;
925 echo "x";
927 if(!empty($metacolumns)) {
928 $fields_table = array_map(create_function('$a', 'return $a->name;'), $metacolumns);
929 $fields = array_intersect($fields_records, $fields_table);
931 else {
932 $fields = $fields_records;
935 fwrite($fp, implode(',', $fields));
936 fwrite($fp, "\r\n");
938 foreach($records as $record) {
939 $array = (array)$record;
940 $values = array();
941 foreach($fields as $field) {
942 if(strpos($array[$field], ',')) {
943 $values[] = '"'.str_replace('"', '\"', $array[$field]).'"';
945 else {
946 $values[] = $array[$field];
949 fwrite($fp, implode(',', $values)."\r\n");
952 fclose($fp);
953 return true;
958 * Recursively delete the file or folder with path $location. That is,
959 * if it is a file delete it. If it is a folder, delete all its content
960 * then delete it. If $location does not exist to start, that is not
961 * considered an error.
963 * @param $location the path to remove.
965 function fulldelete($location) {
966 if (is_dir($location) and !is_link($location)) {
967 $currdir = opendir($location);
968 while (false !== ($file = readdir($currdir))) {
969 if ($file <> ".." && $file <> ".") {
970 $fullfile = $location."/".$file;
971 if (is_dir($fullfile)) {
972 if (!fulldelete($fullfile)) {
973 return false;
975 } else {
976 if (!unlink($fullfile)) {
977 return false;
982 closedir($currdir);
983 if (! rmdir($location)) {
984 return false;
987 } else if (file_exists($location)) {
988 if (!unlink($location)) {
989 return false;
992 return true;
996 * Improves memory consumptions and works around buggy readfile() in PHP 5.0.4 (2MB readfile limit).
998 function readfile_chunked($filename, $retbytes=true) {
999 $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
1000 $buffer = '';
1001 $cnt =0;
1002 $handle = fopen($filename, 'rb');
1003 if ($handle === false) {
1004 return false;
1007 while (!feof($handle)) {
1008 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
1009 $buffer = fread($handle, $chunksize);
1010 echo $buffer;
1011 flush();
1012 if ($retbytes) {
1013 $cnt += strlen($buffer);
1016 $status = fclose($handle);
1017 if ($retbytes && $status) {
1018 return $cnt; // return num. bytes delivered like readfile() does.
1020 return $status;
1024 * Send requested byterange of file.
1026 function byteserving_send_file($filename, $mimetype, $ranges) {
1027 $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
1028 $handle = fopen($filename, 'rb');
1029 if ($handle === false) {
1030 die;
1032 if (count($ranges) == 1) { //only one range requested
1033 $length = $ranges[0][2] - $ranges[0][1] + 1;
1034 @header('HTTP/1.1 206 Partial content');
1035 @header('Content-Length: '.$length);
1036 @header('Content-Range: bytes '.$ranges[0][1].'-'.$ranges[0][2].'/'.filesize($filename));
1037 @header('Content-Type: '.$mimetype);
1038 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
1039 $buffer = '';
1040 fseek($handle, $ranges[0][1]);
1041 while (!feof($handle) && $length > 0) {
1042 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
1043 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
1044 echo $buffer;
1045 flush();
1046 $length -= strlen($buffer);
1048 fclose($handle);
1049 die;
1050 } else { // multiple ranges requested - not tested much
1051 $totallength = 0;
1052 foreach($ranges as $range) {
1053 $totallength += strlen($range[0]) + $range[2] - $range[1] + 1;
1055 $totallength += strlen("\r\n--".BYTESERVING_BOUNDARY."--\r\n");
1056 @header('HTTP/1.1 206 Partial content');
1057 @header('Content-Length: '.$totallength);
1058 @header('Content-Type: multipart/byteranges; boundary='.BYTESERVING_BOUNDARY);
1059 //TODO: check if "multipart/x-byteranges" is more compatible with current readers/browsers/servers
1060 while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
1061 foreach($ranges as $range) {
1062 $length = $range[2] - $range[1] + 1;
1063 echo $range[0];
1064 $buffer = '';
1065 fseek($handle, $range[1]);
1066 while (!feof($handle) && $length > 0) {
1067 @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
1068 $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
1069 echo $buffer;
1070 flush();
1071 $length -= strlen($buffer);
1074 echo "\r\n--".BYTESERVING_BOUNDARY."--\r\n";
1075 fclose($handle);
1076 die;
1081 * add includes (js and css) into uploaded files
1082 * before returning them, useful for themes and utf.js includes
1083 * @param string text - text to search and replace
1084 * @return string - text with added head includes
1086 function file_modify_html_header($text) {
1087 // first look for <head> tag
1088 global $CFG;
1090 $stylesheetshtml = '';
1091 foreach ($CFG->stylesheets as $stylesheet) {
1092 $stylesheetshtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
1095 $filters = explode(",", $CFG->textfilters);
1096 if (in_array('filter/mediaplugin', $filters)) {
1097 // this script is needed by most media filter plugins.
1098 $ufo = "\n".'<script type="text/javascript" src="'.$CFG->wwwroot.'/lib/ufo.js"></script>'."\n";
1099 } else {
1100 $ufo = '';
1103 preg_match('/\<head\>|\<HEAD\>/', $text, $matches);
1104 if ($matches) {
1105 $replacement = '<head>'.$ufo.$stylesheetshtml;
1106 $text = preg_replace('/\<head\>|\<HEAD\>/', $replacement, $text, 1);
1107 return $text;
1110 // if not, look for <html> tag, and stick <head> right after
1111 preg_match('/\<html\>|\<HTML\>/', $text, $matches);
1112 if ($matches) {
1113 // replace <html> tag with <html><head>includes</head>
1114 $replacement = '<html>'."\n".'<head>'.$ufo.$stylesheetshtml.'</head>';
1115 $text = preg_replace('/\<html\>|\<HTML\>/', $replacement, $text, 1);
1116 return $text;
1119 // if not, look for <body> tag, and stick <head> before body
1120 preg_match('/\<body\>|\<BODY\>/', $text, $matches);
1121 if ($matches) {
1122 $replacement = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".'<body>';
1123 $text = preg_replace('/\<body\>|\<BODY\>/', $replacement, $text, 1);
1124 return $text;
1127 // if not, just stick a <head> tag at the beginning
1128 $text = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".$text;
1129 return $text;