berkshelf-store 0.2.0

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