Subversion-Projekte lars-tiefland.ci

Revision

Revision 2156 | Revision 2160 | 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 2158 2017-11-25 23:50:52Z 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(
83
			'script_url' => $this->get_full_url() . '/' . $this->basename($this->
84
				get_server_var('SCRIPT_NAME')),
2153 lars 85
			'upload_dir' => $GLOBALS["webs"]["verzeichnis"] . "/images/upload/orig/",
2152 lars 86
			'upload_url' => $real_url . "orig/",
2144 lars 87
			'input_stream' => 'php://input',
88
			'user_dirs' => false,
89
			'mkdir_mode' => 0755,
90
			'param_name' => 'files',
91
			// Set the following option to 'POST', if your server does not support
92
			// DELETE requests. This is a parameter sent to the client:
93
			'delete_type' => 'DELETE',
94
			'access_control_allow_origin' => '*',
95
			'access_control_allow_credentials' => false,
96
			'access_control_allow_methods' => array(
97
				'OPTIONS',
98
				'HEAD',
99
				'GET',
100
				'POST',
101
				'PUT',
102
				'PATCH',
103
				'DELETE',
104
				),
105
			'access_control_allow_headers' => array(
106
				'Content-Type',
107
				'Content-Range',
108
				'Content-Disposition',
109
				),
110
			// By default, allow redirects to the referer protocol+host:
111
			'redirect_allow_target' => '/^' . preg_quote(parse_url($this->get_server_var('HTTP_REFERER'),
112
				PHP_URL_SCHEME) . '://' . parse_url($this->get_server_var('HTTP_REFERER'),
113
				PHP_URL_HOST) . '/', // Trailing slash to not match subdomains by mistake
114
				'/' // preg_quote delimiter param
115
				) . '/',
116
			// Enable to provide file downloads via GET requests to the PHP script:
117
			//     1. Set to 1 to download files via readfile method through PHP
118
			//     2. Set to 2 to send a X-Sendfile header for lighttpd/Apache
119
			//     3. Set to 3 to send a X-Accel-Redirect header for nginx
120
			// If set to 2 or 3, adjust the upload_url option to the base path of
121
			// the redirect parameter, e.g. '/files/'.
122
			'download_via_php' => false,
123
			// Read files in chunks to avoid memory limits when download_via_php
124
			// is enabled, set to 0 to disable chunked reading of files:
125
			'readfile_chunk_size' => 10 * 1024 * 1024, // 10 MiB
126
			// Defines which files can be displayed inline when downloaded:
127
			'inline_file_types' => '/\.(gif|jpe?g|png|svg)$/i',
128
			// Defines which files (based on their names) are accepted for upload:
129
			'accept_file_types' => '/.+$/i',
130
			// The php.ini settings upload_max_filesize and post_max_size
131
			// take precedence over the following max_file_size setting:
132
			'max_file_size' => null,
133
			'min_file_size' => 1,
134
			// The maximum number of files for the upload directory:
135
			'max_number_of_files' => null,
136
			// Defines which files are handled as image files:
137
			'image_file_types' => '/\.(gif|jpe?g|png)$/i',
138
			// Use exif_imagetype on all files to correct file extensions:
139
			'correct_image_extensions' => false,
140
			// Image resolution restrictions:
141
			'max_width' => null,
142
			'max_height' => null,
143
			'min_width' => 1,
144
			'min_height' => 1,
145
			// Set the following option to false to enable resumable uploads:
146
			'discard_aborted_uploads' => true,
147
			// Set to 0 to use the GD library to scale and orient images,
148
			// set to 1 to use imagick (if installed, falls back to GD),
149
			// set to 2 to use the ImageMagick convert binary directly:
2145 lars 150
			'image_library' => 1,
2144 lars 151
			// Uncomment the following to define an array of resource limits
152
			// for imagick:
153
			/*
154
			'imagick_resource_limits' => array(
155
			imagick::RESOURCETYPE_MAP => 32,
156
			imagick::RESOURCETYPE_MEMORY => 32
157
			),
158
			*/
159
			// Command or path for to the ImageMagick convert binary:
160
			'convert_bin' => 'convert',
161
			// Uncomment the following to add parameters in front of each
162
			// ImageMagick convert call (the limit constraints seem only
163
			// to have an effect if put in front):
164
			/*
165
			'convert_params' => '-limit memory 32MiB -limit map 32MiB',
166
			*/
167
			// Command or path for to the ImageMagick identify binary:
168
			'identify_bin' => 'identify',
169
			'print_response' => true,
170
			);
171
		foreach ($GLOBALS["Imagedaten"] as $nr => $set) {
172
			$this->options["image_versions"][$set[0]] = array(
173
				"upload_dir" => $real_folder . $set[1] . "/",
174
				"upload_url" => $real_url . $set[1] . "/",
175
				"max_width" => $set[2],
176
				"max_height" => $set[3],
177
				);
178
		}
179
		if ($options) {
180
			$this->options = $options + $this->options;
181
		}
182
		if ($error_messages) {
183
			$this->error_messages = $error_messages + $this->error_messages;
184
		}
185
		if ($initialize) {
186
			$this->initialize();
187
		}
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
				$info = pathinfo($file_path);
1070
				$ext = strtolower($info["extension"]);
1071
				$file->url = $this->get_download_url($file->name);
1072
				$typ = 4;
1073
				if ($this->is_valid_image_file($file_path)) {
1074
					$typ = 1;
1075
					$this->handle_image_file($file_path, $file);
1076
				} elseif (in_array($ext, $docs)) {
1077
					$typ = 2;
1078
				} elseif (in_array($ext, $videos)) {
1079
					$typ = 3;
1080
				}
1081
				$f = $GLOBALS["folder"];
1082
				$sql = "INSERT INTO
1083
                        medien
1084
                    SET
1085
                        name='" . $fName . "',
1086
                        folder='" . $f . "',
1087
                        erstellt_am=UNIX_TIMESTAMP(),
1088
                        erstellt_von='" . $_SERVER["PHP_AUTH_USER"] . "',
1089
                        typ=" . $typ . "
1090
                ";
1091
				//$GLOBALS["ci"]->db->query($sql);
1092
			} else {
1093
				$file->size = $file_size;
1094
				if (!$content_range && $this->options['discard_aborted_uploads']) {
1095
					unlink($file_path);
1096
					$file->error = $this->get_error_message('abort');
1097
				}
1098
			}
1099
			$this->set_additional_file_properties($file);
1100
		}
1101
		return $file;
1102
	}
2121 lars 1103
 
2144 lars 1104
	protected function readfile($file_path)
1105
	{
1106
		$file_size = $this->get_file_size($file_path);
1107
		$chunk_size = $this->options['readfile_chunk_size'];
1108
		if ($chunk_size && $file_size > $chunk_size) {
1109
			$handle = fopen($file_path, 'rb');
1110
			while (!feof($handle)) {
1111
				echo fread($handle, $chunk_size);
1112
				@ob_flush();
1113
				@flush();
1114
			}
1115
			fclose($handle);
1116
			return $file_size;
1117
		}
1118
		return readfile($file_path);
1119
	}
2121 lars 1120
 
2144 lars 1121
	protected function body($str)
1122
	{
1123
		echo $str;
1124
	}
2121 lars 1125
 
2144 lars 1126
	protected function header($str)
1127
	{
1128
		header($str);
1129
	}
2121 lars 1130
 
2144 lars 1131
	protected function get_upload_data($id)
1132
	{
1133
		return @$_FILES[$id];
1134
	}
2121 lars 1135
 
2144 lars 1136
	protected function get_post_param($id)
1137
	{
1138
		return @$_POST[$id];
1139
	}
2121 lars 1140
 
2144 lars 1141
	protected function get_query_param($id)
1142
	{
1143
		return @$_GET[$id];
1144
	}
2121 lars 1145
 
2144 lars 1146
	protected function get_server_var($id)
1147
	{
1148
		return @$_SERVER[$id];
1149
	}
2121 lars 1150
 
2144 lars 1151
	protected function handle_form_data($file, $index)
1152
	{
1153
		// Handle form data, e.g. $_POST['description'][$index]
1154
	}
2121 lars 1155
 
2144 lars 1156
	protected function get_version_param()
1157
	{
1158
		return $this->basename(stripslashes($this->get_query_param('version')));
1159
	}
2121 lars 1160
 
2144 lars 1161
	protected function get_singular_param_name()
1162
	{
1163
		return substr($this->options['param_name'], 0, -1);
1164
	}
2121 lars 1165
 
2144 lars 1166
	protected function get_file_name_param()
1167
	{
1168
		$name = $this->get_singular_param_name();
1169
		return $this->basename(stripslashes($this->get_query_param($name)));
1170
	}
2121 lars 1171
 
2144 lars 1172
	protected function get_file_names_params()
1173
	{
1174
		$params = $this->get_query_param($this->options['param_name']);
1175
		if (!$params) {
1176
			return null;
1177
		}
1178
		foreach ($params as $key => $value) {
1179
			$params[$key] = $this->basename(stripslashes($value));
1180
		}
1181
		return $params;
1182
	}
2121 lars 1183
 
2144 lars 1184
	protected function get_file_type($file_path)
1185
	{
1186
		switch (strtolower(pathinfo($file_path, PATHINFO_EXTENSION))) {
1187
			case 'jpeg':
1188
			case 'jpg':
1189
				return 'image/jpeg';
1190
			case 'png':
1191
				return 'image/png';
1192
			case 'gif':
1193
				return 'image/gif';
1194
			case 'svg':
1195
				return 'image/svg';
1196
			default:
1197
				return '';
1198
		}
1199
	}
2121 lars 1200
 
2144 lars 1201
	protected function download()
1202
	{
1203
		switch ($this->options['download_via_php']) {
1204
			case 1:
1205
				$redirect_header = null;
1206
				break;
1207
			case 2:
1208
				$redirect_header = 'X-Sendfile';
1209
				break;
1210
			case 3:
1211
				$redirect_header = 'X-Accel-Redirect';
1212
				break;
1213
			default:
1214
				return $this->header('HTTP/1.1 403 Forbidden');
1215
		}
1216
		$file_name = $this->get_file_name_param();
1217
		if (!$this->is_valid_file_object($file_name)) {
1218
			return $this->header('HTTP/1.1 404 Not Found');
1219
		}
1220
		if ($redirect_header) {
1221
			return $this->header($redirect_header . ': ' . $this->get_download_url($file_name,
1222
				$this->get_version_param(), true));
1223
		}
1224
		$file_path = $this->get_upload_path($file_name, $this->get_version_param());
1225
		// Prevent browsers from MIME-sniffing the content-type:
1226
		$this->header('X-Content-Type-Options: nosniff');
1227
		if (!preg_match($this->options['inline_file_types'], $file_name)) {
1228
			$this->header('Content-Type: application/octet-stream');
1229
			$this->header('Content-Disposition: attachment; filename="' . $file_name . '"');
1230
		} else {
1231
			$this->header('Content-Type: ' . $this->get_file_type($file_path));
1232
			$this->header('Content-Disposition: inline; filename="' . $file_name . '"');
1233
		}
1234
		$this->header('Content-Length: ' . $this->get_file_size($file_path));
1235
		$this->header('Last-Modified: ' . gmdate('D, d M Y H:i:s T', filemtime($file_path)));
1236
		$this->readfile($file_path);
1237
	}
2121 lars 1238
 
2144 lars 1239
	protected function send_content_type_header()
1240
	{
1241
		$this->header('Vary: Accept');
1242
		if (strpos($this->get_server_var('HTTP_ACCEPT'), 'application/json') !== false) {
1243
			$this->header('Content-type: application/json');
1244
		} else {
1245
			$this->header('Content-type: text/plain');
1246
		}
1247
	}
2121 lars 1248
 
2144 lars 1249
	protected function send_access_control_headers()
1250
	{
1251
		$this->header('Access-Control-Allow-Origin: ' . $this->options['access_control_allow_origin']);
1252
		$this->header('Access-Control-Allow-Credentials: ' . ($this->options['access_control_allow_credentials'] ?
1253
			'true' : 'false'));
1254
		$this->header('Access-Control-Allow-Methods: ' . implode(', ', $this->options['access_control_allow_methods']));
1255
		$this->header('Access-Control-Allow-Headers: ' . implode(', ', $this->options['access_control_allow_headers']));
1256
	}
2121 lars 1257
 
2144 lars 1258
	public function generate_response($content, $print_response = true)
1259
	{
1260
		$this->response = $content;
1261
		if ($print_response) {
1262
			$json = json_encode($content);
1263
			$redirect = stripslashes($this->get_post_param('redirect'));
1264
			if ($redirect && preg_match($this->options['redirect_allow_target'], $redirect)) {
1265
				$this->header('Location: ' . sprintf($redirect, rawurlencode($json)));
1266
				return;
1267
			}
1268
			$this->head();
1269
			if ($this->get_server_var('HTTP_CONTENT_RANGE')) {
1270
				$files = isset($content[$this->options['param_name']]) ? $content[$this->
1271
					options['param_name']] : null;
1272
				if ($files && is_array($files) && is_object($files[0]) && $files[0]->size) {
1273
					$this->header('Range: 0-' . ($this->fix_integer_overflow((int)$files[0]->size) -
1274
						1));
1275
				}
1276
			}
1277
			$this->body($json);
1278
		}
1279
		return $content;
1280
	}
2121 lars 1281
 
2144 lars 1282
	public function get_response()
1283
	{
1284
		return $this->response;
1285
	}
2121 lars 1286
 
2144 lars 1287
	public function head()
1288
	{
1289
		$this->header('Pragma: no-cache');
1290
		$this->header('Cache-Control: no-store, no-cache, must-revalidate');
1291
		$this->header('Content-Disposition: inline; filename="files.json"');
1292
		// Prevent Internet Explorer from MIME-sniffing the content-type:
1293
		$this->header('X-Content-Type-Options: nosniff');
1294
		if ($this->options['access_control_allow_origin']) {
1295
			$this->send_access_control_headers();
1296
		}
1297
		$this->send_content_type_header();
1298
	}
2121 lars 1299
 
2144 lars 1300
	public function get($print_response = true)
1301
	{
1302
		if ($print_response && $this->get_query_param('download')) {
1303
			return $this->download();
1304
		}
1305
		$file_name = $this->get_file_name_param();
1306
		if ($file_name) {
1307
			$response = array($this->get_singular_param_name() => $this->get_file_object($file_name));
1308
		} else {
1309
			$response = array($this->options['param_name'] => $this->get_file_objects());
1310
		}
1311
		return $this->generate_response($response, $print_response);
1312
	}
2121 lars 1313
 
2144 lars 1314
	public function post($print_response = true)
1315
	{
1316
		if ($this->get_query_param('_method') === 'DELETE') {
1317
			return $this->delete($print_response);
1318
		}
1319
		$upload = $this->get_upload_data($this->options['param_name']);
1320
		// Parse the Content-Disposition header, if available:
1321
		$content_disposition_header = $this->get_server_var('HTTP_CONTENT_DISPOSITION');
1322
		$file_name = $content_disposition_header ? rawurldecode(preg_replace('/(^[^"]+")|("$)/',
1323
			'', $content_disposition_header)) : null;
1324
		// Parse the Content-Range header, which has the following form:
1325
		// Content-Range: bytes 0-524287/2000000
1326
		$content_range_header = $this->get_server_var('HTTP_CONTENT_RANGE');
1327
		$content_range = $content_range_header ? preg_split('/[^0-9]+/', $content_range_header) : null;
1328
		$size = $content_range ? $content_range[3] : null;
1329
		$files = array();
1330
		if ($upload) {
1331
			if (is_array($upload['tmp_name'])) {
1332
				// param_name is an array identifier like "files[]",
1333
				// $upload is a multi-dimensional array:
1334
				foreach ($upload['tmp_name'] as $index => $value) {
1335
					$files[] = $this->handle_file_upload($upload['tmp_name'][$index], $file_name ? $file_name :
1336
						$upload['name'][$index], $size ? $size : $upload['size'][$index], $upload['type'][$index],
1337
						$upload['error'][$index], $index, $content_range);
1338
				}
1339
			} else {
1340
				// param_name is a single object identifier like "file",
1341
				// $upload is a one-dimensional array:
1342
				$files[] = $this->handle_file_upload(isset($upload['tmp_name']) ? $upload['tmp_name'] : null,
1343
					$file_name ? $file_name : (isset($upload['name']) ? $upload['name'] : null), $size ?
1344
					$size : (isset($upload['size']) ? $upload['size'] : $this->get_server_var('CONTENT_LENGTH')),
1345
					isset($upload['type']) ? $upload['type'] : $this->get_server_var('CONTENT_TYPE'),
1346
					isset($upload['error']) ? $upload['error'] : null, null, $content_range);
1347
			}
1348
		}
1349
		$response = array($this->options['param_name'] => $files);
1350
		return $this->generate_response($response, $print_response);
1351
	}
2121 lars 1352
 
2144 lars 1353
	public function delete($print_response = true)
1354
	{
1355
		$file_names = $this->get_file_names_params();
1356
		if (empty($file_names)) {
1357
			$file_names = array($this->get_file_name_param());
1358
		}
1359
		$response = array();
1360
		foreach ($file_names as $file_name) {
1361
			$file_path = $this->get_upload_path($file_name);
1362
			$success = is_file($file_path) && $file_name[0] !== '.' && unlink($file_path);
1363
			if ($success) {
1364
				foreach ($this->options['image_versions'] as $version => $options) {
1365
					if (!empty($version)) {
1366
						$file = $this->get_upload_path($file_name, $version);
1367
						if (is_file($file)) {
1368
							unlink($file);
1369
						}
1370
					}
1371
				}
1372
			}
1373
			$response[$file_name] = $success;
1374
		}
1375
		return $this->generate_response($response, $print_response);
1376
	}
2121 lars 1377
 
2144 lars 1378
	protected function basename($filepath, $suffix = null)
1379
	{
1380
		$splited = preg_split('/\//', rtrim($filepath, '/ '));
1381
		return substr(basename('X' . $splited[count($splited) - 1], $suffix), 1);
1382
	}
2121 lars 1383
}