/
UploadBase.php
2086 lines (1808 loc) 路 61.9 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
*/
/**
* @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.
*
* @author Brion Vibber
* @author Bryan Tong Minh
* @author Michael Dale
*/
abstract class UploadBase {
/** @var string 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;
protected $mDesiredDestName, $mDestName, $mRemoveTempFile, $mSourceType;
protected $mTitle = false, $mTitleError = 0;
protected $mFilteredName, $mFinalExtension;
protected $mLocalFile, $mStashFile, $mFileSize, $mFileProps;
protected $mBlackListedExtensions;
protected $mJavaDetected, $mSVGNSError;
protected static $safeXmlEncodings = [
'UTF-8',
'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',
];
const SUCCESS = 0;
const OK = 0;
const EMPTY_FILE = 3;
const MIN_LENGTH_PARTNAME = 4;
const ILLEGAL_FILENAME = 5;
const OVERWRITE_EXISTING_FILE = 7; # Not used anymore; handled by verifyTitlePermissions()
const FILETYPE_MISSING = 8;
const FILETYPE_BADTYPE = 9;
const VERIFICATION_ERROR = 10;
const HOOK_ABORTED = 11;
const FILE_TOO_LARGE = 12;
const WINDOWS_NONASCII_FILENAME = 13;
const FILENAME_TOO_LONG = 14;
/**
* @param int $error
* @return string
*/
public function getVerificationErrorCode( $error ) {
$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',
];
if ( isset( $code_to_status[$error] ) ) {
return $code_to_status[$error];
}
return 'unknown-error';
}
/**
* Returns true if uploads are enabled.
* Can be override by subclasses.
* @return bool
*/
public static function isEnabled() {
global $wgEnableUploads;
if ( !$wgEnableUploads ) {
return false;
}
# Check php's file_uploads setting
return wfIsHHVM() || 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 User $user
* @return bool|string
*/
public static function isAllowed( $user ) {
foreach ( [ 'upload', 'edit' ] as $permission ) {
if ( !$user->isAllowed( $permission ) ) {
return $permission;
}
}
return true;
}
/**
* Returns true if the user has surpassed the upload rate limit, false otherwise.
*
* @param User $user
* @return bool
*/
public static function isThrottled( $user ) {
return $user->pingLimiter( 'upload' );
}
// Upload handlers. Should probably just be a global.
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|UploadBase
*/
public static function createFromRequest( &$request, $type = null ) {
$type = $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
$className = null;
Hooks::run( 'UploadCreateFromRequest', [ $type, &$className ] );
if ( is_null( $className ) ) {
$className = 'UploadFrom' . $type;
wfDebug( __METHOD__ . ": class name: $className\n" );
if ( !in_array( $type, self::$uploadHandlers ) ) {
return null;
}
}
// Check whether this upload class is enabled
if ( !call_user_func( [ $className, 'isEnabled' ] ) ) {
return null;
}
// Check whether the request is valid
if ( !call_user_func( [ $className, 'isValidRequest' ], $request ) ) {
return null;
}
/** @var UploadBase $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;
}
public function __construct() {
}
/**
* Returns the upload type. Should be overridden by child classes
*
* @since 1.18
* @return string
*/
public function getSourceType() {
return null;
}
/**
* Initialize the path information
* @param string $name The desired destination name
* @param string $tempPath The temporary path
* @param int $fileSize The file size
* @param bool $removeTempFile (false) remove the temporary file?
* @throws MWException
*/
public function initializePathInfo( $name, $tempPath, $fileSize, $removeTempFile = false ) {
$this->mDesiredDestName = $name;
if ( FileBackend::isStoragePath( $tempPath ) ) {
throw new MWException( __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 $tempPath File system path to temporary file containing the upload
* @param integer $fileSize
*/
protected function setTempFile( $tempPath, $fileSize = null ) {
$this->mTempPath = $tempPath;
$this->mFileSize = $fileSize ?: 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
* @return Status
*/
public function fetchFile() {
return Status::newGood();
}
/**
* Return true if the file is empty
* @return bool
*/
public function isEmptyFile() {
return empty( $this->mFileSize );
}
/**
* Return the file size
* @return int
*/
public function getFileSize() {
return $this->mFileSize;
}
/**
* Get the base 36 SHA1 of the file
* @return string
*/
public function getTempFileSha1Base36() {
return FSFile::getSha1Base36FromPath( $this->mTempPath );
}
/**
* @param string $srcPath The source path
* @return string|bool The real path if it was a virtual URL Returns false on failure
*/
function getRealPath( $srcPath ) {
$repo = RepoGroup::singleton()->getLocalRepo();
if ( $repo->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 sane.
* @return mixed Const self::OK or else an array with error information
*/
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;
}
$error = '';
if ( !Hooks::run( 'UploadVerification',
[ $this->mDestName, $this->mTempPath, &$error ], '1.28' )
) {
return [ 'status' => self::HOOK_ABORTED, 'error' => $error ];
}
return [ 'status' => self::OK ];
}
/**
* Verify that the name is valid and, if necessary, that we can overwrite
*
* @return mixed True if valid, otherwise and array with 'status'
* and other keys
*/
public function validateName() {
$nt = $this->getTitle();
if ( is_null( $nt ) ) {
$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
* correct extension given its MIME type?" check is in verifyFile.
* in `verifyFile()` that MIME type and file extension correlate.
* @param string $mime Representing the MIME
* @return mixed True if the file is verified, an array otherwise
*/
protected function verifyMimeType( $mime ) {
global $wgVerifyMimeType;
if ( $wgVerifyMimeType ) {
wfDebug( "mime: <$mime> extension: <{$this->mFinalExtension}>\n" );
global $wgMimeTypeBlacklist;
if ( $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
return [ 'filetype-badmime', $mime ];
}
# Check what Internet Explorer would detect
$fp = fopen( $this->mTempPath, 'rb' );
$chunk = fread( $fp, 256 );
fclose( $fp );
$magic = MimeMagic::singleton();
$extMime = $magic->guessTypesForExtension( $this->mFinalExtension );
$ieTypes = $magic->getIEMimeTypes( $this->mTempPath, $chunk, $extMime );
foreach ( $ieTypes as $ieType ) {
if ( $this->checkFileExtension( $ieType, $wgMimeTypeBlacklist ) ) {
return [ 'filetype-bad-ie-mime', $ieType ];
}
}
}
return true;
}
/**
* Verifies that it's ok to include the uploaded file
*
* @return mixed True of the file is verified, array otherwise.
*/
protected function verifyFile() {
global $wgVerifyMimeType, $wgDisableUploadScriptChecks;
$status = $this->verifyPartialFile();
if ( $status !== true ) {
return $status;
}
$this->mFileProps = FSFile::getPropsFromPath( $this->mTempPath, $this->mFinalExtension );
$mime = $this->mFileProps['mime'];
if ( $wgVerifyMimeType ) {
# XXX: Missing extension will be caught by validateName() via getTitle()
if ( $this->mFinalExtension != '' && !$this->verifyExtension( $mime, $this->mFinalExtension ) ) {
return [ 'filetype-mime-mismatch', $this->mFinalExtension, $mime ];
}
}
# check for htmlish code and javascript
if ( !$wgDisableUploadScriptChecks ) {
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;
Hooks::run( 'UploadVerifyFile', [ $this, $mime, &$error ] );
if ( $error !== true ) {
if ( !is_array( $error ) ) {
$error = [ $error ];
}
return $error;
}
wfDebug( __METHOD__ . ": all clear; passing.\n" );
return true;
}
/**
* A verification routine suitable for partial files
*
* Runs the blacklist checks, but not any checks that may
* assume the entire file is present.
*
* @return mixed True for valid or array with error message key.
*/
protected function verifyPartialFile() {
global $wgAllowJavaUploads, $wgDisableUploadScriptChecks;
# getTitle() sets some internal parameters like $this->mFinalExtension
$this->getTitle();
$this->mFileProps = FSFile::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 ( !$wgDisableUploadScriptChecks ) {
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;
}
}
}
# Check for Java applets, which if uploaded can bypass cross-site
# restrictions.
if ( !$wgAllowJavaUploads ) {
$this->mJavaDetected = false;
$zipStatus = ZipDirectoryReader::read( $this->mTempPath,
[ $this, 'zipEntryCallback' ] );
if ( !$zipStatus->isOK() ) {
$errors = $zipStatus->getErrorsArray();
$error = reset( $errors );
if ( $error[0] !== 'zip-wrong-format' ) {
return $error;
}
}
if ( $this->mJavaDetected ) {
return [ 'uploadjava' ];
}
}
# Scan the uploaded file for viruses
$virus = $this->detectVirus( $this->mTempPath );
if ( $virus ) {
return [ 'uploadvirus', $virus ];
}
return true;
}
/**
* Callback for ZipDirectoryReader to detect Java class files.
*
* @param array $entry
*/
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 User $user User object to verify the permissions against
* @return mixed An array as returned by getUserPermissionsErrors or true
* in case the user has proper permissions.
*/
public function verifyPermissions( $user ) {
return $this->verifyTitlePermissions( $user );
}
/**
* 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 User $user User object to verify the permissions against
* @return mixed An array as returned by getUserPermissionsErrors or true
* in case the user has proper permissions.
*/
public function verifyTitlePermissions( $user ) {
/**
* If the image is protected, non-sysop users won't be able
* to modify it by uploading a new revision.
*/
$nt = $this->getTitle();
if ( is_null( $nt ) ) {
return true;
}
$permErrors = $nt->getUserPermissionsErrors( 'edit', $user );
$permErrorsUpload = $nt->getUserPermissionsErrors( 'upload', $user );
if ( !$nt->exists() ) {
$permErrorsCreate = $nt->getUserPermissionsErrors( 'create', $user );
} else {
$permErrorsCreate = [];
}
if ( $permErrors || $permErrorsUpload || $permErrorsCreate ) {
$permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsUpload, $permErrors ) );
$permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsCreate, $permErrors ) );
return $permErrors;
}
$overwriteError = $this->checkOverwrite( $user );
if ( $overwriteError !== true ) {
return [ $overwriteError ];
}
return true;
}
/**
* Check for non fatal problems with the file.
*
* This should not assume that mTempPath is set.
*
* @return array Array of warnings
*/
public function checkWarnings() {
global $wgLang;
$warnings = [];
$localFile = $this->getLocalFile();
$localFile->load( File::READ_LATEST );
$filename = $localFile->getName();
/**
* Check whether the resulting filename is different from the desired one,
* but ignore things like ucfirst() and spaces/underscore things
*/
$comparableName = str_replace( ' ', '_', $this->mDesiredDestName );
$comparableName = Title::capitalize( $comparableName, NS_FILE );
if ( $this->mDesiredDestName != $filename && $comparableName != $filename ) {
$warnings['badfilename'] = $filename;
}
// Check whether the file extension is on the unwanted list
global $wgCheckFileExtensions, $wgFileExtensions;
if ( $wgCheckFileExtensions ) {
$extensions = array_unique( $wgFileExtensions );
if ( !$this->checkFileExtension( $this->mFinalExtension, $extensions ) ) {
$warnings['filetype-unwanted-type'] = [ $this->mFinalExtension,
$wgLang->commaList( $extensions ), count( $extensions ) ];
}
}
global $wgUploadSizeWarning;
if ( $wgUploadSizeWarning && ( $this->mFileSize > $wgUploadSizeWarning ) ) {
$warnings['large-file'] = [ $wgUploadSizeWarning, $this->mFileSize ];
}
if ( $this->mFileSize == 0 ) {
$warnings['empty-file'] = true;
}
$exists = self::getExistsWarning( $localFile );
if ( $exists !== false ) {
$warnings['exists'] = $exists;
}
if ( $localFile->wasDeleted() && !$localFile->exists() ) {
$warnings['was-deleted'] = $filename;
}
// Check dupes against existing files
$hash = $this->getTempFileSha1Base36();
$dupes = RepoGroup::singleton()->findBySha1( $hash );
$title = $this->getTitle();
// Remove all matches against self
foreach ( $dupes as $key => $dupe ) {
if ( $title->equals( $dupe->getTitle() ) ) {
unset( $dupes[$key] );
}
}
if ( $dupes ) {
$warnings['duplicate'] = $dupes;
}
// Check dupes against archives
$archivedFile = new ArchivedFile( null, 0, '', $hash );
if ( $archivedFile->getID() > 0 ) {
if ( $archivedFile->userCan( File::DELETED_FILE ) ) {
$warnings['duplicate-archive'] = $archivedFile->getName();
} else {
$warnings['duplicate-archive'] = '';
}
}
return $warnings;
}
/**
* Really perform the upload. Stores the file in the local repo, watches
* if necessary and runs the UploadComplete hook.
*
* @param string $comment
* @param string $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.)
* @return Status Indicating the whether the upload succeeded.
*/
public function performUpload( $comment, $pageText, $watch, $user, $tags = [] ) {
$this->getLocalFile()->load( File::READ_LATEST );
$props = $this->mFileProps;
$error = null;
Hooks::run( 'UploadVerifyUpload', [ $this, $user, $props, $comment, $pageText, &$error ] );
if ( $error ) {
if ( !is_array( $error ) ) {
$error = [ $error ];
}
return call_user_func_array( 'Status::newFatal', $error );
}
$status = $this->getLocalFile()->upload(
$this->mTempPath,
$comment,
$pageText,
File::DELETE_SOURCE,
$props,
false,
$user,
$tags
);
if ( $status->isGood() ) {
if ( $watch ) {
WatchAction::doWatch(
$this->getLocalFile()->getTitle(),
$user,
User::IGNORE_USER_RIGHTS
);
}
Hooks::run( 'UploadComplete', [ &$this ] );
$this->postProcessUpload();
}
return $status;
}
/**
* Perform extra steps after a successful upload.
*
* @since 1.25
*/
public function postProcessUpload() {
}
/**
* Returns the title of the file to be uploaded. Sets mTitleError in case
* the name was illegal.
*
* @return Title The title of the file or null in case the name was illegal
*/
public function getTitle() {
if ( $this->mTitle !== false ) {
return $this->mTitle;
}
if ( !is_string( $this->mDesiredDestName ) ) {
$this->mTitleError = self::ILLEGAL_FILENAME;
$this->mTitle = null;
return $this->mTitle;
}
/* Assume that if a user specified File:Something.jpg, this is an error
* and that the namespace prefix needs to be stripped of.
*/
$title = Title::newFromText( $this->mDesiredDestName );
if ( $title && $title->getNamespace() == NS_FILE ) {
$this->mFilteredName = $title->getDBkey();
} else {
$this->mFilteredName = $this->mDesiredDestName;
}
# oi_archive_name is max 255 bytes, which include a timestamp and an
# exclamation mark, so restrict file name to 240 bytes.
if ( strlen( $this->mFilteredName ) > 240 ) {
$this->mTitleError = self::FILENAME_TOO_LONG;
$this->mTitle = null;
return $this->mTitle;
}
/**
* Chop off any directories in the given filename. Then
* filter out illegal characters, and try to make a legible name
* out of it. We'll strip some silently that Title would die on.
*/
$this->mFilteredName = wfStripIllegalFilenameChars( $this->mFilteredName );
/* Normalize to title form before we do any further processing */
$nt = Title::makeTitleSafe( NS_FILE, $this->mFilteredName );
if ( is_null( $nt ) ) {
$this->mTitleError = self::ILLEGAL_FILENAME;
$this->mTitle = null;
return $this->mTitle;
}
$this->mFilteredName = $nt->getDBkey();
/**
* We'll want to blacklist against *any* 'extension', and use
* only the final one for the whitelist.
*/
list( $partname, $ext ) = $this->splitExtensions( $this->mFilteredName );
if ( count( $ext ) ) {
$this->mFinalExtension = trim( $ext[count( $ext ) - 1] );
} else {
$this->mFinalExtension = '';
# No extension, try guessing one
$magic = MimeMagic::singleton();
$mime = $magic->guessMimeType( $this->mTempPath );
if ( $mime !== 'unknown/unknown' ) {
# Get a space separated list of extensions
$extList = $magic->getExtensionsForType( $mime );
if ( $extList ) {
# Set the extension to the canonical extension
$this->mFinalExtension = strtok( $extList, ' ' );
# Fix up the other variables
$this->mFilteredName .= ".{$this->mFinalExtension}";
$nt = Title::makeTitleSafe( NS_FILE, $this->mFilteredName );
$ext = [ $this->mFinalExtension ];
}
}
}
/* Don't allow users to override the blacklist (check file extension) */
global $wgCheckFileExtensions, $wgStrictFileExtensions;
global $wgFileExtensions, $wgFileBlacklist;
$blackListedExtensions = $this->checkFileExtensionList( $ext, $wgFileBlacklist );
if ( $this->mFinalExtension == '' ) {
$this->mTitleError = self::FILETYPE_MISSING;
$this->mTitle = null;
return $this->mTitle;
} elseif ( $blackListedExtensions ||
( $wgCheckFileExtensions && $wgStrictFileExtensions &&
!$this->checkFileExtension( $this->mFinalExtension, $wgFileExtensions ) )
) {
$this->mBlackListedExtensions = $blackListedExtensions;
$this->mTitleError = self::FILETYPE_BADTYPE;
$this->mTitle = null;
return $this->mTitle;
}
// Windows may be broken with special characters, see bug 1780
if ( !preg_match( '/^[\x0-\x7f]*$/', $nt->getText() )
&& !RepoGroup::singleton()->getLocalRepo()->backendSupportsUnicodePaths()
) {
$this->mTitleError = self::WINDOWS_NONASCII_FILENAME;
$this->mTitle = null;
return $this->mTitle;
}
# If there was more than one "extension", reassemble the base
# filename to prevent bogus complaints about length
if ( count( $ext ) > 1 ) {
$iterations = count( $ext ) - 1;
for ( $i = 0; $i < $iterations; $i++ ) {
$partname .= '.' . $ext[$i];
}
}
if ( strlen( $partname ) < 1 ) {
$this->mTitleError = self::MIN_LENGTH_PARTNAME;
$this->mTitle = null;
return $this->mTitle;
}
$this->mTitle = $nt;
return $this->mTitle;
}
/**
* Return the local file and initializes if necessary.
*
* @return LocalFile|null
*/
public function getLocalFile() {
if ( is_null( $this->mLocalFile ) ) {
$nt = $this->getTitle();
$this->mLocalFile = is_null( $nt ) ? null : wfLocalFile( $nt );
}
return $this->mLocalFile;
}
/**
* @return UploadStashFile|null
*/
public function getStashFile() {
return $this->mStashFile;
}
/**
* Like stashFile(), but respects extensions' wishes to prevent the stashing. verifyUpload() must
* be called before calling this method (unless $isPartial is true).
*
* Upload stash exceptions are also caught and converted to an error status.
*
* @since 1.28
* @param User $user
* @param bool $isPartial Pass `true` if this is a part of a chunked upload (not a complete file).
* @return Status If successful, value is an UploadStashFile instance
*/
public function tryStashFile( User $user, $isPartial = false ) {
if ( !$isPartial ) {
$error = $this->runUploadStashFileHook( $user );
if ( $error ) {
return call_user_func_array( 'Status::newFatal', $error );
}
}
try {
$file = $this->doStashFile( $user );
return Status::newGood( $file );
} catch ( UploadStashException $e ) {
return Status::newFatal( 'uploadstash-exception', get_class( $e ), $e->getMessage() );
}
}
/**
* @param User $user
* @return array|null Error message and parameters, null if there's no error
*/
protected function runUploadStashFileHook( User $user ) {
$props = $this->mFileProps;
$error = null;
Hooks::run( 'UploadStashFile', [ $this, $user, $props, &$error ] );
if ( $error ) {
if ( !is_array( $error ) ) {
$error = [ $error ];
}
}
return $error;
}
/**
* If the user does not supply all necessary information in the first upload
* form submission (either by accident or by design) then we may want to
* stash the file temporarily, get more information, and publish the file
* later.
*
* This method will stash a file in a temporary directory for later
* processing, and save the necessary descriptive info into the database.
* This method returns the file object, which also has a 'fileKey' property
* which can be passed through a form or API request to find this stashed
* file again.
*
* @deprecated since 1.28 Use tryStashFile() instead
* @param User $user
* @return UploadStashFile Stashed file
* @throws UploadStashBadPathException
* @throws UploadStashFileException
* @throws UploadStashNotLoggedInException
*/
public function stashFile( User $user = null ) {
return $this->doStashFile( $user );
}
/**
* Implementation for stashFile() and tryStashFile().
*