Subversion-Projekte lars-tiefland.ci

Revision

Revision 2133 | Revision 2135 | Zur aktuellen Revision | Details | Vergleich mit vorheriger | Letzte Änderung | Log anzeigen | RSS feed

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