forked from flourishlib/flourish-classes
-
Notifications
You must be signed in to change notification settings - Fork 10
/
fUpload.php
714 lines (622 loc) · 21.1 KB
/
fUpload.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
<?php
/**
* Provides validation and movement of uploaded files
*
* @copyright Copyright (c) 2007-2012 Will Bond, others
* @author Will Bond [wb] <will@flourishlib.com>
* @author Will Bond, iMarc LLC [wb-imarc] <will@imarc.net>
* @author Brian Tam, [bt] <brian@imarc.net>
* @license http://flourishlib.com/license
*
* @package Flourish
* @link http://flourishlib.com/fUpload
*
*/
class fUpload
{
// The following constants allow for nice looking callbacks to static methods
const check = 'fUpload::check';
const count = 'fUpload::count';
const filter = 'fUpload::filter';
/**
* Checks to see if the field specified is a valid file upload field
*
* @throws fValidationException If `$throw_exception` is `TRUE` and the request was not a POST or the content type is not multipart/form-data
*
* @param string $field The field to check
* @param boolean $throw_exception If an exception should be thrown when there are issues with the form
* @return boolean If the field is a valid file upload field
*/
static public function check($field, $throw_exception=TRUE)
{
if (isset($_GET[$field]) && $_SERVER['REQUEST_METHOD'] != 'POST') {
if ($throw_exception) {
throw new fValidationException(
'Missing method="post" attribute in form tag'
);
}
return FALSE;
}
if (isset($_POST[$field]) && (!isset($_SERVER['CONTENT_TYPE']) || stripos($_SERVER['CONTENT_TYPE'], 'multipart/form-data') === FALSE)) {
if ($throw_exception) {
throw new fValidationException(
'Missing enctype="multipart/form-data" attribute in form tag'
);
}
return FALSE;
}
return isset($_FILES) && isset($_FILES[$field]) && is_array($_FILES[$field]);
}
/**
* Returns the number of files uploaded to a file upload array field
*
* @throws fValidationException If the form is not properly configured for file uploads
*
* @param string $field The field to get the number of files for
* @return integer The number of uploaded files
*/
static public function count($field)
{
if (!self::check($field)) {
throw new fValidationException(
'The field specified, %s, does not appear to be a file upload field',
$field
);
}
if (!is_array($_FILES[$field]['name'])) {
throw new fValidationException(
'The field specified, %s, does not appear to be an array file upload field',
$field
);
}
return sizeof($_FILES[$field]['name']);
}
/**
* Composes text using fText if loaded
*
* @param string $message The message to compose
* @param mixed $component A string or number to insert into the message
* @param mixed ...
* @return string The composed and possible translated message
*/
static protected function compose($message)
{
$args = array_slice(func_get_args(), 1);
if (class_exists('fText', FALSE)) {
return call_user_func_array(
array('fText', 'compose'),
array($message, $args)
);
} else {
return vsprintf($message, $args);
}
}
/**
* Removes individual file upload entries from an array of file inputs in `$_FILES` when no file was uploaded
*
* @throws fValidationException If the form is not properly configured for file uploads
*
* @param string $field The field to filter
* @return array The indexes of the files that were uploaded
*/
static public function filter($field)
{
$indexes = array();
$columns = array('name', 'type', 'tmp_name', 'error', 'size');
if (!self::count($field)) {
return;
}
foreach (array_keys($_FILES[$field]['name']) as $index) {
if ($_FILES[$field]['error'][$index] == UPLOAD_ERR_NO_FILE) {
foreach ($columns as $column) {
unset($_FILES[$field][$column][$index]);
}
} else {
$indexes[] = $index;
}
}
return $indexes;
}
/**
* If files starting with `.` can be uploaded
*
* @var boolean
*/
private $allow_dot_files = FALSE;
/**
* If PHP files can be uploaded
*
* @var boolean
*/
private $allow_php = FALSE;
/**
* The dimension restrictions for uploaded images
*
* @var array
*/
private $image_dimensions = array();
/**
* The dimension ratio restriction for uploaded images
*
* @var array
*/
private $image_ratio = array();
/**
* If existing files of the same name should be overwritten
*
* @var boolean
*/
private $enable_overwrite = FALSE;
/**
* The maximum file size in bytes
*
* @var integer
*/
private $max_size = 0;
/**
* The error message to display if the mime types do not match
*
* @var string
*/
private $mime_type_message = NULL;
/**
* The mime types of files accepted
*
* @var array
*/
private $mime_types = array();
/**
* If the file upload is required
*
* @var boolean
*/
private $required = TRUE;
/**
* All requests that hit this method should be requests for callbacks
*
* @internal
*
* @param string $method The method to create a callback for
* @return callback The callback for the method requested
*/
public function __get($method)
{
return array($this, $method);
}
/**
* Sets the upload class to allow files starting with a `.`
*
* Files starting with `.` may change the behaviour of web servers,
* for instance `.htaccess` files for Apache.
*
* @return void
*/
public function allowDotFiles()
{
$this->allow_dot_files = TRUE;
}
/**
* Sets the upload class to allow PHP files
*
* @return void
*/
public function allowPHP()
{
$this->allow_php = TRUE;
}
/**
* Set the class to overwrite existing files in the destination directory instead of renaming the file
*
* @return void
*/
public function enableOverwrite()
{
$this->enable_overwrite = TRUE;
}
/**
* Returns the `$_FILES` array for the field specified.
*
* @param string $field The field to get the file array for
* @param mixed $index If the field is an array file upload field, use this to specify which array index to return
* @return array The file info array from `$_FILES`
*/
private function extractFileUploadArray($field, $index=NULL)
{
if ($index === NULL) {
return $_FILES[$field];
}
if (!is_array($_FILES[$field]['name'])) {
throw new fValidationException(
'The field specified, %s, does not appear to be an array file upload field',
$field
);
}
if (!isset($_FILES[$field]['name'][$index])) {
throw new fValidationException(
'The index specified, %1$s, is invalid for the field %2$s',
$index,
$field
);
}
$file_array = array();
$file_array['name'] = $_FILES[$field]['name'][$index];
$file_array['type'] = $_FILES[$field]['type'][$index];
$file_array['tmp_name'] = $_FILES[$field]['tmp_name'][$index];
$file_array['error'] = $_FILES[$field]['error'][$index];
$file_array['size'] = $_FILES[$field]['size'][$index];
return $file_array;
}
/**
* Moves an uploaded file from the temp directory to a permanent location
*
* @throws fValidationException When the form is not setup for file uploads, the `$directory` is somehow invalid or ::validate() thows an exception
*
* @param string|fDirectory $directory The directory to upload the file to
* @param string $field The file upload field to get the file from
* @param mixed $index If the field was an array file upload field, upload the file corresponding to this index
* @return fFile|NULL An fFile (or fImage) object, or `NULL` if no file was uploaded
*/
public function move($directory, $field, $index=NULL)
{
if (!is_object($directory)) {
$directory = new fDirectory($directory);
}
if (!$directory->isWritable()) {
throw new fEnvironmentException(
'The directory specified, %s, is not writable',
$directory->getPath()
);
}
if (!self::check($field)) {
throw new fValidationException(
'The field specified, %s, does not appear to be a file upload field',
$field
);
}
$file_array = $this->extractFileUploadArray($field, $index);
$error = $this->validateField($file_array);
if ($error) {
throw new fValidationException($error);
}
// This will only ever be true if the file is optional
if ($file_array['name'] == '' || $file_array['tmp_name'] == '' || $file_array['size'] == 0) {
return NULL;
}
$file_name = fFilesystem::makeURLSafe($file_array['name']);
$file_name = $directory->getPath() . $file_name;
if (!$this->enable_overwrite) {
$file_name = fFilesystem::makeUniqueName($file_name);
}
if (!move_uploaded_file($file_array['tmp_name'], $file_name)) {
throw new fEnvironmentException('There was an error moving the uploaded file');
}
if (!chmod($file_name, 0644)) {
throw new fEnvironmentException('Unable to change permissions on the uploaded file');
}
return fFilesystem::createObject($file_name);
}
/**
* Get uploaded parameters from fUpload
*
* @param string $parameter The file upload array field to get
* @param string $field The file upload field to get the file from
* @param mixed $index If the field was an array file upload field, upload the file corresponding to this index
* @return string|NULL the requested value, or `NULL` if no file was uploaded
*/
public function getParameter($parameter, $field, $index=NULL) {
$file_array = $this->extractFileUploadArray($field, $index);
// This will only ever be true if the file is optional
if ($file_array['name'] == '' || $file_array['tmp_name'] == '' || $file_array['size'] == 0) {
return NULL;
}
switch ($parameter) {
case 'name':
return $file_array['name'];
case 'size':
return $file_array['size'];
case 'type':
return $file_array['type'];
case 'contents':
return file_get_contents($file_array['tmp_name']);
default:
return NULL;
}
}
/**
* Sets the allowable dimensions for an uploaded image
*
* @param integer $min_width The minimum width - `0` for no minimum
* @param integer $min_height The minimum height - `0` for no minimum
* @param integer $max_width The maximum width - `0` for no maximum
* @param integer $max_height The maximum height - `0` for no maximum
* @return void
*/
public function setImageDimensions($min_width, $min_height, $max_width=0, $max_height=0)
{
if (!is_numeric($min_width) || $min_width < 0) {
throw new fProgrammerException(
'The minimum width specified, %s, is not an integer, or is less than 0',
$min_width
);
}
if (!is_numeric($min_height) || $min_height < 0) {
throw new fProgrammerException(
'The minimum height specified, %s, is not an integer, or is less than 0',
$min_height
);
}
if (!is_numeric($max_width) || $max_width < 0) {
throw new fProgrammerException(
'The maximum width specified, %s, is not an integer, or is less than 0',
$max_width
);
}
if (!is_numeric($max_height) || $max_height < 0) {
throw new fProgrammerException(
'The maximum height specified, %s, is not an integer, or is less than 0',
$max_height
);
}
settype($min_width, 'int');
settype($min_height, 'int');
settype($max_width, 'int');
settype($max_height, 'int');
// If everything is 0 then there are no restrictions
if (!$min_width && !$min_height && !$max_width && !$max_height) {
$this->image_dimensions = array();
return;
}
$this->image_dimensions = array(
'min_width' => $min_width,
'min_height' => $min_height,
'max_width' => $max_width,
'max_height' => $max_height
);
}
/**
* Sets the allowable dimensions for an uploaded image
*
* @param numeric $width The minimum ratio width
* @param numeric $height The minimum ratio height
* @param string $allow_excess_dimension The dimension that should allow for excess pixels
* @return void
*/
public function setImageRatio($width, $height, $allow_excess_dimension)
{
if (!is_numeric($width) || $width <= 0) {
throw new fProgrammerException(
'The width specified, %s, is not a number, or is less than or equal to 0',
$width
);
}
if (!is_numeric($height) || $height <= 0) {
throw new fProgrammerException(
'The height specified, %s, is not a number, or is less than or equal to 0',
$height
);
}
$valid_dimensions = array('width', 'height');
if (!in_array($allow_excess_dimension, $valid_dimensions)) {
throw new fProgrammerException(
'The allow excess dimension specified, %1$s, is not valid. Must be one of: %2$s.',
$allow_excess_dimension,
$valid_dimensions
);
}
$this->image_ratio = array(
'width' => $width,
'height' => $height,
'allow_excess_dimension' => $allow_excess_dimension
);
}
/**
* Sets the maximum size the uploaded file may be
*
* This method should be used with the
* [http://php.net/file-upload.post-method `MAX_FILE_SIZE`] hidden form
* input since the hidden form input will reject a file that is too large
* before the file completely uploads, while this method will wait until the
* whole file has been uploaded. This method should always be used since it
* is very easy for the `MAX_FILE_SIZE` post field to be manipulated on the
* client side.
*
* This method can only further restrict the
* [http://php.net/upload_max_filesize `upload_max_filesize` ini setting],
* it can not increase that setting. `upload_max_filesize` must be set
* in the php.ini (or an Apache configuration) since file uploads are
* handled before the request is handed off to PHP.
*
* @param string $size The maximum file size (e.g. `1MB`, `200K`, `10.5M`) - `0` for no limit
* @return void
*/
public function setMaxSize($size)
{
$ini_max_size = ini_get('upload_max_filesize');
$ini_max_size = (!is_numeric($ini_max_size)) ? fFilesystem::convertToBytes($ini_max_size) : $ini_max_size;
$size = fFilesystem::convertToBytes($size);
if ($size && $size > $ini_max_size) {
throw new fEnvironmentException(
'The requested max file upload size, %1$s, is larger than the %2$s ini setting, which is currently set at %3$s. The ini setting must be increased to allow files of this size.',
$size,
'upload_max_filesize',
$ini_max_size
);
}
$this->max_size = $size;
}
/**
* Sets the file mime types accepted
*
* @param array $mime_types The mime types to accept
* @param string $message The message to display if the uploaded file is not one of the mime type specified
* @return void
*/
public function setMIMETypes($mime_types, $message)
{
$this->mime_types = $mime_types;
$this->mime_type_message = $message;
}
/**
* Sets the file upload to be optional instead of required
*
* @return void
*/
public function setOptional()
{
$this->required = FALSE;
}
/**
* Validates the uploaded file, ensuring a file was actually uploaded and that is matched the restrictions put in place
*
* @throws fValidationException When the form is not configured for file uploads, no file is uploaded or the uploaded file violates the options set for this object
*
* @param string $field The field the file was uploaded through
* @param mixed $index If the field was an array of file uploads, this specifies which one to validate
* @param boolean $return_message If any validation error should be returned as a string instead of being thrown as an fValidationException
* @param string |$field
* @param boolean |$return_message
* @return NULL|string If `$return_message` is not `TRUE` or if no error occurs, `NULL`, otherwise a string error message
*/
public function validate($field, $index=NULL, $return_message=NULL)
{
if (is_bool($index) && $return_message === NULL) {
$return_message = $index;
$index = NULL;
}
if (!self::check($field)) {
throw new fValidationException(
'The field specified, %s, does not appear to be a file upload field',
$field
);
}
$file_array = $this->extractFileUploadArray($field, $index);
$error = $this->validateField($file_array);
if ($error) {
if ($return_message) {
return $error;
}
throw new fValidationException($error);
}
}
/**
* Validates a $_FILES array against the upload configuration
*
* @param array $file_array The $_FILES array for a single file
* @return string The validation error message
*/
private function validateField($file_array)
{
if (empty($file_array['name'])) {
if ($this->required) {
return self::compose('Please upload a file');
}
return NULL;
}
if ($file_array['error'] == UPLOAD_ERR_FORM_SIZE || $file_array['error'] == UPLOAD_ERR_INI_SIZE) {
$max_size = (!empty($_POST['MAX_FILE_SIZE'])) ? $_POST['MAX_FILE_SIZE'] : ini_get('upload_max_filesize');
$max_size = (!is_numeric($max_size)) ? fFilesystem::convertToBytes($max_size) : $max_size;
return self::compose(
'The file uploaded is over the limit of %s',
fFilesystem::formatFilesize($max_size)
);
}
if ($this->max_size && $file_array['size'] > $this->max_size) {
return self::compose(
'The file uploaded is over the limit of %s',
fFilesystem::formatFilesize($this->max_size)
);
}
if (empty($file_array['tmp_name']) || empty($file_array['size'])) {
if ($this->required) {
return self::compose('Please upload a file');
}
return NULL;
}
if (!empty($this->mime_types) && file_exists($file_array['tmp_name'])) {
$contents = file_get_contents($file_array['tmp_name'], FALSE, NULL, 0, 4096);
if (!in_array(fFile::determineMimeType($file_array, $contents), $this->mime_types)) {
return self::compose($this->mime_type_message);
}
}
if (!$this->allow_php) {
$file_info = fFilesystem::getPathInfo($file_array['name']);
if (in_array(strtolower($file_info['extension']), array('php', 'php4', 'php5'))) {
return self::compose('The file uploaded is a PHP file, but those are not permitted');
}
}
if (!$this->allow_dot_files) {
if (substr($file_array['name'], 0, 1) == '.') {
return self::compose('The name of the uploaded file may not being with a .');
}
}
if ($this->image_dimensions && file_exists($file_array['tmp_name'])) {
if (fImage::isImageCompatible($file_array['tmp_name'])) {
list($width, $height, $other) = getimagesize($file_array['tmp_name']);
if ($this->image_dimensions['min_width'] && $width < $this->image_dimensions['min_width']) {
return self::compose(
'The uploaded image is narrower than the minimum width of %spx',
$this->image_dimensions['min_width']
);
}
if ($this->image_dimensions['min_height'] && $height < $this->image_dimensions['min_height']) {
return self::compose(
'The uploaded image is shorter than the minimum height of %spx',
$this->image_dimensions['min_height']
);
}
if ($this->image_dimensions['max_width'] && $width > $this->image_dimensions['max_width']) {
return self::compose(
'The uploaded image is wider than the maximum width of %spx',
$this->image_dimensions['max_width']
);
}
if ($this->image_dimensions['max_height'] && $height > $this->image_dimensions['max_height']) {
return self::compose(
'The uploaded image is taller than the maximum height of %spx',
$this->image_dimensions['max_height']
);
}
}
}
if ($this->image_ratio && file_exists($file_array['tmp_name'])) {
if (fImage::isImageCompatible($file_array['tmp_name'])) {
list($width, $height, $other) = getimagesize($file_array['tmp_name']);
if ($this->image_ratio['allow_excess_dimension'] == 'width' && $width/$height < $this->image_ratio['width']/$this->image_ratio['height']) {
return self::compose(
'The uploaded image is too narrow for its height. The required ratio is %1$sx%2$s or wider.',
$this->image_ratio['width'],
$this->image_ratio['height']
);
}
if ($this->image_ratio['allow_excess_dimension'] == 'height' && $width/$height > $this->image_ratio['width']/$this->image_ratio['height']) {
return self::compose(
'The uploaded image is too short for its width. The required ratio is %1$sx%2$s or taller.',
$this->image_ratio['width'],
$this->image_ratio['height']
);
}
}
}
}
}
/**
* Copyright (c) 2007-2012 Will Bond <will@flourishlib.com>, others
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/