Subversion-Projekte lars-tiefland.ci

Revision

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