Subversion-Projekte lars-tiefland.ci

Revision

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

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