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