/
File.php
1516 lines (1443 loc) · 37.2 KB
/
File.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
namespace App\Fields;
use App\Log;
/**
* File class.
*
* @package App
*
* @copyright YetiForce Sp. z o.o
* @license YetiForce Public License 4.0 (licenses/LicenseEN.txt or yetiforce.com)
* @author Mariusz Krzaczkowski <m.krzaczkowski@yetiforce.com>
* @author Radosław Skrzypczak <r.skrzypczak@yetiforce.com>
*/
class File
{
/**
* Temporary table name.
*/
public const TABLE_NAME_TEMP = 'u_#__file_upload_temp';
/**
* Allowed formats.
*
* @var array
*/
public static $allowedFormats = ['image' => ['jpeg', 'png', 'jpg', 'pjpeg', 'x-png', 'gif', 'bmp', 'x-ms-bmp', 'webp']];
/**
* Mime types.
*
* @var string[]
*/
private static $mimeTypes;
/**
* What file types to validate by php injection.
*
* @var string[]
*/
private static $phpInjection = ['image'];
/**
* Directory path used for temporary files.
*
* @var string
*/
private static $tmpPath;
/**
* File path.
*
* @var string
*/
private $path;
/**
* File extension.
*
* @var string
*/
private $ext;
/**
* File mime type.
*
* @var string
*/
private $mimeType;
/**
* File short mime type.
*
* @var string
*/
private $mimeShortType;
/**
* Size.
*
* @var int
*/
private $size;
/**
* File content.
*
* @var string
*/
private $content;
/**
* Error code.
*
* @var bool|int
*/
private $error = false;
/**
* Last validate error.
*
* @var string
*/
public $validateError = '';
/**
* Validate all files by code injection.
*
* @var bool
*/
private $validateAllCodeInjection = false;
/**
* Load file instance from file info.
*
* @param array $fileInfo
*
* @return \self
*/
public static function loadFromInfo($fileInfo)
{
$instance = new self();
foreach ($fileInfo as $key => $value) {
$instance->{$key} = $fileInfo[$key];
}
if (isset($instance->name)) {
$instance->name = trim(\App\Purifier::purify($instance->name));
}
return $instance;
}
/**
* Load file instance from request.
*
* @param array $file
*
* @return \self
*/
public static function loadFromRequest($file)
{
$instance = new self();
$instance->name = trim(\App\Purifier::purify($file['name']));
$instance->path = $file['tmp_name'];
$instance->size = $file['size'];
$instance->error = $file['error'];
return $instance;
}
/**
* Load file instance from file path.
*
* @param string $path
*
* @return \self
*/
public static function loadFromPath(string $path)
{
$instance = new self();
$instance->name = trim(\App\Purifier::purify(basename($path)));
$instance->path = $path;
return $instance;
}
/**
* Load file instance from content.
*
* @param string $contents
* @param string $name
* @param string[] $param
*
* @return bool|\self
*/
public static function loadFromContent(string $contents, $name = false, array $param = [])
{
if (empty($contents)) {
Log::warning("Empty content, unable to create file: $name | Size: " . \strlen($contents), __CLASS__);
return false;
}
static::initMimeTypes();
$extension = 'tmp';
if (empty($name)) {
if (!empty($param['mimeType']) && !($extension = array_search($param['mimeType'], self::$mimeTypes))) {
[, $extension] = explode('/', $param['mimeType']);
}
$name = uniqid() . '.' . $extension;
} elseif ('tmp' === $extension) {
if (($fileExt = pathinfo($name, PATHINFO_EXTENSION)) && isset(self::$mimeTypes[$fileExt])) {
$extension = $fileExt;
if (isset($param['mimeType']) && $param['mimeType'] !== self::$mimeTypes[$fileExt]) {
Log::error("Invalid file content type File: $name | {$param['mimeType']} <> " . self::$mimeTypes[$fileExt], __CLASS__);
return false;
}
} elseif (!empty($param['mimeType']) && !($extension = array_search($param['mimeType'], self::$mimeTypes))) {
[, $extension] = explode('/', $param['mimeType']);
}
}
$path = tempnam(static::getTmpPath(), 'YFF');
if (!file_put_contents($path, $contents)) {
Log::error("Error while saving the file: $path | Size: " . \strlen($contents), __CLASS__);
return false;
}
if (mb_strlen($name) > 180) {
$name = \App\TextParser::textTruncate($name, 180, false) . '_' . uniqid() . ".$extension";
}
$instance = new self();
$instance->name = trim(\App\Purifier::purify($name));
$instance->path = $path;
$instance->ext = $extension;
foreach ($param as $key => $value) {
$instance->{$key} = $value;
}
return $instance;
}
/**
* Load file instance from url.
*
* @param string $url
* @param string[] $param
*
* @return self|bool
*/
public static function loadFromUrl($url, $param = [])
{
if (empty($url)) {
Log::warning('No url: ' . $url, __CLASS__);
return false;
}
if (!\App\RequestUtil::isNetConnection()) {
return false;
}
try {
\App\Log::beginProfile("GET|File::loadFromUrl|{$url}", __NAMESPACE__);
$response = (new \GuzzleHttp\Client(\App\RequestHttp::getOptions()))->request('GET', $url, ['timeout' => 5, 'connect_timeout' => 1]);
\App\Log::endProfile("GET|File::loadFromUrl|{$url}", __NAMESPACE__);
if (200 !== $response->getStatusCode()) {
Log::warning('Error when downloading content: ' . $url . ' | Status code: ' . $response->getStatusCode(), __CLASS__);
return false;
}
$contents = $response->getBody()->getContents();
$param['mimeType'] = explode(';', $response->getHeaderLine('Content-Type'))[0];
$param['size'] = \strlen($contents);
} catch (\Throwable $exc) {
Log::warning('Error when downloading content: ' . $url . ' | ' . $exc->getMessage(), __CLASS__);
return false;
}
if (empty($contents)) {
Log::warning('Url does not contain content: ' . $url, __CLASS__);
return false;
}
return static::loadFromContent($contents, static::sanitizeFileNameFromUrl($url), $param);
}
/**
* Get size.
*
* @return int
*/
public function getSize()
{
if (empty($this->size)) {
$this->size = filesize($this->path);
}
return $this->size;
}
/**
* Function to sanitize the upload file name when the file name is detected to have bad extensions.
*
* @return string
*/
public function getSanitizeName()
{
return static::sanitizeUploadFileName($this->name);
}
/**
* Get file name.
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Get mime type.
*
* @return string
*/
public function getMimeType()
{
if (empty($this->mimeType)) {
static::initMimeTypes();
$extension = $this->getExtension(true);
if (isset(static::$mimeTypes[$extension])) {
$this->mimeType = static::$mimeTypes[$extension];
} elseif (\function_exists('mime_content_type')) {
$this->mimeType = mime_content_type($this->path);
} elseif (\function_exists('finfo_open')) {
$finfo = finfo_open(FILEINFO_MIME);
$this->mimeType = finfo_file($finfo, $this->path);
finfo_close($finfo);
} else {
$this->mimeType = 'application/octet-stream';
}
}
return $this->mimeType;
}
/**
* Get short mime type.
*
* @param int $type 0 or 1
*
* @return string
*/
public function getShortMimeType($type = 1)
{
if (empty($this->mimeShortType)) {
$this->mimeShortType = explode('/', $this->getMimeType());
}
return $this->mimeShortType[$type];
}
/**
* Get file extension.
*
* @param mixed $fromName
*
* @return string
*/
public function getExtension($fromName = false)
{
if (isset($this->ext)) {
return $this->ext;
}
if ($fromName) {
$extension = explode('.', $this->name);
return $this->ext = strtolower(array_pop($extension));
}
return $this->ext = strtolower(pathinfo($this->path, PATHINFO_EXTENSION));
}
/**
* Get file path.
*
* @return string
*/
public function getPath(): string
{
return $this->path;
}
/**
* Get file encoding.
*
* @param array|null $list
*
* @return string
*/
public function getEncoding(?array $list = null): string
{
return \strtoupper(mb_detect_encoding($this->getContents(), ($list ?? mb_list_encodings()), true));
}
/**
* Get directory path.
*
* @return string
*/
public function getDirectoryPath()
{
return pathinfo($this->getPath(), PATHINFO_DIRNAME);
}
/**
* Validate whether the file is safe.
*
* @param string|null $type
*
* @throws \Exception
*
* @return bool
*/
public function validate(?string $type = null): bool
{
$return = true;
try {
if ($type && $this->getShortMimeType(0) !== $type) {
throw new \App\Exceptions\DangerousFile('ERR_FILE_ILLEGAL_FORMAT');
}
$this->checkFile();
if (!empty($this->validateAllowedFormat)) {
$this->validateFormat();
}
$this->validateCodeInjection();
if (($type && 'image' === $type) || 'image' === $this->getShortMimeType(0)) {
$this->validateImage();
}
} catch (\Exception $e) {
$return = false;
$message = $e->getMessage();
if (false === strpos($message, '||')) {
$message = \App\Language::translateSingleMod($message, 'Other.Exceptions');
} else {
$params = explode('||', $message);
$message = \call_user_func_array('vsprintf', [\App\Language::translateSingleMod(array_shift($params), 'Other.Exceptions'), $params]);
}
$this->validateError = $message;
Log::error("Error during file validation: {$this->getName()} | Size: {$this->getSize()}\n {$e->__toString()}", __CLASS__);
}
return $return;
}
/**
* Validate and secure the file.
*
* @param string|null $type
*
* @return bool
*/
public function validateAndSecure(?string $type = null): bool
{
if ($this->validate($type)) {
return true;
}
$reValidate = false;
if (static::secureFile($this)) {
$this->size = filesize($this->path);
$this->content = file_get_contents($this->path);
$reValidate = true;
}
if ($reValidate && $this->validate($type)) {
return true;
}
return false;
}
/**
* Validate image content.
*
* @throws \App\Exceptions\DangerousFile
*
* @return bool
*/
public function validateImageContent(): bool
{
$returnVal = false;
if (\extension_loaded('imagick')) {
try {
$img = new \imagick($this->path);
$returnVal = $img->valid();
$img->clear();
$img->destroy();
} catch (\ImagickException $e) {
$this->validateError = $e->getMessage();
$returnVal = false;
}
} else {
$img = \imagecreatefromstring($this->getContents());
if (false !== $img) {
$returnVal = true;
\imagedestroy($img);
}
}
return $returnVal;
}
/**
* Basic check file.
*
* @throws \Exception
*/
private function checkFile()
{
if (false !== $this->error && UPLOAD_ERR_OK != $this->error) {
throw new \App\Exceptions\DangerousFile('ERR_FILE_ERROR_REQUEST||' . self::getErrorMessage($this->error));
}
if (empty($this->name)) {
throw new \App\Exceptions\DangerousFile('ERR_FILE_EMPTY_NAME');
}
if (!$this->validateInjection($this->name)) {
throw new \App\Exceptions\DangerousFile('ERR_FILE_ILLEGAL_NAME');
}
if (0 === $this->getSize()) {
throw new \App\Exceptions\DangerousFile('ERR_FILE_WRONG_SIZE');
}
}
/**
* Validate format.
*
* @throws \Exception
*/
private function validateFormat()
{
if ($this->validateAllowedFormat !== $this->getShortMimeType(0)) {
throw new \App\Exceptions\DangerousFile('ERR_FILE_ILLEGAL_MIME_TYPE');
}
if (isset(self::$allowedFormats[$this->validateAllowedFormat]) && !\in_array($this->getShortMimeType(1), self::$allowedFormats[$this->validateAllowedFormat])) {
throw new \App\Exceptions\DangerousFile('ERR_FILE_ILLEGAL_FORMAT');
}
}
/**
* Validate image.
*
* @throws \Exception
*/
private function validateImage()
{
if (!getimagesize($this->path)) {
throw new \App\Exceptions\DangerousFile('ERR_FILE_WRONG_IMAGE');
}
if (preg_match('[\x01-\x08\x0c-\x1f]', $this->getContents())) {
throw new \App\Exceptions\DangerousFile('ERR_FILE_WRONG_IMAGE');
}
$this->validateCodeInjectionInMetadata();
if (!$this->validateImageContent()) {
throw new \App\Exceptions\DangerousFile('ERR_FILE_WRONG_IMAGE ||' . $this->validateError);
}
}
/**
* Validate code injection.
*
* @throws \Exception
*/
private function validateCodeInjection()
{
$shortMimeType = $this->getShortMimeType(0);
if ($this->validateAllCodeInjection || \in_array($shortMimeType, static::$phpInjection)) {
$contents = $this->getContents();
if ((1 === preg_match('/(<\?php?(.*?))/si', $contents)
|| false !== stripos($contents, '<?=')
|| false !== stripos($contents, '<? ')) && $this->searchCodeInjection()
) {
throw new \App\Exceptions\DangerousFile('ERR_FILE_CODE_INJECTION');
}
}
}
/**
* Search code injection in content.
*
* @return bool
*/
private function searchCodeInjection(): bool
{
if (!\function_exists('token_get_all')) {
return true;
}
try {
$tokens = token_get_all($this->getContents(), TOKEN_PARSE);
foreach ($tokens as $token) {
switch (\is_array($token) ? $token[0] : $token) {
case T_COMMENT:
case T_DOC_COMMENT:
case T_WHITESPACE:
case T_CURLY_OPEN:
case T_OPEN_TAG:
case T_CLOSE_TAG:
case T_INLINE_HTML:
case T_DOLLAR_OPEN_CURLY_BRACES:
continue 2;
case T_DOUBLE_COLON:
case T_ABSTRACT:
case T_ARRAY:
case T_AS:
case T_BREAK:
case T_CALLABLE:
case T_CASE:
case T_CATCH:
case T_CLASS:
case T_CLONE:
case T_CONTINUE:
case T_DEFAULT:
case T_ECHO:
case T_ELSE:
case T_ELSEIF:
case T_EMPTY:
case T_ENDIF:
case T_ENDSWITCH:
case T_ENDWHILE:
case T_EXIT:
case T_EXTENDS:
case T_FINAL:
case T_FINALLY:
case T_FOREACH:
case T_FUNCTION:
case T_GLOBAL:
case T_IF:
case T_IMPLEMENTS:
case T_INCLUDE:
case T_INCLUDE_ONCE:
case T_INSTANCEOF:
case T_INSTEADOF:
case T_INTERFACE:
case T_ISSET:
case T_LOGICAL_AND:
case T_LOGICAL_OR:
case T_LOGICAL_XOR:
case T_NAMESPACE:
case T_NEW:
case T_PRIVATE:
case T_PROTECTED:
case T_PUBLIC:
case T_REQUIRE:
case T_REQUIRE_ONCE:
case T_RETURN:
case T_STATIC:
case T_THROW:
case T_TRAIT:
case T_TRY:
case T_UNSET:
case T_USE:
case T_VAR:
case T_WHILE:
case T_YIELD:
return true;
default:
$text = \is_array($token) ? $token[1] : $token;
if (\function_exists($text) || \defined($text)) {
return true;
}
}
}
} catch (\Throwable $e) {
Log::warning($e->getMessage(), __METHOD__);
}
return false;
}
/**
* Validate code injection in metadata.
*
* @throws \App\Exceptions\DangerousFile
*/
private function validateCodeInjectionInMetadata()
{
if (\extension_loaded('imagick')) {
try {
$img = new \imagick($this->path);
$this->validateInjection($img->getImageProperties());
} catch (\Throwable $e) {
throw new \App\Exceptions\DangerousFile('ERR_FILE_CODE_INJECTION', $e->getCode(), $e);
}
} elseif (
\function_exists('exif_read_data')
&& \in_array($this->getMimeType(), ['image/jpeg', 'image/tiff'])
&& \in_array(exif_imagetype($this->path), [IMAGETYPE_JPEG, IMAGETYPE_TIFF_II, IMAGETYPE_TIFF_MM])
) {
$imageSize = getimagesize($this->path, $imageInfo);
try {
if (
$imageSize
&& (empty($imageInfo['APP1']) || 0 === strpos($imageInfo['APP1'], 'Exif'))
&& ($exifData = exif_read_data($this->path)) && !$this->validateInjection($exifData)
) {
throw new \App\Exceptions\DangerousFile('ERR_FILE_CODE_INJECTION');
}
} catch (\Throwable $e) {
throw new \App\Exceptions\DangerousFile('ERR_FILE_CODE_INJECTION', $e->getCode(), $e);
}
}
}
/**
* Validate injection.
*
* @param string|array $data
*
* @return bool
*/
private function validateInjection($data): bool
{
$return = true;
if (\is_array($data)) {
foreach ($data as $value) {
if (!$this->validateInjection($value)) {
return false;
}
}
} else {
if (1 === preg_match('/(<\?php?(.*?))/i', $data) || false !== stripos($data, '<?=') || false !== stripos($data, '<? ')) {
$return = false;
} else {
\App\Purifier::purifyHtmlEventAttributes($data);
}
}
return $return;
}
/**
* Get file ontent.
*
* @return string
*/
public function getContents()
{
if (empty($this->content)) {
$this->content = file_get_contents($this->path);
}
return $this->content;
}
/**
* Move file.
*
* @param string $target
*
* @return bool
*/
public function moveFile($target)
{
if (is_uploaded_file($this->path)) {
$uploadStatus = move_uploaded_file($this->path, $target);
} else {
$uploadStatus = rename($this->path, $target);
}
$this->path = $target;
return $uploadStatus;
}
/**
* Delete file.
*
* @return bool
*/
public function delete()
{
if (file_exists($this->path)) {
return unlink($this->path);
}
return false;
}
/**
* Generate file hash.
*
* @param bool $checkInAttachments
* @param string $uploadFilePath
*
* @return string File hash sha256
*/
public function generateHash(bool $checkInAttachments = false, string $uploadFilePath = '')
{
if ($checkInAttachments) {
$hash = hash('sha1', $this->getContents()) . \App\Encryption::generatePassword(10);
if ($uploadFilePath && file_exists($uploadFilePath . $hash)) {
$hash = $this->generateHash($checkInAttachments);
}
return $hash;
}
return hash('sha256', $this->getContents() . \App\Encryption::generatePassword(10));
}
/**
* Function to sanitize the upload file name when the file name is detected to have bad extensions.
*
* @param string $fileName File name to be sanitized
* @param bool|string $badFileExtensions
*
* @return string
*/
public static function sanitizeUploadFileName($fileName, $badFileExtensions = false)
{
if (!$badFileExtensions) {
$badFileExtensions = \App\Config::main('upload_badext');
}
$fileName = preg_replace('/\s+/', '_', \App\Utils::sanitizeSpecialChars($fileName));
$fileName = rtrim($fileName, '\\/<>?*:"<>|');
$fileNameParts = explode('.', $fileName);
$badExtensionFound = false;
foreach ($fileNameParts as $key => &$partOfFileName) {
if (\in_array(strtolower($partOfFileName), $badFileExtensions)) {
$badExtensionFound = true;
$fileNameParts[$key] = $partOfFileName;
}
}
$newFileName = implode('.', $fileNameParts);
if ($badExtensionFound) {
$newFileName .= '.txt';
}
return $newFileName;
}
/**
* Function to get base name of file.
*
* @param string $url
*
* @return string
*/
public static function sanitizeFileNameFromUrl($url)
{
$partsUrl = parse_url($url);
return static::sanitizeUploadFileName(basename($partsUrl['path']));
}
/**
* Get temporary directory path.
*
* @return string
*/
public static function getTmpPath()
{
if (isset(self::$tmpPath)) {
return self::$tmpPath;
}
$hash = hash('crc32', ROOT_DIRECTORY);
if (!empty(ini_get('upload_tmp_dir')) && is_writable(ini_get('upload_tmp_dir'))) {
self::$tmpPath = ini_get('upload_tmp_dir') . \DIRECTORY_SEPARATOR . 'YetiForceTemp' . $hash . \DIRECTORY_SEPARATOR;
if (!is_dir(self::$tmpPath)) {
mkdir(self::$tmpPath, 0755);
}
} elseif (is_writable(sys_get_temp_dir())) {
self::$tmpPath = sys_get_temp_dir() . \DIRECTORY_SEPARATOR . 'YetiForceTemp' . $hash . \DIRECTORY_SEPARATOR;
if (!is_dir(self::$tmpPath)) {
mkdir(self::$tmpPath, 0755);
}
} elseif (is_writable(ROOT_DIRECTORY . \DIRECTORY_SEPARATOR . 'cache' . \DIRECTORY_SEPARATOR . 'upload')) {
self::$tmpPath = ROOT_DIRECTORY . \DIRECTORY_SEPARATOR . 'cache' . \DIRECTORY_SEPARATOR . 'upload' . \DIRECTORY_SEPARATOR;
}
return self::$tmpPath;
}
/**
* Init mime types.
*/
public static function initMimeTypes()
{
if (empty(self::$mimeTypes)) {
self::$mimeTypes = require ROOT_DIRECTORY . '/config/mimetypes.php';
}
}
/**
* Get mime content type ex. image/png.
*
* @param string $fileName
*
* @return string
*/
public static function getMimeContentType($fileName)
{
static::initMimeTypes();
$extension = explode('.', $fileName);
$extension = strtolower(array_pop($extension));
if (isset(self::$mimeTypes[$extension])) {
$mimeType = self::$mimeTypes[$extension];
} elseif (\function_exists('mime_content_type')) {
$mimeType = mime_content_type($fileName);
} elseif (\function_exists('finfo_open')) {
$finfo = finfo_open(FILEINFO_MIME);
$mimeType = finfo_file($finfo, $fileName);
finfo_close($finfo);
} else {
$mimeType = 'application/octet-stream';
}
return $mimeType;
}
/**
* Create document from string.
*
* @param string $contents
* @param array $param
*
* @return bool|self
*/
public static function saveFromString(string $contents, array $param = [])
{
$result = explode(',', $contents, 2);
$contentType = $isBase64 = false;
if (2 === \count($result)) {
[$metadata, $data] = $result;
foreach (explode(';', $metadata) as $cur) {
if ('base64' === $cur) {
$isBase64 = true;
} elseif ('data:' === substr($cur, 0, 5)) {
$contentType = str_replace('data:', '', $cur);
}
}
} else {
$data = $result[0];
}
$data = rawurldecode($data);
$rawData = $isBase64 ? base64_decode($data) : $data;
if (\strlen($rawData) < 12) {
Log::error('Incorrect content value: ' . $contents, __CLASS__);
return false;
}
$fileInstance = static::loadFromContent($rawData, false, array_merge($param, ['mimeType' => $contentType]));
if ($fileInstance->validateAndSecure()) {
return $fileInstance;
}
$fileInstance->delete();
return false;
}
/**
* Create document from url.
*
* @param string $url Url
* @param array $params
*
* @return array|bool
*/
public static function saveFromUrl($url, $params = [])
{
$fileInstance = static::loadFromUrl($url, $params['param'] ?? []);
if (!$fileInstance) {
return false;
}
if ($fileInstance->validateAndSecure() && ($id = static::saveFromContent($fileInstance, $params))) {
return $id;
}
$fileInstance->delete();
return false;
}
/**
* Create document from content.
*
* @param \self $file
* @param array $params
*
* @throws \Exception
*
* @return array|bool
*/
public static function saveFromContent(self $file, $params = [])
{
$fileName = $file->getName();
$fileNameLength = \App\TextParser::getTextLength($fileName);
$record = \Vtiger_Record_Model::getCleanInstance('Documents');
if ($fileNameLength > ($maxLength = $record->getField('filename')->get('maximumlength'))) {
$extLength = 0;
if ($ext = $file->getExtension()) {
$ext .= ".{$ext}";
$extLength = \App\TextParser::getTextLength($ext);
$fileName = substr($fileName, 0, $fileNameLength - $extLength);
}
$fileName = \App\TextParser::textTruncate($fileName, $maxLength - $extLength, false) . $ext;
}
$fileName = \App\Purifier::decodeHtml(\App\Purifier::purify($fileName));
$record->setData($params);
$record->set('notes_title', $fileName);
$record->set('filename', $fileName);
$record->set('filestatus', 1);
$record->set('filelocationtype', 'I');
$record->file = [
'name' => $fileName,
'size' => $file->getSize(),
'type' => $file->getMimeType(),
'tmp_name' => $file->getPath(),
'error' => 0,
];
$record->save();
$file->delete();
if (isset($record->ext['attachmentsId'])) {
return array_merge(['crmid' => $record->getId()], $record->ext);
}
return false;
}
/**
* Init storage file directory.
*
* @param string $suffix
*
* @return string
*/
public static function initStorageFileDirectory($suffix = false)
{
if (!$filepath = \App\Config::module($suffix, 'storagePath')) {
$filepath = 'storage' . \DIRECTORY_SEPARATOR;
}
if ($suffix) {
$filepath .= $suffix . \DIRECTORY_SEPARATOR;
}
if (!is_dir($filepath)) { //create new folder
mkdir($filepath, 0755, true);
}
$year = date('Y');
$month = date('F');
$day = date('j');
$filepath .= $year;
if (!is_dir($filepath)) { //create new folder
mkdir($filepath, 0755, true);
}
$filepath .= \DIRECTORY_SEPARATOR . $month;
if (!is_dir($filepath)) { //create new folder
mkdir($filepath, 0755, true);