Subversion-Projekte lars-tiefland.ci

Revision

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