Subversion-Projekte lars-tiefland.ci

Revision

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