Subversion-Projekte lars-tiefland.ci

Revision

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