Subversion-Projekte lars-tiefland.ci

Revision

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

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