Subversion-Projekte lars-tiefland.ci

Revision

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