Subversion-Projekte lars-tiefland.ci

Revision

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