-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
UploadBase.php
2370 lines (2076 loc) · 71.8 KB
/
UploadBase.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
/**
* Base class for the backend of file upload.
*
* 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.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
* http://www.gnu.org/copyleft/gpl.html
*
* @file
* @ingroup Upload
*/
use MediaWiki\Api\ApiResult;
use MediaWiki\Api\ApiUpload;
use MediaWiki\Context\RequestContext;
use MediaWiki\HookContainer\HookRunner;
use MediaWiki\HookContainer\ProtectedHookAccessorTrait;
use MediaWiki\Logger\LoggerFactory;
use MediaWiki\MainConfigNames;
use MediaWiki\MediaWikiServices;
use MediaWiki\Message\Message;
use MediaWiki\Parser\Sanitizer;
use MediaWiki\Permissions\Authority;
use MediaWiki\Permissions\PermissionStatus;
use MediaWiki\Request\WebRequest;
use MediaWiki\Shell\Shell;
use MediaWiki\Status\Status;
use MediaWiki\Title\Title;
use MediaWiki\User\User;
use MediaWiki\User\UserIdentity;
use Wikimedia\AtEase\AtEase;
use Wikimedia\FileBackend\FileBackend;
use Wikimedia\FileBackend\FSFile\FSFile;
use Wikimedia\FileBackend\FSFile\TempFSFile;
use Wikimedia\Mime\XmlTypeCheck;
use Wikimedia\ObjectCache\BagOStuff;
use Wikimedia\Rdbms\IDBAccessObject;
/**
* @defgroup Upload Upload related
*/
/**
* @ingroup Upload
*
* UploadBase and subclasses are the backend of MediaWiki's file uploads.
* The frontends are formed by ApiUpload and SpecialUpload.
*
* @stable to extend
*
* @author Brooke Vibber
* @author Bryan Tong Minh
* @author Michael Dale
*/
abstract class UploadBase {
use ProtectedHookAccessorTrait;
/** @var string|null Local file system path to the file to upload (or a local copy) */
protected $mTempPath;
/** @var TempFSFile|null Wrapper to handle deleting the temp file */
protected $tempFileObj;
/** @var string|null */
protected $mDesiredDestName;
/** @var string|null */
protected $mDestName;
/** @var bool|null */
protected $mRemoveTempFile;
/** @var string|null */
protected $mSourceType;
/** @var Title|false|null */
protected $mTitle = false;
/** @var int */
protected $mTitleError = 0;
/** @var string|null */
protected $mFilteredName;
/** @var string|null */
protected $mFinalExtension;
/** @var LocalFile|null */
protected $mLocalFile;
/** @var UploadStashFile|null */
protected $mStashFile;
/** @var int|null */
protected $mFileSize;
/** @var array|null */
protected $mFileProps;
/** @var string[] */
protected $mBlackListedExtensions;
/** @var bool|null */
protected $mJavaDetected;
/** @var string|false */
protected $mSVGNSError;
private const SAFE_XML_ENCONDINGS = [
'UTF-8',
'US-ASCII',
'ISO-8859-1',
'ISO-8859-2',
'UTF-16',
'UTF-32',
'WINDOWS-1250',
'WINDOWS-1251',
'WINDOWS-1252',
'WINDOWS-1253',
'WINDOWS-1254',
'WINDOWS-1255',
'WINDOWS-1256',
'WINDOWS-1257',
'WINDOWS-1258',
];
public const SUCCESS = 0;
public const OK = 0;
public const EMPTY_FILE = 3;
public const MIN_LENGTH_PARTNAME = 4;
public const ILLEGAL_FILENAME = 5;
public const OVERWRITE_EXISTING_FILE = 7; # Not used anymore; handled by verifyTitlePermissions()
public const FILETYPE_MISSING = 8;
public const FILETYPE_BADTYPE = 9;
public const VERIFICATION_ERROR = 10;
public const HOOK_ABORTED = 11;
public const FILE_TOO_LARGE = 12;
public const WINDOWS_NONASCII_FILENAME = 13;
public const FILENAME_TOO_LONG = 14;
private const CODE_TO_STATUS = [
self::EMPTY_FILE => 'empty-file',
self::FILE_TOO_LARGE => 'file-too-large',
self::FILETYPE_MISSING => 'filetype-missing',
self::FILETYPE_BADTYPE => 'filetype-banned',
self::MIN_LENGTH_PARTNAME => 'filename-tooshort',
self::ILLEGAL_FILENAME => 'illegal-filename',
self::OVERWRITE_EXISTING_FILE => 'overwrite',
self::VERIFICATION_ERROR => 'verification-error',
self::HOOK_ABORTED => 'hookaborted',
self::WINDOWS_NONASCII_FILENAME => 'windows-nonascii-filename',
self::FILENAME_TOO_LONG => 'filename-toolong',
];
/**
* @param int $error
* @return string
*/
public function getVerificationErrorCode( $error ) {
return self::CODE_TO_STATUS[$error] ?? 'unknown-error';
}
/**
* Returns true if uploads are enabled.
* Can be override by subclasses.
* @stable to override
* @return bool
*/
public static function isEnabled() {
$enableUploads = MediaWikiServices::getInstance()->getMainConfig()->get( MainConfigNames::EnableUploads );
return $enableUploads && wfIniGetBool( 'file_uploads' );
}
/**
* Returns true if the user can use this upload module or else a string
* identifying the missing permission.
* Can be overridden by subclasses.
*
* @param Authority $performer
* @return bool|string
*/
public static function isAllowed( Authority $performer ) {
foreach ( [ 'upload', 'edit' ] as $permission ) {
if ( !$performer->isAllowed( $permission ) ) {
return $permission;
}
}
return true;
}
/**
* Returns true if the user has surpassed the upload rate limit, false otherwise.
*
* @deprecated since 1.41, use verifyTitlePermissions() instead.
* Rate limit checks are now implicit in permission checks.
*
* @param User $user
* @return bool
*/
public static function isThrottled( $user ) {
wfDeprecated( __METHOD__, '1.41' );
return $user->pingLimiter( 'upload' );
}
/** @var string[] Upload handlers. Should probably just be a configuration variable. */
private static $uploadHandlers = [ 'Stash', 'File', 'Url' ];
/**
* Create a form of UploadBase depending on wpSourceType and initializes it.
*
* @param WebRequest &$request
* @param string|null $type
* @return null|self
*/
public static function createFromRequest( &$request, $type = null ) {
$type = $type ?: $request->getVal( 'wpSourceType', 'File' );
if ( !$type ) {
return null;
}
// Get the upload class
$type = ucfirst( $type );
// Give hooks the chance to handle this request
/** @var self|null $className */
$className = null;
( new HookRunner( MediaWikiServices::getInstance()->getHookContainer() ) )
// @phan-suppress-next-line PhanTypeMismatchArgument Type mismatch on pass-by-ref args
->onUploadCreateFromRequest( $type, $className );
if ( $className === null ) {
$className = 'UploadFrom' . $type;
wfDebug( __METHOD__ . ": class name: $className" );
if ( !in_array( $type, self::$uploadHandlers ) ) {
return null;
}
}
if ( !$className::isEnabled() || !$className::isValidRequest( $request ) ) {
return null;
}
/** @var self $handler */
$handler = new $className;
$handler->initializeFromRequest( $request );
return $handler;
}
/**
* Check whether a request if valid for this handler.
* @param WebRequest $request
* @return bool
*/
public static function isValidRequest( $request ) {
return false;
}
/**
* Get the desired destination name.
* @return string|null
*/
public function getDesiredDestName() {
return $this->mDesiredDestName;
}
/**
* @stable to call
*/
public function __construct() {
}
/**
* Returns the upload type. Should be overridden by child classes.
*
* @since 1.18
* @stable to override
* @return string|null
*/
public function getSourceType() {
return null;
}
/**
* @param string $name The desired destination name
* @param string|null $tempPath Callers should make sure this is not a storage path
* @param int|null $fileSize
* @param bool $removeTempFile (false) remove the temporary file?
*/
public function initializePathInfo( $name, $tempPath, $fileSize, $removeTempFile = false ) {
$this->mDesiredDestName = $name;
if ( FileBackend::isStoragePath( $tempPath ) ) {
throw new InvalidArgumentException( __METHOD__ . " given storage path `$tempPath`." );
}
$this->setTempFile( $tempPath, $fileSize );
$this->mRemoveTempFile = $removeTempFile;
}
/**
* Initialize from a WebRequest. Override this in a subclass.
*
* @param WebRequest &$request
*/
abstract public function initializeFromRequest( &$request );
/**
* @param string|null $tempPath File system path to temporary file containing the upload
* @param int|null $fileSize
*/
protected function setTempFile( $tempPath, $fileSize = null ) {
$this->mTempPath = $tempPath ?? '';
$this->mFileSize = $fileSize ?: null;
$this->mFileProps = null;
if ( strlen( $this->mTempPath ) && file_exists( $this->mTempPath ) ) {
$this->tempFileObj = new TempFSFile( $this->mTempPath );
if ( !$fileSize ) {
$this->mFileSize = filesize( $this->mTempPath );
}
} else {
$this->tempFileObj = null;
}
}
/**
* Fetch the file. Usually a no-op.
* @stable to override
* @return Status
*/
public function fetchFile() {
return Status::newGood();
}
/**
* Perform checks to see if the file can be fetched. Usually a no-op.
* @stable to override
* @return Status
*/
public function canFetchFile() {
return Status::newGood();
}
/**
* Return true if the file is empty.
* @return bool
*/
public function isEmptyFile() {
return !$this->mFileSize;
}
/**
* Return the file size.
* @return int
*/
public function getFileSize() {
return $this->mFileSize;
}
/**
* Get the base 36 SHA1 of the file.
* @stable to override
* @return string|false
*/
public function getTempFileSha1Base36() {
// Use cached version if we already have it.
if ( $this->mFileProps && is_string( $this->mFileProps['sha1'] ) ) {
return $this->mFileProps['sha1'];
}
return FSFile::getSha1Base36FromPath( $this->mTempPath );
}
/**
* @param string $srcPath The source path
* @return string|false The real path if it was a virtual URL Returns false on failure
*/
public function getRealPath( $srcPath ) {
$repo = MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo();
if ( FileRepo::isVirtualUrl( $srcPath ) ) {
/** @todo Just make uploads work with storage paths UploadFromStash
* loads files via virtual URLs.
*/
$tmpFile = $repo->getLocalCopy( $srcPath );
if ( $tmpFile ) {
$tmpFile->bind( $this ); // keep alive with $this
}
$path = $tmpFile ? $tmpFile->getPath() : false;
} else {
$path = $srcPath;
}
return $path;
}
/**
* Verify whether the upload is sensible.
*
* Return a status array representing the outcome of the verification.
* Possible keys are:
* - 'status': set to self::OK in case of success, or to one of the error constants defined in
* this class in case of failure
* - 'max': set to the maximum allowed file size ($wgMaxUploadSize) if the upload is too large
* - 'details': set to error details if the file type is valid but contents are corrupt
* - 'filtered': set to the sanitized file name if the requested file name is invalid
* - 'finalExt': set to the file's file extension if it is not an allowed file extension
* - 'blacklistedExt': set to the list of disallowed file extensions if the current file extension
* is not allowed for uploads and the list is not empty
*
* @stable to override
* @return mixed[] array representing the result of the verification
*/
public function verifyUpload() {
/**
* If there was no filename or a zero size given, give up quick.
*/
if ( $this->isEmptyFile() ) {
return [ 'status' => self::EMPTY_FILE ];
}
/**
* Honor $wgMaxUploadSize
*/
$maxSize = self::getMaxUploadSize( $this->getSourceType() );
if ( $this->mFileSize > $maxSize ) {
return [
'status' => self::FILE_TOO_LARGE,
'max' => $maxSize,
];
}
/**
* Look at the contents of the file; if we can recognize the
* type, but it's corrupt or data of the wrong type, we should
* probably not accept it.
*/
$verification = $this->verifyFile();
if ( $verification !== true ) {
return [
'status' => self::VERIFICATION_ERROR,
'details' => $verification
];
}
/**
* Make sure this file can be created
*/
$result = $this->validateName();
if ( $result !== true ) {
return $result;
}
return [ 'status' => self::OK ];
}
/**
* Verify that the name is valid and, if necessary, that we can overwrite
*
* @return array|bool True if valid, otherwise an array with 'status'
* and other keys
*/
public function validateName() {
$nt = $this->getTitle();
if ( $nt === null ) {
$result = [ 'status' => $this->mTitleError ];
if ( $this->mTitleError === self::ILLEGAL_FILENAME ) {
$result['filtered'] = $this->mFilteredName;
}
if ( $this->mTitleError === self::FILETYPE_BADTYPE ) {
$result['finalExt'] = $this->mFinalExtension;
if ( count( $this->mBlackListedExtensions ) ) {
$result['blacklistedExt'] = $this->mBlackListedExtensions;
}
}
return $result;
}
$this->mDestName = $this->getLocalFile()->getName();
return true;
}
/**
* Verify the MIME type.
*
* @note Only checks that it is not an evil MIME.
* The "does it have the correct file extension given its MIME type?" check is in verifyFile.
* @param string $mime Representing the MIME
* @return array|bool True if the file is verified, an array otherwise
*/
protected function verifyMimeType( $mime ) {
$verifyMimeType = MediaWikiServices::getInstance()->getMainConfig()->get( MainConfigNames::VerifyMimeType );
if ( $verifyMimeType ) {
wfDebug( "mime: <$mime> extension: <{$this->mFinalExtension}>" );
$mimeTypeExclusions = MediaWikiServices::getInstance()->getMainConfig()
->get( MainConfigNames::MimeTypeExclusions );
if ( self::checkFileExtension( $mime, $mimeTypeExclusions ) ) {
return [ 'filetype-badmime', $mime ];
}
}
return true;
}
/**
* Verifies that it's ok to include the uploaded file
*
* @return array|true True of the file is verified, array otherwise.
*/
protected function verifyFile() {
$config = MediaWikiServices::getInstance()->getMainConfig();
$verifyMimeType = $config->get( MainConfigNames::VerifyMimeType );
$disableUploadScriptChecks = $config->get( MainConfigNames::DisableUploadScriptChecks );
$status = $this->verifyPartialFile();
if ( $status !== true ) {
return $status;
}
// Calculating props calculates the sha1 which is expensive.
// reuse props if we already have them
if ( !is_array( $this->mFileProps ) ) {
$mwProps = new MWFileProps( MediaWikiServices::getInstance()->getMimeAnalyzer() );
$this->mFileProps = $mwProps->getPropsFromPath( $this->mTempPath, $this->mFinalExtension );
}
$mime = $this->mFileProps['mime'];
if ( $verifyMimeType ) {
# XXX: Missing extension will be caught by validateName() via getTitle()
if ( (string)$this->mFinalExtension !== '' &&
!self::verifyExtension( $mime, $this->mFinalExtension )
) {
return [ 'filetype-mime-mismatch', $this->mFinalExtension, $mime ];
}
}
# check for htmlish code and javascript
if ( !$disableUploadScriptChecks ) {
if ( $this->mFinalExtension === 'svg' || $mime === 'image/svg+xml' ) {
$svgStatus = $this->detectScriptInSvg( $this->mTempPath, false );
if ( $svgStatus !== false ) {
return $svgStatus;
}
}
}
$handler = MediaHandler::getHandler( $mime );
if ( $handler ) {
$handlerStatus = $handler->verifyUpload( $this->mTempPath );
if ( !$handlerStatus->isOK() ) {
$errors = $handlerStatus->getErrorsArray();
return reset( $errors );
}
}
$error = true;
$this->getHookRunner()->onUploadVerifyFile( $this, $mime, $error );
if ( $error !== true ) {
if ( !is_array( $error ) ) {
$error = [ $error ];
}
return $error;
}
wfDebug( __METHOD__ . ": all clear; passing." );
return true;
}
/**
* A verification routine suitable for partial files
*
* Runs the deny list checks, but not any checks that may
* assume the entire file is present.
*
* @return array|true True, if the file is valid, else an array with error message key.
* @phan-return non-empty-array|true
*/
protected function verifyPartialFile() {
$config = MediaWikiServices::getInstance()->getMainConfig();
$disableUploadScriptChecks = $config->get( MainConfigNames::DisableUploadScriptChecks );
# getTitle() sets some internal parameters like $this->mFinalExtension
$this->getTitle();
// Calculating props calculates the sha1 which is expensive.
// reuse props if we already have them (e.g. During stashed upload)
if ( !is_array( $this->mFileProps ) ) {
$mwProps = new MWFileProps( MediaWikiServices::getInstance()->getMimeAnalyzer() );
$this->mFileProps = $mwProps->getPropsFromPath( $this->mTempPath, $this->mFinalExtension );
}
# check MIME type, if desired
$mime = $this->mFileProps['file-mime'];
$status = $this->verifyMimeType( $mime );
if ( $status !== true ) {
return $status;
}
# check for htmlish code and javascript
if ( !$disableUploadScriptChecks ) {
if ( self::detectScript( $this->mTempPath, $mime, $this->mFinalExtension ) ) {
return [ 'uploadscripted' ];
}
if ( $this->mFinalExtension === 'svg' || $mime === 'image/svg+xml' ) {
$svgStatus = $this->detectScriptInSvg( $this->mTempPath, true );
if ( $svgStatus !== false ) {
return $svgStatus;
}
}
}
# Scan the uploaded file for viruses
$virus = self::detectVirus( $this->mTempPath );
if ( $virus ) {
return [ 'uploadvirus', $virus ];
}
return true;
}
/**
* Callback for ZipDirectoryReader to detect Java class files.
*
* @param array $entry
*/
public function zipEntryCallback( $entry ) {
$names = [ $entry['name'] ];
// If there is a null character, cut off the name at it, because JDK's
// ZIP_GetEntry() uses strcmp() if the name hashes match. If a file name
// were constructed which had ".class\0" followed by a string chosen to
// make the hash collide with the truncated name, that file could be
// returned in response to a request for the .class file.
$nullPos = strpos( $entry['name'], "\000" );
if ( $nullPos !== false ) {
$names[] = substr( $entry['name'], 0, $nullPos );
}
// If there is a trailing slash in the file name, we have to strip it,
// because that's what ZIP_GetEntry() does.
if ( preg_grep( '!\.class/?$!', $names ) ) {
$this->mJavaDetected = true;
}
}
/**
* Alias for verifyTitlePermissions. The function was originally
* 'verifyPermissions', but that suggests it's checking the user, when it's
* really checking the title + user combination.
*
* @param Authority $performer to verify the permissions against
* @return array|bool An array as returned by getPermissionErrors or true
* in case the user has proper permissions.
*/
public function verifyPermissions( Authority $performer ) {
return $this->verifyTitlePermissions( $performer );
}
/**
* Check whether the user can edit, upload and create the image. This
* checks only against the current title; if it returns errors, it may
* very well be that another title will not give errors. Therefore
* isAllowed() should be called as well for generic is-user-blocked or
* can-user-upload checking.
*
* @param Authority $performer to verify the permissions against
* @return array|bool An array as returned by getPermissionErrors or true
* in case the user has proper permissions.
*/
public function verifyTitlePermissions( Authority $performer ) {
/**
* If the image is protected, non-sysop users won't be able
* to modify it by uploading a new revision.
*/
$nt = $this->getTitle();
if ( $nt === null ) {
return true;
}
$status = PermissionStatus::newEmpty();
$performer->authorizeWrite( 'edit', $nt, $status );
$performer->authorizeWrite( 'upload', $nt, $status );
if ( !$status->isGood() ) {
return $status->toLegacyErrorArray();
}
$overwriteError = $this->checkOverwrite( $performer );
if ( $overwriteError !== true ) {
return [ $overwriteError ];
}
return true;
}
/**
* Check for non fatal problems with the file.
*
* This should not assume that mTempPath is set.
*
* @param User|null $user Accepted since 1.35
*
* @return mixed[] Array of warnings
*/
public function checkWarnings( $user = null ) {
if ( $user === null ) {
// TODO check uses and hard deprecate
$user = RequestContext::getMain()->getUser();
}
$warnings = [];
$localFile = $this->getLocalFile();
$localFile->load( IDBAccessObject::READ_LATEST );
$filename = $localFile->getName();
$hash = $this->getTempFileSha1Base36();
$badFileName = $this->checkBadFileName( $filename, $this->mDesiredDestName );
if ( $badFileName !== null ) {
$warnings['badfilename'] = $badFileName;
}
$unwantedFileExtensionDetails = $this->checkUnwantedFileExtensions( (string)$this->mFinalExtension );
if ( $unwantedFileExtensionDetails !== null ) {
$warnings['filetype-unwanted-type'] = $unwantedFileExtensionDetails;
}
$fileSizeWarnings = $this->checkFileSize( $this->mFileSize );
if ( $fileSizeWarnings ) {
$warnings = array_merge( $warnings, $fileSizeWarnings );
}
$localFileExistsWarnings = $this->checkLocalFileExists( $localFile, $hash );
if ( $localFileExistsWarnings ) {
$warnings = array_merge( $warnings, $localFileExistsWarnings );
}
if ( $this->checkLocalFileWasDeleted( $localFile ) ) {
$warnings['was-deleted'] = $filename;
}
// If a file with the same name exists locally then the local file has already been tested
// for duplication of content
$ignoreLocalDupes = isset( $warnings['exists'] );
$dupes = $this->checkAgainstExistingDupes( $hash, $ignoreLocalDupes );
if ( $dupes ) {
$warnings['duplicate'] = $dupes;
}
$archivedDupes = $this->checkAgainstArchiveDupes( $hash, $user );
if ( $archivedDupes !== null ) {
$warnings['duplicate-archive'] = $archivedDupes;
}
return $warnings;
}
/**
* Convert the warnings array returned by checkWarnings() to something that
* can be serialized. File objects will be converted to an associative array
* with the following keys:
*
* - fileName: The name of the file
* - timestamp: The upload timestamp
*
* @param mixed[] $warnings
* @return mixed[]
*/
public static function makeWarningsSerializable( $warnings ) {
array_walk_recursive( $warnings, static function ( &$param, $key ) {
if ( $param instanceof File ) {
$param = [
'fileName' => $param->getName(),
'timestamp' => $param->getTimestamp()
];
} elseif ( is_object( $param ) ) {
throw new InvalidArgumentException(
'UploadBase::makeWarningsSerializable: ' .
'Unexpected object of class ' . get_class( $param ) );
}
} );
return $warnings;
}
/**
* Convert the serialized warnings array created by makeWarningsSerializable()
* back to the output of checkWarnings().
*
* @param mixed[] $warnings
* @return mixed[]
*/
public static function unserializeWarnings( $warnings ) {
foreach ( $warnings as $key => $value ) {
if ( is_array( $value ) ) {
if ( isset( $value['fileName'] ) && isset( $value['timestamp'] ) ) {
$warnings[$key] = MediaWikiServices::getInstance()->getRepoGroup()->findFile(
$value['fileName'],
[ 'time' => $value['timestamp'] ]
);
} else {
$warnings[$key] = self::unserializeWarnings( $value );
}
}
}
return $warnings;
}
/**
* Check whether the resulting filename is different from the desired one,
* but ignore things like ucfirst() and spaces/underscore things
*
* @param string $filename
* @param string $desiredFileName
*
* @return string|null String that was determined to be bad or null if the filename is okay
*/
private function checkBadFileName( $filename, $desiredFileName ) {
$comparableName = str_replace( ' ', '_', $desiredFileName );
$comparableName = Title::capitalize( $comparableName, NS_FILE );
if ( $desiredFileName != $filename && $comparableName != $filename ) {
return $filename;
}
return null;
}
/**
* @param string $fileExtension The file extension to check
*
* @return array|null array with the following keys:
* 0 => string The final extension being used
* 1 => string[] The extensions that are allowed
* 2 => int The number of extensions that are allowed.
*/
private function checkUnwantedFileExtensions( $fileExtension ) {
$checkFileExtensions = MediaWikiServices::getInstance()->getMainConfig()
->get( MainConfigNames::CheckFileExtensions );
$fileExtensions = MediaWikiServices::getInstance()->getMainConfig()->get( MainConfigNames::FileExtensions );
if ( $checkFileExtensions ) {
$extensions = array_unique( $fileExtensions );
if ( !self::checkFileExtension( $fileExtension, $extensions ) ) {
return [
$fileExtension,
Message::listParam( $extensions, 'comma' ),
count( $extensions )
];
}
}
return null;
}
/**
* @param int $fileSize
*
* @return array warnings
*/
private function checkFileSize( $fileSize ) {
$uploadSizeWarning = MediaWikiServices::getInstance()->getMainConfig()
->get( MainConfigNames::UploadSizeWarning );
$warnings = [];
if ( $uploadSizeWarning && ( $fileSize > $uploadSizeWarning ) ) {
$warnings['large-file'] = [
Message::sizeParam( $uploadSizeWarning ),
Message::sizeParam( $fileSize ),
];
}
if ( $fileSize == 0 ) {
$warnings['empty-file'] = true;
}
return $warnings;
}
/**
* @param LocalFile $localFile
* @param string|false $hash sha1 hash of the file to check
*
* @return array warnings
*/
private function checkLocalFileExists( LocalFile $localFile, $hash ) {
$warnings = [];
$exists = self::getExistsWarning( $localFile );
if ( $exists !== false ) {
$warnings['exists'] = $exists;
// check if file is an exact duplicate of current file version
if ( $hash !== false && $hash === $localFile->getSha1() ) {
$warnings['no-change'] = $localFile;
}
// check if file is an exact duplicate of older versions of this file
$history = $localFile->getHistory();
foreach ( $history as $oldFile ) {
if ( $hash === $oldFile->getSha1() ) {
$warnings['duplicate-version'][] = $oldFile;
}
}
}
return $warnings;
}
private function checkLocalFileWasDeleted( LocalFile $localFile ) {
return $localFile->wasDeleted() && !$localFile->exists();
}
/**
* @param string|false $hash sha1 hash of the file to check
* @param bool $ignoreLocalDupes True to ignore local duplicates
*
* @return File[] Duplicate files, if found.
*/
private function checkAgainstExistingDupes( $hash, $ignoreLocalDupes ) {
if ( $hash === false ) {
return [];
}
$dupes = MediaWikiServices::getInstance()->getRepoGroup()->findBySha1( $hash );
$title = $this->getTitle();
foreach ( $dupes as $key => $dupe ) {
if (
( $dupe instanceof LocalFile ) &&
$ignoreLocalDupes &&
$title->equals( $dupe->getTitle() )
) {
unset( $dupes[$key] );
}
}
return $dupes;
}
/**
* @param string|false $hash sha1 hash of the file to check
* @param Authority $performer
*
* @return string|null Name of the dupe or empty string if discovered (depending on visibility)
* null if the check discovered no dupes.
*/
private function checkAgainstArchiveDupes( $hash, Authority $performer ) {
if ( $hash === false ) {
return null;
}
$archivedFile = new ArchivedFile( null, 0, '', $hash );
if ( $archivedFile->getID() > 0 ) {
if ( $archivedFile->userCan( File::DELETED_FILE, $performer ) ) {
return $archivedFile->getName();
}
return '';
}
return null;
}
/**
* Really perform the upload. Stores the file in the local repo, watches
* if necessary and runs the UploadComplete hook.
*
* @param string $comment
* @param string|false $pageText
* @param bool $watch Whether the file page should be added to user's watchlist.
* (This doesn't check $user's permissions.)
* @param User $user
* @param string[] $tags Change tags to add to the log entry and page revision.
* (This doesn't check $user's permissions.)
* @param string|null $watchlistExpiry Optional watchlist expiry timestamp in any format
* acceptable to wfTimestamp().
* @return Status Indicating the whether the upload succeeded.
*
* @since 1.35 Accepts $watchlistExpiry parameter.
*/
public function performUpload(
$comment, $pageText, $watch, $user, $tags = [], ?string $watchlistExpiry = null
) {
$this->getLocalFile()->load( IDBAccessObject::READ_LATEST );
$props = $this->mFileProps;
$error = null;
$this->getHookRunner()->onUploadVerifyUpload( $this, $user, $props, $comment, $pageText, $error );
if ( $error ) {
if ( !is_array( $error ) ) {
$error = [ $error ];
}
return Status::newFatal( ...$error );
}
$status = $this->getLocalFile()->upload(
$this->mTempPath,
$comment,
$pageText !== false ? $pageText : '',
File::DELETE_SOURCE,
$props,
false,
$user,
$tags
);
if ( $status->isGood() ) {
if ( $watch ) {
MediaWikiServices::getInstance()->getWatchlistManager()->addWatchIgnoringRights(