Subversion-Projekte lars-tiefland.ci

Revision

Revision 2148 | Zur aktuellen Revision | Details | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
2147 lars 1
<?php
2
/*
3
 * jQuery File Upload Plugin PHP Class
4
 * https://github.com/blueimp/jQuery-File-Upload
5
 *
6
 * Copyright 2010, Sebastian Tschan
7
 * https://blueimp.net
8
 *
9
 * Licensed under the MIT license:
10
 * https://opensource.org/licenses/MIT
11
 */
12
 
13
class UploadHandler
14
{
15
 
16
    protected $options;
17
 
18
    // PHP File Upload error message codes:
19
    // http://php.net/manual/en/features.file-upload.errors.php
20
    protected $error_messages = array(
21
        1 => 'The uploaded file exceeds the upload_max_filesize directive in php.ini',
22
        2 => 'The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form',
23
        3 => 'The uploaded file was only partially uploaded',
24
        4 => 'No file was uploaded',
25
        6 => 'Missing a temporary folder',
26
        7 => 'Failed to write file to disk',
27
        8 => 'A PHP extension stopped the file upload',
28
        'post_max_size' => 'The uploaded file exceeds the post_max_size directive in php.ini',
29
        'max_file_size' => 'File is too big',
30
        'min_file_size' => 'File is too small',
31
        'accept_file_types' => 'Filetype not allowed',
32
        'max_number_of_files' => 'Maximum number of files exceeded',
33
        'max_width' => 'Image exceeds maximum width',
34
        'min_width' => 'Image requires a minimum width',
35
        'max_height' => 'Image exceeds maximum height',
36
        'min_height' => 'Image requires a minimum height',
37
        'abort' => 'File upload aborted',
38
        'image_resize' => 'Failed to resize image'
39
    );
40
 
41
    protected $image_objects = array();
42
 
43
    public function __construct($options = null, $initialize = true, $error_messages = null) {
44
        $this->response = array();
45
        $this->options = array(
46
            'script_url' => $this->get_full_url().'/'.$this->basename($this->get_server_var('SCRIPT_NAME')),
47
            'upload_dir' => dirname($this->get_server_var('SCRIPT_FILENAME')).'/files/',
48
            'upload_url' => $this->get_full_url().'/files/',
49
            'input_stream' => 'php://input',
50
            'user_dirs' => false,
51
            'mkdir_mode' => 0755,
52
            'param_name' => 'files',
53
            // Set the following option to 'POST', if your server does not support
54
            // DELETE requests. This is a parameter sent to the client:
55
            'delete_type' => 'DELETE',
56
            'access_control_allow_origin' => '*',
57
            'access_control_allow_credentials' => false,
58
            'access_control_allow_methods' => array(
59
                'OPTIONS',
60
                'HEAD',
61
                'GET',
62
                'POST',
63
                'PUT',
64
                'PATCH',
65
                'DELETE'
66
            ),
67
            'access_control_allow_headers' => array(
68
                'Content-Type',
69
                'Content-Range',
70
                'Content-Disposition'
71
            ),
72
            // By default, allow redirects to the referer protocol+host:
73
            'redirect_allow_target' => '/^'.preg_quote(
74
              parse_url($this->get_server_var('HTTP_REFERER'), PHP_URL_SCHEME)
75
                .'://'
76
                .parse_url($this->get_server_var('HTTP_REFERER'), PHP_URL_HOST)
77
                .'/', // Trailing slash to not match subdomains by mistake
78
              '/' // preg_quote delimiter param
79
            ).'/',
80
            // Enable to provide file downloads via GET requests to the PHP script:
81
            //     1. Set to 1 to download files via readfile method through PHP
82
            //     2. Set to 2 to send a X-Sendfile header for lighttpd/Apache
83
            //     3. Set to 3 to send a X-Accel-Redirect header for nginx
84
            // If set to 2 or 3, adjust the upload_url option to the base path of
85
            // the redirect parameter, e.g. '/files/'.
86
            'download_via_php' => false,
87
            // Read files in chunks to avoid memory limits when download_via_php
88
            // is enabled, set to 0 to disable chunked reading of files:
89
            'readfile_chunk_size' => 10 * 1024 * 1024, // 10 MiB
90
            // Defines which files can be displayed inline when downloaded:
91
            'inline_file_types' => '/\.(gif|jpe?g|png)$/i',
92
            // Defines which files (based on their names) are accepted for upload:
93
            'accept_file_types' => '/.+$/i',
94
            // The php.ini settings upload_max_filesize and post_max_size
95
            // take precedence over the following max_file_size setting:
96
            'max_file_size' => null,
97
            'min_file_size' => 1,
98
            // The maximum number of files for the upload directory:
99
            'max_number_of_files' => null,
100
            // Defines which files are handled as image files:
101
            'image_file_types' => '/\.(gif|jpe?g|png)$/i',
102
            // Use exif_imagetype on all files to correct file extensions:
103
            'correct_image_extensions' => false,
104
            // Image resolution restrictions:
105
            'max_width' => null,
106
            'max_height' => null,
107
            'min_width' => 1,
108
            'min_height' => 1,
109
            // Set the following option to false to enable resumable uploads:
110
            'discard_aborted_uploads' => true,
111
            // Set to 0 to use the GD library to scale and orient images,
112
            // set to 1 to use imagick (if installed, falls back to GD),
113
            // set to 2 to use the ImageMagick convert binary directly:
114
            'image_library' => 1,
115
            // Uncomment the following to define an array of resource limits
116
            // for imagick:
117
            /*
118
            'imagick_resource_limits' => array(
119
                imagick::RESOURCETYPE_MAP => 32,
120
                imagick::RESOURCETYPE_MEMORY => 32
121
            ),
122
            */
123
            // Command or path for to the ImageMagick convert binary:
124
            'convert_bin' => 'convert',
125
            // Uncomment the following to add parameters in front of each
126
            // ImageMagick convert call (the limit constraints seem only
127
            // to have an effect if put in front):
128
            /*
129
            'convert_params' => '-limit memory 32MiB -limit map 32MiB',
130
            */
131
            // Command or path for to the ImageMagick identify binary:
132
            'identify_bin' => 'identify',
133
            'image_versions' => array(
134
                // The empty image version key defines options for the original image:
135
                // Keep in mind that these options are inherited by all other image versions!
136
                '' => array(
137
                    // Automatically rotate images based on EXIF meta data:
138
                    'auto_orient' => true
139
                ),
140
                // Uncomment the following to create medium sized images:
141
                /*
142
                'medium' => array(
143
                    'max_width' => 800,
144
                    'max_height' => 600
145
                ),
146
                */
147
                'thumbnail' => array(
148
                    // Uncomment the following to use a defined directory for the thumbnails
149
                    // instead of a subdirectory based on the version identifier.
150
                    // Make sure that this directory doesn't allow execution of files if you
151
                    // don't pose any restrictions on the type of uploaded files, e.g. by
152
                    // copying the .htaccess file from the files directory for Apache:
153
                    //'upload_dir' => dirname($this->get_server_var('SCRIPT_FILENAME')).'/thumb/',
154
                    //'upload_url' => $this->get_full_url().'/thumb/',
155
                    // Uncomment the following to force the max
156
                    // dimensions and e.g. create square thumbnails:
157
                    //'crop' => true,
158
                    'max_width' => 80,
159
                    'max_height' => 80
160
                )
161
            ),
162
            'print_response' => true
163
        );
164
        if ($options) {
165
            $this->options = $options + $this->options;
166
        }
167
        if ($error_messages) {
168
            $this->error_messages = $error_messages + $this->error_messages;
169
        }
170
        if ($initialize) {
171
            $this->initialize();
172
        }
173
		trigger_error(var_export($this->options, true));
174
    }
175
 
176
    protected function initialize() {
177
        switch ($this->get_server_var('REQUEST_METHOD')) {
178
            case 'OPTIONS':
179
            case 'HEAD':
180
                $this->head();
181
                break;
182
            case 'GET':
183
                $this->get($this->options['print_response']);
184
                break;
185
            case 'PATCH':
186
            case 'PUT':
187
            case 'POST':
188
                $this->post($this->options['print_response']);
189
                break;
190
            case 'DELETE':
191
                $this->delete($this->options['print_response']);
192
                break;
193
            default:
194
                $this->header('HTTP/1.1 405 Method Not Allowed');
195
        }
196
    }
197
 
198
    protected function get_full_url() {
199
        $https = !empty($_SERVER['HTTPS']) && strcasecmp($_SERVER['HTTPS'], 'on') === 0 ||
200
            !empty($_SERVER['HTTP_X_FORWARDED_PROTO']) &&
201
                strcasecmp($_SERVER['HTTP_X_FORWARDED_PROTO'], 'https') === 0;
202
        return
203
            ($https ? 'https://' : 'http://').
204
            (!empty($_SERVER['REMOTE_USER']) ? $_SERVER['REMOTE_USER'].'@' : '').
205
            (isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : ($_SERVER['SERVER_NAME'].
206
            ($https && $_SERVER['SERVER_PORT'] === 443 ||
207
            $_SERVER['SERVER_PORT'] === 80 ? '' : ':'.$_SERVER['SERVER_PORT']))).
208
            substr($_SERVER['SCRIPT_NAME'],0, strrpos($_SERVER['SCRIPT_NAME'], '/'));
209
    }
210
 
211
    protected function get_user_id() {
212
        @session_start();
213
        return session_id();
214
    }
215
 
216
    protected function get_user_path() {
217
        if ($this->options['user_dirs']) {
218
            return $this->get_user_id().'/';
219
        }
220
        return '';
221
    }
222
 
223
    protected function get_upload_path($file_name = null, $version = null) {
224
        $file_name = $file_name ? $file_name : '';
225
        if (empty($version)) {
226
            $version_path = '';
227
        } else {
228
            $version_dir = @$this->options['image_versions'][$version]['upload_dir'];
229
            if ($version_dir) {
230
                return $version_dir.$this->get_user_path().$file_name;
231
            }
232
            $version_path = $version.'/';
233
        }
234
        return $this->options['upload_dir'].$this->get_user_path()
235
            .$version_path.$file_name;
236
    }
237
 
238
    protected function get_query_separator($url) {
239
        return strpos($url, '?') === false ? '?' : '&';
240
    }
241
 
242
    protected function get_download_url($file_name, $version = null, $direct = false) {
243
        if (!$direct && $this->options['download_via_php']) {
244
            $url = $this->options['script_url']
245
                .$this->get_query_separator($this->options['script_url'])
246
                .$this->get_singular_param_name()
247
                .'='.rawurlencode($file_name);
248
            if ($version) {
249
                $url .= '&version='.rawurlencode($version);
250
            }
251
            return $url.'&download=1';
252
        }
253
        if (empty($version)) {
254
            $version_path = '';
255
        } else {
256
            $version_url = @$this->options['image_versions'][$version]['upload_url'];
257
            if ($version_url) {
258
                return $version_url.$this->get_user_path().rawurlencode($file_name);
259
            }
260
            $version_path = rawurlencode($version).'/';
261
        }
262
        return $this->options['upload_url'].$this->get_user_path()
263
            .$version_path.rawurlencode($file_name);
264
    }
265
 
266
    protected function set_additional_file_properties($file) {
267
        $file->deleteUrl = $this->options['script_url']
268
            .$this->get_query_separator($this->options['script_url'])
269
            .$this->get_singular_param_name()
270
            .'='.rawurlencode($file->name);
271
        $file->deleteType = $this->options['delete_type'];
272
        if ($file->deleteType !== 'DELETE') {
273
            $file->deleteUrl .= '&_method=DELETE';
274
        }
275
        if ($this->options['access_control_allow_credentials']) {
276
            $file->deleteWithCredentials = true;
277
        }
278
    }
279
 
280
    // Fix for overflowing signed 32 bit integers,
281
    // works for sizes up to 2^32-1 bytes (4 GiB - 1):
282
    protected function fix_integer_overflow($size) {
283
        if ($size < 0) {
284
            $size += 2.0 * (PHP_INT_MAX + 1);
285
        }
286
        return $size;
287
    }
288
 
289
    protected function get_file_size($file_path, $clear_stat_cache = false) {
290
        if ($clear_stat_cache) {
291
            if (version_compare(PHP_VERSION, '5.3.0') >= 0) {
292
                clearstatcache(true, $file_path);
293
            } else {
294
                clearstatcache();
295
            }
296
        }
297
        return $this->fix_integer_overflow(filesize($file_path));
298
    }
299
 
300
    protected function is_valid_file_object($file_name) {
301
        $file_path = $this->get_upload_path($file_name);
302
        if (is_file($file_path) && $file_name[0] !== '.') {
303
            return true;
304
        }
305
        return false;
306
    }
307
 
308
    protected function get_file_object($file_name) {
309
        if ($this->is_valid_file_object($file_name)) {
310
            $file = new \stdClass();
311
            $file->name = $file_name;
312
            $file->size = $this->get_file_size(
313
                $this->get_upload_path($file_name)
314
            );
315
            $file->url = $this->get_download_url($file->name);
316
            foreach ($this->options['image_versions'] as $version => $options) {
317
                if (!empty($version)) {
318
                    if (is_file($this->get_upload_path($file_name, $version))) {
319
                        $file->{$version.'Url'} = $this->get_download_url(
320
                            $file->name,
321
                            $version
322
                        );
323
                    }
324
                }
325
            }
326
            $this->set_additional_file_properties($file);
327
            return $file;
328
        }
329
        return null;
330
    }
331
 
332
    protected function get_file_objects($iteration_method = 'get_file_object') {
333
        $upload_dir = $this->get_upload_path();
334
        if (!is_dir($upload_dir)) {
335
            return array();
336
        }
337
        return array_values(array_filter(array_map(
338
            array($this, $iteration_method),
339
            scandir($upload_dir)
340
        )));
341
    }
342
 
343
    protected function count_file_objects() {
344
        return count($this->get_file_objects('is_valid_file_object'));
345
    }
346
 
347
    protected function get_error_message($error) {
348
        return isset($this->error_messages[$error]) ?
349
            $this->error_messages[$error] : $error;
350
    }
351
 
352
    public function get_config_bytes($val) {
353
        $val = trim($val);
354
        $last = strtolower($val[strlen($val)-1]);
355
        $val = (int)$val;
356
        switch ($last) {
357
            case 'g':
358
                $val *= 1024;
359
            case 'm':
360
                $val *= 1024;
361
            case 'k':
362
                $val *= 1024;
363
        }
364
        return $this->fix_integer_overflow($val);
365
    }
366
 
367
    protected function validate($uploaded_file, $file, $error, $index) {
368
        if ($error) {
369
            $file->error = $this->get_error_message($error);
370
            return false;
371
        }
372
        $content_length = $this->fix_integer_overflow(
373
            (int)$this->get_server_var('CONTENT_LENGTH')
374
        );
375
        $post_max_size = $this->get_config_bytes(ini_get('post_max_size'));
376
        if ($post_max_size && ($content_length > $post_max_size)) {
377
            $file->error = $this->get_error_message('post_max_size');
378
            return false;
379
        }
380
        if (!preg_match($this->options['accept_file_types'], $file->name)) {
381
            $file->error = $this->get_error_message('accept_file_types');
382
            return false;
383
        }
384
        if ($uploaded_file && is_uploaded_file($uploaded_file)) {
385
            $file_size = $this->get_file_size($uploaded_file);
386
        } else {
387
            $file_size = $content_length;
388
        }
389
        if ($this->options['max_file_size'] && (
390
                $file_size > $this->options['max_file_size'] ||
391
                $file->size > $this->options['max_file_size'])
392
            ) {
393
            $file->error = $this->get_error_message('max_file_size');
394
            return false;
395
        }
396
        if ($this->options['min_file_size'] &&
397
            $file_size < $this->options['min_file_size']) {
398
            $file->error = $this->get_error_message('min_file_size');
399
            return false;
400
        }
401
        if (is_int($this->options['max_number_of_files']) &&
402
                ($this->count_file_objects() >= $this->options['max_number_of_files']) &&
403
                // Ignore additional chunks of existing files:
404
                !is_file($this->get_upload_path($file->name))) {
405
            $file->error = $this->get_error_message('max_number_of_files');
406
            return false;
407
        }
408
        $max_width = @$this->options['max_width'];
409
        $max_height = @$this->options['max_height'];
410
        $min_width = @$this->options['min_width'];
411
        $min_height = @$this->options['min_height'];
412
        if (($max_width || $max_height || $min_width || $min_height)
413
           && preg_match($this->options['image_file_types'], $file->name)) {
414
            list($img_width, $img_height) = $this->get_image_size($uploaded_file);
415
 
416
            // If we are auto rotating the image by default, do the checks on
417
            // the correct orientation
418
            if (
419
                @$this->options['image_versions']['']['auto_orient'] &&
420
                function_exists('exif_read_data') &&
421
                ($exif = @exif_read_data($uploaded_file)) &&
422
                (((int) @$exif['Orientation']) >= 5)
423
            ) {
424
                $tmp = $img_width;
425
                $img_width = $img_height;
426
                $img_height = $tmp;
427
                unset($tmp);
428
            }
429
 
430
        }
431
        if (!empty($img_width)) {
432
            if ($max_width && $img_width > $max_width) {
433
                $file->error = $this->get_error_message('max_width');
434
                return false;
435
            }
436
            if ($max_height && $img_height > $max_height) {
437
                $file->error = $this->get_error_message('max_height');
438
                return false;
439
            }
440
            if ($min_width && $img_width < $min_width) {
441
                $file->error = $this->get_error_message('min_width');
442
                return false;
443
            }
444
            if ($min_height && $img_height < $min_height) {
445
                $file->error = $this->get_error_message('min_height');
446
                return false;
447
            }
448
        }
449
        return true;
450
    }
451
 
452
    protected function upcount_name_callback($matches) {
453
        $index = isset($matches[1]) ? ((int)$matches[1]) + 1 : 1;
454
        $ext = isset($matches[2]) ? $matches[2] : '';
455
        return ' ('.$index.')'.$ext;
456
    }
457
 
458
    protected function upcount_name($name) {
459
        return preg_replace_callback(
460
            '/(?:(?: \(([\d]+)\))?(\.[^.]+))?$/',
461
            array($this, 'upcount_name_callback'),
462
            $name,
463
            1
464
        );
465
    }
466
 
467
    protected function get_unique_filename($file_path, $name, $size, $type, $error,
468
            $index, $content_range) {
469
        while(is_dir($this->get_upload_path($name))) {
470
            $name = $this->upcount_name($name);
471
        }
472
        // Keep an existing filename if this is part of a chunked upload:
473
        $uploaded_bytes = $this->fix_integer_overflow((int)$content_range[1]);
474
        while (is_file($this->get_upload_path($name))) {
475
            if ($uploaded_bytes === $this->get_file_size(
476
                    $this->get_upload_path($name))) {
477
                break;
478
            }
479
            $name = $this->upcount_name($name);
480
        }
481
        return $name;
482
    }
483
 
484
    protected function fix_file_extension($file_path, $name, $size, $type, $error,
485
            $index, $content_range) {
486
        // Add missing file extension for known image types:
487
        if (strpos($name, '.') === false &&
488
                preg_match('/^image\/(gif|jpe?g|png)/', $type, $matches)) {
489
            $name .= '.'.$matches[1];
490
        }
491
        if ($this->options['correct_image_extensions'] &&
492
                function_exists('exif_imagetype')) {
493
            switch (@exif_imagetype($file_path)){
494
                case IMAGETYPE_JPEG:
495
                    $extensions = array('jpg', 'jpeg');
496
                    break;
497
                case IMAGETYPE_PNG:
498
                    $extensions = array('png');
499
                    break;
500
                case IMAGETYPE_GIF:
501
                    $extensions = array('gif');
502
                    break;
503
            }
504
            // Adjust incorrect image file extensions:
505
            if (!empty($extensions)) {
506
                $parts = explode('.', $name);
507
                $extIndex = count($parts) - 1;
508
                $ext = strtolower(@$parts[$extIndex]);
509
                if (!in_array($ext, $extensions)) {
510
                    $parts[$extIndex] = $extensions[0];
511
                    $name = implode('.', $parts);
512
                }
513
            }
514
        }
515
        return $name;
516
    }
517
 
518
    protected function trim_file_name($file_path, $name, $size, $type, $error,
519
            $index, $content_range) {
520
        // Remove path information and dots around the filename, to prevent uploading
521
        // into different directories or replacing hidden system files.
522
        // Also remove control characters and spaces (\x00..\x20) around the filename:
523
        $name = trim($this->basename(stripslashes($name)), ".\x00..\x20");
524
        // Use a timestamp for empty filenames:
525
        if (!$name) {
526
            $name = str_replace('.', '-', microtime(true));
527
        }
528
        return $name;
529
    }
530
 
531
    protected function get_file_name($file_path, $name, $size, $type, $error,
532
            $index, $content_range) {
533
        $name = $this->trim_file_name($file_path, $name, $size, $type, $error,
534
            $index, $content_range);
535
        return $this->get_unique_filename(
536
            $file_path,
537
            $this->fix_file_extension($file_path, $name, $size, $type, $error,
538
                $index, $content_range),
539
            $size,
540
            $type,
541
            $error,
542
            $index,
543
            $content_range
544
        );
545
    }
546
 
547
    protected function get_scaled_image_file_paths($file_name, $version) {
548
        $file_path = $this->get_upload_path($file_name);
549
        if (!empty($version)) {
550
            $version_dir = $this->get_upload_path(null, $version);
551
            if (!is_dir($version_dir)) {
552
                mkdir($version_dir, $this->options['mkdir_mode'], true);
553
            }
554
            $new_file_path = $version_dir.'/'.$file_name;
555
        } else {
556
            $new_file_path = $file_path;
557
        }
558
        return array($file_path, $new_file_path);
559
    }
560
 
561
    protected function gd_get_image_object($file_path, $func, $no_cache = false) {
562
        if (empty($this->image_objects[$file_path]) || $no_cache) {
563
            $this->gd_destroy_image_object($file_path);
564
            $this->image_objects[$file_path] = $func($file_path);
565
        }
566
        return $this->image_objects[$file_path];
567
    }
568
 
569
    protected function gd_set_image_object($file_path, $image) {
570
        $this->gd_destroy_image_object($file_path);
571
        $this->image_objects[$file_path] = $image;
572
    }
573
 
574
    protected function gd_destroy_image_object($file_path) {
575
        $image = (isset($this->image_objects[$file_path])) ? $this->image_objects[$file_path] : null ;
576
        return $image && imagedestroy($image);
577
    }
578
 
579
    protected function gd_imageflip($image, $mode) {
580
        if (function_exists('imageflip')) {
581
            return imageflip($image, $mode);
582
        }
583
        $new_width = $src_width = imagesx($image);
584
        $new_height = $src_height = imagesy($image);
585
        $new_img = imagecreatetruecolor($new_width, $new_height);
586
        $src_x = 0;
587
        $src_y = 0;
588
        switch ($mode) {
589
            case '1': // flip on the horizontal axis
590
                $src_y = $new_height - 1;
591
                $src_height = -$new_height;
592
                break;
593
            case '2': // flip on the vertical axis
594
                $src_x  = $new_width - 1;
595
                $src_width = -$new_width;
596
                break;
597
            case '3': // flip on both axes
598
                $src_y = $new_height - 1;
599
                $src_height = -$new_height;
600
                $src_x  = $new_width - 1;
601
                $src_width = -$new_width;
602
                break;
603
            default:
604
                return $image;
605
        }
606
        imagecopyresampled(
607
            $new_img,
608
            $image,
609
            0,
610
            0,
611
            $src_x,
612
            $src_y,
613
            $new_width,
614
            $new_height,
615
            $src_width,
616
            $src_height
617
        );
618
        return $new_img;
619
    }
620
 
621
    protected function gd_orient_image($file_path, $src_img) {
622
        if (!function_exists('exif_read_data')) {
623
            return false;
624
        }
625
        $exif = @exif_read_data($file_path);
626
        if ($exif === false) {
627
            return false;
628
        }
629
        $orientation = (int)@$exif['Orientation'];
630
        if ($orientation < 2 || $orientation > 8) {
631
            return false;
632
        }
633
        switch ($orientation) {
634
            case 2:
635
                $new_img = $this->gd_imageflip(
636
                    $src_img,
637
                    defined('IMG_FLIP_VERTICAL') ? IMG_FLIP_VERTICAL : 2
638
                );
639
                break;
640
            case 3:
641
                $new_img = imagerotate($src_img, 180, 0);
642
                break;
643
            case 4:
644
                $new_img = $this->gd_imageflip(
645
                    $src_img,
646
                    defined('IMG_FLIP_HORIZONTAL') ? IMG_FLIP_HORIZONTAL : 1
647
                );
648
                break;
649
            case 5:
650
                $tmp_img = $this->gd_imageflip(
651
                    $src_img,
652
                    defined('IMG_FLIP_HORIZONTAL') ? IMG_FLIP_HORIZONTAL : 1
653
                );
654
                $new_img = imagerotate($tmp_img, 270, 0);
655
                imagedestroy($tmp_img);
656
                break;
657
            case 6:
658
                $new_img = imagerotate($src_img, 270, 0);
659
                break;
660
            case 7:
661
                $tmp_img = $this->gd_imageflip(
662
                    $src_img,
663
                    defined('IMG_FLIP_VERTICAL') ? IMG_FLIP_VERTICAL : 2
664
                );
665
                $new_img = imagerotate($tmp_img, 270, 0);
666
                imagedestroy($tmp_img);
667
                break;
668
            case 8:
669
                $new_img = imagerotate($src_img, 90, 0);
670
                break;
671
            default:
672
                return false;
673
        }
674
        $this->gd_set_image_object($file_path, $new_img);
675
        return true;
676
    }
677
 
678
    protected function gd_create_scaled_image($file_name, $version, $options) {
679
        if (!function_exists('imagecreatetruecolor')) {
680
            error_log('Function not found: imagecreatetruecolor');
681
            return false;
682
        }
683
        list($file_path, $new_file_path) =
684
            $this->get_scaled_image_file_paths($file_name, $version);
685
        $type = strtolower(substr(strrchr($file_name, '.'), 1));
686
        switch ($type) {
687
            case 'jpg':
688
            case 'jpeg':
689
                $src_func = 'imagecreatefromjpeg';
690
                $write_func = 'imagejpeg';
691
                $image_quality = isset($options['jpeg_quality']) ?
692
                    $options['jpeg_quality'] : 75;
693
                break;
694
            case 'gif':
695
                $src_func = 'imagecreatefromgif';
696
                $write_func = 'imagegif';
697
                $image_quality = null;
698
                break;
699
            case 'png':
700
                $src_func = 'imagecreatefrompng';
701
                $write_func = 'imagepng';
702
                $image_quality = isset($options['png_quality']) ?
703
                    $options['png_quality'] : 9;
704
                break;
705
            default:
706
                return false;
707
        }
708
        $src_img = $this->gd_get_image_object(
709
            $file_path,
710
            $src_func,
711
            !empty($options['no_cache'])
712
        );
713
        $image_oriented = false;
714
        if (!empty($options['auto_orient']) && $this->gd_orient_image(
715
                $file_path,
716
                $src_img
717
            )) {
718
            $image_oriented = true;
719
            $src_img = $this->gd_get_image_object(
720
                $file_path,
721
                $src_func
722
            );
723
        }
724
        $max_width = $img_width = imagesx($src_img);
725
        $max_height = $img_height = imagesy($src_img);
726
        if (!empty($options['max_width'])) {
727
            $max_width = $options['max_width'];
728
        }
729
        if (!empty($options['max_height'])) {
730
            $max_height = $options['max_height'];
731
        }
732
        $scale = min(
733
            $max_width / $img_width,
734
            $max_height / $img_height
735
        );
736
        if ($scale >= 1) {
737
            if ($image_oriented) {
738
                return $write_func($src_img, $new_file_path, $image_quality);
739
            }
740
            if ($file_path !== $new_file_path) {
741
                return copy($file_path, $new_file_path);
742
            }
743
            return true;
744
        }
745
        if (empty($options['crop'])) {
746
            $new_width = $img_width * $scale;
747
            $new_height = $img_height * $scale;
748
            $dst_x = 0;
749
            $dst_y = 0;
750
            $new_img = imagecreatetruecolor($new_width, $new_height);
751
        } else {
752
            if (($img_width / $img_height) >= ($max_width / $max_height)) {
753
                $new_width = $img_width / ($img_height / $max_height);
754
                $new_height = $max_height;
755
            } else {
756
                $new_width = $max_width;
757
                $new_height = $img_height / ($img_width / $max_width);
758
            }
759
            $dst_x = 0 - ($new_width - $max_width) / 2;
760
            $dst_y = 0 - ($new_height - $max_height) / 2;
761
            $new_img = imagecreatetruecolor($max_width, $max_height);
762
        }
763
        // Handle transparency in GIF and PNG images:
764
        switch ($type) {
765
            case 'gif':
766
            case 'png':
767
                imagecolortransparent($new_img, imagecolorallocate($new_img, 0, 0, 0));
768
            case 'png':
769
                imagealphablending($new_img, false);
770
                imagesavealpha($new_img, true);
771
                break;
772
        }
773
        $success = imagecopyresampled(
774
            $new_img,
775
            $src_img,
776
            $dst_x,
777
            $dst_y,
778
            0,
779
            0,
780
            $new_width,
781
            $new_height,
782
            $img_width,
783
            $img_height
784
        ) && $write_func($new_img, $new_file_path, $image_quality);
785
        $this->gd_set_image_object($file_path, $new_img);
786
        return $success;
787
    }
788
 
789
    protected function imagick_get_image_object($file_path, $no_cache = false) {
790
        if (empty($this->image_objects[$file_path]) || $no_cache) {
791
            $this->imagick_destroy_image_object($file_path);
792
            $image = new \Imagick();
793
            if (!empty($this->options['imagick_resource_limits'])) {
794
                foreach ($this->options['imagick_resource_limits'] as $type => $limit) {
795
                    $image->setResourceLimit($type, $limit);
796
                }
797
            }
798
            $image->readImage($file_path);
799
            $this->image_objects[$file_path] = $image;
800
        }
801
        return $this->image_objects[$file_path];
802
    }
803
 
804
    protected function imagick_set_image_object($file_path, $image) {
805
        $this->imagick_destroy_image_object($file_path);
806
        $this->image_objects[$file_path] = $image;
807
    }
808
 
809
    protected function imagick_destroy_image_object($file_path) {
810
        $image = (isset($this->image_objects[$file_path])) ? $this->image_objects[$file_path] : null ;
811
        return $image && $image->destroy();
812
    }
813
 
814
    protected function imagick_orient_image($image) {
815
        $orientation = $image->getImageOrientation();
816
        $background = new \ImagickPixel('none');
817
        switch ($orientation) {
818
            case \imagick::ORIENTATION_TOPRIGHT: // 2
819
                $image->flopImage(); // horizontal flop around y-axis
820
                break;
821
            case \imagick::ORIENTATION_BOTTOMRIGHT: // 3
822
                $image->rotateImage($background, 180);
823
                break;
824
            case \imagick::ORIENTATION_BOTTOMLEFT: // 4
825
                $image->flipImage(); // vertical flip around x-axis
826
                break;
827
            case \imagick::ORIENTATION_LEFTTOP: // 5
828
                $image->flopImage(); // horizontal flop around y-axis
829
                $image->rotateImage($background, 270);
830
                break;
831
            case \imagick::ORIENTATION_RIGHTTOP: // 6
832
                $image->rotateImage($background, 90);
833
                break;
834
            case \imagick::ORIENTATION_RIGHTBOTTOM: // 7
835
                $image->flipImage(); // vertical flip around x-axis
836
                $image->rotateImage($background, 270);
837
                break;
838
            case \imagick::ORIENTATION_LEFTBOTTOM: // 8
839
                $image->rotateImage($background, 270);
840
                break;
841
            default:
842
                return false;
843
        }
844
        $image->setImageOrientation(\imagick::ORIENTATION_TOPLEFT); // 1
845
        return true;
846
    }
847
 
848
    protected function imagick_create_scaled_image($file_name, $version, $options) {
849
        list($file_path, $new_file_path) =
850
            $this->get_scaled_image_file_paths($file_name, $version);
851
        $image = $this->imagick_get_image_object(
852
            $file_path,
853
            !empty($options['crop']) || !empty($options['no_cache'])
854
        );
855
        if ($image->getImageFormat() === 'GIF') {
856
            // Handle animated GIFs:
857
            $images = $image->coalesceImages();
858
            foreach ($images as $frame) {
859
                $image = $frame;
860
                $this->imagick_set_image_object($file_name, $image);
861
                break;
862
            }
863
        }
864
        $image_oriented = false;
865
        if (!empty($options['auto_orient'])) {
866
            $image_oriented = $this->imagick_orient_image($image);
867
        }
868
        $new_width = $max_width = $img_width = $image->getImageWidth();
869
        $new_height = $max_height = $img_height = $image->getImageHeight();
870
        if (!empty($options['max_width'])) {
871
            $new_width = $max_width = $options['max_width'];
872
        }
873
        if (!empty($options['max_height'])) {
874
            $new_height = $max_height = $options['max_height'];
875
        }
876
        $image_strip = false;
877
        if( !empty($options["strip"]) ) {
878
            $image_strip = $options["strip"];
879
        }
880
        if ( !$image_oriented && ($max_width >= $img_width) && ($max_height >= $img_height) && !$image_strip && empty($options["jpeg_quality"]) ) {
881
            if ($file_path !== $new_file_path) {
882
                return copy($file_path, $new_file_path);
883
            }
884
            return true;
885
        }
886
        $crop = !empty($options['crop']);
887
        if ($crop) {
888
            $x = 0;
889
            $y = 0;
890
            if (($img_width / $img_height) >= ($max_width / $max_height)) {
891
                $new_width = 0; // Enables proportional scaling based on max_height
892
                $x = ($img_width / ($img_height / $max_height) - $max_width) / 2;
893
            } else {
894
                $new_height = 0; // Enables proportional scaling based on max_width
895
                $y = ($img_height / ($img_width / $max_width) - $max_height) / 2;
896
            }
897
        }
898
        $success = $image->resizeImage(
899
            $new_width,
900
            $new_height,
901
            isset($options['filter']) ? $options['filter'] : \imagick::FILTER_LANCZOS,
902
            isset($options['blur']) ? $options['blur'] : 1,
903
            $new_width && $new_height // fit image into constraints if not to be cropped
904
        );
905
        if ($success && $crop) {
906
            $success = $image->cropImage(
907
                $max_width,
908
                $max_height,
909
                $x,
910
                $y
911
            );
912
            if ($success) {
913
                $success = $image->setImagePage($max_width, $max_height, 0, 0);
914
            }
915
        }
916
        $type = strtolower(substr(strrchr($file_name, '.'), 1));
917
        switch ($type) {
918
            case 'jpg':
919
            case 'jpeg':
920
                if (!empty($options['jpeg_quality'])) {
921
                    $image->setImageCompression(\imagick::COMPRESSION_JPEG);
922
                    $image->setImageCompressionQuality($options['jpeg_quality']);
923
                }
924
                break;
925
        }
926
        if ( $image_strip ) {
927
            $image->stripImage();
928
        }
929
        return $success && $image->writeImage($new_file_path);
930
    }
931
 
932
    protected function imagemagick_create_scaled_image($file_name, $version, $options) {
933
        list($file_path, $new_file_path) =
934
            $this->get_scaled_image_file_paths($file_name, $version);
935
        $resize = @$options['max_width']
936
            .(empty($options['max_height']) ? '' : 'X'.$options['max_height']);
937
        if (!$resize && empty($options['auto_orient'])) {
938
            if ($file_path !== $new_file_path) {
939
                return copy($file_path, $new_file_path);
940
            }
941
            return true;
942
        }
943
        $cmd = $this->options['convert_bin'];
944
        if (!empty($this->options['convert_params'])) {
945
            $cmd .= ' '.$this->options['convert_params'];
946
        }
947
        $cmd .= ' '.escapeshellarg($file_path);
948
        if (!empty($options['auto_orient'])) {
949
            $cmd .= ' -auto-orient';
950
        }
951
        if ($resize) {
952
            // Handle animated GIFs:
953
            $cmd .= ' -coalesce';
954
            if (empty($options['crop'])) {
955
                $cmd .= ' -resize '.escapeshellarg($resize.'>');
956
            } else {
957
                $cmd .= ' -resize '.escapeshellarg($resize.'^');
958
                $cmd .= ' -gravity center';
959
                $cmd .= ' -crop '.escapeshellarg($resize.'+0+0');
960
            }
961
            // Make sure the page dimensions are correct (fixes offsets of animated GIFs):
962
            $cmd .= ' +repage';
963
        }
964
        if (!empty($options['convert_params'])) {
965
            $cmd .= ' '.$options['convert_params'];
966
        }
967
        $cmd .= ' '.escapeshellarg($new_file_path);
968
        exec($cmd, $output, $error);
969
        if ($error) {
970
            error_log(implode('\n', $output));
971
            return false;
972
        }
973
        return true;
974
    }
975
 
976
    protected function get_image_size($file_path) {
977
        if ($this->options['image_library']) {
978
            if (extension_loaded('imagick')) {
979
                $image = new \Imagick();
980
                try {
981
                    if (@$image->pingImage($file_path)) {
982
                        $dimensions = array($image->getImageWidth(), $image->getImageHeight());
983
                        $image->destroy();
984
                        return $dimensions;
985
                    }
986
                    return false;
987
                } catch (\Exception $e) {
988
                    error_log($e->getMessage());
989
                }
990
            }
991
            if ($this->options['image_library'] === 2) {
992
                $cmd = $this->options['identify_bin'];
993
                $cmd .= ' -ping '.escapeshellarg($file_path);
994
                exec($cmd, $output, $error);
995
                if (!$error && !empty($output)) {
996
                    // image.jpg JPEG 1920x1080 1920x1080+0+0 8-bit sRGB 465KB 0.000u 0:00.000
997
                    $infos = preg_split('/\s+/', substr($output[0], strlen($file_path)));
998
                    $dimensions = preg_split('/x/', $infos[2]);
999
                    return $dimensions;
1000
                }
1001
                return false;
1002
            }
1003
        }
1004
        if (!function_exists('getimagesize')) {
1005
            error_log('Function not found: getimagesize');
1006
            return false;
1007
        }
1008
        return @getimagesize($file_path);
1009
    }
1010
 
1011
    protected function create_scaled_image($file_name, $version, $options) {
1012
        if ($this->options['image_library'] === 2) {
1013
            return $this->imagemagick_create_scaled_image($file_name, $version, $options);
1014
        }
1015
        if ($this->options['image_library'] && extension_loaded('imagick')) {
1016
            return $this->imagick_create_scaled_image($file_name, $version, $options);
1017
        }
1018
        return $this->gd_create_scaled_image($file_name, $version, $options);
1019
    }
1020
 
1021
    protected function destroy_image_object($file_path) {
1022
        if ($this->options['image_library'] && extension_loaded('imagick')) {
1023
            return $this->imagick_destroy_image_object($file_path);
1024
        }
1025
    }
1026
 
1027
    protected function is_valid_image_file($file_path) {
1028
        if (!preg_match($this->options['image_file_types'], $file_path)) {
1029
            return false;
1030
        }
1031
        if (function_exists('exif_imagetype')) {
1032
            return @exif_imagetype($file_path);
1033
        }
1034
        $image_info = $this->get_image_size($file_path);
1035
        return $image_info && $image_info[0] && $image_info[1];
1036
    }
1037
 
1038
    protected function handle_image_file($file_path, $file) {
1039
        $failed_versions = array();
1040
        foreach ($this->options['image_versions'] as $version => $options) {
1041
            if ($this->create_scaled_image($file->name, $version, $options)) {
1042
                if (!empty($version)) {
1043
                    $file->{$version.'Url'} = $this->get_download_url(
1044
                        $file->name,
1045
                        $version
1046
                    );
1047
                } else {
1048
                    $file->size = $this->get_file_size($file_path, true);
1049
                }
1050
            } else {
1051
                $failed_versions[] = $version ? $version : 'original';
1052
            }
1053
        }
1054
        if (count($failed_versions)) {
1055
            $file->error = $this->get_error_message('image_resize')
1056
                    .' ('.implode($failed_versions, ', ').')';
1057
        }
1058
        // Free memory:
1059
        $this->destroy_image_object($file_path);
1060
    }
1061
 
1062
    protected function handle_file_upload($uploaded_file, $name, $size, $type, $error,
1063
            $index = null, $content_range = null) {
1064
        $file = new \stdClass();
1065
        $file->name = $this->get_file_name($uploaded_file, $name, $size, $type, $error,
1066
            $index, $content_range);
1067
        $file->size = $this->fix_integer_overflow((int)$size);
1068
        $file->type = $type;
1069
        if ($this->validate($uploaded_file, $file, $error, $index)) {
1070
            $this->handle_form_data($file, $index);
1071
            $upload_dir = $this->get_upload_path();
1072
            if (!is_dir($upload_dir)) {
1073
                mkdir($upload_dir, $this->options['mkdir_mode'], true);
1074
            }
1075
            $file_path = $this->get_upload_path($file->name);
1076
            $append_file = $content_range && is_file($file_path) &&
1077
                $file->size > $this->get_file_size($file_path);
1078
            if ($uploaded_file && is_uploaded_file($uploaded_file)) {
1079
                // multipart/formdata uploads (POST method uploads)
1080
                if ($append_file) {
1081
                    file_put_contents(
1082
                        $file_path,
1083
                        fopen($uploaded_file, 'r'),
1084
                        FILE_APPEND
1085
                    );
1086
                } else {
1087
                    move_uploaded_file($uploaded_file, $file_path);
1088
                }
1089
            } else {
1090
                // Non-multipart uploads (PUT method support)
1091
                file_put_contents(
1092
                    $file_path,
1093
                    fopen($this->options['input_stream'], 'r'),
1094
                    $append_file ? FILE_APPEND : 0
1095
                );
1096
            }
1097
            $file_size = $this->get_file_size($file_path, $append_file);
1098
            if ($file_size === $file->size) {
1099
                $file->url = $this->get_download_url($file->name);
1100
                if ($this->is_valid_image_file($file_path)) {
1101
                    $this->handle_image_file($file_path, $file);
1102
                }
1103
            } else {
1104
                $file->size = $file_size;
1105
                if (!$content_range && $this->options['discard_aborted_uploads']) {
1106
                    unlink($file_path);
1107
                    $file->error = $this->get_error_message('abort');
1108
                }
1109
            }
1110
            $this->set_additional_file_properties($file);
1111
        }
1112
        return $file;
1113
    }
1114
 
1115
    protected function readfile($file_path) {
1116
        $file_size = $this->get_file_size($file_path);
1117
        $chunk_size = $this->options['readfile_chunk_size'];
1118
        if ($chunk_size && $file_size > $chunk_size) {
1119
            $handle = fopen($file_path, 'rb');
1120
            while (!feof($handle)) {
1121
                echo fread($handle, $chunk_size);
1122
                @ob_flush();
1123
                @flush();
1124
            }
1125
            fclose($handle);
1126
            return $file_size;
1127
        }
1128
        return readfile($file_path);
1129
    }
1130
 
1131
    protected function body($str) {
1132
        echo $str;
1133
    }
1134
 
1135
    protected function header($str) {
1136
        header($str);
1137
    }
1138
 
1139
    protected function get_upload_data($id) {
1140
        return @$_FILES[$id];
1141
    }
1142
 
1143
    protected function get_post_param($id) {
1144
        return @$_POST[$id];
1145
    }
1146
 
1147
    protected function get_query_param($id) {
1148
        return @$_GET[$id];
1149
    }
1150
 
1151
    protected function get_server_var($id) {
1152
        return @$_SERVER[$id];
1153
    }
1154
 
1155
    protected function handle_form_data($file, $index) {
1156
        // Handle form data, e.g. $_POST['description'][$index]
1157
    }
1158
 
1159
    protected function get_version_param() {
1160
        return $this->basename(stripslashes($this->get_query_param('version')));
1161
    }
1162
 
1163
    protected function get_singular_param_name() {
1164
        return substr($this->options['param_name'], 0, -1);
1165
    }
1166
 
1167
    protected function get_file_name_param() {
1168
        $name = $this->get_singular_param_name();
1169
        return $this->basename(stripslashes($this->get_query_param($name)));
1170
    }
1171
 
1172
    protected function get_file_names_params() {
1173
        $params = $this->get_query_param($this->options['param_name']);
1174
        if (!$params) {
1175
            return null;
1176
        }
1177
        foreach ($params as $key => $value) {
1178
            $params[$key] = $this->basename(stripslashes($value));
1179
        }
1180
        return $params;
1181
    }
1182
 
1183
    protected function get_file_type($file_path) {
1184
        switch (strtolower(pathinfo($file_path, PATHINFO_EXTENSION))) {
1185
            case 'jpeg':
1186
            case 'jpg':
1187
                return 'image/jpeg';
1188
            case 'png':
1189
                return 'image/png';
1190
            case 'gif':
1191
                return 'image/gif';
1192
            default:
1193
                return '';
1194
        }
1195
    }
1196
 
1197
    protected function download() {
1198
        switch ($this->options['download_via_php']) {
1199
            case 1:
1200
                $redirect_header = null;
1201
                break;
1202
            case 2:
1203
                $redirect_header = 'X-Sendfile';
1204
                break;
1205
            case 3:
1206
                $redirect_header = 'X-Accel-Redirect';
1207
                break;
1208
            default:
1209
                return $this->header('HTTP/1.1 403 Forbidden');
1210
        }
1211
        $file_name = $this->get_file_name_param();
1212
        if (!$this->is_valid_file_object($file_name)) {
1213
            return $this->header('HTTP/1.1 404 Not Found');
1214
        }
1215
        if ($redirect_header) {
1216
            return $this->header(
1217
                $redirect_header.': '.$this->get_download_url(
1218
                    $file_name,
1219
                    $this->get_version_param(),
1220
                    true
1221
                )
1222
            );
1223
        }
1224
        $file_path = $this->get_upload_path($file_name, $this->get_version_param());
1225
        // Prevent browsers from MIME-sniffing the content-type:
1226
        $this->header('X-Content-Type-Options: nosniff');
1227
        if (!preg_match($this->options['inline_file_types'], $file_name)) {
1228
            $this->header('Content-Type: application/octet-stream');
1229
            $this->header('Content-Disposition: attachment; filename="'.$file_name.'"');
1230
        } else {
1231
            $this->header('Content-Type: '.$this->get_file_type($file_path));
1232
            $this->header('Content-Disposition: inline; filename="'.$file_name.'"');
1233
        }
1234
        $this->header('Content-Length: '.$this->get_file_size($file_path));
1235
        $this->header('Last-Modified: '.gmdate('D, d M Y H:i:s T', filemtime($file_path)));
1236
        $this->readfile($file_path);
1237
    }
1238
 
1239
    protected function send_content_type_header() {
1240
        $this->header('Vary: Accept');
1241
        if (strpos($this->get_server_var('HTTP_ACCEPT'), 'application/json') !== false) {
1242
            $this->header('Content-type: application/json');
1243
        } else {
1244
            $this->header('Content-type: text/plain');
1245
        }
1246
    }
1247
 
1248
    protected function send_access_control_headers() {
1249
        $this->header('Access-Control-Allow-Origin: '.$this->options['access_control_allow_origin']);
1250
        $this->header('Access-Control-Allow-Credentials: '
1251
            .($this->options['access_control_allow_credentials'] ? 'true' : 'false'));
1252
        $this->header('Access-Control-Allow-Methods: '
1253
            .implode(', ', $this->options['access_control_allow_methods']));
1254
        $this->header('Access-Control-Allow-Headers: '
1255
            .implode(', ', $this->options['access_control_allow_headers']));
1256
    }
1257
 
1258
    public function generate_response($content, $print_response = true) {
1259
        $this->response = $content;
1260
        if ($print_response) {
1261
            $json = json_encode($content);
1262
            $redirect = stripslashes($this->get_post_param('redirect'));
1263
            if ($redirect && preg_match($this->options['redirect_allow_target'], $redirect)) {
1264
                $this->header('Location: '.sprintf($redirect, rawurlencode($json)));
1265
                return;
1266
            }
1267
            $this->head();
1268
            if ($this->get_server_var('HTTP_CONTENT_RANGE')) {
1269
                $files = isset($content[$this->options['param_name']]) ?
1270
                    $content[$this->options['param_name']] : null;
1271
                if ($files && is_array($files) && is_object($files[0]) && $files[0]->size) {
1272
                    $this->header('Range: 0-'.(
1273
                        $this->fix_integer_overflow((int)$files[0]->size) - 1
1274
                    ));
1275
                }
1276
            }
1277
            $this->body($json);
1278
        }
1279
        return $content;
1280
    }
1281
 
1282
    public function get_response () {
1283
        return $this->response;
1284
    }
1285
 
1286
    public function head() {
1287
        $this->header('Pragma: no-cache');
1288
        $this->header('Cache-Control: no-store, no-cache, must-revalidate');
1289
        $this->header('Content-Disposition: inline; filename="files.json"');
1290
        // Prevent Internet Explorer from MIME-sniffing the content-type:
1291
        $this->header('X-Content-Type-Options: nosniff');
1292
        if ($this->options['access_control_allow_origin']) {
1293
            $this->send_access_control_headers();
1294
        }
1295
        $this->send_content_type_header();
1296
    }
1297
 
1298
    public function get($print_response = true) {
1299
        if ($print_response && $this->get_query_param('download')) {
1300
            return $this->download();
1301
        }
1302
        $file_name = $this->get_file_name_param();
1303
        if ($file_name) {
1304
            $response = array(
1305
                $this->get_singular_param_name() => $this->get_file_object($file_name)
1306
            );
1307
        } else {
1308
            $response = array(
1309
                $this->options['param_name'] => $this->get_file_objects()
1310
            );
1311
        }
1312
        return $this->generate_response($response, $print_response);
1313
    }
1314
 
1315
    public function post($print_response = true) {
1316
        if ($this->get_query_param('_method') === 'DELETE') {
1317
            return $this->delete($print_response);
1318
        }
1319
        $upload = $this->get_upload_data($this->options['param_name']);
1320
        // Parse the Content-Disposition header, if available:
1321
        $content_disposition_header = $this->get_server_var('HTTP_CONTENT_DISPOSITION');
1322
        $file_name = $content_disposition_header ?
1323
            rawurldecode(preg_replace(
1324
                '/(^[^"]+")|("$)/',
1325
                '',
1326
                $content_disposition_header
1327
            )) : null;
1328
        // Parse the Content-Range header, which has the following form:
1329
        // Content-Range: bytes 0-524287/2000000
1330
        $content_range_header = $this->get_server_var('HTTP_CONTENT_RANGE');
1331
        $content_range = $content_range_header ?
1332
            preg_split('/[^0-9]+/', $content_range_header) : null;
1333
        $size =  $content_range ? $content_range[3] : null;
1334
        $files = array();
1335
        if ($upload) {
1336
            if (is_array($upload['tmp_name'])) {
1337
                // param_name is an array identifier like "files[]",
1338
                // $upload is a multi-dimensional array:
1339
                foreach ($upload['tmp_name'] as $index => $value) {
1340
                    $files[] = $this->handle_file_upload(
1341
                        $upload['tmp_name'][$index],
1342
                        $file_name ? $file_name : $upload['name'][$index],
1343
                        $size ? $size : $upload['size'][$index],
1344
                        $upload['type'][$index],
1345
                        $upload['error'][$index],
1346
                        $index,
1347
                        $content_range
1348
                    );
1349
                }
1350
            } else {
1351
                // param_name is a single object identifier like "file",
1352
                // $upload is a one-dimensional array:
1353
                $files[] = $this->handle_file_upload(
1354
                    isset($upload['tmp_name']) ? $upload['tmp_name'] : null,
1355
                    $file_name ? $file_name : (isset($upload['name']) ?
1356
                            $upload['name'] : null),
1357
                    $size ? $size : (isset($upload['size']) ?
1358
                            $upload['size'] : $this->get_server_var('CONTENT_LENGTH')),
1359
                    isset($upload['type']) ?
1360
                            $upload['type'] : $this->get_server_var('CONTENT_TYPE'),
1361
                    isset($upload['error']) ? $upload['error'] : null,
1362
                    null,
1363
                    $content_range
1364
                );
1365
            }
1366
        }
1367
        $response = array($this->options['param_name'] => $files);
1368
        return $this->generate_response($response, $print_response);
1369
    }
1370
 
1371
    public function delete($print_response = true) {
1372
        $file_names = $this->get_file_names_params();
1373
        if (empty($file_names)) {
1374
            $file_names = array($this->get_file_name_param());
1375
        }
1376
        $response = array();
1377
        foreach ($file_names as $file_name) {
1378
            $file_path = $this->get_upload_path($file_name);
1379
            $success = is_file($file_path) && $file_name[0] !== '.' && unlink($file_path);
1380
            if ($success) {
1381
                foreach ($this->options['image_versions'] as $version => $options) {
1382
                    if (!empty($version)) {
1383
                        $file = $this->get_upload_path($file_name, $version);
1384
                        if (is_file($file)) {
1385
                            unlink($file);
1386
                        }
1387
                    }
1388
                }
1389
            }
1390
            $response[$file_name] = $success;
1391
        }
1392
        return $this->generate_response($response, $print_response);
1393
    }
1394
 
1395
    protected function basename($filepath, $suffix = null) {
1396
        $splited = preg_split('/\//', rtrim ($filepath, '/ '));
1397
        return substr(basename('X'.$splited[count($splited)-1], $suffix), 1);
1398
    }
1399
}