-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathphpFileHandler.php
More file actions
1208 lines (1105 loc) · 48 KB
/
Copy pathphpFileHandler.php
File metadata and controls
1208 lines (1105 loc) · 48 KB
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
/***
* phpFileHandler - All in one PHP file handling class
*/
class phpFileHandler {
/**
* The phpFileHandler Version number
* @var string
*/
public $Version = '1.0';
/**
* Is ... extension loaded?
* @var boolean $is_mbstring_ext Is the mbstring extension loaded?
* @var boolean $is_gd2_ext Is the gd2 extension loaded?
* @var boolean $is_allow_url_fopen Is 'allow_url_fopen' set to 'On' in php.ini ?
*/
public $is_mbstring_ext;
public $is_gd2_ext;
public $is_allow_url_fopen;
/**
* Got phpFileHandler->add_uploaded_files() called?
* @var boolean
*/
public $is_add_uploaded = false;
/**
* Shall @phpFileHandler->save() generate unique filenames?
* @var boolean
*/
public $is_uniq_filenames = true;
/**
* The string length generated by @phpFileHandler::uniqString() for the phpFileHandler->save() filenames
* Only when @phpFileHandler->$is_uniq_filenames = true
* @var integer
*/
public $uniq_string_length = 12;
/**
* The maximum allowed filesize in bytes
* '0' means no limit, NOTE that this does NOT represent the 'post_max_size' or 'upload_max_filesize' set in the php.ini,
* $_POST and $_FILES superglobals are empty if the the maximum '-> POST size is exceeded !
* @var integer
*/
public $MaxFileSize = 0;
/**
* The allowed file types
* @var array
*/
public $AllowedFileTypes;
/**
* Set to true to only let a file pass when it paases the $AllowedFileTypes AND file signature check
* * See -> guess_fileextension() for which file signatures can be detected
* @var boolean
*/
public $is_strict_filecheck = false;
/**
* An error String containing information about non fatal errors like invalid file uploads
* Secure for user output
* @var string
*/
//public $Error = '';
/**
* File packs
* @var array $Files_ready Files on the server ready for further usage
* @var array $Files_valid Valid sanitized files
* @var array $Files_invalid Invalid files which could not pass the checks
*/
public $Files_ready = array();
public $Files_valid = array();
public $Files_invalid = array();
/**
* File counters
* @var integer $Files_count added files count
* @var integer $Files_valid_count valid file count
* @var integer $Files_invalid_count invalid file count
*/
public $Files_ready_count = 0;
public $Files_valid_count = 0;
public $Files_invalid_count = 0;
/**
* File array template
* @var array FILE_OBJECT_TEMPLATE
*/
const FILE_OBJECT_TEMPLATE = array( 'path' => '',
'dirname' => '',
'origname' => '',
'name' => '',
'savename' => '',
'uploadKey' => null,
'isnew' => true,
'size' => 0,
'error' => '',
'errorCode' => null,
'isvalid' => false,
'ext' => '',
'issaved' => false );
/**
* Allowed file types presets
* @var array FTY_IMAGES_COMMON typical for default image only uploads
* @var array FTY_IMAGES_GD all types processable with the PHP GD extension
* @var array FTY_VIDEO_COMMON typical for default video only uploads
* @var array FTY_MEDIA_COMMON common image & videos
*/
const FTY_IMAGES_COMMON = ['jpg','gif','png'];
const FTY_IMAGES_GD = ['jpg','gif','png','gd','gd2','bmp','wbmp','webp','xbm','xpm'];
const FTY_VIDEO_COMMON = ['mp4','webm'];
const FTY_MEDIA_COMMON = ['jpg','gif','png','mp4','webm'];
/**
* Error severity:
* @var integer ERR_FILE_UPLOAD_SIZE file exceeding the maximum filesize limit
* @var integer ERR_FILE_TYPE filetype is not allowed
* @var integer ERR_FILE_URL_READ could not reach or read the file from the URL location
* @var integer ERR_FILE_EMPTY file is empty or invalid
* @var integer ERR_FILE_SAVE file could not be saved
*/
const ERR_FILE_UPLOAD_SIZE = 0;
const ERR_FILE_TYPE = 1;
const ERR_FILE_URL_READ = 2;
const ERR_FILE_EMPTY = 3;
const ERR_FILE_SAVE = 4;
/**
* Constructor
*/
public function __construct() {
// check if the mbstring extension is loaded
$this->is_mbstring_ext = extension_loaded( 'mbstring' );
$this->is_gd2_ext = extension_loaded( 'gd2' );
$allow_url_fopen = ini_get( 'allow_url_fopen' );
$this->is_allow_url_fopen = ( $allow_url_fopen == '1' || strtolower( $allow_url_fopen ) == 'on' ) ? true : false;
}
/**
* Set the maximum filesize
* @param integer $size The maximum filesize in megabytes, or "0" for no limit
* @param boolean $isMB Whether or not $size is in megabyte format
*/
public function setMaxFileSize( $size, $isMB = true ) {
$size = ( $size < 0 ) ? 0 : $size;
// convert to byte if $isMB = true
$this->MaxFileSize = ( $isMB ) ? $size * 1000000 : $size;
}
/**
* Sets the allowed file types, which counts as valid for the next file adds
* @param array $types pass False for no restriction
*/
public function setAllowedFileTypes( $types ) {
if ( $types === false ) {
// allow all filetypes
$this->AllowedFileTypes = null;
} else {
$types = (array)$types;
for( $i = 0, $count = count( $types ); $i < $count; $i++ ) {
$types[$i] = (string)$types[$i];
}
$this->AllowedFileTypes = $types;
}
}
/**
* Whether filechecking pass shall be strict or not
* @param boolean $bool
*/
public function setStrictFilecheck( $bool ) {
$this->is_strict_filecheck = (boolean)$bool;
}
/**
* Whether the filesnames will become a unique name after phpFileHandler->save() got called or not
* @param boolean $bool
*/
public function setUniqFilenames( $bool ) {
$this->is_uniq_filenames = (boolean)$bool;
}
/**
* Set the default filename length generated by phpFileHandler::uniqString() when called from phpFileHandler->save()
* @param integer $length
*/
public function setUniqFilenameLength( $length ) {
$this->uniq_string_length = (int)$length;
}
/**
* Generate a unique random string (for multiple calls directly successively the $length should be atleast 10 otherwise it will generate the same strings )
* @param integer $length The length of the output string, must be greater than 0
* @return string A unique alphanumeric string
*/
public static function uniqString( $length = 12 ) {
// if $length is less than 1 the output string would be ~9 characters long
$lenght = ( $length < 1 ) ? 1 : $length;
$uString = base_convert( microtime( true ), 10, 36 );
$padLength = $length - strlen( $uString );
// if $padLength is greater than 0, extend to string to the given $length using random byte generator combined with hex conversion
// else substring it to the given $length
if ( $padLength > 0 ) {
if ( version_compare( PHP_VERSION, '7.0.0' ) >= 0 ) {
$rBytes = random_bytes( ceil( $padLength / 2 ) );
} else {
$rBytes = openssl_random_pseudo_bytes( ceil( $padLength / 2 ) );
}
$uString = str_pad( $uString, $length, bin2hex( $rBytes ) );
} else {
$uString = substr( $uString, -$length );
}
return $uString;
}
/**
* Adds all files from the PHP superglobal $_FILES
* @param array | string $keys Only files within these keys will be added
*/
public function add_uploaded_files( $keys = null ) {
if ( $this->is_add_uploaded ) {
return;
}
$keys = ( $keys ) ? (array)$keys : null;
$this->is_add_uploaded = true;
foreach( $_FILES as $key => $data ) {
if ( $keys && !in_array( $key, $keys ) ) {
continue;
}
$data['tmp_name'] = (array)$data['tmp_name'];
$data['name'] = (array)$data['name'];
$data['error'] = (array)$data['error'];
$data['type'] = (array)$data['type'];
for( $i = 0, $count = count( $data['tmp_name'] ); $i < $count; $i++ ) {
$file = self::FILE_OBJECT_TEMPLATE;
$file['path'] = $data['tmp_name'][$i];
$file['origname'] = $data['name'][$i];
$file['name'] = self::strip_to_valid_filename( $data['name'][$i] );
$file['uploadKey'] = $key;
$file['mime'] = $data['type'][$i];
// php.ini -> 'upload_max_filesize' exceeded error
if ( $data['error'][$i] === UPLOAD_ERR_INI_SIZE ) {
$this->add_invalid_file( $file, self::ERR_FILE_UPLOAD_SIZE );
continue;
}
$this->process_file_add( $file );
}
}
}
/**
* Add a file from a web url
* @param string $url The file's web url
*/
public function add_file_from_url( $url ) {
$url = ( substr( $url, 0, 4 ) !== 'http' ) ? 'http://' . str_replace( '//', '', $url ) : $url;
$file = self::FILE_OBJECT_TEMPLATE;
$file['path'] = $url;
$file['origname'] = $url;
$file['name'] = self::strip_to_valid_filename( substr( strrchr( $url, '/' ), 1 ) );
$file['isurl'] = true;
$this->process_file_add( $file, true );
}
/**
* Adds files which are already existing on the Server for further processing
* @param string | array $filenames The file paths to add
*/
public function add_existing_files( $filenames ) {
$filenames = (array)$filenames;
for( $i = 0, $count = count( $filenames ); $i < $count; $i++ ) {
$file = self::FILE_OBJECT_TEMPLATE;
if ( is_file( $filenames[$i] ) ) {
$pathinfo = pathinfo( $filenames[$i] );
$file['path'] = $pathinfo['dirname'] . '/' . $pathinfo['basename'];
$file['dirname'] = $pathinfo['dirname'];
$file['origname'] = $pathinfo['basename'];
$file['name'] = $pathinfo['filename'];
$file['savename'] = $pathinfo['basename'];
$file['isnew'] = false;
$file['ext'] = $pathinfo['extension'];
$this->process_file_add( $file );
} else {
$file['path'] = $filenames[$i];
$this->add_invalid_file( $file, self::ERR_FILE_EMPTY );
}
}
}
/**
* Removes all added files
*/
public function remove_added_files() {
$this->Files_ready = array();
$this->Files_valid = array();
$this->Files_invalid = array();
$this->Files_ready_count = 0;
$this->Files_valid_count = 0;
$this->Files_invalid_count = 0;
}
/**
* Runs a file trough the main file checking process which is the only way to get valid files into @phpFileHandler->Files_valid
* @param array $file A phpFileHandler $file array
* @param boolean $isUrl True if $file['path'] is an web url
*/
protected function process_file_add( $file, $isUrl = false ) {
// get the raw file content
$filecontent = $this->getFileContents( $file['path'], $isUrl );
if ( $filecontent === false || empty( $filecontent ) ) {
return $this->add_invalid_file( $file, ( $isUrl ) ? self::ERR_FILE_URL_READ : self::ERR_FILE_EMPTY );
}
if ( empty( $file['ext'] ) ) {
// guess the file extension
$file['ext'] = self::guess_fileextension( null, $filecontent );
if ( !$file['ext'] ) {
// if file extension could not be guessed and phpFileHandler::is_strict_filecheck is set to true.. dont let the file pass
if ( $this->is_strict_filecheck && $file['isnew'] ) {
return $this->add_invalid_file( $file, self::ERR_FILE_TYPE );
}
// otherwise try to get the extension via mime type (only for uploads)
// or from the file's basename
if ( isset( $file['mime'] ) && !empty( $file['mime'] ) ) {
$ext_guess = substr( strrchr( $file['mime'], '/' ), 1 );
} else if ( strpos( $file['name'], '.' ) !== false ) {
$ext_guess = substr( strrchr( $file['name'], '.' ), 1 );
}
// in the worst case the file becomes the extension 'file'
$file['ext'] = $ext_guess ?? 'file';
}
}
// 'jpeg' to 'jpg'
$file['ext'] = str_replace( 'jpeg', 'jpg', $file['ext'] );
// get the file size using mb_strlen or strlen (fallback when php_mbstring module is not loaded)
// Note that this is only accurate when using mb_strlen because of mbstring.func_overload (which has been DEPRECATED as of PHP 7.2.0)
$filesize = ( $this->is_mbstring_ext ) ? mb_strlen( $filecontent, '8bit' ) : strlen( $filecontent );
$file['size'] = $filesize;
if ( $this->MaxFileSize !== 0 && $filesize > $this->MaxFileSize ) {
return $this->add_invalid_file( $file, self::ERR_FILE_UPLOAD_SIZE );
}
if ( $this->AllowedFileTypes ) {
// check if the extension is allowed
if ( !in_array( $file['ext'], $this->AllowedFileTypes ) ) {
return $this->add_invalid_file( $file, self::ERR_FILE_TYPE );
}
}
// remove the extension from the filename
$dot_pos = strrpos( $file['name'], '.' );
if ( $dot_pos !== false ) {
$file['name'] = substr( $file['name'], 0, $dot_pos );
}
if ( $isUrl ) {
// generate a random temporary name for the file and save it to the system's default temp directory
$file['path'] = tempnam( sys_get_temp_dir(), self::uniqString( 24 ) );
file_put_contents( $file['path'], $filecontent );
}
if ( $file['isnew'] && $file['ext'] === 'jpg' && $this->is_gd2_ext ) {
// only jpg supported
$this->fix_image_orientation( $file['path'], $filecontent );
}
if ( $file['isnew'] ) {
$this->add_valid_file( $file );
} else {
// existing file on server
$this->add_ready_file( $file );
}
}
/**
* Saves all files in phpFileHandler->Files_valid in to the given directory
* @param string $to The file save path
* @param boolean $allow_dir_create True to allow phpFileHandler to create the save path if not existing (recursive)
* @param boolean $allow_override True to allow file overwriting
* @param integer $file_index Index of an phpFileHandler->Files_valid file
*/
public function save( $to, $allow_dir_create = false, $allow_override = false, $file_index = null ) {
$to = ( $to === '/' || empty( $to ) ) ? './' : $to;
for( $i = 0; $i < $this->Files_valid_count; $i++ ) {
if ( $file_index !== null && $file_index != $i ) {
continue;
}
if ( !$this->Files_valid[$i]['issaved'] ) {
// generate a new filename or take the original
$name = ( $this->is_uniq_filenames ) ? self::uniqString( $this->uniq_string_length ) : $this->Files_valid[$i]['name'];
$this->Files_valid[$i]['name'] = $name;
$this->Files_valid[$i]['savename'] = $name . '.' . $this->Files_valid[$i]['ext'];
// try to move the file to its destination
if ( $this->move_file( $i, $to, $allow_dir_create, $allow_override, false, true ) ) {
$this->add_ready_file( $this->Files_valid[$i] );
} else {
// error moving the file to its new destination
$this->add_invalid_file( $this->Files_valid[$i], self::ERR_FILE_SAVE );
}
}
}
}
/**
* Securely moves or copys a file to a new location
* @param mixed $file_index Index of the file in
* @param string $dest The destination path
* @param boolean $allow_dir_create True to allow phpFileHandler to create the save path if not existing (recursive)
* @param boolean $allow_override True to allow file override
* @param boolean $copy True to copy the file to the given location
* @param boolean $isValidFile True if the $file_index is a ::Files_valid index (only for internal usage)
* @return boolean True on success, False on failure
*/
public function move_file( $file_index, $to, $allow_dir_create = false, $allow_override = false, $copy = false, $isValidFile = false ) {
if ( $isValidFile ) {
$FilePointer = & $this->Files_valid[ $file_index ];
} else {
if ( !isset( $this->Files_ready[ $file_index ] ) ) {
return false;
}
$FilePointer = & $this->Files_ready[ $file_index ];
}
$to = self::prepare_path_string( $to, true );
// will throw error if the folder does not exist and $allow_dir_create is set to false
self::try_create_folder( $to, $allow_dir_create );
if ( $copy ) {
// just a file copy..
return copy( $FilePointer['path'], $to . $FilePointer['savename'] );
} else {
// get the destination file path
$dest_file = $to . $FilePointer['savename'];
// check if file overriding is enabled
if ( !$allow_override && is_file( $dest_file ) ) {
return false;
}
// move the file to the new destination
if ( is_uploaded_file( $FilePointer['path'] ) ) {
$isSuccess = move_uploaded_file( $FilePointer['path'], $dest_file );
} else {
$isSuccess = rename( $FilePointer['path'], $dest_file );
}
if ( $isSuccess ) {
// set the new dirname and path on success
$FilePointer['dirname'] = rtrim( $to, '/' );
$FilePointer['path'] = $dest_file;
}
return $isSuccess;
}
}
/**
* Adds an invalid file with its error to $Files_invalid
* Secure for client output as error messge
* @param array $file
* @param integer $errorCode An error severity constant
*/
protected function add_invalid_file( $file, $errorCode ) {
switch( $errorCode ) {
case self::ERR_FILE_UPLOAD_SIZE: { $errorMsg = 'Exceeding the maximum upload file size. '; } break;
case self::ERR_FILE_TYPE: { $errorMsg = 'Filetype not allowed.'; } break;
case self::ERR_FILE_URL_READ: { $errorMsg = 'Could not fetch the file from the web address.'; } break;
case self::ERR_FILE_EMPTY: { $errorMsg = 'Empty or invalid file.'; } break;
case self::ERR_FILE_SAVE: { $errorMsg = 'Could not save the file.'; } break;
}
$file['errorCode'] = $errorCode;
$file['error'] = $errorMsg;
$this->Files_invalid[] = $file;
$this->Files_invalid_count++;
}
/**
* Adds an valid file to $Files_valid
* @param array $file
*/
protected function add_valid_file( $file ) {
$file['isvalid'] = true;
$file['name'] = ( empty( $file['name'] ) ) ? self::uniqString() : $file['name'];
$this->Files_valid[] = $file;
$this->Files_valid_count++;
}
/**
* Adds a ready file to $Files_ready
* @param array $file
*/
protected function add_ready_file( $file ) {
$file['isvalid'] = true;
$file['issaved'] = true;
$this->Files_ready[] = $file;
$this->Files_ready_count++;
}
/**
* Securely deletes a folder
* @param string $dir Folder path
* @return boolean True on success, False on failure
*/
public static function delete_folder( $dir ) {
if ( !is_dir( $dir ) ) {
return false;
}
if ( self::emtpy_folder( $dir ) ) {
// sleep 1 second
// when a folder contains sub folders it will take the OS time to update internally
// without a sleep rmdir will throw a Warning that the folder could not be removed because its not empty
sleep( 1 );
return rmdir( $dir );
}
return false;
}
/**
* Securely empties a folder
* @param string $dir Folder path
* @param boolean $keepSubFolders Whether or not to keep the sub folders
* @param array | string An array containing file extensions to avoid deleting (for a single extension a string can be passed too)
* * Note: When passing this argument PHP will warn you when it cant delete a non empty directory..
* @return boolean True on success, False on failure
*/
public static function emtpy_folder( $dir, $keepSubFolders = false, $fileExceptions = null ) {
if ( !is_dir( $dir ) ) {
return false;
}
$fileExceptions = ( $fileExceptions ) ? (array)$fileExceptions : $fileExceptions;
$it = new RecursiveDirectoryIterator( $dir );
$it = new RecursiveIteratorIterator( $it, RecursiveIteratorIterator::CHILD_FIRST );
foreach( $it as $file ) {
if ( $file->getBasename() === "." || $file->getBasename() === ".." ) {
continue;
}
if ( $file->isDir() ) {
// keep sub folder?
if ( !$keepSubFolders ) {
rmdir( $file->getPathname() ); // delete folder
}
} else {
// is an exception file?
if ( $fileExceptions && in_array( $file->getExtension(), $fileExceptions ) ) {
continue;
}
unlink( $file->getPathname() ); // delete file
}
}
return true;
}
/**
* Guesses the file's type by checking its signature
* @param string $filecontent A raw file content as string
* @return string | boolean Return the guessed file extension or false if the file or web url is invalid (see @->getFileContents()) none of the following signature could be found:
* * jpg (jpeg), gif, png, bmp, mp4, webm, webp, gzip, 7zip, rar, exe, tif, tiff, pdf, wav, avi, xml, mp3, wmv, wma
*/
public static function guess_fileextension( $filename = null, $filecontent = null ) {
if ( $filename ) {
$filecontent = $this->getFileContents( $filename );
if ( !$filecontent ) {
return false;
}
} else if ( !$filecontent ) {
throw new Exception( 'This function needs atleast one argument!' );
}
$signature = self::getFileSignature( $filecontent );
switch( $signature[0] ) {
case 'FF': { return ( self::is_jpg( null, $signature ) ) ? 'jpg' : (( self::is_mp3( null, $signature ) ) ? 'mp3' : false ); } break;
case '47': { return ( self::is_gif( null, $signature ) ) ? 'gif' : false; } break;
case '89': { return ( self::is_png( null, $signature ) ) ? 'png' : false; } break;
case '42': { return ( self::is_bmp( null, $signature ) ) ? 'bmp' : false; } break;
case '52': { return ( self::is_webp( null, $signature ) ) ? 'webp' : (( self::is_rar( null, $signature ) ) ? 'rar' : false ); } break;
case '1F': { return ( self::is_gzip( null, $signature ) ) ? 'gz' : false; } break;
case '37': { return ( self::is_7zip( null, $signature ) ) ? '7z' : false; } break;
case '4D': { return ( self::is_exe( null, $signature ) ) ? 'exe' : (( self::is_tiff( null, $signature ) ) ? 'tiff' : false ); } break;
case '49': { return ( self::is_tif( null, $signature ) ) ? 'tif' : (( self::is_mp3( null, $signature ) ) ? 'mp3' : false ); } break;
case '25': { return ( self::is_pdf( null, $signature ) ) ? 'pdf' : false; } break;
case '30': { return ( self::is_wmv( null, $signature ) ) ? 'wmv' : false; } break;
case '75': { return ( self::is_tar( null, $signature ) ) ? 'tar' : false; } break;
case '3C': { return ( self::is_xml( null, $signature ) ) ? 'xml' : false; } break;
default: {
$signature = self::getFileSignature( $filecontent, 4 );
switch( $signature[0] ) {
case '66': { return ( self::is_mp4( null, $signature ) ) ? 'mp4' : false; } break;
case '1A': { return ( self::is_webm( null, $signature ) ) ? 'webm' : false; } break;
default: {
$signature = self::getFileSignature( $filecontent, 8 );
switch( $signature[0] ) {
case '57': { return ( self::is_wav( null, $signature ) ) ? 'wav' : false; } break;
case '41': { return ( self::is_avi( null, $signature ) ) ? 'avi' : false; } break;
}
}
}
}
}
return false;
}
/**
* Converts raw filecontent file data to an array of x ($count) elements containing the hexadecimal representation of the bytes
* @param string $filecontent Raw file data
* @param integer $index The starting index
* @param integer $count The amount of bytes to convert and push into the returning array
* @return array of hexadecimal string elements
*/
public static function getFileSignature( $filecontent, $index = 0, $count = 4 ) {
$signature = array();
for( $range = $index + $count; $index < $range; $index++ ) {
$signature[] = ( isset( $filecontent[ $index ] ) ) ? strtoupper( bin2hex( $filecontent[ $index ] ) ) : '';
}
return $signature;
}
/**
* Converts raw filecontent file data to an array of x ($count) elements containing the hexadecimal representation of the bytes
* @param array $comparison A signature array as comparison reference
* @param array $signature A signature array to compare against $comparison
* @param string $filename A filepath to get the signature from and compare against $comparison
* @param integer $index If $filename is given, $index defines the starting index from which byte to begin fetching the file's signature
* @return boolean True if the signature array equals the comparison
*/
public static function compareFileSignature( $comparison, $signature = null, $filename = null, $index = 0 ) {
$count = count( $comparison );
if ( $filename ) {
$filecontent = $this->getFileContents( $filename );
if ( !$filecontent ) {
return false;
}
$signature = self::getFileSignature( $filecontent, $index, $count );
}
for( $i = 0; $i < $count; $i++ ) {
if ( $comparison[$i] !== $signature[$i] ) {
return false;
}
}
return true;
}
/**
* Checks if the file signature given as hexadecimal array is correct
* * see the description of ->guess_fileextension() for a list of checked file types
* @param string $filename The path to the file
* @param array $signature An array containing hexadecimal representation of bytes from a file
*/
public static function is_jpg( $filename = null, $signature = null ) {
return self::compareFileSignature( array('FF','D8','FF'), $signature, $filename );
}
public static function is_gif( $filename = null, $signature = null ) {
return self::compareFileSignature( array('47','49','46'), $signature, $filename );
}
public static function is_png( $filename = null, $signature = null ) {
return self::compareFileSignature( array('89','50','4E'), $signature, $filename );
}
public static function is_bmp( $filename = null, $signature = null ) {
return self::compareFileSignature( array('42','4D'), $signature, $filename );
}
public static function is_webp( $filename = null, $signature = null ) {
return self::compareFileSignature( array('52','49','46','46'), $signature, $filename );
}
public static function is_mp4( $filename = null, $signature = null ) {
return self::compareFileSignature( array('66','74','79','70'), $signature, $filename, 4 );
}
// detects a Matroska media container aka 'mkv', 'mka', 'mks', 'mk3d', 'webm'
public static function is_webm( $filename = null, $signature = null ) {
return self::compareFileSignature( array('1A','45','DF','A3'), $signature, $filename, 4 );
}
public static function is_gzip( $filename = null, $signature = null ) {
return self::compareFileSignature( array('1F','8B'), $signature, $filename );
}
public static function is_7zip( $filename = null, $signature = null ) {
return self::compareFileSignature( array('37','7A','BC','AF'), $signature, $filename );
}
public static function is_rar( $filename = null, $signature = null ) {
return self::compareFileSignature( array('52','61','72','21'), $signature, $filename );
}
public static function is_exe( $filename = null, $signature = null ) {
return self::compareFileSignature( array('4D','5A'), $signature, $filename );
}
// little endian format
public static function is_tif( $filename = null, $signature = null ) {
return self::compareFileSignature( array('49','49','2A','00'), $signature, $filename );
}
// big endian format
public static function is_tiff( $filename = null, $signature = null ) {
return self::compareFileSignature( array('4D','4D','00','2A'), $signature, $filename );
}
public static function is_pdf( $filename = null, $signature = null ) {
return self::compareFileSignature( array('25','50','44','46'), $signature, $filename );
}
public static function is_wav( $filename = null, $signature = null ) {
return self::compareFileSignature( array('57','41','56','45'), $signature, $filename, 8 );
}
public static function is_avi( $filename = null, $signature = null ) {
return self::compareFileSignature( array('41','56','49','20'), $signature, $filename, 8 );
}
public static function is_tar( $filename = null, $signature = null ) {
return self::compareFileSignature( array('75','73','74','61'), $signature, $filename );
}
public static function is_xml( $filename = null, $signature = null ) {
return self::compareFileSignature( array('3C','3F','78','6D'), $signature, $filename );
}
// 49: mp3 with an ID3v2 container, FF: MPEG-1 Layer 3 without and ID3 tag or with an ID3v1 tag at the end of the file
public static function is_mp3( $filename = null, $signature = null ) {
return self::compareFileSignature( array('49','44','33'), $signature, $filename ) || self::compareFileSignature( array('FF','FB'), $signature, $filename );
}
public static function is_wmv( $filename = null, $signature = null ) {
return self::compareFileSignature( array('30','26','B2','75'), $signature, $filename );
}
// wma is identical to wmv in its basic internal structure, only difference is the extension and mime type..
public static function is_wma( $filename = null, $signature = null ) {
return self::is_wma( $filename, $signature );
}
/**
* Trys to create a folder (recursive)
* @param string $dir The folder path
* @param boolean $allow_dir_create
* @throws Exception IF the folder does not exists AND:
* * - $allow_dir_create is false
* * - PHP has no permission to create folders at the given location
*/
protected static function try_create_folder( $dir, $allow_dir_create ) {
if ( !is_dir( $dir ) ) {
if ( $allow_dir_create ) {
if ( !mkdir( $dir, 0777, true ) ) {
throw new Exception( 'Unable to create folder, check the parent folder\'s permissions it must be writable for the system user which executes PHP.' );
}
// ensure file mode
chmod( $dir, 0777 );
} else {
throw new Exception( '"' . htmlspecialchars( $dir ) . '" \n\n\npath does not exist, set @param $allow_dir_create to TRUE to allow path creation.' );
}
}
}
/**
* Gets the raw file byte data as string
* @param string $filename Path to the file
* @return string | boolean The raw byte stream from the given file as string OR false if the file does not exist or the web url could not be reached
*/
protected function getFileContents( $filename, $isUrl = false ) {
$isUrl = ( !$isUrl && filter_var( $filename, FILTER_VALIDATE_URL ) ) ? true : $isUrl;
if ( $isUrl ) {
// $filename is a web url
try {
$filecontent = file_get_contents(
$filename,
false,
stream_context_create(
array(
'http' => array(
'method' => 'GET',
'timeout' => 10 // timout after a 10 seconds connection attempt
)
)
),
0, // 'upload_max_filesize' return something like 8M (for 8megabyte) convert it to integer and format to bytes
( $this->MaxFileSize === 0 ) ? ((int)ini_get( 'upload_max_filesize' ))*1000000 : $this->MaxFileSize
);
} catch( Exception $exc ) {
return false;
}
} else {
if ( !is_file( $filename ) ) {
return false;
}
$filecontent = file_get_contents( $filename );
}
return $filecontent;
}
/**
* Strips all characters except from the folowing: 'a-z' 'A-Z' '0-9' '_' '-' '.'
* and shortens the string to a maximum of 100 characters
* If the string is not utf-8 encoded a random string will get returned!
* @param string $string
* @return string A valid utf-8 string
*/
private static function strip_to_valid_filename( $string ) {
if ( !mb_detect_encoding( $string, 'UTF-8', true ) ) {
return self::uniqString( 12 );
}
$string = preg_replace( '/[^\w-.]/', '', $string );
return substr( $string, 0, 100 );
}
/**
* Filters a path string for proper usage in this class
* @param string $dir
* @return string A proper path string with a leading '/' for directory paths
*/
private static function prepare_path_string( $path, $forceDir = false ) {
$path = trim( str_replace( '\\', '/', $path ), '/' );
if ( is_file( $path ) ) {
if ( $forceDir ) {
$path = dirname( $path ) . '/';
}
} else {
$path = $path . '/';
}
return $path;
}
/******
* -------------------------------------------------------------
* | |
* | IMAGE HANDLING SECTION |
* | |
* -------------------------------------------------------------
*
* phpImageHandler - All in one php image handling using the GD extension !
* make sure the gd2 extension is loaded
* NOTE: For very big images the script memory usage may need to be elevated
* On my machine (WIN7, XAMPP, PHP7) a 12MB image took ~32MB on peak
* PHP's default 'memory_limit' is set to '128M'...
* Nonetheless you will notice when getting the Fatal error: 'Out of memory' occurs
*
**/
/*
* Create a thumbnail in the same folder as the reference image
* @param string $size See @param $type for explanation
* @param string $type The thumb generation type
* * If the image is smaller than $size it will just create a copy with the prefixed name
* * - '': $size will define the maximum height or width depending on the largest side, image will scale down proportional
* * - 'iso': The image will be cropped centered to a Isosceles square each side with the lenght of $size
* @param string $prefix Adds a prefix after the filename ( 'image.jpg' -> 'image_thumb.jpg' )
* * Note when you set an empty prefix if a file with the same name exists in the given directory it will be overwritten !
* @param boolean $allowGrowth Whether or not to allow a bigger output image
* @param string $to Set a save path for the thumb
* @param boolean $allow_dir_create Set to true to enable folder creation, only applies when $to is set
* @param mixed $file_index An array index of Files_ready
*/
public function thumb( $size, $type = '', $prefix = '_thumb', $allowGrowth = false, $to = null, $allow_dir_create = false, $file_index = null ) {
if ( $to ) {
$to = self::prepare_path_string( $to, true );
self::try_create_folder( $to, $allow_dir_create );
}
for( $i = 0; $i < $this->Files_ready_count; $i++ ) {
if ( $file_index !== null && $file_index != $i ) {
continue;
}
if ( in_array( $this->Files_ready[$i]['ext'], self::FTY_IMAGES_GD ) ) {
// get the processed image ressource
$image = $this->create_image( $i, $size, $type, $allowGrowth );
$this->save_image( $image, $i, $to, $prefix );
}
}
}
/*
* Resizes the image proportional
* * see @thumb() description for the details
* @param integer $size See @param $type for more info
* @param string $to Set a save path for the thumb
* @param string $prefix If not set the file will be overwritten (if the output is in the same folder)
* @param mixed $file_index An array index of Files_ready
*/
public function resize( $size, $to = null, $prefix = '', $file_index = null ) {
$this->thumb( $size, '', $prefix, true, $to, false, $file_index );
}
/*
* Converts images to the given type
* @param string $output_type The output file type (see @save_image() for which output types are supported)
* @param boolean $keepOriginal whether to keep or delete the original file
* @param mixed $file_index An array index of Files_ready
*/
public function convert_image( $output_type, $keepOriginal = false, $file_index = null ) {
$output_type = strtolower( str_replace( 'jpeg', 'jpg', $output_type ) );
for( $i = 0; $i < $this->Files_ready_count; $i++ ) {
if ( $file_index !== null && $file_index != $i ) {
continue;
}
if ( in_array( $this->Files_ready[$i]['ext'], self::FTY_IMAGES_GD ) ) {
// continue if the file type already is the same as output_type
if ( $this->Files_ready[$i]['ext'] === $output_type ) {
continue;
}
$original_file = $this->Files_ready[$i]['path'];
$image = $this->create_image( $i );
$this->save_image( $image, $i, null, '', $output_type );
// whether or not to delete the original file
if ( !$keepOriginal ) {
unlink( $original_file );
}
}
}
}
/*
* Adds an watermark to the image
* @param string $watermark Path to the watermark image
* @param float $opacity The watermark's opacity From 0.00 (fully transparent) to 1.00 (fully visible)
* @param string $position The watermark's position
* @param integer $offsetX Horizontal offset
* @param integer $offsetY Vertical offset
* @param mixed $file_index An array index of Files_ready
* @throws Exception
*/
public function put_watermark( $watermark, $opacity = 0.5, $position = 'center', $offsetX = 0, $offsetY = 0, $file_index = null ) {
if ( !is_file( $watermark ) ) {
throw new Exception( 'Watermark file does not exist (' . htmlspecialchars( $watermark ) . ')' );
}
$watermark_image = imagecreatefromstring( file_get_contents( $watermark ) );
if ( !$watermark_image ) {
throw new Exception( 'GD extension cannot create an image from the Watermark image' );
}
$watermark_width = imagesx( $watermark_image );
$watermark_height = imagesy( $watermark_image );
// keep the opacity value in range
$opacity = (int) ((( $opacity < 0 ) ? 0 : (( $opacity > 1 ) ? 1 : $opacity )) * 100);
if ( $opacity < 100 ) {
// workaround for transparent images because PHP's imagecopymerge does not support alpha channel
imagealphablending( $watermark_image, false );
imagefilter( $watermark_image, IMG_FILTER_COLORIZE, 0, 0, 0, 127 * ((100 - $opacity) / 100) );
}
for( $i = 0; $i < $this->Files_ready_count; $i++ ) {
if ( $file_index !== null && $file_index != $i ) {
continue;
}
if ( in_array( $this->Files_ready[$i]['ext'], self::FTY_IMAGES_GD ) ) {
$target_image = $this->create_image( $i );
$target_width = imagesx( $target_image );
$target_height = imagesy( $target_image );
switch( $position ) {
case 'top': {
$x = ($target_width / 2) - ($watermark_width / 2) + $offsetX;
$y = $offsetY;
} break;
case 'left': {
$x = $offsetX;
$y = ($target_height / 2) - ($watermark_height / 2) + $offsetY;
} break;
case 'right': {
$x = $target_width - $watermark_width + $offsetX;
$y = ($target_height / 2) - ($watermark_height / 2) + $offsetY;
} break;
case 'bottom': {
$x = ($target_width / 2) - ($watermark_width / 2) + $offsetX;
$y = $target_height - $watermark_height + $offsetY;
} break;
case 'top left': {
$x = $offsetX;
$y = $offsetY;
} break;
case 'top right': {
$x = $target_width - $watermark_width + $offsetX;
$y = $offsetY;
} break;
case 'bottom left': {
$x = $offsetX;
$y = $target_height - $watermark_height + $offsetY;
} break;
case 'bottom right': {
$x = $target_width - $watermark_width + $offsetX;
$y = $target_height - $watermark_height + $offsetY;
} break;
default: { // center
$x = ($target_width / 2) - ($watermark_width / 2) + $offsetX;
$y = ($target_height / 2) - ($watermark_height / 2) + $offsetY;
} break;
}
// put the watermark on the target image
imagecopy( $target_image, $watermark_image, $x, $y, 0, 0, $watermark_width, $watermark_height );