-
Notifications
You must be signed in to change notification settings - Fork 19
/
upload.class.php
1643 lines (1428 loc) · 51.5 KB
/
upload.class.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
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/* Reminder: always indent with 4 spaces (no tabs). */
// +---------------------------------------------------------------------------+
// | Geeklog 2.1 |
// +---------------------------------------------------------------------------+
// | upload.class.php |
// | |
// | Geeklog file upload class library. |
// +---------------------------------------------------------------------------+
// | Copyright (C) 2002-2009 by the following authors: |
// | |
// | Authors: Tony Bibbs - tony AT tonybibbs DOT com |
// | Dirk Haun - dirk AT haun-online DOT de |
// +---------------------------------------------------------------------------+
// | |
// | This program is free software; you can redistribute it and/or |
// | modify it under the terms of the GNU General Public License |
// | as published by the Free Software Foundation; either version 2 |
// | of the License, or (at your option) any later version. |
// | |
// | This program is distributed in the hope that it will be useful, |
// | but WITHOUT ANY WARRANTY; without even the implied warranty of |
// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
// | GNU General Public License for more details. |
// | |
// | You should have received a copy of the GNU General Public License |
// | along with this program; if not, write to the Free Software Foundation, |
// | Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. |
// | |
// +---------------------------------------------------------------------------+
/**
* This class will allow you to securely upload one or more files from a form
* submitted via POST method. Please read documentation as there are a number of
* security related features that will come in handy for you.
*
* @author Tony Bibbs, tony AT tonybibbs DOT com
*/
class Upload
{
/**
* @var array
*/
private $_errors = array();
/**
* @var array
*/
private $_warnings = array();
/**
* @var array
*/
private $_debugMessages = array();
/**
* @var array
*/
private $_allowedMimeTypes = array();
/**
* @var array
*/
private $_availableMimeTypes = array();
/**
* @var array
*/
private $_filesToUpload = array();
/**
* @var array
*/
private $_currentFile = array();
/**
* @var array
*/
private $_allowedIPS = array();
/**
* @var array
*/
private $_uploadedFiles = array();
/**
* @var int Pixels
*/
private $_maxImageWidth = 300;
/**
* @var int Pixels
*/
private $_maxImageHeight = 300;
/**
* @var int in bytes
*/
private $_maxFileSize = 1048576;
/**
* @var int (0-100)
*/
private $_jpegQuality = 0;
/**
* @var string
*/
private $_pathToMogrify = '';
/**
* @var string
*/
private $_pathToNetPBM = '';
/**
* @var string
*/
private $_imageLib = '';
/**
* @var bool
*/
private $_autoResize = false;
/**
* @var bool
*/
private $_keepOriginalImage = false;
/**
* @var int
*/
private $_maxFileUploadsPerForm = 5;
/**
* @var string
*/
private $_fileUploadDirectory = '';
/**
* @var string
*/
private $_fileNames = '';
/**
* @var string
*/
private $_permissions = '';
/**
* @var string
*/
private $_logFile = '';
/**
* @var bool
*/
private $_doLogging = false;
/**
* @var bool
*/
private $_continueOnError = false;
/**
* @var bool
*/
private $_debug = false;
/**
* @var bool
*/
private $_limitByIP = false;
/**
* @var int
*/
private $_imageIndex = 0;
/**
* @var bool
*/
private $_ignoreMimeTest = false;
/**
* @var string
*/
private $_thumbsDirectory = '';
/**
* Constructor
*/
public function __construct()
{
$this->_setAvailableMimeTypes();
}
/**
* Adds a warning that was encountered
*
* @param string $warningText Text of warning
*/
private function _addWarning($warningText)
{
$numWarnings = count($this->_warnings);
$numWarnings = $numWarnings + 1;
$this->_warnings[$numWarnings] = $warningText;
if ($this->loggingEnabled()) {
$this->_logItem('Warning', $warningText);
}
}
/**
* Adds an error that was encountered
*
* @param string $errorText Text of error
*/
private function _addError($errorText)
{
$numErrors = count($this->_errors);
$numErrors = $numErrors + 1;
$this->_errors[$numErrors] = $errorText;
if ($this->loggingEnabled()) {
$this->_logItem('Error', $errorText);
}
}
/**
* Adds a debug message
*
* @param string $debugText Text of debug message
*/
private function _addDebugMsg($debugText)
{
$numMessages = count($this->_debugMessages);
$numMessages = $numMessages + 1;
$this->_debugMessages[$numMessages] = $debugText;
if ($this->loggingEnabled()) {
$this->_logItem('Debug', $debugText);
}
}
/**
* Logs an item to the log file
*
* @param string $logType can be 'warning' or 'error'
* @param string $text Text to log to log file
* @return boolean Whether or not we successfully logged an item
*/
private function _logItem($logType, $text)
{
$timestamp = strftime("%c");
if (!$file = fopen($this->_logFile, 'a')) {
// couldn't open log file for writing so let's disable logging and add an error
$this->setLogging(false);
$this->_addError('Error writing to log file: ' . $this->_logFile . '. Logging has been disabled');
return false;
}
fputs($file, "{$timestamp} - {$logType}: {$text} " . PHP_EOL);
fclose($file);
return true;
}
/**
* Defines superset of available Mime types.
*
* @param array $mimeTypes string array of valid mime types this object will accept
*/
private function _setAvailableMimeTypes($mimeTypes = array())
{
if (count($mimeTypes) === 0) {
$this->_availableMimeTypes =
array(
'application/x-gzip-compressed' => '.tar.gz,.tgz',
'application/x-zip-compressed' => '.zip',
'application/x-tar' => '.tar',
'application/x-gtar' => '.tar',
'text/plain' => '.phps,.txt,.inc',
'text/html' => '.html,.htm',
'image/bmp' => '.bmp,.ico',
'image/gif' => '.gif',
'image/pjpeg' => '.jpg,.jpeg',
'image/jpeg' => '.jpg,.jpeg',
'image/png' => '.png',
'image/x-png' => '.png',
'audio/mpeg' => '.mp3',
'audio/wav' => '.wav',
'application/pdf' => '.pdf',
'application/x-shockwave-flash' => '.swf',
'application/msword' => '.doc',
'application/vnd.ms-excel' => '.xls',
'application/octet-stream' => '.fla,.psd',
);
} else {
$this->_availableMimeTypes = $mimeTypes;
}
}
/**
* Checks if current file is an image
*
* @return boolean returns true if file is an image, otherwise false
*/
private function _isImage()
{
if (strpos($this->_currentFile['type'], 'image/') === 0) {
$isImage = true;
} else {
$isImage = false;
}
if ($this->_debug) {
$msg = 'File, ' . $this->_currentFile['name'] . ' is of mime type '
. $this->_currentFile['type'];
if (!$isImage) {
$msg .= ' and is NOT an image file.';
} else {
$msg .= ' and IS an image file.';
}
$this->_addDebugMsg($msg);
}
return $isImage;
}
/**
* Verifies the file size meets specified size limitations
*
* @return boolean returns true of file size is within our limits otherwise false
*/
private function _fileSizeOk()
{
if ($this->_debug) {
$this->_addDebugMsg('File size for ' . $this->_currentFile['name'] . ' is ' . $this->_currentFile['size'] . ' bytes');
}
return ($this->_currentFile['size'] <= $this->_maxFileSize);
}
/**
* Checks to see if file is an image and, if so, whether or not
* it meets width and height limitations
*
* @param bool $doResizeCheck
* @return bool returns true if image height/width meet our limitations otherwise false
*/
private function _imageSizeOK($doResizeCheck = true)
{
if (!$this->_isImage()) {
return true;
}
$imageInfo = $this->_getImageDimensions();
$sizeOK = true;
if ($this->_debug) {
$this->_addDebugMsg('Max allowed width = ' . $this->_maxImageWidth . ', Image width = ' . $imageInfo['width']);
$this->_addDebugMsg('Max allowed height = ' . $this->_maxImageHeight . ', Image height = ' . $imageInfo['height']);
}
// If user set _autoResize then ignore these settings and try to resize on upload
if (($doResizeCheck && !($this->_autoResize)) || (!($doResizeCheck))) {
if ($imageInfo['width'] > $this->_maxImageWidth) {
$sizeOK = false;
if ($doResizeCheck) {
$this->_addError('Image, ' . $this->_currentFile['name'] . ' does not meet width limitations (is: ' . $imageInfo['width'] . ', max: ' . $this->_maxImageWidth . ')');
}
}
if ($imageInfo['height'] > $this->_maxImageHeight) {
$sizeOK = false;
if ($doResizeCheck) {
$this->_addError('Image, ' . $this->_currentFile['name'] . ' does not meet height limitations (is: ' . $imageInfo['height'] . ', max: ' . $this->_maxImageHeight . ')');
}
}
}
if ($this->_debug) {
$this->_addDebugMsg('File, ' . $this->_currentFile['name'] . ' has a width of '
. $imageInfo['width'] . ' and a height of ' . $imageInfo['height']);
}
return $sizeOK;
}
/**
* Gets the width and height of an image
*
* @return array Array with width and height of current image
*/
private function _getImageDimensions()
{
$dimensions = getimagesize($this->_currentFile['tmp_name']);
if ($this->_debug) {
$this->_addDebugMsg('in _getImageDimensions I got a width of ' . $dimensions[0] . ', and a height of ' . $dimensions[1]);
}
return array('width' => $dimensions[0], 'height' => $dimensions[1]);
}
/**
* Calculate the factor to scale images with if they're not meeting
* the size restrictions.
*
* @param int $width width of the unscaled image
* @param int $height height of the unscaled image
* @return double resize factor
*/
private function _calcSizeFactor($width, $height) // 1000
{
if (($width > $this->_maxImageWidth) ||
($height > $this->_maxImageHeight)
) {
// get both size factors that would resize one dimension correctly
$sizeFactorWidth = (double) ($this->_maxImageWidth / $width);
$sizeFactorHeight = (double) ($this->_maxImageHeight / $height);
// check if the height is ok after resizing the width
if (($height * $sizeFactorWidth) > ($this->_maxImageHeight)) {
// if no, get new size factor from height instead
$sizeFactor = $sizeFactorHeight;
} else {
// otherwise the width factor it ok to fit max dimensions
$sizeFactor = $sizeFactorWidth;
}
} else {
$sizeFactor = 1.0;
}
return $sizeFactor;
}
/**
* Keep the original (unscaled) image file, if configured.
*
* @param string $filename name of uploaded file
* @return boolean true: okay, false: an error occurred
*/
private function _keepOriginalFile($filename)
{
if ($this->_keepOriginalImage) {
$lFilename_large = substr_replace($this->_getDestinationName(),
'_original.', strrpos($this->_getDestinationName(), '.'), 1);
$lFilename_large_complete = $this->_fileUploadDirectory . '/'
. $lFilename_large;
if (!copy($filename, $lFilename_large_complete)) {
$this->_addError("Couldn't copy $filename to $lFilename_large_complete. You'll need to remove both files.");
$this->printErrors();
return false;
} else {
$this->createThumbnail($lFilename_large);
}
}
return true;
}
/**
* Gets destination file name for current file
*
* @return string returns destination file name
*/
private function _getDestinationName()
{
if (is_array($this->_fileNames)) {
$name = $this->_fileNames[$this->_imageIndex];
}
if (empty($name)) {
$name = $this->_currentFile['name'];
}
return $name;
}
/**
* Gets permissions for a file. This is used to do a chmod
*
* @return string returns final permissions for current file
*/
private function _getPermissions()
{
if (is_array($this->_permissions)) {
if (count($this->_permissions) > 1) {
$perms = $this->_permissions[$this->_imageIndex];
} else {
$perms = $this->_permissions[0];
}
}
if (empty($perms)) {
$perms = '';
}
return $perms;
}
/**
* This function actually completes the upload of a file
*
* @return boolean true if copy succeeds otherwise false
*/
private function _copyFile()
{
if (!is_writable($this->_fileUploadDirectory)) {
// Developer didn't check return value of setPath() method which would
// have told them the upload directory was not writable. Error out now
$this->_addError('Specified upload directory, ' . $this->_fileUploadDirectory . ' exists but is not writable');
return false;
}
$sizeOK = true;
if (!($this->_imageSizeOK(false)) && $this->_autoResize) {
$imageInfo = $this->_getImageDimensions();
if ($imageInfo['width'] > $this->_maxImageWidth) {
$sizeOK = false;
}
if ($imageInfo['height'] > $this->_maxImageHeight) {
$sizeOK = false;
}
}
if (isset($this->_currentFile['non_upload']) && $this->_currentFile['non_upload'] == true) {
// Not from the upload file dialogue so just move
$returnMove = rename($this->_currentFile['tmp_name'], $this->_fileUploadDirectory . '/' . $this->_getDestinationName());
} else {
if (isset($this->_currentFile['_gl_data_dir']) &&
$this->_currentFile['_gl_data_dir']
) {
// uploaded file was involved in a recreated POST after an expired
// token - can't use move_uploaded_file() here
$returnMove = rename($this->_currentFile['tmp_name'], $this->_fileUploadDirectory . '/' . $this->_getDestinationName());
} else {
$returnMove = move_uploaded_file($this->_currentFile['tmp_name'], $this->_fileUploadDirectory . '/' . $this->_getDestinationName());
}
}
if (!$sizeOK) {
// OK, resize
$sizeFactor = $this->_calcSizeFactor($imageInfo['width'], $imageInfo['height']);
$newWidth = (int) ($imageInfo['width'] * $sizeFactor);
$newHeight = (int) ($imageInfo['height'] * $sizeFactor);
$this->_addDebugMsg('Going to resize image to ' . $newWidth . 'x'
. $newHeight . ' using ' . $this->_imageLib);
$filename = $this->_fileUploadDirectory . '/' . $this->_getDestinationName();
if (!$this->_keepOriginalFile($filename)) {
exit;
}
if ($this->_imageLib == 'imagemagick') {
$newSize = $newWidth . 'x' . $newHeight;
$quality = '';
if ($this->_jpegQuality > 0) {
$quality = sprintf(' -quality %d', $this->_jpegQuality);
}
$cmd = $this->_pathToMogrify . $quality . ' -resize ' . $newSize . ' "' . $filename . '" 2>&1';
$this->_addDebugMsg('Attempting to resize with this command (imagemagick): ' . $cmd);
exec($cmd, $mogrify_output, $retval);
} elseif ($this->_imageLib === 'netpbm') {
$cmd = $this->_pathToNetPBM;
$cmd_end = " '" . $filename . "' | " . $this->_pathToNetPBM . 'pnmscale -xsize=' . $newWidth . ' -ysize=' . $newHeight . ' | ' . $this->_pathToNetPBM;
// convert to pnm, resize, convert back
if (($this->_currentFile['type'] == 'image/png') ||
($this->_currentFile['type'] == 'image/x-png')
) {
$tempFile = $this->_fileUploadDirectory . '/tmp.png';
$cmd .= 'pngtopnm ' . $cmd_end . 'pnmtopng > ' . $tempFile;
} elseif (($this->_currentFile['type'] == 'image/jpeg') ||
($this->_currentFile['type'] == 'image/pjpeg')
) {
$tempFile = $this->_fileUploadDirectory . '/tmp.jpg';
$quality = '';
if ($this->_jpegQuality > 0) {
$quality = sprintf(' -quality=%d', $this->_jpegQuality);
}
$cmd .= 'jpegtopnm ' . $cmd_end . 'pnmtojpeg' . $quality . ' > ' . $tempFile;
} elseif ($this->_currentFile['type'] == 'image/gif') {
$tempFile = $this->_fileUploadDirectory . '/tmp.gif';
$cmd .= 'giftopnm ' . $cmd_end . 'ppmquant 256 | '
. $this->_pathToNetPBM . 'ppmtogif > ' . $tempFile;
} else {
$this->_addError("Image format of file $filename is not supported.");
$this->printErrors();
exit;
}
$this->_addDebugMsg('Attempting to resize with this command (netpbm): ' . $cmd);
exec($cmd, $netpbm_output, $retval);
// Move tmp file to actual file
if (!copy($tempFile, $filename)) {
$this->_addError("Couldn't copy $tempFile to $filename. You'll need remove both files");
$this->printErrors();
exit;
} else {
// resize with netpbm worked, now remove tmpfile
if (!unlink($tempFile)) {
$this->_addError("Couldn't delete $tempFile. You'll need to remove it manually");
$this->printErrors();
exit;
}
}
} elseif ($this->_imageLib === 'gdlib') {
if (!function_exists('gd_info')) {
$this->_addError('GD library does not seem to be enabled.');
$this->printErrors();
exit;
}
$image_source = $this->_createImageFromFile_gdlib($filename);
// do resize
// ImageCreateTrueColor may throw a fatal error on some PHP
// versions when GD2 is not installed. Ugly workaround, but
// there seems to be no better way. Also see the discussion at
// http://php.net/ImageCreateTrueColor
$image_dest = @imagecreatetruecolor($newWidth, $newHeight);
if (!$image_dest) {
$thumb = imagecreate($newWidth, $newHeight);
if ($this->_jpegQuality > 0) {
imagejpeg($thumb, $filename, $this->_jpegQuality);
} else {
imagejpeg($thumb, $filename);
}
imagedestroy($thumb);
$image_dest = @imagecreatefromjpeg($filename);
unlink($filename);
}
// Prevent transparent area of a JPEG image from being painted black
if (is_callable('imagealphablending') && is_callable('imagesavealpha')) {
imagealphablending($image_dest, false);
imagesavealpha($image_dest, true);
}
imagecopyresampled($image_dest, $image_source,
0, 0, 0, 0, $newWidth, $newHeight,
$imageInfo['width'], $imageInfo['height']);
$this->_outputImageToFile_gdlib($image_dest, $filename);
}
if ($retval > 0) {
if ($this->_imageLib === 'imagemagick') {
$this->_addError('Image, ' . $this->_currentFile['name']
. ' had trouble being resized: ' . $mogrify_output[0]);
} elseif ($this->_imageLib === 'netpbm') {
$this->_addError('Image, ' . $this->_currentFile['name']
. ' had trouble being resized: ' . $netpbm_output[0]);
}
$this->printErrors();
exit;
} else {
$this->_addDebugMsg('Image, ' . $this->_currentFile['name'] . ' was resized from ' . $imageInfo['width'] . 'x' . $imageInfo['height'] . ' to ' . $newSize);
}
}
$returnChmod = true;
$perms = $this->_getPermissions();
if (!empty($perms)) {
$returnChmod = chmod($this->_fileUploadDirectory . '/' . $this->_getDestinationName(), octdec($perms));
}
if ($returnMove && $returnChmod) {
return true;
} else {
if (!$returnMove) {
$this->_addError('Upload of ' . $this->_currentFile['name'] . ' failed.');
}
if (!$returnChmod) {
$this->_addError('Chmod of ' . $this->_currentFile['name'] . ' to ' . $perms . ' failed');
}
return false;
}
}
/**
* Sets the path to where the mogrify ImageMagick function is
*
* @param string $path_to_mogrify Absolute path to mogrify
* @return boolean True if set, false otherwise
*/
public function setMogrifyPath($path_to_mogrify)
{
$this->_imageLib = 'imagemagick';
$this->_pathToMogrify = $path_to_mogrify;
return true;
}
/**
* Sets the path to where the netpbm utilities are
*
* @param string $path_to_netpbm Absolute path to netpbm dir
* @return boolean True if set, false otherwise
*/
public function setNetPBM($path_to_netpbm)
{
$this->_imageLib = 'netpbm';
$this->_pathToNetPBM = $path_to_netpbm;
return true;
}
/**
* Configure upload to use GD library
*
* @return boolean True if set, false otherwise
*/
public function setGDLib()
{
$this->_imageLib = 'gdlib';
return true;
}
/**
* Sets mode to automatically resize images that are either too wide or
* too tall
*
* @param boolean $switch True to turn on, false to turn off
*/
public function setAutomaticResize($switch)
{
$this->_autoResize = $switch;
}
/**
* Allows you to override default max file size
*
* @param int $size_in_bytes Max. size for uploaded files
* @return boolean true if we set it OK, otherwise false
*/
public function setMaxFileSize($size_in_bytes)
{
if (!is_numeric($size_in_bytes)) {
return false;
}
$this->_maxFileSize = $size_in_bytes;
return true;
}
/**
* Allows you to override default max. image dimensions
*
* @param int $width_pixels Max. width allowed
* @param int $height_pixels Max. height allowed
* @return boolean true if we set values OK, otherwise false
*/
public function setMaxDimensions($width_pixels, $height_pixels)
{
if (!is_numeric($width_pixels) || !is_numeric($height_pixels)) {
return false;
}
$this->_maxImageWidth = $width_pixels;
$this->_maxImageHeight = $height_pixels;
return true;
}
/**
* Sets the max number of files that can be uploaded per form
*
* @param int $maxFiles Maximum number of files to allow. Default is 5
* @return boolean True if set, false otherwise
*/
public function setMaxFileUploads($maxFiles)
{
$this->_maxFileUploadsPerForm = $maxFiles;
return true;
}
/**
* Allows you to keep the original (unscaled) image.
*
* @param boolean $keepIt true = keep original, false = don't
* @return boolean true if we set values OK, otherwise false
*/
public function keepOriginalImage($keepIt)
{
$this->_keepOriginalImage = $keepIt;
return true;
}
/**
* Set JPEG quality
* NOTE: The 'quality' is an arbitrary value used by the IJG library.
* It is not a percent value! The default (and a good value) is 75.
*
* @param int $quality JPEG quality (0-100)
* @return boolean true if we set values OK, otherwise false
*/
public function setJpegQuality($quality)
{
if (($quality < 0) || ($quality > 100)) {
return false;
}
$this->_jpegQuality = $quality;
return true;
}
/**
* Extra security option that forces all attempts to upload a file to be done
* so from a set of VERY specific IP's. This is only good for those who are
* paranoid
*
* @param array $validIPS Array of valid IP addresses to allow file uploads from
* @return boolean returns true if we successfully limited the IP's, otherwise false
*/
public function limitByIP($validIPS = array('127.0.0.1'))
{
if (is_array($validIPS)) {
$this->_limitByIP = true;
$this->_allowedIPS = $validIPS;
return true;
} else {
$this->_addError('Bad call to method limitByIP(), must pass array of valid IP addresses');
return false;
}
}
/**
* Allows you to specify whether or not to continue processing other files
* when an error occurs or exit immediately. Default is to exit immediately
* NOTE: this only affects the actual file upload process.
*
* @param boolean $switch true or false
*/
public function setContinueOnError($switch)
{
$this->_continueOnError = (bool) $switch;
}
/**
* Sets log file
*
* @param string $logFile fully qualified path to log files
* @return boolean returns true if we set the log file, otherwise false
*/
public function setLogFile($logFile = '')
{
if (empty($logFile) || !file_exists($logFile)) {
// Log file doesn't exist, produce warning
$this->_addWarning('Log file, ' . $logFile . ' does not exists, setLogFile() method failed');
$this->_doLogging = false;
return false;
}
$this->_logFile = $logFile;
return true;
}
/**
* Enables/disables logging of errors and warnings
*
* @param boolean $switch flag, true or false
*/
public function setLogging($switch)
{
if ($switch && !empty($this->_logFile)) {
$this->_doLogging = true;
} else {
if ($switch && empty($this->_logFile)) {
$this->_addWarning('Unable to enable logging because no log file was set. Use setLogFile() method');
}
$this->_doLogging = false;
}
}
/**
* Returns whether or not logging is enabled
*
* @return boolean returns true if logging is enabled otherwise false
*/
public function loggingEnabled()
{
return $this->_doLogging;
}
/**
* Will force the debug messages in this class to be
* printed
*
* @param boolean $switch flag, true or false
*/
public function setDebug($switch)
{
if ($switch) {
$this->_debug = true;
// setting debugs implies logging is on too
$this->setLogging(true);
} else {
$this->_debug = false;
}
}
/**
* If enabled will ignore the MIME checks on file uploads
*
* @param boolean $switch flag, true or false
*/
public function setIgnoreMimeCheck($switch)
{
$this->_ignoreMimeTest = (bool) $switch;
}
/**
* This function will print any errors out. This is useful in debugging
*
* @param boolean $verbose whether or not to print immediately or return only a string
* @return string if $verbose is false it returns all errors otherwise just an empty string
*/
public function printErrors($verbose = true)
{
if (isset($this->_errors) && is_array($this->_errors)) {
$retval = '';
reset($this->_errors);
$numErrors = count($this->_errors);
for ($i = 1; $i <= $numErrors; $i++) {
if ($verbose) {
echo current($this->_errors) . '<br' . XHTML . '>' . PHP_EOL;
} else {
$retval .= current($this->_errors) . '<br' . XHTML . '>' . PHP_EOL;
}
next($this->_errors);
}
return $retval;
} else {
return '';
}
}
/**
* This function will print any warnings out. This is useful in debugging
*/
public function printWarnings()
{
if (isset($this->_warnings) && is_array($this->_warnings)) {
reset($this->_warnings);
$numWarnings = count($this->_warnings);
for ($i = 1; $i <= $numWarnings; $i++) {
echo current($this->_warnings) . '<br' . XHTML . '>' . PHP_EOL;
next($this->_warnings);
}
}
}
/**
* This function will print any debug messages out.
*/
public function printDebugMsgs()
{
if (isset($this->_debugMessages) && is_array($this->_debugMessages)) {
reset($this->_debugMessages);
$numMessages = count($this->_debugMessages);
for ($i = 1; $i <= $numMessages; $i++) {
echo current($this->_debugMessages) . '<br' . XHTML . '>' . PHP_EOL;
next($this->_debugMessages);
}
}
}
/**
* Returns if any errors have been encountered thus far
*
* @return boolean returns true if there were errors otherwise false
*/
public function areErrors()
{
return (count($this->_errors) > 0);
}
/**
* Sets allowed mime types for this instance
*
* @param array $mimeTypes Array of allowed mime types
*/
public function setAllowedMimeTypes($mimeTypes = array())