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