filelib.php 42.7 KB
Newer Older
defacer's avatar
 
defacer committed
1
2
<?php //$Id$

3
4
define('BYTESERVING_BOUNDARY', 's1k2o3d4a5k6s7'); //unique string constant

5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
function get_file_url($path, $options=null, $type='coursefile') {
    global $CFG;

    $path = trim($path, '/'); // no leading and trailing slashes

    // type of file
    switch ($type) {
        case 'coursefile':
        default:
            $url = "$CFG->wwwroot/file.php";
    }

    if ($CFG->slasharguments) {
        $parts = explode('/', $path);
        $parts = array_map('urlencode', $parts);
        $path  = implode('/', $parts);
        $ffurl = "$CFG->wwwroot/file.php/$path";
        $separator = '?';
    } else {
        $path = urlencode("/$path");
        $ffurl = "$CFG->wwwroot/file.php?file=$path";
        $separator = '&amp;';
    }

    if ($options) {
        foreach ($options as $name=>$value) {
            $ffurl = $ffurl.$separator.$name.'='.$value;
            $separator = '&amp;';
        }
    }

    return $ffurl;
}

39
/**
40
 * Fetches content of file from Internet (using proxy if defined). Uses cURL extension if present.
41
42
43
 * Due to security concerns only downloads from http(s) sources are supported.
 *
 * @param string $url file url starting with http(s)://
44
45
 * @param array $headers http headers, null if none. If set, should be an
 *   associative array of header name => value pairs.
46
47
 * @param array $postdata array means use POST request with given parameters
 * @param bool $fullresponse return headers, responses, etc in a similar way snoopy does
48
49
 *   (if false, just returns content)
 * @param int $timeout timeout for complete download process including all file transfer
50
51
52
53
 *   (default 5 minutes)
 * @param int $connecttimeout timeout for connection to server; this is the timeout that
 *   usually happens if the remote server is completely down (default 20 seconds);
 *   may not work when using proxy
54
 * @param bool $skipcertverify If true, the peer's SSL certificate will not be checked. Only use this when already in a trusted location.
55
56
 * @return mixed false if request failed or content of the file as string if ok.
 */
57
function download_file_content($url, $headers=null, $postdata=null, $fullresponse=false, $timeout=300, $connecttimeout=20, $skipcertverify=false) {
58
59
    global $CFG;

60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
    // some extra security
    $newlines = array("\r", "\n");
    if (is_array($headers) ) {
        foreach ($headers as $key => $value) {
            $headers[$key] = str_replace($newlines, '', $value);
        }
    }
    $url = str_replace($newlines, '', $url);
    if (!preg_match('|^https?://|i', $url)) {
        if ($fullresponse) {
            $response = new object();
            $response->status        = 0;
            $response->headers       = array();
            $response->response_code = 'Invalid protocol specified in url';
            $response->results       = '';
            $response->error         = 'Invalid protocol specified in url';
            return $response;
        } else {
            return false;
        }
    }


83
    if (!extension_loaded('curl') or ($ch = curl_init($url)) === false) {
84
85
        require_once($CFG->libdir.'/snoopy/Snoopy.class.inc');
        $snoopy = new Snoopy();
86
        $snoopy->read_timeout = $timeout;
87
        $snoopy->_fp_timeout  = $connecttimeout;
88
89
        $snoopy->proxy_host   = $CFG->proxyhost;
        $snoopy->proxy_port   = $CFG->proxyport;
90
91
92
93
94
        if (!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) {
            // this will probably fail, but let's try it anyway
            $snoopy->proxy_user     = $CFG->proxyuser;
            $snoopy->proxy_password = $CFG->proxypassword;
        }
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
        if (is_array($headers) ) {
            $client->rawheaders = $headers;
        }

        if (is_array($postdata)) {
            $fetch = @$snoopy->fetch($url, $postdata); // use more specific debug code bellow
        } else {
            $fetch = @$snoopy->fetch($url); // use more specific debug code bellow
        }

        if ($fetch) {
            if ($fullresponse) {
                //fix header line endings
                foreach ($snoopy->headers as $key=>$unused) {
                    $snoopy->headers[$key] = trim($snoopy->headers[$key]);
                }
                $response = new object();
                $response->status        = $snoopy->status;
                $response->headers       = $snoopy->headers;
                $response->response_code = trim($snoopy->response_code);
                $response->results       = $snoopy->results;
                $response->error         = $snoopy->error;
                return $response;

            } else if ($snoopy->status != 200) {
120
121
                debugging("Snoopy request for \"$url\" failed, http response code: ".$snoopy->response_code, DEBUG_ALL);
                return false;
122

123
124
125
126
            } else {
                return $snoopy->results;
            }
        } else {
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
            if ($fullresponse) {
                $response = new object();
                $response->status        = $snoopy->status;
                $response->headers       = array();
                $response->response_code = $snoopy->response_code;
                $response->results       = '';
                $response->error         = $snoopy->error;
                return $response;
            } else {
                debugging("Snoopy request for \"$url\" failed with: ".$snoopy->error, DEBUG_ALL);
                return false;
            }
        }
    }

142
    // set extra headers
143
144
145
146
147
148
149
150
    if (is_array($headers) ) {
        $headers2 = array();
        foreach ($headers as $key => $value) {
            $headers2[] = "$key: $value";
        }
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers2);
    }

151
152
153
154
155
        
    if ($skipcertverify) {
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    }
    
156
157
158
159
    // use POST if requested
    if (is_array($postdata)) {
        foreach ($postdata as $k=>$v) {
            $postdata[$k] = urlencode($k).'='.urlencode($v);
160
        }
161
162
163
        $postdata = implode('&', $postdata);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
164
165
    }

166
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
167
    curl_setopt($ch, CURLOPT_HEADER, true);
168
169
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $connecttimeout);
    curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
170
    if (!ini_get('open_basedir') and !ini_get('safe_mode')) {
171
        // TODO: add version test for '7.10.5'
172
173
174
175
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
    }

176
    if (!empty($CFG->proxyhost)) {
177
178
179
180
181
182
        // SOCKS supported in PHP5 only
        if (!empty($CFG->proxytype) and ($CFG->proxytype == 'SOCKS5')) {
            if (defined('CURLPROXY_SOCKS5')) {
                curl_setopt($ch, CURLOPT_PROXYTYPE, CURLPROXY_SOCKS5);
            } else {
                curl_close($ch);
183
184
185
186
187
188
189
190
191
192
193
194
                if ($fullresponse) {
                    $response = new object();
                    $response->status        = '0';
                    $response->headers       = array();
                    $response->response_code = 'SOCKS5 proxy is not supported in PHP4';
                    $response->results       = '';
                    $response->error         = 'SOCKS5 proxy is not supported in PHP4';
                    return $response;
                } else {
                    debugging("SOCKS5 proxy is not supported in PHP4.", DEBUG_ALL);
                    return false;
                }
195
196
197
            }
        }

198
199
        curl_setopt($ch, CURLOPT_HTTPPROXYTUNNEL, false);

200
        if (empty($CFG->proxyport)) {
201
            curl_setopt($ch, CURLOPT_PROXY, $CFG->proxyhost);
202
        } else {
203
            curl_setopt($ch, CURLOPT_PROXY, $CFG->proxyhost.':'.$CFG->proxyport);
204
        }
205
206

        if (!empty($CFG->proxyuser) and !empty($CFG->proxypassword)) {
207
            curl_setopt($ch, CURLOPT_PROXYUSERPWD, $CFG->proxyuser.':'.$CFG->proxypassword);
208
209
210
211
            if (defined('CURLOPT_PROXYAUTH')) {
                // any proxy authentication if PHP 5.1
                curl_setopt($ch, CURLOPT_PROXYAUTH, CURLAUTH_BASIC | CURLAUTH_NTLM);
            }
212
213
        }
    }
214

215
    $data = curl_exec($ch);
216

217
    // try to detect encoding problems
218
219
    if ((curl_errno($ch) == 23 or curl_errno($ch) == 61) and defined('CURLOPT_ENCODING')) {
        curl_setopt($ch, CURLOPT_ENCODING, 'none');
220
        $data = curl_exec($ch);
221
222
    }

223
    if (curl_errno($ch)) {
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
        $error    = curl_error($ch);
        $error_no = curl_errno($ch);
        curl_close($ch);

        if ($fullresponse) {
            $response = new object();
            if ($error_no == 28) {
                $response->status    = '-100'; // mimic snoopy
            } else {
                $response->status    = '0';
            }
            $response->headers       = array();
            $response->response_code = $error;
            $response->results       = '';
            $response->error         = $error;
            return $response;
        } else {
241
            debugging("cURL request for \"$url\" failed with: $error ($error_no)", DEBUG_ALL);
242
243
            return false;
        }
244
245

    } else {
246
247
        $info = curl_getinfo($ch);
        curl_close($ch);
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271

        if (empty($info['http_code'])) {
            // for security reasons we support only true http connections (Location: file:// exploit prevention)
            $response = new object();
            $response->status        = '0';
            $response->headers       = array();
            $response->response_code = 'Unknown cURL error';
            $response->results       = ''; // do NOT change this!
            $response->error         = 'Unknown cURL error';

        } else {
            // strip redirect headers and get headers array and content
            $data = explode("\r\n\r\n", $data, $info['redirect_count'] + 2);
            $results = array_pop($data);
            $headers = array_pop($data);
            $headers = explode("\r\n", trim($headers));

            $response = new object();;
            $response->status        = (string)$info['http_code'];
            $response->headers       = $headers;
            $response->response_code = $headers[0];
            $response->results       = $results;
            $response->error         = '';
        }
272
273
274
275

        if ($fullresponse) {
            return $response;
        } else if ($info['http_code'] != 200) {
276
            debugging("cURL request for \"$url\" failed, HTTP response code: ".$response->response_code, DEBUG_ALL);
277
278
279
            return false;
        } else {
            return $response->results;
280
        }
281
    }
282
283
}

284
/**
285
 * @return List of information about file types based on extensions.
286
287
 *   Associative array of extension (lower-case) to associative array
 *   from 'element name' to data. Current element names are 'type' and 'icon'.
288
 *   Unknown types should use the 'xxx' entry which includes defaults.
289
290
291
 */
function get_mimetypes_array() {
    return array (
292
293
294
295
296
297
298
299
        'xxx'  => array ('type'=>'document/unknown', 'icon'=>'unknown.gif'),
        '3gp'  => array ('type'=>'video/quicktime', 'icon'=>'video.gif'),
        'ai'   => array ('type'=>'application/postscript', 'icon'=>'image.gif'),
        'aif'  => array ('type'=>'audio/x-aiff', 'icon'=>'audio.gif'),
        'aiff' => array ('type'=>'audio/x-aiff', 'icon'=>'audio.gif'),
        'aifc' => array ('type'=>'audio/x-aiff', 'icon'=>'audio.gif'),
        'applescript'  => array ('type'=>'text/plain', 'icon'=>'text.gif'),
        'asc'  => array ('type'=>'text/plain', 'icon'=>'text.gif'),
300
        'asm'  => array ('type'=>'text/plain', 'icon'=>'text.gif'),
301
302
303
        'au'   => array ('type'=>'audio/au', 'icon'=>'audio.gif'),
        'avi'  => array ('type'=>'video/x-ms-wm', 'icon'=>'avi.gif'),
        'bmp'  => array ('type'=>'image/bmp', 'icon'=>'image.gif'),
304
        'c'    => array ('type'=>'text/plain', 'icon'=>'text.gif'),
305
        'cct'  => array ('type'=>'shockwave/director', 'icon'=>'flash.gif'),
306
        'cpp'  => array ('type'=>'text/plain', 'icon'=>'text.gif'),
307
        'cs'   => array ('type'=>'application/x-csh', 'icon'=>'text.gif'),
308
        'css'  => array ('type'=>'text/css', 'icon'=>'text.gif'),
309
        'csv'  => array ('type'=>'text/csv', 'icon'=>'excel.gif'),
310
        'dv'   => array ('type'=>'video/x-dv', 'icon'=>'video.gif'),
311
        'dmg'  => array ('type'=>'application/octet-stream', 'icon'=>'dmg.gif'),
312
        'doc'  => array ('type'=>'application/msword', 'icon'=>'word.gif'),
313
314
315
        'docx' => array ('type'=>'application/msword', 'icon'=>'docx.gif'),
        'docm' => array ('type'=>'application/msword', 'icon'=>'docm.gif'),
        'dotx' => array ('type'=>'application/msword', 'icon'=>'dotx.gif'),
316
317
318
319
320
        'dcr'  => array ('type'=>'application/x-director', 'icon'=>'flash.gif'),
        'dif'  => array ('type'=>'video/x-dv', 'icon'=>'video.gif'),
        'dir'  => array ('type'=>'application/x-director', 'icon'=>'flash.gif'),
        'dxr'  => array ('type'=>'application/x-director', 'icon'=>'flash.gif'),
        'eps'  => array ('type'=>'application/postscript', 'icon'=>'pdf.gif'),
skodak's avatar
skodak committed
321
        'fdf'  => array ('type'=>'application/pdf', 'icon'=>'pdf.gif'),
moodler's avatar
moodler committed
322
        'flv'  => array ('type'=>'video/x-flv', 'icon'=>'video.gif'),
323
324
        'gif'  => array ('type'=>'image/gif', 'icon'=>'image.gif'),
        'gtar' => array ('type'=>'application/x-gtar', 'icon'=>'zip.gif'),
moodler's avatar
moodler committed
325
        'tgz'  => array ('type'=>'application/g-zip', 'icon'=>'zip.gif'),
326
327
328
        'gz'   => array ('type'=>'application/g-zip', 'icon'=>'zip.gif'),
        'gzip' => array ('type'=>'application/g-zip', 'icon'=>'zip.gif'),
        'h'    => array ('type'=>'text/plain', 'icon'=>'text.gif'),
329
        'hpp'  => array ('type'=>'text/plain', 'icon'=>'text.gif'),
330
        'hqx'  => array ('type'=>'application/mac-binhex40', 'icon'=>'zip.gif'),
331
        'htc'  => array ('type'=>'text/x-component', 'icon'=>'text.gif'),
332
        'html' => array ('type'=>'text/html', 'icon'=>'html.gif'),
333
        'xhtml'=> array ('type'=>'application/xhtml+xml', 'icon'=>'html.gif'),
334
        'htm'  => array ('type'=>'text/html', 'icon'=>'html.gif'),
335
336
337
        'ico'  => array ('type'=>'image/vnd.microsoft.icon', 'icon'=>'image.gif'),
        'isf'  => array ('type'=>'application/inspiration', 'icon'=>'isf.gif'),
        'ist'  => array ('type'=>'application/inspiration.template', 'icon'=>'isf.gif'),
338
        'java' => array ('type'=>'text/plain', 'icon'=>'text.gif'),
339
340
341
342
343
        'jcb'  => array ('type'=>'text/xml', 'icon'=>'jcb.gif'),
        'jcl'  => array ('type'=>'text/xml', 'icon'=>'jcl.gif'),
        'jcw'  => array ('type'=>'text/xml', 'icon'=>'jcw.gif'),
        'jmt'  => array ('type'=>'text/xml', 'icon'=>'jmt.gif'),
        'jmx'  => array ('type'=>'text/xml', 'icon'=>'jmx.gif'),
344
345
346
        'jpe'  => array ('type'=>'image/jpeg', 'icon'=>'image.gif'),
        'jpeg' => array ('type'=>'image/jpeg', 'icon'=>'image.gif'),
        'jpg'  => array ('type'=>'image/jpeg', 'icon'=>'image.gif'),
347
        'jqz'  => array ('type'=>'text/xml', 'icon'=>'jqz.gif'),
348
349
350
351
352
353
354
355
356
357
358
        'js'   => array ('type'=>'application/x-javascript', 'icon'=>'text.gif'),
        'latex'=> array ('type'=>'application/x-latex', 'icon'=>'text.gif'),
        'm'    => array ('type'=>'text/plain', 'icon'=>'text.gif'),
        'mov'  => array ('type'=>'video/quicktime', 'icon'=>'video.gif'),
        'movie'=> array ('type'=>'video/x-sgi-movie', 'icon'=>'video.gif'),
        'm3u'  => array ('type'=>'audio/x-mpegurl', 'icon'=>'audio.gif'),
        'mp3'  => array ('type'=>'audio/mp3', 'icon'=>'audio.gif'),
        'mp4'  => array ('type'=>'video/mp4', 'icon'=>'video.gif'),
        'mpeg' => array ('type'=>'video/mpeg', 'icon'=>'video.gif'),
        'mpe'  => array ('type'=>'video/mpeg', 'icon'=>'video.gif'),
        'mpg'  => array ('type'=>'video/mpeg', 'icon'=>'video.gif'),
359
360
361
362

        'odt'  => array ('type'=>'application/vnd.oasis.opendocument.text', 'icon'=>'odt.gif'),
        'ott'  => array ('type'=>'application/vnd.oasis.opendocument.text-template', 'icon'=>'odt.gif'),
        'oth'  => array ('type'=>'application/vnd.oasis.opendocument.text-web', 'icon'=>'odt.gif'),
363
364
365
366
367
368
369
370
371
372
373
        'odm'  => array ('type'=>'application/vnd.oasis.opendocument.text-master', 'icon'=>'odm.gif'),
        'odg'  => array ('type'=>'application/vnd.oasis.opendocument.graphics', 'icon'=>'odg.gif'),
        'otg'  => array ('type'=>'application/vnd.oasis.opendocument.graphics-template', 'icon'=>'odg.gif'),
        'odp'  => array ('type'=>'application/vnd.oasis.opendocument.presentation', 'icon'=>'odp.gif'),
        'otp'  => array ('type'=>'application/vnd.oasis.opendocument.presentation-template', 'icon'=>'odp.gif'),
        'ods'  => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet', 'icon'=>'ods.gif'),
        'ots'  => array ('type'=>'application/vnd.oasis.opendocument.spreadsheet-template', 'icon'=>'ods.gif'),
        'odc'  => array ('type'=>'application/vnd.oasis.opendocument.chart', 'icon'=>'odc.gif'),
        'odf'  => array ('type'=>'application/vnd.oasis.opendocument.formula', 'icon'=>'odf.gif'),
        'odb'  => array ('type'=>'application/vnd.oasis.opendocument.database', 'icon'=>'odb.gif'),
        'odi'  => array ('type'=>'application/vnd.oasis.opendocument.image', 'icon'=>'odi.gif'),
374

375
376
377
378
379
380
381
382
        'pct'  => array ('type'=>'image/pict', 'icon'=>'image.gif'),
        'pdf'  => array ('type'=>'application/pdf', 'icon'=>'pdf.gif'),
        'php'  => array ('type'=>'text/plain', 'icon'=>'text.gif'),
        'pic'  => array ('type'=>'image/pict', 'icon'=>'image.gif'),
        'pict' => array ('type'=>'image/pict', 'icon'=>'image.gif'),
        'png'  => array ('type'=>'image/png', 'icon'=>'image.gif'),
        'pps'  => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'powerpoint.gif'),
        'ppt'  => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'powerpoint.gif'),
383
384
385
386
387
388
389
        'pptx' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'pptx.gif'),
        'pptm' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'pptm.gif'),
        'potx' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'potx.gif'),
        'potm' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'potm.gif'),
        'ppam' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'ppam.gif'),
        'ppsx' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'ppsx.gif'),
        'ppsm' => array ('type'=>'application/vnd.ms-powerpoint', 'icon'=>'ppsm.gif'),
390
391
392
393
        'ps'   => array ('type'=>'application/postscript', 'icon'=>'pdf.gif'),
        'qt'   => array ('type'=>'video/quicktime', 'icon'=>'video.gif'),
        'ra'   => array ('type'=>'audio/x-realaudio', 'icon'=>'audio.gif'),
        'ram'  => array ('type'=>'audio/x-pn-realaudio', 'icon'=>'audio.gif'),
394
        'rhb'  => array ('type'=>'text/xml', 'icon'=>'xml.gif'),
395
396
397
398
399
400
401
        'rm'   => array ('type'=>'audio/x-pn-realaudio', 'icon'=>'audio.gif'),
        'rtf'  => array ('type'=>'text/rtf', 'icon'=>'text.gif'),
        'rtx'  => array ('type'=>'text/richtext', 'icon'=>'text.gif'),
        'sh'   => array ('type'=>'application/x-sh', 'icon'=>'text.gif'),
        'sit'  => array ('type'=>'application/x-stuffit', 'icon'=>'zip.gif'),
        'smi'  => array ('type'=>'application/smil', 'icon'=>'text.gif'),
        'smil' => array ('type'=>'application/smil', 'icon'=>'text.gif'),
402
        'sqt'  => array ('type'=>'text/xml', 'icon'=>'xml.gif'),
403
404
        'svg'  => array ('type'=>'image/svg+xml', 'icon'=>'image.gif'),
        'svgz' => array ('type'=>'image/svg+xml', 'icon'=>'image.gif'),
405
406
407
        'swa'  => array ('type'=>'application/x-director', 'icon'=>'flash.gif'),
        'swf'  => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash.gif'),
        'swfl' => array ('type'=>'application/x-shockwave-flash', 'icon'=>'flash.gif'),
408
409
410
411
412
413
414
415
416
417
418
419

        'sxw'  => array ('type'=>'application/vnd.sun.xml.writer', 'icon'=>'odt.gif'),
        'stw'  => array ('type'=>'application/vnd.sun.xml.writer.template', 'icon'=>'odt.gif'),
        'sxc'  => array ('type'=>'application/vnd.sun.xml.calc', 'icon'=>'odt.gif'),
        'stc'  => array ('type'=>'application/vnd.sun.xml.calc.template', 'icon'=>'odt.gif'),
        'sxd'  => array ('type'=>'application/vnd.sun.xml.draw', 'icon'=>'odt.gif'),
        'std'  => array ('type'=>'application/vnd.sun.xml.draw.template', 'icon'=>'odt.gif'),
        'sxi'  => array ('type'=>'application/vnd.sun.xml.impress', 'icon'=>'odt.gif'),
        'sti'  => array ('type'=>'application/vnd.sun.xml.impress.template', 'icon'=>'odt.gif'),
        'sxg'  => array ('type'=>'application/vnd.sun.xml.writer.global', 'icon'=>'odt.gif'),
        'sxm'  => array ('type'=>'application/vnd.sun.xml.math', 'icon'=>'odt.gif'),

420
421
422
423
424
425
426
427
428
429
430
        'tar'  => array ('type'=>'application/x-tar', 'icon'=>'zip.gif'),
        'tif'  => array ('type'=>'image/tiff', 'icon'=>'image.gif'),
        'tiff' => array ('type'=>'image/tiff', 'icon'=>'image.gif'),
        'tex'  => array ('type'=>'application/x-tex', 'icon'=>'text.gif'),
        'texi' => array ('type'=>'application/x-texinfo', 'icon'=>'text.gif'),
        'texinfo'  => array ('type'=>'application/x-texinfo', 'icon'=>'text.gif'),
        'tsv'  => array ('type'=>'text/tab-separated-values', 'icon'=>'text.gif'),
        'txt'  => array ('type'=>'text/plain', 'icon'=>'text.gif'),
        'wav'  => array ('type'=>'audio/wav', 'icon'=>'audio.gif'),
        'wmv'  => array ('type'=>'video/x-ms-wmv', 'icon'=>'avi.gif'),
        'asf'  => array ('type'=>'video/x-ms-asf', 'icon'=>'avi.gif'),
skodak's avatar
skodak committed
431
432
433
        'xdp'  => array ('type'=>'application/pdf', 'icon'=>'pdf.gif'),
        'xfd'  => array ('type'=>'application/pdf', 'icon'=>'pdf.gif'),
        'xfdf' => array ('type'=>'application/pdf', 'icon'=>'pdf.gif'),
434
        'xls'  => array ('type'=>'application/vnd.ms-excel', 'icon'=>'excel.gif'),
435
436
437
438
439
440
        'xlsx' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'xlsx.gif'),
        'xlsm' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'xlsm.gif'),
        'xltx' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'xltx.gif'),
        'xltm' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'xltm.gif'),
        'xlsb' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'xlsb.gif'),
        'xlam' => array ('type'=>'application/vnd.ms-excel', 'icon'=>'xlam.gif'),
441
442
443
        'xml'  => array ('type'=>'application/xml', 'icon'=>'xml.gif'),
        'xsl'  => array ('type'=>'text/xml', 'icon'=>'xml.gif'),
        'zip'  => array ('type'=>'application/zip', 'icon'=>'zip.gif')
444
    );
445
446
}

447
/**
448
449
450
 * Obtains information about a filetype based on its extension. Will
 * use a default if no information is present about that particular
 * extension.
451
 * @param string $element Desired information (usually 'icon'
452
 *   for icon filename or 'type' for MIME type)
453
 * @param string $filename Filename we're looking up
454
455
456
 * @return string Requested piece of information from array
 */
function mimeinfo($element, $filename) {
457
458
459
460
    static $mimeinfo = null;
    if (is_null($mimeinfo)) {
        $mimeinfo = get_mimetypes_array();
    }
461

462
    if (eregi('\.([a-z0-9]+)$', $filename, $match)) {
463
464
465
        if (isset($mimeinfo[strtolower($match[1])][$element])) {
            return $mimeinfo[strtolower($match[1])][$element];
        } else {
466
            return $mimeinfo['xxx'][$element];   // By default
467
468
        }
    } else {
469
        return $mimeinfo['xxx'][$element];   // By default
470
471
472
    }
}

473
/**
474
475
476
 * Obtains information about a filetype based on the MIME type rather than
 * the other way around.
 * @param string $element Desired information (usually 'icon')
477
 * @param string $mimetype MIME type we're looking up
478
479
480
481
482
 * @return string Requested piece of information from array
 */
function mimeinfo_from_type($element, $mimetype) {
    static $mimeinfo;
    $mimeinfo=get_mimetypes_array();
483

484
485
486
487
488
489
490
491
492
493
    foreach($mimeinfo as $values) {
        if($values['type']==$mimetype) {
            if(isset($values[$element])) {
                return $values[$element];
            }
            break;
        }
    }
    return $mimeinfo['xxx'][$element]; // Default
}
494

495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
/**
 * Get information about a filetype based on the icon file.
 * @param string $element Desired information (usually 'icon')
 * @param string $icon Icon file path.
 * @return string Requested piece of information from array
 */
function mimeinfo_from_icon($element, $icon) {
    static $mimeinfo;
    $mimeinfo=get_mimetypes_array();

    if (preg_match("/\/(.*)/", $icon, $matches)) {
        $icon = $matches[1];
    }
    $info = $mimeinfo['xxx'][$element]; // Default
    foreach($mimeinfo as $values) {
        if($values['icon']==$icon) {
            if(isset($values[$element])) {
                $info = $values[$element];
            }
            //No break, for example for 'excel.gif' we don't want 'csv'!
        }
    }
    return $info;
}

520
/**
521
522
 * Obtains descriptions for file types (e.g. 'Microsoft Word document') from the
 * mimetypes.php language file.
523
524
 * @param string $mimetype MIME type (can be obtained using the mimeinfo function)
 * @param bool $capitalise If true, capitalises first character of result
525
 * @return string Text description
526
527
528
529
530
531
532
 */
function get_mimetype_description($mimetype,$capitalise=false) {
    $result=get_string($mimetype,'mimetypes');
    // Surrounded by square brackets indicates that there isn't a string for that
    // (maybe there is a better way to find this out?)
    if(strpos($result,'[')===0) {
        $result=get_string('document/unknown','mimetypes');
533
    }
534
535
536
537
538
539
    if($capitalise) {
        $result=ucfirst($result);
    }
    return $result;
}

540
541
542
/**
 * Handles the sending of file data to the user's browser, including support for
 * byteranges etc.
sam_marshall's avatar
sam_marshall committed
543
544
545
546
547
548
549
 * @param string $path Path of file on disk (including real filename), or actual content of file as string
 * @param string $filename Filename to send
 * @param int $lifetime Number of seconds before the file should expire from caches (default 24 hours)
 * @param int $filter 0 (default)=no filtering, 1=all files, 2=html files only
 * @param bool $pathisstring If true (default false), $path is the content to send and not the pathname
 * @param bool $forcedownload If true (default false), forces download of file rather than view in browser/plugin
 * @param string $mimetype Include to specify the MIME type; leave blank to have it guess the type from $filename
550
 */
sam_marshall's avatar
sam_marshall committed
551
function send_file($path, $filename, $lifetime=86400 , $filter=0, $pathisstring=false, $forcedownload=false, $mimetype='') {
552
    global $CFG, $COURSE;
553

554
555
556
557
    // Use given MIME type if specified, otherwise guess it using mimeinfo.
    // IE, Konqueror and Opera open html file directly in browser from web even when directed to save it to disk :-O
    // only Firefox saves all files locally before opening when content-disposition: attachment stated
    $isFF         = check_browser_version('Firefox', '1.5'); // only FF > 1.5 properly tested
558
    $mimetype     = ($forcedownload and !$isFF) ? 'application/x-forcedownload' :
559
                         ($mimetype ? $mimetype : mimeinfo('type', $filename));
560
561
562
    $lastmodified = $pathisstring ? time() : filemtime($path);
    $filesize     = $pathisstring ? strlen($path) : filesize($path);

563
/* - MDL-13949
skodak's avatar
skodak committed
564
565
566
567
    //Adobe Acrobat Reader XSS prevention
    if ($mimetype=='application/pdf' or mimeinfo('type', $filename)=='application/pdf') {
        //please note that it prevents opening of pdfs in browser when http referer disabled
        //or file linked from another site; browser caching of pdfs is now disabled too
568
569
        if (!empty($_SERVER['HTTP_RANGE'])) {
            //already byteserving
570
            $lifetime = 1; // >0 needed for byteserving
571
        } else if (empty($_SERVER['HTTP_REFERER']) or strpos($_SERVER['HTTP_REFERER'], $CFG->wwwroot)!==0) {
skodak's avatar
skodak committed
572
573
574
575
            $mimetype = 'application/x-forcedownload';
            $forcedownload = true;
            $lifetime = 0;
        } else {
576
            $lifetime = 1; // >0 needed for byteserving
skodak's avatar
skodak committed
577
        }
578
    }
579
*/
580

581
    //IE compatibiltiy HACK!
582
    if (ini_get('zlib.output_compression')) {
583
584
585
        ini_set('zlib.output_compression', 'Off');
    }

586
    //try to disable automatic sid rewrite in cookieless mode
skodak's avatar
skodak committed
587
    @ini_set("session.use_trans_sid", "false");
588
589
590
591
592
593

    //do not put '@' before the next header to detect incorrect moodle configurations,
    //error should be better than "weird" empty lines for admins/users
    //TODO: should we remove all those @ before the header()? Are all of the values supported on all servers?
    header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');

594
595
    // if user is using IE, urlencode the filename so that multibyte file name will show up correctly on popup
    if (check_browser_version('MSIE')) {
596
        $filename = urlencode($filename);
597
598
    }

599
600
601
602
603
604
    if ($forcedownload) {
        @header('Content-Disposition: attachment; filename='.$filename);
    } else {
        @header('Content-Disposition: inline; filename='.$filename);
    }

605
    if ($lifetime > 0) {
606
607
        @header('Cache-Control: max-age='.$lifetime);
        @header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
608
        @header('Pragma: ');
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649

        if (empty($CFG->disablebyteserving) && !$pathisstring && $mimetype != 'text/plain' && $mimetype != 'text/html') {

            @header('Accept-Ranges: bytes');

            if (!empty($_SERVER['HTTP_RANGE']) && strpos($_SERVER['HTTP_RANGE'],'bytes=') !== FALSE) {
                // byteserving stuff - for acrobat reader and download accelerators
                // see: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35
                // inspired by: http://www.coneural.org/florian/papers/04_byteserving.php
                $ranges = false;
                if (preg_match_all('/(\d*)-(\d*)/', $_SERVER['HTTP_RANGE'], $ranges, PREG_SET_ORDER)) {
                    foreach ($ranges as $key=>$value) {
                        if ($ranges[$key][1] == '') {
                            //suffix case
                            $ranges[$key][1] = $filesize - $ranges[$key][2];
                            $ranges[$key][2] = $filesize - 1;
                        } else if ($ranges[$key][2] == '' || $ranges[$key][2] > $filesize - 1) {
                            //fix range length
                            $ranges[$key][2] = $filesize - 1;
                        }
                        if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
                            //invalid byte-range ==> ignore header
                            $ranges = false;
                            break;
                        }
                        //prepare multipart header
                        $ranges[$key][0] =  "\r\n--".BYTESERVING_BOUNDARY."\r\nContent-Type: $mimetype\r\n";
                        $ranges[$key][0] .= "Content-Range: bytes {$ranges[$key][1]}-{$ranges[$key][2]}/$filesize\r\n\r\n";
                    }
                } else {
                    $ranges = false;
                }
                if ($ranges) {
                    byteserving_send_file($path, $mimetype, $ranges);
                }
            }
        } else {
            /// Do not byteserve (disabled, strings, text and html files).
            @header('Accept-Ranges: none');
        }
    } else { // Do not cache files in proxies and browsers
650
651
        if (strpos($CFG->wwwroot, 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
            @header('Cache-Control: max-age=10');
652
            @header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
653
654
655
            @header('Pragma: ');
        } else { //normal http - prevent caching at all cost
            @header('Cache-Control: private, must-revalidate, pre-check=0, post-check=0, max-age=0');
656
            @header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
657
658
            @header('Pragma: no-cache');
        }
659
        @header('Accept-Ranges: none'); // Do not allow byteserving when caching disabled
660
    }
661

662
    if (empty($filter)) {
663
664
665
666
667
668
669
670
        if ($mimetype == 'text/html' && !empty($CFG->usesid) && empty($_COOKIE['MoodleSession'.$CFG->sessioncookie])) {
            //cookieless mode - rewrite links
            @header('Content-Type: text/html');
            $path = $pathisstring ? $path : implode('', file($path));
            $path = sid_ob_rewrite($path);
            $filesize = strlen($path);
            $pathisstring = true;
        } else if ($mimetype == 'text/plain') {
671
            @header('Content-Type: Text/plain; charset=utf-8'); //add encoding
672
        } else {
673
            @header('Content-Type: '.$mimetype);
674
        }
675
676
        @header('Content-Length: '.$filesize);
        while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
677
678
        if ($pathisstring) {
            echo $path;
679
        } else {
680
            readfile_chunked($path);
681
682
683
        }
    } else {     // Try to put the file through filters
        if ($mimetype == 'text/html') {
684
            $options = new object();
685
            $options->noclean = true;
686
            $options->nocache = true; // temporary workaround for MDL-5136
687
            $text = $pathisstring ? $path : implode('', file($path));
688

689
            $text = file_modify_html_header($text);
690
            $output = format_text($text, FORMAT_HTML, $options, $COURSE->id);
691
692
693
694
            if (!empty($CFG->usesid) && empty($_COOKIE['MoodleSession'.$CFG->sessioncookie])) {
                //cookieless mode - rewrite links
                $output = sid_ob_rewrite($output);
            }
695

696
697
698
            @header('Content-Length: '.strlen($output));
            @header('Content-Type: text/html');
            while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
699
            echo $output;
700
701
        // only filter text if filter all files is selected
        } else if (($mimetype == 'text/plain') and ($filter == 1)) {
702
            $options = new object();
703
704
705
            $options->newlines = false;
            $options->noclean = true;
            $text = htmlentities($pathisstring ? $path : implode('', file($path)));
706
            $output = '<pre>'. format_text($text, FORMAT_MOODLE, $options, $COURSE->id) .'</pre>';
707
708
709
710
            if (!empty($CFG->usesid) && empty($_COOKIE['MoodleSession'.$CFG->sessioncookie])) {
                //cookieless mode - rewrite links
                $output = sid_ob_rewrite($output);
            }
711

712
            @header('Content-Length: '.strlen($output));
713
            @header('Content-Type: text/html; charset=utf-8'); //add encoding
714
            while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
715
716
            echo $output;
        } else {    // Just send it out raw
717
718
719
            @header('Content-Length: '.$filesize);
            @header('Content-Type: '.$mimetype);
            while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
720
721
722
            if ($pathisstring) {
                echo $path;
            }else {
723
                readfile_chunked($path);
724
725
726
727
728
729
            }
        }
    }
    die; //no more chars to output!!!
}

defacer's avatar
   
defacer committed
730
function get_records_csv($file, $table) {
defacer's avatar
 
defacer committed
731
732
733
734
735
736
    global $CFG, $db;

    if (!$metacolumns = $db->MetaColumns($CFG->prefix . $table)) {
        return false;
    }

defacer's avatar
   
defacer committed
737
    if(!($handle = @fopen($file, 'r'))) {
738
        print_error('get_records_csv failed to open '.$file);
defacer's avatar
 
defacer committed
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
    }

    $fieldnames = fgetcsv($handle, 4096);
    if(empty($fieldnames)) {
        fclose($handle);
        return false;
    }

    $columns = array();

    foreach($metacolumns as $metacolumn) {
        $ord = array_search($metacolumn->name, $fieldnames);
        if(is_int($ord)) {
            $columns[$metacolumn->name] = $ord;
        }
    }

    $rows = array();

    while (($data = fgetcsv($handle, 4096)) !== false) {
        $item = new stdClass;
        foreach($columns as $name => $ord) {
            $item->$name = $data[$ord];
        }
        $rows[] = $item;
    }

    fclose($handle);
    return $rows;
}

defacer's avatar
   
defacer committed
770
771
772
function put_records_csv($file, $records, $table = NULL) {
    global $CFG, $db;

773
    if (empty($records)) {
defacer's avatar
   
defacer committed
774
775
776
777
778
779
780
781
        return true;
    }

    $metacolumns = NULL;
    if ($table !== NULL && !$metacolumns = $db->MetaColumns($CFG->prefix . $table)) {
        return false;
    }

782
783
    echo "x";

defacer's avatar
   
defacer committed
784
    if(!($fp = @fopen($CFG->dataroot.'/temp/'.$file, 'w'))) {
785
        print_error('put_records_csv failed to open '.$file);
defacer's avatar
   
defacer committed
786
787
    }

defacer's avatar
   
defacer committed
788
789
790
791
792
793
794
795
796
797
    $proto = reset($records);
    if(is_object($proto)) {
        $fields_records = array_keys(get_object_vars($proto));
    }
    else if(is_array($proto)) {
        $fields_records = array_keys($proto);
    }
    else {
        return false;
    }
798
    echo "x";
defacer's avatar
   
defacer committed
799
800
801
802
803
804
805
806
807
808
809
810
811

    if(!empty($metacolumns)) {
        $fields_table = array_map(create_function('$a', 'return $a->name;'), $metacolumns);
        $fields = array_intersect($fields_records, $fields_table);
    }
    else {
        $fields = $fields_records;
    }

    fwrite($fp, implode(',', $fields));
    fwrite($fp, "\r\n");

    foreach($records as $record) {
defacer's avatar
   
defacer committed
812
        $array  = (array)$record;
defacer's avatar
   
defacer committed
813
814
        $values = array();
        foreach($fields as $field) {
defacer's avatar
   
defacer committed
815
816
            if(strpos($array[$field], ',')) {
                $values[] = '"'.str_replace('"', '\"', $array[$field]).'"';
defacer's avatar
   
defacer committed
817
818
            }
            else {
defacer's avatar
   
defacer committed
819
                $values[] = $array[$field];
defacer's avatar
   
defacer committed
820
821
822
823
824
825
826
827
828
            }
        }
        fwrite($fp, implode(',', $values)."\r\n");
    }

    fclose($fp);
    return true;
}

moodler's avatar
moodler committed
829

830
/**
831
 * Recursively delete the file or folder with path $location. That is,
832
 * if it is a file delete it. If it is a folder, delete all its content
833
834
835
 * then delete it. If $location does not exist to start, that is not
 * considered an error.
 *
836
837
 * @param $location the path to remove.
 */
838
function fulldelete($location) {
moodler's avatar
moodler committed
839
840
841
842
843
    if (is_dir($location)) {
        $currdir = opendir($location);
        while (false !== ($file = readdir($currdir))) {
            if ($file <> ".." && $file <> ".") {
                $fullfile = $location."/".$file;
844
                if (is_dir($fullfile)) {
moodler's avatar
moodler committed
845
846
847
848
849
850
851
                    if (!fulldelete($fullfile)) {
                        return false;
                    }
                } else {
                    if (!unlink($fullfile)) {
                        return false;
                    }
852
                }
moodler's avatar
moodler committed
853
            }
854
        }
moodler's avatar
moodler committed
855
856
857
858
859
        closedir($currdir);
        if (! rmdir($location)) {
            return false;
        }

860
    } else if (file_exists($location)) {
moodler's avatar
moodler committed
861
862
863
864
865
866
867
        if (!unlink($location)) {
            return false;
        }
    }
    return true;
}

868
869
870
871
872
/**
 * Improves memory consumptions and works around buggy readfile() in PHP 5.0.4 (2MB readfile limit).
 */
function readfile_chunked($filename, $retbytes=true) {
    $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
873
    $buffer = '';
874
    $cnt =0;
875
876
877
878
    $handle = fopen($filename, 'rb');
    if ($handle === false) {
        return false;
    }
879

880
    while (!feof($handle)) {
skodak's avatar
skodak committed
881
        @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
882
883
        $buffer = fread($handle, $chunksize);
        echo $buffer;
884
        flush();
885
        if ($retbytes) {
886
887
            $cnt += strlen($buffer);
        }
888
889
890
891
892
893
894
895
    }
    $status = fclose($handle);
    if ($retbytes && $status) {
        return $cnt; // return num. bytes delivered like readfile() does.
    }
    return $status;
}

896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
/**
 * Send requested byterange of file.
 */
function byteserving_send_file($filename, $mimetype, $ranges) {
    $chunksize = 1*(1024*1024); // 1MB chunks - must be less than 2MB!
    $handle = fopen($filename, 'rb');
    if ($handle === false) {
        die;
    }
    if (count($ranges) == 1) { //only one range requested
        $length = $ranges[0][2] - $ranges[0][1] + 1;
        @header('HTTP/1.1 206 Partial content');
        @header('Content-Length: '.$length);
        @header('Content-Range: bytes '.$ranges[0][1].'-'.$ranges[0][2].'/'.filesize($filename));
        @header('Content-Type: '.$mimetype);
        while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
        $buffer = '';
        fseek($handle, $ranges[0][1]);
        while (!feof($handle) && $length > 0) {
skodak's avatar
skodak committed
915
            @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
916
917
918
919
920
921
922
923
924
925
            $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
            echo $buffer;
            flush();
            $length -= strlen($buffer);
        }
        fclose($handle);
        die;
    } else { // multiple ranges requested - not tested much
        $totallength = 0;
        foreach($ranges as $range) {
926
            $totallength += strlen($range[0]) + $range[2] - $range[1] + 1;
927
        }
928
        $totallength += strlen("\r\n--".BYTESERVING_BOUNDARY."--\r\n");
929
930
931
932
933
934
935
936
937
938
939
        @header('HTTP/1.1 206 Partial content');
        @header('Content-Length: '.$totallength);
        @header('Content-Type: multipart/byteranges; boundary='.BYTESERVING_BOUNDARY);
        //TODO: check if "multipart/x-byteranges" is more compatible with current readers/browsers/servers
        while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
        foreach($ranges as $range) {
            $length = $range[2] - $range[1] + 1;
            echo $range[0];
            $buffer = '';
            fseek($handle, $range[1]);
            while (!feof($handle) && $length > 0) {
skodak's avatar
skodak committed
940
                @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
941
942
943
944
945
946
947
948
949
950
951
                $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
                echo $buffer;
                flush();
                $length -= strlen($buffer);
            }
        }
        echo "\r\n--".BYTESERVING_BOUNDARY."--\r\n";
        fclose($handle);
        die;
    }
}
moodler's avatar
moodler committed
952

953
954
955
956
957
958
959
960
961
/**
 * add includes (js and css) into uploaded files
 * before returning them, useful for themes and utf.js includes
 * @param string text - text to search and replace
 * @return string - text with added head includes
 */
function file_modify_html_header($text) {
    // first look for <head> tag
    global $CFG;
962

963
964
965
    $stylesheetshtml = '';
    foreach ($CFG->stylesheets as $stylesheet) {
        $stylesheetshtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
966
967
    }

968
969
    $filters = explode(",", $CFG->textfilters);
    if (in_array('filter/mediaplugin', $filters)) {
970
971
        // this script is needed by most media filter plugins.
        $ufo = "\n".'<script type="text/javascript" src="'.$CFG->wwwroot.'/lib/ufo.js"></script>'."\n";
972
    } else {
973
        $ufo = '';
974
    }
975

976
977
978
979
    preg_match('/\<head\>|\<HEAD\>/', $text, $matches);
    if ($matches) {
        $replacement = '<head>'.$ufo.$stylesheetshtml;
        $text = preg_replace('/\<head\>|\<HEAD\>/', $replacement, $text, 1);
980
        return $text;
981
    }
982

983
984
985
986
    // if not, look for <html> tag, and stick <head> right after
    preg_match('/\<html\>|\<HTML\>/', $text, $matches);
    if ($matches) {
        // replace <html> tag with <html><head>includes</head>
Martin Langhoff's avatar
Martin Langhoff committed
987
        $replacement = '<html>'."\n".'<head>'.$ufo.$stylesheetshtml.'</head>';
988
        $text = preg_replace('/\<html\>|\<HTML\>/', $replacement, $text, 1);
989
        return $text;
990
    }
991

992
993
994
    // if not, look for <body> tag, and stick <head> before body
    preg_match('/\<body\>|\<BODY\>/', $text, $matches);
    if ($matches) {
Martin Langhoff's avatar
Martin Langhoff committed
995
        $replacement = '<head>'.$ufo.$stylesheetshtml.'</head>'."\n".'<body>';
996
        $text = preg_replace('/\<body\>|\<BODY\>/', $replacement, $text, 1);
997
998
999
        return $text;
    }

1000
    // if not, just stick a <head> tag at the beginning
For faster browsing, not all history is shown. View entire blame