Subversion-Projekte lars-tiefland.ci

Revision

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