file.php 15.8 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
<?php
/**
 * This program is part of Mahara
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
 *
 * @package    mahara
 * @subpackage core
21
 * @author     Martin Dougiamas <martin@moodle.com>
22
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL
23 24
 * @copyright  (C) 2001-3001 Martin Dougiamas http://dougiamas.com
 * @copyright  additional modifications (c) Catalyst IT Ltd http://catalyst.net.nz
25 26 27 28 29
 *
 */

defined('INTERNAL') || die();

30
define('BYTESERVING_BOUNDARY', 'm1i2k3e40516'); //unique string constant
31

32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
/**
 * Serves a file from dataroot.
 *
 * This function checks that the file is inside dataroot, but does not perform
 * any other checks. Authors using this function should make sure that their
 * scripts perform appropriate authentication.
 *
 * As an example: If the file is an artefact, you could ask for an artefact and
 * view ID, and check that the artefact is in the view and that the user can
 * view the view.
 *
 * @param string $path     The file to send. Must include the dataroot path.
 * @param string $filename The name of the file as the browser should use to
 *                         serve it.
 * @param array  $options  Any options to use when serving the file. Currently
 *                         there are none.
 */
function serve_file($path, $filename, $options=array()) {
    $dataroot = get_config('dataroot');
    $path = realpath($path);
    $options = array_merge(array(
        'lifetime' => 86400
    ), $options);

    if (substr($path, 0, strlen($dataroot)) != $dataroot) {
        throw new AccessDeniedException();
    }
59

60 61 62
    if (!file_exists($path)) {
        throw new NotFoundException();
    }
63

64
    session_write_close(); // unlock session during fileserving
65

66
    $mimetype     = get_mime_type($path);
67
    if (!$mimetype || (!is_image_mime_type($mimetype) && false !== strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE'))) {
68 69 70 71
        $mimetype = 'application/forcedownload';
    }
    $lastmodified = filemtime($path);
    $filesize     = filesize($path);
72 73 74 75 76

    if (ini_get('zlib.output_compression')) {
        ini_set('zlib.output_compression', 'Off');
    }

77 78
    // Try to disable automatic sid rewrite in cookieless mode
    @ini_set('session.use_trans_sid', 'false');
79 80 81

    header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');

82 83 84 85 86 87 88
    // @todo possibly need addslashes on the filename, but I'm unsure on exactly
    // how the browsers will handle it.
    if ($mimetype == 'application/forcedownload') {
        header('Content-Disposition: attachment; filename="' . $filename . '"');
    }
    else {
        header('Content-Disposition: inline; filename="' . $filename . '"');
89 90
    }

91 92 93 94
    if ($options['lifetime'] > 0) {
        header('Cache-Control: max-age=' . $options['lifetime']);
        header('Expires: '. gmdate('D, d M Y H:i:s', time() + $options['lifetime']) .' GMT');
        header('Pragma: ');
95

96
        if ($mimetype != 'text/plain' && $mimetype != 'text/html') {
97 98 99
            @header('Accept-Ranges: bytes');

            if (!empty($_SERVER['HTTP_RANGE']) && strpos($_SERVER['HTTP_RANGE'],'bytes=') !== FALSE) {
100
                // Byteserving stuff - for Acrobat Reader and download accelerators
101 102 103 104
                // 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)) {
105
                    foreach ($ranges as $key => $value) {
106
                        if ($ranges[$key][1] == '') {
107
                            // Suffix case
108 109
                            $ranges[$key][1] = $filesize - $ranges[$key][2];
                            $ranges[$key][2] = $filesize - 1;
110 111 112
                        }
                        else if ($ranges[$key][2] == '' || $ranges[$key][2] > $filesize - 1) {
                            // Fix range length
113 114 115
                            $ranges[$key][2] = $filesize - 1;
                        }
                        if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
116
                            // Invalid byte-range ==> ignore header
117 118 119
                            $ranges = false;
                            break;
                        }
120 121 122

                        // Prepare multipart header
                        $ranges[$key][0] =  "\r\n--" . BYTESERVING_BOUNDARY . "\r\nContent-Type: $mimetype\r\n";
123 124 125 126 127 128 129 130 131 132
                        $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);
                }
            }
        }
133 134 135
        else {
            // Do not byteserve (disabled, strings, text and html files).
            header('Accept-Ranges: none');
136
        }
137 138 139 140 141 142 143 144 145 146 147 148 149
    }
    else { // Do not cache files in proxies and browsers
        if (strpos(get_config('wwwroot'), 'https://') === 0) { //https sites - watch out for IE! KB812935 and KB316431
            header('Cache-Control: max-age=10');
            header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
            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');
            header('Expires: '. gmdate('D, d M Y H:i:s', 0) .' GMT');
            header('Pragma: no-cache');
        }
        header('Accept-Ranges: none'); // Do not allow byteserving when caching disabled
150 151
    }

152 153 154
    if ($mimetype == 'text/plain') {
        // Add encoding
        header('Content-Type: Text/plain; charset=utf-8');
155
    }
156 157
    else {
        header('Content-Type: ' . $mimetype);
158
    }
159 160 161 162
    header('Content-Length: ' . $filesize);
    while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
    readfile_chunked($path);
    exit;
163 164 165 166 167 168
}

/**
 * Improves memory consumptions and works around buggy readfile() in PHP 5.0.4 (2MB readfile limit).
 */
function readfile_chunked($filename, $retbytes=true) {
169
    $chunksize = 1 * (1024 * 1024); // 1MB chunks - must be less than 2MB!
170
    $buffer = '';
171
    $cnt =0;
172 173 174 175 176
    $handle = fopen($filename, 'rb');
    if ($handle === false) {
        return false;
    }

177 178
    @set_time_limit(60 * 60); //reset time limit to 60 min - should be enough for 1 MB chunk

179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
    while (!feof($handle)) {
        $buffer = fread($handle, $chunksize);
        echo $buffer;
        flush();
        if ($retbytes) {
            $cnt += strlen($buffer);
        }
    }
    $status = fclose($handle);
    if ($retbytes && $status) {
        return $cnt; // return num. bytes delivered like readfile() does.
    }
    return $status;
}

/**
 * Send requested byterange of file.
 */
function byteserving_send_file($filename, $mimetype, $ranges) {
198
    $chunksize = 1 * (1024 * 1024); // 1MB chunks - must be less than 2MB!
199 200 201 202 203 204
    $handle = fopen($filename, 'rb');
    if ($handle === false) {
        die;
    }
    if (count($ranges) == 1) { //only one range requested
        $length = $ranges[0][2] - $ranges[0][1] + 1;
205 206 207 208
        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);
209
        while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
210
        @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
211 212 213 214 215 216 217 218 219
        $buffer = '';
        fseek($handle, $ranges[0][1]);
        while (!feof($handle) && $length > 0) {
            $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
            echo $buffer;
            flush();
            $length -= strlen($buffer);
        }
        fclose($handle);
220 221 222
        exit;
    }
    else { // multiple ranges requested - not tested much
223 224 225 226
        $totallength = 0;
        foreach($ranges as $range) {
            $totallength += strlen($range[0]) + $range[2] - $range[1] + 1;
        }
227 228 229 230
        $totallength += strlen("\r\n--" . BYTESERVING_BOUNDARY . "--\r\n");
        header('HTTP/1.1 206 Partial content');
        header('Content-Length: ' . $totallength);
        header('Content-Type: multipart/byteranges; boundary=' . BYTESERVING_BOUNDARY);
231 232 233 234 235 236 237
        //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]);
238
            @set_time_limit(60 * 60); //reset time limit to 60 min - should be enough for 1 MB chunk
239 240 241 242 243 244 245
            while (!feof($handle) && $length > 0) {
                $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
                echo $buffer;
                flush();
                $length -= strlen($buffer);
            }
        }
246
        echo "\r\n--" . BYTESERVING_BOUNDARY . "--\r\n";
247
        fclose($handle);
248
        exit;
249 250 251
    }
}

Richard Mansfield's avatar
Richard Mansfield committed
252

253
/**
254 255
 * Given a file path, retrieves the mime type of the file using the
 * unix 'file' program.
256 257 258 259
 *
 * This is only implemented for non-windows based operating systems. Mahara
 * does not support windows at this time.
 *
260 261 262
 * Sometimes file will be unable to detect the mimetype, in which case
 * it will return the empty string.
 *
263
 * @param string $file The file to check
264
 * @return string      The mime type of the file, or false if file is not available.
265
 */
Richard Mansfield's avatar
Richard Mansfield committed
266 267
function get_mime_type($file) {
    switch (strtolower(PHP_OS)) {
268 269 270 271 272 273 274
    case 'win' :
        throw new SystemException('retrieving filetype not supported in windows');
    default : 
        $filepath = get_config('pathtofile');
        if (!empty($filepath)) {
            list($output,) = split(';', exec($filepath . ' -ib ' . escapeshellarg($file)));
            return $output;
275
        }
276 277
        return false;
    }
Richard Mansfield's avatar
Richard Mansfield committed
278 279
}

280

281 282 283 284
/**
 * Given a mimetype (perhaps returned by {@link get_mime_type}, returns whether
 * Mahara thinks it is a valid image file.
 *
285 286
 * Not all image types are valid for Mahara. Mahara supports JPEG, PNG, GIF
 * and BMP.
287 288 289 290
 *
 * @param string $type The mimetype to check
 * @return boolean     Whether the type is a valid image type for Mahara
 */
Richard Mansfield's avatar
Richard Mansfield committed
291
function is_image_mime_type($type) {
292 293 294 295 296 297 298 299 300 301 302
    $supported = array(
        'image/jpeg', 'image/jpg',
        'image/gif',
        'image/png'
    );
    if (extension_loaded('imagick')) {
        $supported = array_merge($supported, array(
            'image/bmp', 'image/x-bmp', 'image/ms-bmp', 'image/x-ms-bmp'
        ));
    }
    return in_array($type, $supported);
Richard Mansfield's avatar
Richard Mansfield committed
303 304
}

305 306 307 308 309 310 311 312 313 314 315 316 317 318
/**
 * Given a path under dataroot, an ID and a size, return the path to a file
 * matching all criteria.
 *
 * If the file with the ID exists but not of the correct size, this function
 * will make a copy that is resized to the correct size.
 */
function get_dataroot_image_path($path, $id, $size) {
    $dataroot = get_config('dataroot');
    $imagepath = $dataroot . $path;

    if (!is_dir($imagepath) || !is_readable($imagepath)) {
        return false;
    }
319
    //$imagepath .= "/$id";
320 321 322 323 324 325

    if ($size && !preg_match('/\d+x\d+/', $size)) {
        throw new UserException('Invalid size for image specified');
    }

    // If the image is already available, return the path to it
326
    $path = $imagepath . '/' . ($size ? "$size/" : '') . ($id % 256) . "/$id";
327 328 329
    if (is_readable($path)) {
        return $path;
    }
Nigel McNie's avatar
Nigel McNie committed
330

331 332 333
    if ($size) {
        // Image is not available in this size. If there is a base image for
        // it, we can make one however.
334
        $originalimage = $imagepath . '/' . ($id % 256) . "/$id";
Nigel McNie's avatar
Nigel McNie committed
335
        if (is_readable($originalimage)) {
336 337 338 339

            list($width, $height) = explode('x', $size);

            switch (get_mime_type($originalimage)) {
Nigel McNie's avatar
Nigel McNie committed
340
                case 'image/jpeg':
341
                case 'image/jpg':
Nigel McNie's avatar
Nigel McNie committed
342
                    $oldih = imagecreatefromjpeg($originalimage);
Nigel McNie's avatar
Nigel McNie committed
343
                    break;
Nigel McNie's avatar
Nigel McNie committed
344 345
                case 'image/png':
                    $oldih = imagecreatefrompng($originalimage);
Nigel McNie's avatar
Nigel McNie committed
346
                    break;
Nigel McNie's avatar
Nigel McNie committed
347 348
                case 'image/gif':
                    $oldih = imagecreatefromgif($originalimage);
Nigel McNie's avatar
Nigel McNie committed
349
                    break;
350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365
                case 'image/bmp':
                case 'image/x-bmp':
                case 'image/ms-bmp':
                case 'image/x-ms-bmp':
                    if (!extension_loaded('imagick')) {
                        return false;
                    }
                    // Nightmare...
                    $oldih = imagick_readimage($originalimage);
                    imagick_resize($oldih, $width, $height, IMAGICK_FILTER_UNDEFINED, 1);
                    $newpath = $imagepath . "/$size/" . ($id % 256);
                    check_dir_exists($newpath);
                    $newpath .= "/$id";
                    $result = imagick_writeimage($oldih, $newpath);
                    return $newpath;
                    break;
Nigel McNie's avatar
Nigel McNie committed
366 367
                default:
                    return false;
Nigel McNie's avatar
Nigel McNie committed
368 369
            }

Nigel McNie's avatar
Nigel McNie committed
370 371 372
            if (!$oldih) {
                return false;
            }
373

Nigel McNie's avatar
Nigel McNie committed
374 375
            $oldx = imagesx($oldih);
            $oldy = imagesy($oldih);
376

Nigel McNie's avatar
Nigel McNie committed
377 378 379 380 381 382 383 384
            if ($oldy > $oldx) {
                $newy = $height;
                $newx = ($oldx * $newy) / $oldy;
            }
            else {
                $newx = $width;
                $newy = ($oldx * $newx) / $oldx;
            }
385

Nigel McNie's avatar
Nigel McNie committed
386 387 388
            $newih = imagecreatetruecolor($newx, $newy);
            imagecopyresized($newih, $oldih, 0, 0, 0, 0, $newx, $newy, $oldx, $oldy);
            imageinterlace($newih);
389 390 391 392 393
            $newpath = $imagepath . "/$size/" . ($id % 256);
            check_dir_exists($newpath);
            $newpath .= "/$id";
            $result = imagepng($newih, $newpath);
            return $newpath;
394 395 396 397 398 399
        }
    }

    // Image not available in any size
    return false;
}
400

401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444
/**
 * Deletes an image, including all resized versions of it, from dataroot.
 *
 * This function does not delete anything from anywhere else - it is your
 * responsibility to delete any database records.
 *
 * @param string $path The path in dataroot of the base directory where the
 *                     image resides.
 * @param int $id      The id of the image to delete.
 * @return boolean     Whether the image was deleted successfully.
 */
function delete_image($path, $id) {
    // Check that the image exists.
    $dataroot = get_config('dataroot');
    $imagepath = $dataroot . $path;

    if (!is_dir($imagepath) || !is_readable($imagepath)) {
        return false;
    }

    $originalimage = $imagepath . '/' . ($id % 256) . "/$id";
    if (!is_readable($originalimage)) {
        return false;
    }

    unlink($originalimage);

    // Check the size subdirectories
    $dh = opendir($imagepath);
    while (false !== ($file = readdir($dh))) {
        $path = $imagepath . '/' . $file;
        if (!preg_match('/\d+x\d+/', $file) || !is_dir($path)) {
            continue;
        }

        $image = $path . '/' . ($id % 256) . '/' . $id;
        if (is_readable($image)) {
            unlink($image);
        }
    }

    return true;
}

445
?>