file.php 21.9 KB
Newer Older
1 2
<?php
/**
Francois Marier's avatar
Francois Marier committed
3 4
 * Mahara: Electronic portfolio, weblog, resume builder and social networking
 * Copyright (C) 2006-2007 Catalyst IT Ltd (http://www.catalyst.net.nz)
5
 *
Francois Marier's avatar
Francois Marier committed
6 7 8 9
 * 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 3 of the License, or
 * (at your option) any later version.
10
 *
Francois Marier's avatar
Francois Marier committed
11 12 13 14
 * 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.
15
 *
Francois Marier's avatar
Francois Marier committed
16 17
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18 19 20
 *
 * @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
/**
 * 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
47 48 49
 *                         lifetime = 0 for no cache
 *                         forcedownload - force application rather than inline
 *                         overridecontenttype - send this instead of the mimetype
50 51 52 53 54 55 56 57 58 59 60 61
 *                         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();
    }
62

63 64 65
    if (!file_exists($path)) {
        throw new NotFoundException();
    }
66

67
    session_write_close(); // unlock session during fileserving
68

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

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

80 81
    // Try to disable automatic sid rewrite in cookieless mode
    @ini_set('session.use_trans_sid', 'false');
82 83 84

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

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

94 95 96 97
    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: ');
98

99
        if ($mimetype != 'text/plain' && $mimetype != 'text/html') {
100 101 102
            @header('Accept-Ranges: bytes');

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

                        // Prepare multipart header
                        $ranges[$key][0] =  "\r\n--" . BYTESERVING_BOUNDARY . "\r\nContent-Type: $mimetype\r\n";
126 127 128 129 130 131 132 133 134 135
                        $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);
                }
            }
        }
136 137 138
        else {
            // Do not byteserve (disabled, strings, text and html files).
            header('Accept-Ranges: none');
139
        }
140 141 142 143 144 145 146 147 148 149 150 151 152
    }
    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
153 154
    }

155 156 157
    if ($mimetype == 'text/plain') {
        // Add encoding
        header('Content-Type: Text/plain; charset=utf-8');
158
    }
159
    else {
160 161 162 163 164 165
        if (isset($options['overridecontenttype'])) {
            header('Content-Type: ' . $options['overridecontenttype']);
        }
        else {
            header('Content-Type: ' . $mimetype);
        }
166
    }
167 168 169 170
    header('Content-Length: ' . $filesize);
    while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
    readfile_chunked($path);
    exit;
171 172 173 174 175 176
}

/**
 * Improves memory consumptions and works around buggy readfile() in PHP 5.0.4 (2MB readfile limit).
 */
function readfile_chunked($filename, $retbytes=true) {
177
    $chunksize = 1 * (1024 * 1024); // 1MB chunks - must be less than 2MB!
178
    $buffer = '';
179
    $cnt =0;
180 181 182 183 184
    $handle = fopen($filename, 'rb');
    if ($handle === false) {
        return false;
    }

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

187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205
    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) {
206
    $chunksize = 1 * (1024 * 1024); // 1MB chunks - must be less than 2MB!
207 208 209 210 211 212
    $handle = fopen($filename, 'rb');
    if ($handle === false) {
        die;
    }
    if (count($ranges) == 1) { //only one range requested
        $length = $ranges[0][2] - $ranges[0][1] + 1;
213 214 215 216
        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);
217
        while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
218
        @set_time_limit(60*60); //reset time limit to 60 min - should be enough for 1 MB chunk
219 220 221 222 223 224 225 226 227
        $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);
228 229 230
        exit;
    }
    else { // multiple ranges requested - not tested much
231 232 233 234
        $totallength = 0;
        foreach($ranges as $range) {
            $totallength += strlen($range[0]) + $range[2] - $range[1] + 1;
        }
235 236 237 238
        $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);
239 240 241 242 243 244 245
        //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]);
246
            @set_time_limit(60 * 60); //reset time limit to 60 min - should be enough for 1 MB chunk
247 248 249 250 251 252 253
            while (!feof($handle) && $length > 0) {
                $buffer = fread($handle, ($chunksize < $length ? $chunksize : $length));
                echo $buffer;
                flush();
                $length -= strlen($buffer);
            }
        }
254
        echo "\r\n--" . BYTESERVING_BOUNDARY . "--\r\n";
255
        fclose($handle);
256
        exit;
257 258 259
    }
}

Richard Mansfield's avatar
Richard Mansfield committed
260

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

288

289 290 291 292
/**
 * Given a mimetype (perhaps returned by {@link get_mime_type}, returns whether
 * Mahara thinks it is a valid image file.
 *
293 294
 * Not all image types are valid for Mahara. Mahara supports JPEG, PNG, GIF
 * and BMP.
295 296 297 298
 *
 * @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
299
function is_image_mime_type($type) {
300 301 302 303 304 305 306 307 308 309 310
    $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
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.
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342
 *
 * @param string $path The base path in dataroot where the image is stored. For 
 *                     example, 'artefact/internal/profileicons/' for profile 
 *                     icons
 * @param int $id      The ID of the image to return. Is typically the ID of an 
 *                     artefact
 * @param mixed $size  The size the image should be.
 *
 *                      As a two element hash with 'w' and 'h' keys:
 *                     - If 'w' and 'h' are not empty, the image will be 
 *                       exactly that size
 *                     - If just 'w' is not empty, the image will be that wide, 
 *                       and the height will be set to make the image scale 
 *                       correctly
 *                     - If just 'h' is not empty, the image will be that high, 
 *                       and the width will be set to make the image scale 
 *                       correctly
 *                     - If neither are set or the parameter is not set, the 
 *                       image will not be resized
 *
 *                     As a number, the path returned will have the largest side being 
 *                     the length specified.
 * @return string The path on disk where the appropriate file resides, or false 
 *                if an appropriate file could not be located or generated
343
 */
344
function get_dataroot_image_path($path, $id, $size=null) {
345 346
    $dataroot = get_config('dataroot');
    $imagepath = $dataroot . $path;
347 348 349
    if (substr($imagepath, -1) == '/') {
        $imagepath = substr($imagepath , 0, -1);
    }
350 351 352 353 354

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

355 356
    // Work out the location of the original image
    $originalimage = $imagepath . '/originals/' . ($id % 256) . "/$id";
357

358 359 360 361
    // If the original has been deleted, then don't show any image, even a cached one. 
    // delete_image only deletes the original, not any cached ones, so we have 
    // to make sure the original is still around
    if (!is_readable($originalimage)) {
362
        return false;
363
    }
364 365 366 367 368

    if (!$size) {
        // No size has been asked for. Return the original
        return $originalimage;
    }
369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384
    else {
        // Check if the image is available in the size requested
        $sizestr = serialize($size);
        $md5     = md5("{$id}.{$sizestr}");

        $resizedimagedir = $imagepath . '/resized/';
        check_dir_exists($resizedimagedir);
        for ($i = 0; $i <= 2; $i++) {
           $resizedimagedir .= substr($md5, $i, 1) . '/';
            check_dir_exists($resizedimagedir);
        }
        $resizedimagefile = "{$resizedimagedir}{$md5}.$id";//.$sizestr";

        if (is_readable($resizedimagefile)) {
            return $resizedimagefile;
        }
Nigel McNie's avatar
Nigel McNie committed
385

386 387
        // Image is not available in this size. If there is a base image for
        // it, we can make one however.
Nigel McNie's avatar
Nigel McNie committed
388
        if (is_readable($originalimage)) {
389

390 391
            $originalmimetype = get_mime_type($originalimage);
            switch ($originalmimetype) {
Nigel McNie's avatar
Nigel McNie committed
392
                case 'image/jpeg':
393
                case 'image/jpg':
Nigel McNie's avatar
Nigel McNie committed
394
                    $oldih = imagecreatefromjpeg($originalimage);
Nigel McNie's avatar
Nigel McNie committed
395
                    break;
Nigel McNie's avatar
Nigel McNie committed
396 397
                case 'image/png':
                    $oldih = imagecreatefrompng($originalimage);
Nigel McNie's avatar
Nigel McNie committed
398
                    break;
Nigel McNie's avatar
Nigel McNie committed
399 400
                case 'image/gif':
                    $oldih = imagecreatefromgif($originalimage);
Nigel McNie's avatar
Nigel McNie committed
401
                    break;
402 403 404 405 406
                case 'image/bmp':
                case 'image/x-bmp':
                case 'image/ms-bmp':
                case 'image/x-ms-bmp':
                    if (!extension_loaded('imagick')) {
407
                        log_info('Bitmap image detected for resizing, but imagick extension is not available');
408 409
                        return false;
                    }
410 411 412 413 414 415 416 417 418 419

                    $ih = imagick_readimage($originalimage);
                    if (!$newdimensions = image_get_new_dimensions(imagick_getwidth($ih), imagick_getheight($ih), $size)) {
                        return false;
                    }
                    imagick_resize($ih, $newdimensions['w'], $newdimensions['h'], IMAGICK_FILTER_LANCZOS, 1);
                    if (imagick_writeimage($ih, $resizedimagefile)) {
                        return $resizedimagefile;
                    }
                    return false;
Nigel McNie's avatar
Nigel McNie committed
420 421
                default:
                    return false;
Nigel McNie's avatar
Nigel McNie committed
422 423
            }

Nigel McNie's avatar
Nigel McNie committed
424 425 426
            if (!$oldih) {
                return false;
            }
427

Nigel McNie's avatar
Nigel McNie committed
428 429
            $oldx = imagesx($oldih);
            $oldy = imagesy($oldih);
430

431 432
            if (!$newdimensions = image_get_new_dimensions($oldx, $oldy, $size)) {
                return false;
Nigel McNie's avatar
Nigel McNie committed
433
            }
434

435
            $newih = imagecreatetruecolor($newdimensions['w'], $newdimensions['h']);
436 437 438 439 440 441 442 443 444 445

            if ($originalmimetype == 'image/png' || $originalmimetype == 'image/gif') {
                // Create a new destination image which is completely 
                // transparent and turn off alpha blending for it, so that when 
                // the PNG source file is copied, the alpha channel is retained.
                // Thanks to http://alexle.net/archives/131

                $background = imagecolorallocate($newih, 0, 0, 0);
                imagecolortransparent($newih, $background);
                imagealphablending($newih, false);
446
                imagecopyresampled($newih, $oldih, 0, 0, 0, 0, $newdimensions['w'], $newdimensions['h'], $oldx, $oldy);
447 448 449 450 451 452
                imagesavealpha($newih, true);
            }
            else {
                // imagecopyresized is faster, but results in noticeably worse image quality. 
                // Given the images are resized only once each time they're 
                // made, I suggest you just leave the good quality one in place
453 454
                imagecopyresampled($newih, $oldih, 0, 0, 0, 0, $newdimensions['w'], $newdimensions['h'], $oldx, $oldy);
                //imagecopyresized($newih, $oldih, 0, 0, 0, 0, $newdimensions['w'], $newdimensions['h'], $oldx, $oldy);
455 456
            }

457 458 459 460 461
            $result = imagepng($newih, $resizedimagefile);
            if ($result) {
                return $resizedimagefile;
            }
        } // end attempting to build a resized image
462 463 464 465 466
    }

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

468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504
/**
 * Given the old dimensions of an image and a size object as obtained from 
 * get_imagesize_parameters(), calculates what the new size of the image should 
 * be
 *
 * @param int $oldx   The width of the image to calculate the new size for
 * @param int $oldy   The height of the image to calculate the new size for
 * @param mixed $size The size data
 * @return array      A hash with the new width and height, keyed by 'w' and 'h'
 */
function image_get_new_dimensions($oldx, $oldy, $size) {
    if (is_int($size)) {
        // If just a number (number is width AND height here)
        if ($oldy > $oldx) {
            $newy = $size;
            $newx = ($oldx * $newy) / $oldy;
        }
        else {
            $newx = $size;
            $newy = ($oldy * $newx) / $oldx;
        }
    }
    else if (isset($size['w']) && isset($size['h'])) {
        // If size explicitly X by Y
        $newx = $size['w'];
        $newy = $size['h'];
    }
    else if (isset($size['w'])) {
        // Else if just width
        $newx = $size['w'];
        $newy = ($oldy * $newx) / $oldx;
    }
    else if (isset($size['h'])) {
        // Else if just height
        $newy = $size['h'];
        $newx = ($oldx * $newy) / $oldy;
    }
505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526
    else if (isset($size['maxw'])) {
        // Else if just maximum width
        if ($oldx > $size['maxw']) {
            $newx = $size['maxw'];
            $newy = ($oldy * $newx) / $oldx;
        }
        else {
            $newx = $oldx;
            $newy = $oldy;
        }
    }
    else if (isset($size['maxh'])) {
        // Else if just maximum height
        if ($oldy > $size['maxh']) {
            $newy = $size['maxh'];
            $newx = ($oldx * $newy) / $oldy;
        }
        else {
            $newx = $oldx;
            $newy = $oldy;
        }
    }
527 528 529 530 531 532
    else {
        return false;
    }
    return array('w' => $newx, 'h' => $newy);
}

533 534 535 536 537 538 539 540 541 542 543 544 545 546
/**
 * 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');
547
    $imagepath = $dataroot . $path . '/originals';
548 549 550 551 552 553 554 555 556 557 558

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

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

    unlink($originalimage);
559 560
    return true;
}
561

562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587
/**
 * Delete a file, or a folder and its contents
 *
 * @author      Aidan Lister <aidan@php.net>
 * @version     1.0.3
 * @link        http://aidanlister.com/repos/v/function.rmdirr.php
 * @param       string   $dirname    Directory to delete
 * @return      bool     Returns TRUE on success, FALSE on failure
 */
function rmdirr($dirname)
{
    // Sanity check
    if (!file_exists($dirname)) {
        return false;
    }
 
    // Simple delete for a file
    if (is_file($dirname) || is_link($dirname)) {
        return unlink($dirname);
    }
 
    // Loop through the folder
    $dir = dir($dirname);
    while (false !== $entry = $dir->read()) {
        // Skip pointers
        if ($entry == '.' || $entry == '..') {
588 589
            continue;
        }
590 591 592
 
        // Recurse
        rmdirr($dirname . DIRECTORY_SEPARATOR . $entry);
593
    }
594 595 596 597
 
    // Clean up
    $dir->close();
    return rmdir($dirname);
598 599
}

600
?>