file.php 31.6 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
/**
 * 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.
46
 * @param string $mimetype Mime type to be sent in header
47
 * @param array  $options  Any options to use when serving the file. Currently
48 49 50
 *                         lifetime = 0 for no cache
 *                         forcedownload - force application rather than inline
 *                         overridecontenttype - send this instead of the mimetype
51 52
 *                         there are none.
 */
53
function serve_file($path, $filename, $mimetype, $options=array()) {
54
    $dataroot = realpath(get_config('dataroot'));
55 56 57 58 59
    $path = realpath($path);
    $options = array_merge(array(
        'lifetime' => 86400
    ), $options);

60
    if (!get_config('insecuredataroot') && substr($path, 0, strlen($dataroot)) != $dataroot) {
61 62
        throw new AccessDeniedException();
    }
63

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

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

70 71
    $lastmodified = filemtime($path);
    $filesize     = filesize($path);
72

73
    if ($mimetype == 'text/html' || $mimetype == 'text/xml' || $mimetype == 'application/xhtml+xml' || $mimetype == 'image/svg+xml') {
74 75
        if (isset($options['downloadurl']) && $filesize < 1024 * 1024) {
            display_cleaned_html(file_get_contents($path), $filename, $options);
76
            exit;
Richard Mansfield's avatar
Richard Mansfield committed
77
        }
78 79
        $options['forcedownload'] = true;
        $mimetype = 'application/octet-stream';
Richard Mansfield's avatar
Richard Mansfield committed
80 81
    }

82
    if (!$mimetype) {
Richard Mansfield's avatar
Richard Mansfield committed
83 84 85
        $mimetype = 'application/forcedownload';
    }

86 87 88 89
    if (ini_get('zlib.output_compression')) {
        ini_set('zlib.output_compression', 'Off');
    }

90 91
    // Try to disable automatic sid rewrite in cookieless mode
    @ini_set('session.use_trans_sid', 'false');
92 93 94

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

95 96
    // @todo possibly need addslashes on the filename, but I'm unsure on exactly
    // how the browsers will handle it.
97
    if ($mimetype == 'application/forcedownload' || isset($options['forcedownload'])) {
98 99 100 101
        header('Content-Disposition: attachment; filename="' . $filename . '"');
    }
    else {
        header('Content-Disposition: inline; filename="' . $filename . '"');
102 103
    }

104 105 106 107
    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: ');
108

Richard Mansfield's avatar
Richard Mansfield committed
109
        if ($mimetype != 'text/plain' && $mimetype != 'text/html' && !isset($fileoutput)) {
110 111 112
            @header('Accept-Ranges: bytes');

            if (!empty($_SERVER['HTTP_RANGE']) && strpos($_SERVER['HTTP_RANGE'],'bytes=') !== FALSE) {
113
                // Byteserving stuff - for Acrobat Reader and download accelerators
114 115 116 117
                // 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)) {
118
                    foreach ($ranges as $key => $value) {
119
                        if ($ranges[$key][1] == '') {
120
                            // Suffix case
121 122
                            $ranges[$key][1] = $filesize - $ranges[$key][2];
                            $ranges[$key][2] = $filesize - 1;
123 124 125
                        }
                        else if ($ranges[$key][2] == '' || $ranges[$key][2] > $filesize - 1) {
                            // Fix range length
126 127 128
                            $ranges[$key][2] = $filesize - 1;
                        }
                        if ($ranges[$key][2] != '' && $ranges[$key][2] < $ranges[$key][1]) {
129
                            // Invalid byte-range ==> ignore header
130 131 132
                            $ranges = false;
                            break;
                        }
133 134 135

                        // Prepare multipart header
                        $ranges[$key][0] =  "\r\n--" . BYTESERVING_BOUNDARY . "\r\nContent-Type: $mimetype\r\n";
136 137 138 139 140 141 142 143 144 145
                        $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);
                }
            }
        }
146 147 148
        else {
            // Do not byteserve (disabled, strings, text and html files).
            header('Accept-Ranges: none');
149
        }
150 151
    }
    else { // Do not cache files in proxies and browsers
152
        if (is_https() === true) { //https sites - watch out for IE! KB812935 and KB316431
153 154 155 156 157 158 159 160 161 162
            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
163 164
    }

165 166 167
    if ($mimetype == 'text/plain') {
        // Add encoding
        header('Content-Type: Text/plain; charset=utf-8');
168
    }
169
    else {
170 171 172 173 174 175
        if (isset($options['overridecontenttype'])) {
            header('Content-Type: ' . $options['overridecontenttype']);
        }
        else {
            header('Content-Type: ' . $mimetype);
        }
176
    }
177 178
    header('Content-Length: ' . $filesize);
    while (@ob_end_flush()); //flush the buffers - save memory and disable sid rewrite
179
    readfile_chunked($path);
180
    perf_to_log();
181
    exit;
182 183 184 185 186 187
}

/**
 * Improves memory consumptions and works around buggy readfile() in PHP 5.0.4 (2MB readfile limit).
 */
function readfile_chunked($filename, $retbytes=true) {
188
    $chunksize = 1 * (1024 * 1024); // 1MB chunks - must be less than 2MB!
189
    $buffer = '';
190
    $cnt =0;
191 192 193 194 195
    $handle = fopen($filename, 'rb');
    if ($handle === false) {
        return false;
    }

196

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

Richard Mansfield's avatar
Richard Mansfield committed
271

272
/**
273 274
 * Given a file path, retrieves the mime type of the file using the
 * unix 'file' program.
275 276 277 278
 *
 * This is only implemented for non-windows based operating systems. Mahara
 * does not support windows at this time.
 *
279 280 281
 * Sometimes file will be unable to detect the mimetype, in which case
 * it will return the empty string.
 *
282 283 284 285 286 287 288 289
 *
 * This function should no longer be required.  Mime types are now
 * stored along with files in the artefact tables, and passed directly
 * to serve_file.  Left in place for the upgrade to initially populate
 * the mime type of existing files.
 * See htdocs/artefact/file/db/upgrade.php.
 *
 *
290
 * @param string $file The file to check
291
 * @return string      The mime type of the file, or false if file is not available.
292
 */
Richard Mansfield's avatar
Richard Mansfield committed
293 294
function get_mime_type($file) {
    switch (strtolower(PHP_OS)) {
295 296 297 298 299
    case 'win' :
        throw new SystemException('retrieving filetype not supported in windows');
    default : 
        $filepath = get_config('pathtofile');
        if (!empty($filepath)) {
300
            list($output,) = preg_split('/[\s;]/', exec($filepath . ' -ib ' . escapeshellarg($file)));
301
            return $output;
302
        }
303 304
        return false;
    }
Richard Mansfield's avatar
Richard Mansfield committed
305 306
}

307

308 309 310 311 312 313
/**
 * Given a file path, guesses the mime type of the file using the
 * php functions finfo_file, mime_content_type, or looking for the
 * file extension in the artefact_file_mime_types table
 *
 * @param string $file The file to check
314
 * @param string $originalfilename The original name of the file (so we can check its extension)
315 316
 * @return string      The mime type of the file
 */
317
function file_mime_type($file, $originalfilename=false) {
318 319 320
    static $mimetypes = null;

    if (class_exists('finfo')) {
321 322 323 324 325 326 327 328 329
        // upstream bug in php #54714
        // http://bugs.php.net/bug.php?id=54714
        //
        // according to manual (http://www.php.net/manual/en/function.finfo-open.php)
        // default option is /usr/share/misc/magic, then /usr/share/misc/magic.mgc
        //
        // if /usr/share/misc/magic is a directory then finfo still succeeds and 
        // doesn't fall back onto the .mcg magic_file
        // force /usr/share/misc/magic.mgc instead in this case
330 331 332 333 334
        $MAGICPATH = '/usr/share/misc/magic';
        $magicfile = null;
        if (is_dir($MAGICPATH) or is_link($MAGICPATH)) {
            $magicfile = '/usr/share/misc/magic.mgc';
        }
335

336
        if (defined('FILEINFO_MIME_TYPE')) {
337
            if ($finfo = @new finfo(FILEINFO_MIME_TYPE, $magicfile)) {
338
                $type = @$finfo->file($file);
339 340
            }
        }
341
        else if ($finfo = @new finfo(FILEINFO_MIME, $magicfile)) {
342 343 344
            if ($typecharset = @$finfo->file($file)) {
                if ($bits = explode(';', $typecharset)) {
                    $type = $bits[0];
345 346 347 348 349
                }
            }
        }
    }
    else if (function_exists('mime_content_type')) {
350 351 352 353 354
        $type = mime_content_type($file);
    }

    if (!empty($type) && $type != 'application/octet-stream') {
        return $type;
355 356 357 358 359 360
    }

    // Try the filename extension in case it's a file that Mahara
    // cares about.  For now, use the artefact_file_mime_types table,
    // even though it's in a plugin and the description column doesn't
    // really contain filename extensions.
361 362 363 364 365 366
    if ($originalfilename) {
        $basename = $originalfilename;
    }
    else {
        $basename = basename($file);
    }
367 368 369 370 371 372 373 374 375 376 377 378 379 380
    if (strpos($basename, '.', 1)) {
        if (is_null($mimetypes)) {
            $mimetypes = get_records_assoc('artefact_file_mime_types', '', '', '', 'description,mimetype');
        }
        $ext = strtolower(array_pop(explode('.', $basename)));
        if (isset($mimetypes[$ext])) {
            return $mimetypes[$ext]->mimetype;
        }
    }

    return 'application/octet-stream';
}


381 382 383 384
/**
 * Given a mimetype (perhaps returned by {@link get_mime_type}, returns whether
 * Mahara thinks it is a valid image file.
 *
385 386
 * Not all image types are valid for Mahara. Mahara supports JPEG, PNG, GIF
 * and BMP.
387 388 389 390
 *
 * @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
391
function is_image_mime_type($type) {
392 393 394 395 396 397 398 399 400 401 402
    $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
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

/**
 * Given an image type returned by getimagesize or exif_imagetype, returns whether
 * Mahara thinks it is a valid image type.
 *
 * Not all image types are valid for Mahara. Mahara supports JPEG, PNG, GIF
 * and BMP.
 *
 * @param string $type The type to check
 * @return boolean     Whether the type is a valid image type for Mahara
 */
function is_image_type($type) {
    $supported = array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG);
    if (extension_loaded('imagick')) {
        $supported[] = IMAGETYPE_BMP;
    }
    return $type && in_array($type, $supported);
}


/**
 * Given path to a file, returns whether Mahara thinks it is a valid image file.
 *
 * Not all image types are valid for Mahara. Mahara supports JPEG, PNG, GIF
 * and BMP.
 *
 * @param string $path The file to check
 * @return boolean     Whether the file is a valid image file for Mahara
 */
function is_image_file($path) {
435 436
    if (function_exists('exif_imagetype')) {
        // exif_imagetype is faster
437 438 439
        // surpressing errors because exif_imagetype spews "read error!" to the logs on small files
        // http://nz.php.net/manual/en/function.exif-imagetype.php#79283
        if (!$type = @exif_imagetype($path)) {
440 441 442 443 444 445 446 447
            return false;
        }
    }
    else {
        // getimagesize returns the same answer
        if (!list ($width, $height, $type) = getimagesize($path)) {
            return false;
        }
448 449 450 451 452
    }
    return is_image_type($type);
}


453 454 455 456 457 458
/**
 * 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.
459 460
 *
 * @param string $path The base path in dataroot where the image is stored. For 
461
 *                     example, 'artefact/file/profileicons/' for profile 
462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482
 *                     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
483
 */
484
function get_dataroot_image_path($path, $id, $size=null) {
485
    global $THEME;
486 487
    $dataroot = get_config('dataroot');
    $imagepath = $dataroot . $path;
488 489 490
    if (substr($imagepath, -1) == '/') {
        $imagepath = substr($imagepath , 0, -1);
    }
491 492 493 494 495

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

496 497
    // Work out the location of the original image
    $originalimage = $imagepath . '/originals/' . ($id % 256) . "/$id";
498

499 500 501 502
    // 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)) {
503
        return false;
504
    }
505 506 507 508 509

    if (!$size) {
        // No size has been asked for. Return the original
        return $originalimage;
    }
510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525
    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
526

527 528
        // Image is not available in this size. If there is a base image for
        // it, we can make one however.
529
        if (is_readable($originalimage) && filesize($originalimage)) {
530

531 532
            $imageinfo = getimagesize($originalimage);
            $originalmimetype = $imageinfo['mime'];
533 534 535

            // gd can eat a lot of memory shrinking large images, so use a placeholder image
            // here if necessary
536 537 538 539 540 541 542 543
            if (isset($imageinfo['bits'])) {
                $bits = $imageinfo['bits'];
            }
            else if ($imageinfo['mime'] == 'image/gif') {
                $bits = 8;
            }
            if (isset($imageinfo[0]) && isset($imageinfo[1]) && !empty($bits)) {
                $approxmem = $imageinfo[0] * $imageinfo[1] * ($bits / 8)
544 545 546 547 548 549 550 551 552 553 554 555 556
                    * (isset($imageinfo['channels']) ? $imageinfo['channels'] : 3);
            }
            if (empty($approxmem) || $approxmem > get_config('maximageresizememory')) {
                log_debug("Refusing to resize large image $originalimage $originalmimetype "
                    . $imageinfo[0] . 'x' .  $imageinfo[1] . ' ' . $imageinfo['bits'] . '-bit');
                $originalimage = $THEME->get_path('images/no_thumbnail.png');
                if (empty($originalimage) || !is_readable($originalimage)) {
                    return false;
                }
                $imageinfo = getimagesize($originalimage);
                $originalmimetype = $imageinfo['mime'];
            }

557
            $format = 'png';
558
            switch ($originalmimetype) {
Nigel McNie's avatar
Nigel McNie committed
559
                case 'image/jpeg':
560
                case 'image/jpg':
561
                    $format = 'jpeg';
Nigel McNie's avatar
Nigel McNie committed
562
                    $oldih = imagecreatefromjpeg($originalimage);
Nigel McNie's avatar
Nigel McNie committed
563
                    break;
Nigel McNie's avatar
Nigel McNie committed
564 565
                case 'image/png':
                    $oldih = imagecreatefrompng($originalimage);
Nigel McNie's avatar
Nigel McNie committed
566
                    break;
Nigel McNie's avatar
Nigel McNie committed
567
                case 'image/gif':
568
                    $format = 'gif';
Nigel McNie's avatar
Nigel McNie committed
569
                    $oldih = imagecreatefromgif($originalimage);
Nigel McNie's avatar
Nigel McNie committed
570
                    break;
571 572 573 574
                case 'image/bmp':
                case 'image/x-bmp':
                case 'image/ms-bmp':
                case 'image/x-ms-bmp':
575
                    if (!extension_loaded('imagick') || !class_exists('Imagick')) {
576
                        log_info('Bitmap image detected for resizing, but imagick extension is not available');
577 578
                        return false;
                    }
579

580 581
                    $ih = new Imagick($originalimage);
                    if (!$newdimensions = image_get_new_dimensions($ih->getImageWidth(), $ih->getImageHeight(), $size)) {
582 583
                        return false;
                    }
584 585
                    $ih->resizeImage($newdimensions['w'], $newdimensions['h'], imagick::FILTER_LANCZOS, 1);
                    if ($ih->writeImage($resizedimagefile)) {
586 587 588
                        return $resizedimagefile;
                    }
                    return false;
Nigel McNie's avatar
Nigel McNie committed
589 590
                default:
                    return false;
Nigel McNie's avatar
Nigel McNie committed
591 592
            }

Nigel McNie's avatar
Nigel McNie committed
593 594 595
            if (!$oldih) {
                return false;
            }
596

Nigel McNie's avatar
Nigel McNie committed
597 598
            $oldx = imagesx($oldih);
            $oldy = imagesy($oldih);
599

600 601
            if (!$newdimensions = image_get_new_dimensions($oldx, $oldy, $size)) {
                return false;
Nigel McNie's avatar
Nigel McNie committed
602
            }
603

604
            $newih = imagecreatetruecolor($newdimensions['w'], $newdimensions['h']);
605 606 607 608 609 610 611 612 613 614

            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);
615
                imagecopyresampled($newih, $oldih, 0, 0, 0, 0, $newdimensions['w'], $newdimensions['h'], $oldx, $oldy);
616 617 618 619 620 621
                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
622 623
                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);
624 625
            }

626 627
            $outputfunction = "image$format";
            $result = $outputfunction($newih, $resizedimagefile);
628 629 630 631
            if ($result) {
                return $resizedimagefile;
            }
        } // end attempting to build a resized image
632 633 634 635 636
    }

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

638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674
/**
 * 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;
    }
675 676
    else if (isset($size['maxw']) && isset($size['maxh'])) {
        $scale = min(min($size['maxw'], $oldx) / $oldx, min($size['maxh'], $oldy) / $oldy);
677 678
        $newx = max(1, $oldx * $scale);
        $newy = max(1, $oldy * $scale);
679
    }
680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701
    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;
        }
    }
702 703 704 705 706 707
    else {
        return false;
    }
    return array('w' => $newx, 'h' => $newy);
}

708
/**
709
 * Deletes an image, excluding all resized versions of it, from dataroot.
710 711 712 713
 *
 * This function does not delete anything from anywhere else - it is your
 * responsibility to delete any database records.
 *
714 715 716
 * This function also does not try to delete all resized versions of this
 * image, as it would take a lot of effort to find them all.
 *
717 718 719 720 721 722 723 724
 * @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');
725
    $imagepath = $dataroot . $path . '/originals';
726 727 728 729 730 731 732 733 734 735 736

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

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

    unlink($originalimage);
737 738
    return true;
}
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
/**
 * 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 == '..') {
766 767
            continue;
        }
768 769
 
        // Recurse
770
        rmdirr($dirname . '/' . $entry);
771
    }
772 773 774 775
 
    // Clean up
    $dir->close();
    return rmdir($dirname);
776 777
}

778 779 780 781 782 783
/**
 * Copy a file, or recursively copy a folder and its contents
 *
 * @author      Aidan Lister <aidan@php.net>
 * @version     1.0.1
 * @link        http://aidanlister.com/repos/v/function.copyr.php
784
 * @license     Public Domain
785 786 787 788 789 790
 * @param       string   $source    Source path
 * @param       string   $dest      Destination path
 * @return      bool     Returns TRUE on success, FALSE on failure
 */
function copyr($source, $dest)
{
791
    $dest = trim($dest);
792 793 794 795 796 797 798 799 800 801 802 803
    // Check for symlinks
    if (is_link($source)) {
        return symlink(readlink($source), $dest);
    }

    // Simple copy for a file
    if (is_file($source)) {
        return copy($source, $dest);
    }

    // Make destination directory
    if (!is_dir($dest)) {
Hugh Davenport's avatar
Hugh Davenport committed
804
        mkdir($dest, get_config('directorypermissions'));
805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822
    }

    // Loop through the folder
    $dir = dir($source);
    while (false !== $entry = $dir->read()) {
        // Skip pointers
        if ($entry == '.' || $entry == '..') {
            continue;
        }

        // Deep copy directories
        copyr("$source/$entry", "$dest/$entry");
    }

    // Clean up
    $dir->close();
    return true;
}
823 824 825 826 827 828 829 830 831 832 833 834 835

function file_cleanup_old_cached_files() {
    global $THEME;
    $dirs = array('', '/profileicons');
    foreach (get_all_theme_objects() as $basename => $theme) {
        $dirs[] = '/profileicons/no_userphoto/' . $basename;
    }
    foreach ($dirs as $dir) {
        $basedir = get_config('dataroot') . 'artefact/file' . $dir . '/resized/';
        if (!check_dir_exists($basedir, false)) {
            continue;
        }

836
        $mintime = time() - (12 * 7 * 24 * 60 * 60); // delete caches older than 12 weeks
837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874

        // Cached files are stored in a three tier md5sum layout
        // The actual files are stored in the third directory
        // This loops through all three directories, then checks the files for age
        // It cleans up any empty directories on the way down again

        $iter1 = new DirectoryIterator($basedir);
        foreach ($iter1 as $dir1) {
            if ($dir1->isDot()) continue;
            $dir1path = $dir1->getPath() . '/' . $dir1->getFilename();
            $iter2 = new DirectoryIterator($dir1path);
            foreach ($iter2 as $dir2) {
                if ($dir2->isDot()) continue;
                $dir2path = $dir2->getPath() . '/' . $dir2->getFilename();
                $iter3 = new DirectoryIterator($dir2path);
                foreach ($iter3 as $dir3) {
                    if ($dir3->isDot()) continue;
                    $dir3path = $dir3->getPath() . '/' . $dir3->getFilename();
                    $fileiter = new DirectoryIterator($dir3path);
                    foreach ($fileiter as $file) {
                        if ($file->isFile() && $file->getCTime() < $mintime) {
                            unlink($file->getPath() . '/' . $file->getFilename());
                        }
                    }
                    if (sizeof(scandir($dir3path)) <= 2) {   // first 2 entries are . and ..
                        rmdir($dir3path);
                    }
                }
                if (sizeof(scandir($dir2path)) <= 2) {   // first 2 entries are . and ..
                    rmdir($dir2path);
                }
            }
            if (sizeof(scandir($dir1path)) <= 2) {   // first 2 entries are . and ..
                rmdir($dir1path);
            }
        }
    }
}