Subversion-Projekte lars-tiefland.ci

Revision

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

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