MediaWiki  master
UploadBase.php
Go to the documentation of this file.
1 <?php
24 use MediaWiki\HookContainer\ProtectedHookAccessorTrait;
28 
45 abstract class UploadBase {
46  use ProtectedHookAccessorTrait;
47 
49  protected $mTempPath;
51  protected $tempFileObj;
53  protected $mDesiredDestName;
55  protected $mDestName;
57  protected $mRemoveTempFile;
59  protected $mSourceType;
61  protected $mTitle = false;
63  protected $mTitleError = 0;
65  protected $mFilteredName;
67  protected $mFinalExtension;
69  protected $mLocalFile;
71  protected $mStashFile;
73  protected $mFileSize;
75  protected $mFileProps;
79  protected $mJavaDetected;
81  protected $mSVGNSError;
82 
83  protected static $safeXmlEncodings = [
84  'UTF-8',
85  'ISO-8859-1',
86  'ISO-8859-2',
87  'UTF-16',
88  'UTF-32',
89  'WINDOWS-1250',
90  'WINDOWS-1251',
91  'WINDOWS-1252',
92  'WINDOWS-1253',
93  'WINDOWS-1254',
94  'WINDOWS-1255',
95  'WINDOWS-1256',
96  'WINDOWS-1257',
97  'WINDOWS-1258',
98  ];
99 
100  public const SUCCESS = 0;
101  public const OK = 0;
102  public const EMPTY_FILE = 3;
103  public const MIN_LENGTH_PARTNAME = 4;
104  public const ILLEGAL_FILENAME = 5;
105  public const OVERWRITE_EXISTING_FILE = 7; # Not used anymore; handled by verifyTitlePermissions()
106  public const FILETYPE_MISSING = 8;
107  public const FILETYPE_BADTYPE = 9;
108  public const VERIFICATION_ERROR = 10;
109  public const HOOK_ABORTED = 11;
110  public const FILE_TOO_LARGE = 12;
111  public const WINDOWS_NONASCII_FILENAME = 13;
112  public const FILENAME_TOO_LONG = 14;
113 
118  public function getVerificationErrorCode( $error ) {
119  $code_to_status = [
120  self::EMPTY_FILE => 'empty-file',
121  self::FILE_TOO_LARGE => 'file-too-large',
122  self::FILETYPE_MISSING => 'filetype-missing',
123  self::FILETYPE_BADTYPE => 'filetype-banned',
124  self::MIN_LENGTH_PARTNAME => 'filename-tooshort',
125  self::ILLEGAL_FILENAME => 'illegal-filename',
126  self::OVERWRITE_EXISTING_FILE => 'overwrite',
127  self::VERIFICATION_ERROR => 'verification-error',
128  self::HOOK_ABORTED => 'hookaborted',
129  self::WINDOWS_NONASCII_FILENAME => 'windows-nonascii-filename',
130  self::FILENAME_TOO_LONG => 'filename-toolong',
131  ];
132  return $code_to_status[$error] ?? 'unknown-error';
133  }
134 
141  public static function isEnabled() {
142  global $wgEnableUploads;
143 
144  return $wgEnableUploads && wfIniGetBool( 'file_uploads' );
145  }
146 
155  public static function isAllowed( UserIdentity $user ) {
156  $permissionManager = MediaWikiServices::getInstance()->getPermissionManager();
157  foreach ( [ 'upload', 'edit' ] as $permission ) {
158  if ( !$permissionManager->userHasRight( $user, $permission ) ) {
159  return $permission;
160  }
161  }
162 
163  return true;
164  }
165 
172  public static function isThrottled( $user ) {
173  return $user->pingLimiter( 'upload' );
174  }
175 
177  private static $uploadHandlers = [ 'Stash', 'File', 'Url' ];
178 
186  public static function createFromRequest( &$request, $type = null ) {
187  $type = $type ?: $request->getVal( 'wpSourceType', 'File' );
188 
189  if ( !$type ) {
190  return null;
191  }
192 
193  // Get the upload class
194  $type = ucfirst( $type );
195 
196  // Give hooks the chance to handle this request
198  $className = null;
199  Hooks::runner()->onUploadCreateFromRequest( $type, $className );
200  if ( $className === null ) {
201  $className = 'UploadFrom' . $type;
202  wfDebug( __METHOD__ . ": class name: $className" );
203  if ( !in_array( $type, self::$uploadHandlers ) ) {
204  return null;
205  }
206  }
207 
208  // Check whether this upload class is enabled
209  if ( !$className::isEnabled() ) {
210  return null;
211  }
212 
213  // Check whether the request is valid
214  if ( !$className::isValidRequest( $request ) ) {
215  return null;
216  }
217 
219  $handler = new $className;
220 
221  $handler->initializeFromRequest( $request );
222 
223  return $handler;
224  }
225 
231  public static function isValidRequest( $request ) {
232  return false;
233  }
234 
238  public function __construct() {
239  }
240 
248  public function getSourceType() {
249  return null;
250  }
251 
259  public function initializePathInfo( $name, $tempPath, $fileSize, $removeTempFile = false ) {
260  $this->mDesiredDestName = $name;
261  if ( FileBackend::isStoragePath( $tempPath ) ) {
262  throw new MWException( __METHOD__ . " given storage path `$tempPath`." );
263  }
264 
265  $this->setTempFile( $tempPath, $fileSize );
266  $this->mRemoveTempFile = $removeTempFile;
267  }
268 
274  abstract public function initializeFromRequest( &$request );
275 
280  protected function setTempFile( $tempPath, $fileSize = null ) {
281  $this->mTempPath = $tempPath;
282  $this->mFileSize = $fileSize ?: null;
283  if ( strlen( $this->mTempPath ) && file_exists( $this->mTempPath ) ) {
284  $this->tempFileObj = new TempFSFile( $this->mTempPath );
285  if ( !$fileSize ) {
286  $this->mFileSize = filesize( $this->mTempPath );
287  }
288  } else {
289  $this->tempFileObj = null;
290  }
291  }
292 
298  public function fetchFile() {
299  return Status::newGood();
300  }
301 
306  public function isEmptyFile() {
307  return empty( $this->mFileSize );
308  }
309 
314  public function getFileSize() {
315  return $this->mFileSize;
316  }
317 
323  public function getTempFileSha1Base36() {
324  return FSFile::getSha1Base36FromPath( $this->mTempPath );
325  }
326 
331  public function getRealPath( $srcPath ) {
332  $repo = MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo();
333  if ( FileRepo::isVirtualUrl( $srcPath ) ) {
337  $tmpFile = $repo->getLocalCopy( $srcPath );
338  if ( $tmpFile ) {
339  $tmpFile->bind( $this ); // keep alive with $this
340  }
341  $path = $tmpFile ? $tmpFile->getPath() : false;
342  } else {
343  $path = $srcPath;
344  }
345 
346  return $path;
347  }
348 
366  public function verifyUpload() {
370  if ( $this->isEmptyFile() ) {
371  return [ 'status' => self::EMPTY_FILE ];
372  }
373 
377  $maxSize = self::getMaxUploadSize( $this->getSourceType() );
378  if ( $this->mFileSize > $maxSize ) {
379  return [
380  'status' => self::FILE_TOO_LARGE,
381  'max' => $maxSize,
382  ];
383  }
384 
390  $verification = $this->verifyFile();
391  if ( $verification !== true ) {
392  return [
393  'status' => self::VERIFICATION_ERROR,
394  'details' => $verification
395  ];
396  }
397 
401  $result = $this->validateName();
402  if ( $result !== true ) {
403  return $result;
404  }
405 
406  return [ 'status' => self::OK ];
407  }
408 
415  public function validateName() {
416  $nt = $this->getTitle();
417  if ( $nt === null ) {
418  $result = [ 'status' => $this->mTitleError ];
419  if ( $this->mTitleError == self::ILLEGAL_FILENAME ) {
420  $result['filtered'] = $this->mFilteredName;
421  }
422  if ( $this->mTitleError == self::FILETYPE_BADTYPE ) {
423  $result['finalExt'] = $this->mFinalExtension;
424  if ( count( $this->mBlackListedExtensions ) ) {
425  $result['blacklistedExt'] = $this->mBlackListedExtensions;
426  }
427  }
428 
429  return $result;
430  }
431  $this->mDestName = $this->getLocalFile()->getName();
432 
433  return true;
434  }
435 
445  protected function verifyMimeType( $mime ) {
447  if ( $wgVerifyMimeType ) {
448  wfDebug( "mime: <$mime> extension: <{$this->mFinalExtension}>" );
449  global $wgMimeTypeBlacklist;
450  if ( $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
451  return [ 'filetype-badmime', $mime ];
452  }
453 
454  if ( $wgVerifyMimeTypeIE ) {
455  # Check what Internet Explorer would detect
456  $fp = fopen( $this->mTempPath, 'rb' );
457  $chunk = fread( $fp, 256 );
458  fclose( $fp );
459 
460  $magic = MediaWiki\MediaWikiServices::getInstance()->getMimeAnalyzer();
461  $extMime = $magic->getMimeTypeFromExtensionOrNull( $this->mFinalExtension );
462  $ieTypes = $magic->getIEMimeTypes( $this->mTempPath, $chunk, $extMime );
463  foreach ( $ieTypes as $ieType ) {
464  if ( $this->checkFileExtension( $ieType, $wgMimeTypeBlacklist ) ) {
465  return [ 'filetype-bad-ie-mime', $ieType ];
466  }
467  }
468  }
469  }
470 
471  return true;
472  }
473 
479  protected function verifyFile() {
481 
482  $status = $this->verifyPartialFile();
483  if ( $status !== true ) {
484  return $status;
485  }
486 
487  $mwProps = new MWFileProps( MediaWiki\MediaWikiServices::getInstance()->getMimeAnalyzer() );
488  $this->mFileProps = $mwProps->getPropsFromPath( $this->mTempPath, $this->mFinalExtension );
489  $mime = $this->mFileProps['mime'];
490 
491  if ( $wgVerifyMimeType ) {
492  # XXX: Missing extension will be caught by validateName() via getTitle()
493  if ( $this->mFinalExtension != '' && !$this->verifyExtension( $mime, $this->mFinalExtension ) ) {
494  return [ 'filetype-mime-mismatch', $this->mFinalExtension, $mime ];
495  }
496  }
497 
498  # check for htmlish code and javascript
500  if ( $this->mFinalExtension == 'svg' || $mime == 'image/svg+xml' ) {
501  $svgStatus = $this->detectScriptInSvg( $this->mTempPath, false );
502  if ( $svgStatus !== false ) {
503  return $svgStatus;
504  }
505  }
506  }
507 
508  $handler = MediaHandler::getHandler( $mime );
509  if ( $handler ) {
510  $handlerStatus = $handler->verifyUpload( $this->mTempPath );
511  if ( !$handlerStatus->isOK() ) {
512  $errors = $handlerStatus->getErrorsArray();
513 
514  return reset( $errors );
515  }
516  }
517 
518  $error = true;
519  $this->getHookRunner()->onUploadVerifyFile( $this, $mime, $error );
520  if ( $error !== true ) {
521  if ( !is_array( $error ) ) {
522  $error = [ $error ];
523  }
524  return $error;
525  }
526 
527  wfDebug( __METHOD__ . ": all clear; passing." );
528 
529  return true;
530  }
531 
540  protected function verifyPartialFile() {
542 
543  # getTitle() sets some internal parameters like $this->mFinalExtension
544  $this->getTitle();
545 
546  $mwProps = new MWFileProps( MediaWiki\MediaWikiServices::getInstance()->getMimeAnalyzer() );
547  $this->mFileProps = $mwProps->getPropsFromPath( $this->mTempPath, $this->mFinalExtension );
548 
549  # check MIME type, if desired
550  $mime = $this->mFileProps['file-mime'];
551  $status = $this->verifyMimeType( $mime );
552  if ( $status !== true ) {
553  return $status;
554  }
555 
556  # check for htmlish code and javascript
558  if ( self::detectScript( $this->mTempPath, $mime, $this->mFinalExtension ) ) {
559  return [ 'uploadscripted' ];
560  }
561  if ( $this->mFinalExtension == 'svg' || $mime == 'image/svg+xml' ) {
562  $svgStatus = $this->detectScriptInSvg( $this->mTempPath, true );
563  if ( $svgStatus !== false ) {
564  return $svgStatus;
565  }
566  }
567  }
568 
569  # Check for Java applets, which if uploaded can bypass cross-site
570  # restrictions.
571  if ( !$wgAllowJavaUploads ) {
572  $this->mJavaDetected = false;
573  $zipStatus = ZipDirectoryReader::read( $this->mTempPath,
574  [ $this, 'zipEntryCallback' ] );
575  if ( !$zipStatus->isOK() ) {
576  $errors = $zipStatus->getErrorsArray();
577  $error = reset( $errors );
578  if ( $error[0] !== 'zip-wrong-format' ) {
579  return $error;
580  }
581  }
582  if ( $this->mJavaDetected ) {
583  return [ 'uploadjava' ];
584  }
585  }
586 
587  # Scan the uploaded file for viruses
588  $virus = $this->detectVirus( $this->mTempPath );
589  if ( $virus ) {
590  return [ 'uploadvirus', $virus ];
591  }
592 
593  return true;
594  }
595 
601  public function zipEntryCallback( $entry ) {
602  $names = [ $entry['name'] ];
603 
604  // If there is a null character, cut off the name at it, because JDK's
605  // ZIP_GetEntry() uses strcmp() if the name hashes match. If a file name
606  // were constructed which had ".class\0" followed by a string chosen to
607  // make the hash collide with the truncated name, that file could be
608  // returned in response to a request for the .class file.
609  $nullPos = strpos( $entry['name'], "\000" );
610  if ( $nullPos !== false ) {
611  $names[] = substr( $entry['name'], 0, $nullPos );
612  }
613 
614  // If there is a trailing slash in the file name, we have to strip it,
615  // because that's what ZIP_GetEntry() does.
616  if ( preg_grep( '!\.class/?$!', $names ) ) {
617  $this->mJavaDetected = true;
618  }
619  }
620 
630  public function verifyPermissions( $user ) {
631  return $this->verifyTitlePermissions( $user );
632  }
633 
645  public function verifyTitlePermissions( $user ) {
650  $nt = $this->getTitle();
651  if ( $nt === null ) {
652  return true;
653  }
654  $permManager = MediaWikiServices::getInstance()->getPermissionManager();
655  $permErrors = $permManager->getPermissionErrors( 'edit', $user, $nt );
656  $permErrorsUpload = $permManager->getPermissionErrors( 'upload', $user, $nt );
657  if ( !$nt->exists() ) {
658  $permErrorsCreate = $permManager->getPermissionErrors( 'create', $user, $nt );
659  } else {
660  $permErrorsCreate = [];
661  }
662  if ( $permErrors || $permErrorsUpload || $permErrorsCreate ) {
663  $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsUpload, $permErrors ) );
664  $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsCreate, $permErrors ) );
665 
666  return $permErrors;
667  }
668 
669  $overwriteError = $this->checkOverwrite( $user );
670  if ( $overwriteError !== true ) {
671  return [ $overwriteError ];
672  }
673 
674  return true;
675  }
676 
686  public function checkWarnings( $user = null ) {
687  if ( $user === null ) {
688  // TODO check uses and hard deprecate
689  $user = RequestContext::getMain()->getUser();
690  }
691 
692  $warnings = [];
693 
694  $localFile = $this->getLocalFile();
695  $localFile->load( File::READ_LATEST );
696  $filename = $localFile->getName();
697  $hash = $this->getTempFileSha1Base36();
698 
699  $badFileName = $this->checkBadFileName( $filename, $this->mDesiredDestName );
700  if ( $badFileName !== null ) {
701  $warnings['badfilename'] = $badFileName;
702  }
703 
704  $unwantedFileExtensionDetails = $this->checkUnwantedFileExtensions( $this->mFinalExtension );
705  if ( $unwantedFileExtensionDetails !== null ) {
706  $warnings['filetype-unwanted-type'] = $unwantedFileExtensionDetails;
707  }
708 
709  $fileSizeWarnings = $this->checkFileSize( $this->mFileSize );
710  if ( $fileSizeWarnings ) {
711  $warnings = array_merge( $warnings, $fileSizeWarnings );
712  }
713 
714  $localFileExistsWarnings = $this->checkLocalFileExists( $localFile, $hash );
715  if ( $localFileExistsWarnings ) {
716  $warnings = array_merge( $warnings, $localFileExistsWarnings );
717  }
718 
719  if ( $this->checkLocalFileWasDeleted( $localFile ) ) {
720  $warnings['was-deleted'] = $filename;
721  }
722 
723  // If a file with the same name exists locally then the local file has already been tested
724  // for duplication of content
725  $ignoreLocalDupes = isset( $warnings['exists'] );
726  $dupes = $this->checkAgainstExistingDupes( $hash, $ignoreLocalDupes );
727  if ( $dupes ) {
728  $warnings['duplicate'] = $dupes;
729  }
730 
731  $archivedDupes = $this->checkAgainstArchiveDupes( $hash, $user );
732  if ( $archivedDupes !== null ) {
733  $warnings['duplicate-archive'] = $archivedDupes;
734  }
735 
736  return $warnings;
737  }
738 
750  public static function makeWarningsSerializable( $warnings ) {
751  array_walk_recursive( $warnings, function ( &$param, $key ) {
752  if ( $param instanceof File ) {
753  $param = [
754  'fileName' => $param->getName(),
755  'timestamp' => $param->getTimestamp()
756  ];
757  } elseif ( is_object( $param ) ) {
758  throw new InvalidArgumentException(
759  'UploadBase::makeWarningsSerializable: ' .
760  'Unexpected object of class ' . get_class( $param ) );
761  }
762  } );
763  return $warnings;
764  }
765 
775  private function checkBadFileName( $filename, $desiredFileName ) {
776  $comparableName = str_replace( ' ', '_', $desiredFileName );
777  $comparableName = Title::capitalize( $comparableName, NS_FILE );
778 
779  if ( $desiredFileName != $filename && $comparableName != $filename ) {
780  return $filename;
781  }
782 
783  return null;
784  }
785 
794  private function checkUnwantedFileExtensions( $fileExtension ) {
796 
797  if ( $wgCheckFileExtensions ) {
798  $extensions = array_unique( $wgFileExtensions );
799  if ( !$this->checkFileExtension( $fileExtension, $extensions ) ) {
800  return [
801  $fileExtension,
802  $wgLang->commaList( $extensions ),
803  count( $extensions )
804  ];
805  }
806  }
807 
808  return null;
809  }
810 
816  private function checkFileSize( $fileSize ) {
817  global $wgUploadSizeWarning;
818 
819  $warnings = [];
820 
821  if ( $wgUploadSizeWarning && ( $fileSize > $wgUploadSizeWarning ) ) {
822  $warnings['large-file'] = [
824  Message::sizeParam( $fileSize ),
825  ];
826  }
827 
828  if ( $fileSize == 0 ) {
829  $warnings['empty-file'] = true;
830  }
831 
832  return $warnings;
833  }
834 
841  private function checkLocalFileExists( LocalFile $localFile, $hash ) {
842  $warnings = [];
843 
844  $exists = self::getExistsWarning( $localFile );
845  if ( $exists !== false ) {
846  $warnings['exists'] = $exists;
847 
848  // check if file is an exact duplicate of current file version
849  if ( $hash === $localFile->getSha1() ) {
850  $warnings['no-change'] = $localFile;
851  }
852 
853  // check if file is an exact duplicate of older versions of this file
854  $history = $localFile->getHistory();
855  foreach ( $history as $oldFile ) {
856  if ( $hash === $oldFile->getSha1() ) {
857  $warnings['duplicate-version'][] = $oldFile;
858  }
859  }
860  }
861 
862  return $warnings;
863  }
864 
865  private function checkLocalFileWasDeleted( LocalFile $localFile ) {
866  return $localFile->wasDeleted() && !$localFile->exists();
867  }
868 
875  private function checkAgainstExistingDupes( $hash, $ignoreLocalDupes ) {
876  $dupes = MediaWikiServices::getInstance()->getRepoGroup()->findBySha1( $hash );
877  $title = $this->getTitle();
878  foreach ( $dupes as $key => $dupe ) {
879  if (
880  ( $dupe instanceof LocalFile ) &&
881  $ignoreLocalDupes &&
882  $title->equals( $dupe->getTitle() )
883  ) {
884  unset( $dupes[$key] );
885  }
886  }
887 
888  return $dupes;
889  }
890 
898  private function checkAgainstArchiveDupes( $hash, User $user ) {
899  $archivedFile = new ArchivedFile( null, 0, '', $hash );
900  if ( $archivedFile->getID() > 0 ) {
901  if ( $archivedFile->userCan( File::DELETED_FILE, $user ) ) {
902  return $archivedFile->getName();
903  } else {
904  return '';
905  }
906  }
907 
908  return null;
909  }
910 
928  public function performUpload(
929  $comment, $pageText, $watch, $user, $tags = [], ?string $watchlistExpiry = null
930  ) {
931  $this->getLocalFile()->load( File::READ_LATEST );
932  $props = $this->mFileProps;
933 
934  $error = null;
935  $this->getHookRunner()->onUploadVerifyUpload( $this, $user, $props, $comment, $pageText, $error );
936  if ( $error ) {
937  if ( !is_array( $error ) ) {
938  $error = [ $error ];
939  }
940  return Status::newFatal( ...$error );
941  }
942 
943  $status = $this->getLocalFile()->upload(
944  $this->mTempPath,
945  $comment,
946  $pageText,
948  $props,
949  false,
950  $user,
951  $tags
952  );
953 
954  if ( $status->isGood() ) {
955  if ( $watch ) {
957  $this->getLocalFile()->getTitle(),
958  $user,
960  $watchlistExpiry
961  );
962  }
963  $this->getHookRunner()->onUploadComplete( $this );
964 
965  $this->postProcessUpload();
966  }
967 
968  return $status;
969  }
970 
977  public function postProcessUpload() {
978  }
979 
986  public function getTitle() {
987  if ( $this->mTitle !== false ) {
988  return $this->mTitle;
989  }
990  if ( !is_string( $this->mDesiredDestName ) ) {
991  $this->mTitleError = self::ILLEGAL_FILENAME;
992  $this->mTitle = null;
993 
994  return $this->mTitle;
995  }
996  /* Assume that if a user specified File:Something.jpg, this is an error
997  * and that the namespace prefix needs to be stripped of.
998  */
999  $title = Title::newFromText( $this->mDesiredDestName );
1000  if ( $title && $title->getNamespace() === NS_FILE ) {
1001  $this->mFilteredName = $title->getDBkey();
1002  } else {
1003  $this->mFilteredName = $this->mDesiredDestName;
1004  }
1005 
1006  # oi_archive_name is max 255 bytes, which include a timestamp and an
1007  # exclamation mark, so restrict file name to 240 bytes.
1008  if ( strlen( $this->mFilteredName ) > 240 ) {
1009  $this->mTitleError = self::FILENAME_TOO_LONG;
1010  $this->mTitle = null;
1011 
1012  return $this->mTitle;
1013  }
1014 
1020  $this->mFilteredName = wfStripIllegalFilenameChars( $this->mFilteredName );
1021  /* Normalize to title form before we do any further processing */
1022  $nt = Title::makeTitleSafe( NS_FILE, $this->mFilteredName );
1023  if ( $nt === null ) {
1024  $this->mTitleError = self::ILLEGAL_FILENAME;
1025  $this->mTitle = null;
1026 
1027  return $this->mTitle;
1028  }
1029  $this->mFilteredName = $nt->getDBkey();
1030 
1035  list( $partname, $ext ) = $this->splitExtensions( $this->mFilteredName );
1036 
1037  if ( $ext !== [] ) {
1038  $this->mFinalExtension = trim( end( $ext ) );
1039  } else {
1040  $this->mFinalExtension = '';
1041 
1042  # No extension, try guessing one
1043  $magic = MediaWiki\MediaWikiServices::getInstance()->getMimeAnalyzer();
1044  $mime = $magic->guessMimeType( $this->mTempPath );
1045  if ( $mime !== 'unknown/unknown' ) {
1046  # Get a space separated list of extensions
1047  $mimeExt = $magic->getExtensionFromMimeTypeOrNull( $mime );
1048  if ( $mimeExt !== null ) {
1049  # Set the extension to the canonical extension
1050  $this->mFinalExtension = $mimeExt;
1051 
1052  # Fix up the other variables
1053  $this->mFilteredName .= ".{$this->mFinalExtension}";
1054  $nt = Title::makeTitleSafe( NS_FILE, $this->mFilteredName );
1056  }
1057  }
1058  }
1059 
1060  /* Don't allow users to override the blacklist (check file extension) */
1063 
1064  $blackListedExtensions = $this->checkFileExtensionList( $ext, $wgFileBlacklist );
1065 
1066  if ( $this->mFinalExtension == '' ) {
1067  $this->mTitleError = self::FILETYPE_MISSING;
1068  $this->mTitle = null;
1069 
1070  return $this->mTitle;
1071  } elseif ( $blackListedExtensions ||
1073  !$this->checkFileExtension( $this->mFinalExtension, $wgFileExtensions ) )
1074  ) {
1075  $this->mBlackListedExtensions = $blackListedExtensions;
1076  $this->mTitleError = self::FILETYPE_BADTYPE;
1077  $this->mTitle = null;
1078 
1079  return $this->mTitle;
1080  }
1081 
1082  // Windows may be broken with special characters, see T3780
1083  if ( !preg_match( '/^[\x0-\x7f]*$/', $nt->getText() )
1084  && !MediaWikiServices::getInstance()->getRepoGroup()
1085  ->getLocalRepo()->backendSupportsUnicodePaths()
1086  ) {
1087  $this->mTitleError = self::WINDOWS_NONASCII_FILENAME;
1088  $this->mTitle = null;
1089 
1090  return $this->mTitle;
1091  }
1092 
1093  # If there was more than one "extension", reassemble the base
1094  # filename to prevent bogus complaints about length
1095  if ( count( $ext ) > 1 ) {
1096  $iterations = count( $ext ) - 1;
1097  for ( $i = 0; $i < $iterations; $i++ ) {
1098  $partname .= '.' . $ext[$i];
1099  }
1100  }
1101 
1102  if ( strlen( $partname ) < 1 ) {
1103  $this->mTitleError = self::MIN_LENGTH_PARTNAME;
1104  $this->mTitle = null;
1105 
1106  return $this->mTitle;
1107  }
1108 
1109  $this->mTitle = $nt;
1110 
1111  return $this->mTitle;
1112  }
1113 
1120  public function getLocalFile() {
1121  if ( $this->mLocalFile === null ) {
1122  $nt = $this->getTitle();
1123  $this->mLocalFile = $nt === null
1124  ? null
1125  : MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo()->newFile( $nt );
1126  }
1127 
1128  return $this->mLocalFile;
1129  }
1130 
1134  public function getStashFile() {
1135  return $this->mStashFile;
1136  }
1137 
1150  public function tryStashFile( User $user, $isPartial = false ) {
1151  if ( !$isPartial ) {
1152  $error = $this->runUploadStashFileHook( $user );
1153  if ( $error ) {
1154  return Status::newFatal( ...$error );
1155  }
1156  }
1157  try {
1158  $file = $this->doStashFile( $user );
1159  return Status::newGood( $file );
1160  } catch ( UploadStashException $e ) {
1161  return Status::newFatal( 'uploadstash-exception', get_class( $e ), $e->getMessage() );
1162  }
1163  }
1164 
1169  protected function runUploadStashFileHook( User $user ) {
1170  $props = $this->mFileProps;
1171  $error = null;
1172  $this->getHookRunner()->onUploadStashFile( $this, $user, $props, $error );
1173  if ( $error && !is_array( $error ) ) {
1174  $error = [ $error ];
1175  }
1176  return $error;
1177  }
1178 
1198  public function stashFile( User $user = null ) {
1199  wfDeprecated( __METHOD__, '1.28' );
1200 
1201  return $this->doStashFile( $user );
1202  }
1203 
1211  protected function doStashFile( User $user = null ) {
1212  $stash = MediaWikiServices::getInstance()->getRepoGroup()
1213  ->getLocalRepo()->getUploadStash( $user );
1214  $file = $stash->stashFile( $this->mTempPath, $this->getSourceType() );
1215  $this->mStashFile = $file;
1216 
1217  return $file;
1218  }
1219 
1224  public function cleanupTempFile() {
1225  if ( $this->mRemoveTempFile && $this->tempFileObj ) {
1226  // Delete when all relevant TempFSFile handles go out of scope
1227  wfDebug( __METHOD__ . ": Marked temporary file '{$this->mTempPath}' for removal" );
1228  $this->tempFileObj->autocollect();
1229  }
1230  }
1231 
1232  public function getTempPath() {
1233  return $this->mTempPath;
1234  }
1235 
1245  public static function splitExtensions( $filename ) {
1246  $bits = explode( '.', $filename );
1247  $basename = array_shift( $bits );
1248 
1249  return [ $basename, $bits ];
1250  }
1251 
1260  public static function checkFileExtension( $ext, $list ) {
1261  return in_array( strtolower( $ext ), $list );
1262  }
1263 
1272  public static function checkFileExtensionList( $ext, $list ) {
1273  return array_intersect( array_map( 'strtolower', $ext ), $list );
1274  }
1275 
1283  public static function verifyExtension( $mime, $extension ) {
1284  $magic = MediaWiki\MediaWikiServices::getInstance()->getMimeAnalyzer();
1285 
1286  if ( !$mime || $mime == 'unknown' || $mime == 'unknown/unknown' ) {
1287  if ( !$magic->isRecognizableExtension( $extension ) ) {
1288  wfDebug( __METHOD__ . ": passing file with unknown detected mime type; " .
1289  "unrecognized extension '$extension', can't verify" );
1290 
1291  return true;
1292  } else {
1293  wfDebug( __METHOD__ . ": rejecting file with unknown detected mime type; " .
1294  "recognized extension '$extension', so probably invalid file" );
1295 
1296  return false;
1297  }
1298  }
1299 
1300  $match = $magic->isMatchingExtension( $extension, $mime );
1301 
1302  if ( $match === null ) {
1303  if ( $magic->getTypesForExtension( $extension ) !== null ) {
1304  wfDebug( __METHOD__ . ": No extension known for $mime, but we know a mime for $extension" );
1305 
1306  return false;
1307  } else {
1308  wfDebug( __METHOD__ . ": no file extension known for mime type $mime, passing file" );
1309 
1310  return true;
1311  }
1312  } elseif ( $match === true ) {
1313  wfDebug( __METHOD__ . ": mime type $mime matches extension $extension, passing file" );
1314 
1316  return true;
1317  } else {
1318  wfDebug( __METHOD__
1319  . ": mime type $mime mismatches file extension $extension, rejecting file" );
1320 
1321  return false;
1322  }
1323  }
1324 
1336  public static function detectScript( $file, $mime, $extension ) {
1337  # ugly hack: for text files, always look at the entire file.
1338  # For binary field, just check the first K.
1339 
1340  $isText = strpos( $mime, 'text/' ) === 0;
1341  if ( $isText ) {
1342  $chunk = file_get_contents( $file );
1343  } else {
1344  $fp = fopen( $file, 'rb' );
1345  $chunk = fread( $fp, 1024 );
1346  fclose( $fp );
1347  }
1348 
1349  $chunk = strtolower( $chunk );
1350 
1351  if ( !$chunk ) {
1352  return false;
1353  }
1354 
1355  # decode from UTF-16 if needed (could be used for obfuscation).
1356  if ( substr( $chunk, 0, 2 ) == "\xfe\xff" ) {
1357  $enc = 'UTF-16BE';
1358  } elseif ( substr( $chunk, 0, 2 ) == "\xff\xfe" ) {
1359  $enc = 'UTF-16LE';
1360  } else {
1361  $enc = null;
1362  }
1363 
1364  if ( $enc !== null ) {
1365  $chunk = iconv( $enc, "ASCII//IGNORE", $chunk );
1366  }
1367 
1368  $chunk = trim( $chunk );
1369 
1371  wfDebug( __METHOD__ . ": checking for embedded scripts and HTML stuff" );
1372 
1373  # check for HTML doctype
1374  if ( preg_match( "/<!DOCTYPE *X?HTML/i", $chunk ) ) {
1375  return true;
1376  }
1377 
1378  // Some browsers will interpret obscure xml encodings as UTF-8, while
1379  // PHP/expat will interpret the given encoding in the xml declaration (T49304)
1380  if ( $extension == 'svg' || strpos( $mime, 'image/svg' ) === 0 ) {
1381  if ( self::checkXMLEncodingMissmatch( $file ) ) {
1382  return true;
1383  }
1384  }
1385 
1386  // Quick check for HTML heuristics in old IE and Safari.
1387  //
1388  // The exact heuristics IE uses are checked separately via verifyMimeType(), so we
1389  // don't need them all here as it can cause many false positives.
1390  //
1391  // Check for `<script` and such still to forbid script tags and embedded HTML in SVG:
1392  $tags = [
1393  '<body',
1394  '<head',
1395  '<html', # also in safari
1396  '<script', # also in safari
1397  ];
1398 
1399  foreach ( $tags as $tag ) {
1400  if ( strpos( $chunk, $tag ) !== false ) {
1401  wfDebug( __METHOD__ . ": found something that may make it be mistaken for html: $tag" );
1402 
1403  return true;
1404  }
1405  }
1406 
1407  /*
1408  * look for JavaScript
1409  */
1410 
1411  # resolve entity-refs to look at attributes. may be harsh on big files... cache result?
1412  $chunk = Sanitizer::decodeCharReferences( $chunk );
1413 
1414  # look for script-types
1415  if ( preg_match( '!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim', $chunk ) ) {
1416  wfDebug( __METHOD__ . ": found script types" );
1417 
1418  return true;
1419  }
1420 
1421  # look for html-style script-urls
1422  if ( preg_match( '!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
1423  wfDebug( __METHOD__ . ": found html-style script urls" );
1424 
1425  return true;
1426  }
1427 
1428  # look for css-style script-urls
1429  if ( preg_match( '!url\s*\‍(\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
1430  wfDebug( __METHOD__ . ": found css-style script urls" );
1431 
1432  return true;
1433  }
1434 
1435  wfDebug( __METHOD__ . ": no scripts found" );
1436 
1437  return false;
1438  }
1439 
1447  public static function checkXMLEncodingMissmatch( $file ) {
1448  global $wgSVGMetadataCutoff;
1449  $contents = file_get_contents( $file, false, null, 0, $wgSVGMetadataCutoff );
1450  $encodingRegex = '!encoding[ \t\n\r]*=[ \t\n\r]*[\'"](.*?)[\'"]!si';
1451 
1452  if ( preg_match( "!<\?xml\b(.*?)\?>!si", $contents, $matches ) ) {
1453  if ( preg_match( $encodingRegex, $matches[1], $encMatch )
1454  && !in_array( strtoupper( $encMatch[1] ), self::$safeXmlEncodings )
1455  ) {
1456  wfDebug( __METHOD__ . ": Found unsafe XML encoding '{$encMatch[1]}'" );
1457 
1458  return true;
1459  }
1460  } elseif ( preg_match( "!<\?xml\b!si", $contents ) ) {
1461  // Start of XML declaration without an end in the first $wgSVGMetadataCutoff
1462  // bytes. There shouldn't be a legitimate reason for this to happen.
1463  wfDebug( __METHOD__ . ": Unmatched XML declaration start" );
1464 
1465  return true;
1466  } elseif ( substr( $contents, 0, 4 ) == "\x4C\x6F\xA7\x94" ) {
1467  // EBCDIC encoded XML
1468  wfDebug( __METHOD__ . ": EBCDIC Encoded XML" );
1469 
1470  return true;
1471  }
1472 
1473  // It's possible the file is encoded with multi-byte encoding, so re-encode attempt to
1474  // detect the encoding in case is specifies an encoding not whitelisted in self::$safeXmlEncodings
1475  $attemptEncodings = [ 'UTF-16', 'UTF-16BE', 'UTF-32', 'UTF-32BE' ];
1476  foreach ( $attemptEncodings as $encoding ) {
1477  Wikimedia\suppressWarnings();
1478  $str = iconv( $encoding, 'UTF-8', $contents );
1479  Wikimedia\restoreWarnings();
1480  if ( $str != '' && preg_match( "!<\?xml\b(.*?)\?>!si", $str, $matches ) ) {
1481  if ( preg_match( $encodingRegex, $matches[1], $encMatch )
1482  && !in_array( strtoupper( $encMatch[1] ), self::$safeXmlEncodings )
1483  ) {
1484  wfDebug( __METHOD__ . ": Found unsafe XML encoding '{$encMatch[1]}'" );
1485 
1486  return true;
1487  }
1488  } elseif ( $str != '' && preg_match( "!<\?xml\b!si", $str ) ) {
1489  // Start of XML declaration without an end in the first $wgSVGMetadataCutoff
1490  // bytes. There shouldn't be a legitimate reason for this to happen.
1491  wfDebug( __METHOD__ . ": Unmatched XML declaration start" );
1492 
1493  return true;
1494  }
1495  }
1496 
1497  return false;
1498  }
1499 
1505  protected function detectScriptInSvg( $filename, $partial ) {
1506  $this->mSVGNSError = false;
1507  $check = new XmlTypeCheck(
1508  $filename,
1509  [ $this, 'checkSvgScriptCallback' ],
1510  true,
1511  [
1512  'processing_instruction_handler' => [ __CLASS__, 'checkSvgPICallback' ],
1513  'external_dtd_handler' => [ __CLASS__, 'checkSvgExternalDTD' ],
1514  ]
1515  );
1516  if ( $check->wellFormed !== true ) {
1517  // Invalid xml (T60553)
1518  // But only when non-partial (T67724)
1519  return $partial ? false : [ 'uploadinvalidxml' ];
1520  } elseif ( $check->filterMatch ) {
1521  if ( $this->mSVGNSError ) {
1522  return [ 'uploadscriptednamespace', $this->mSVGNSError ];
1523  }
1524 
1525  return $check->filterMatchType;
1526  }
1527 
1528  return false;
1529  }
1530 
1537  public static function checkSvgPICallback( $target, $data ) {
1538  // Don't allow external stylesheets (T59550)
1539  if ( preg_match( '/xml-stylesheet/i', $target ) ) {
1540  return [ 'upload-scripted-pi-callback' ];
1541  }
1542 
1543  return false;
1544  }
1545 
1557  public static function checkSvgExternalDTD( $type, $publicId, $systemId ) {
1558  // This doesn't include the XHTML+MathML+SVG doctype since we don't
1559  // allow XHTML anyways.
1560  $allowedDTDs = [
1561  'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd',
1562  'http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd',
1563  'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11-basic.dtd',
1564  'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11-tiny.dtd',
1565  // https://phabricator.wikimedia.org/T168856
1566  'http://www.w3.org/TR/2001/PR-SVG-20010719/DTD/svg10.dtd',
1567  ];
1568  if ( $type !== 'PUBLIC'
1569  || !in_array( $systemId, $allowedDTDs )
1570  || strpos( $publicId, "-//W3C//" ) !== 0
1571  ) {
1572  return [ 'upload-scripted-dtd' ];
1573  }
1574  return false;
1575  }
1576 
1584  public function checkSvgScriptCallback( $element, $attribs, $data = null ) {
1585  list( $namespace, $strippedElement ) = $this->splitXmlNamespace( $element );
1586 
1587  // We specifically don't include:
1588  // http://www.w3.org/1999/xhtml (T62771)
1589  static $validNamespaces = [
1590  '',
1591  'adobe:ns:meta/',
1592  'http://creativecommons.org/ns#',
1593  'http://inkscape.sourceforge.net/dtd/sodipodi-0.dtd',
1594  'http://ns.adobe.com/adobeillustrator/10.0/',
1595  'http://ns.adobe.com/adobesvgviewerextensions/3.0/',
1596  'http://ns.adobe.com/extensibility/1.0/',
1597  'http://ns.adobe.com/flows/1.0/',
1598  'http://ns.adobe.com/illustrator/1.0/',
1599  'http://ns.adobe.com/imagereplacement/1.0/',
1600  'http://ns.adobe.com/pdf/1.3/',
1601  'http://ns.adobe.com/photoshop/1.0/',
1602  'http://ns.adobe.com/saveforweb/1.0/',
1603  'http://ns.adobe.com/variables/1.0/',
1604  'http://ns.adobe.com/xap/1.0/',
1605  'http://ns.adobe.com/xap/1.0/g/',
1606  'http://ns.adobe.com/xap/1.0/g/img/',
1607  'http://ns.adobe.com/xap/1.0/mm/',
1608  'http://ns.adobe.com/xap/1.0/rights/',
1609  'http://ns.adobe.com/xap/1.0/stype/dimensions#',
1610  'http://ns.adobe.com/xap/1.0/stype/font#',
1611  'http://ns.adobe.com/xap/1.0/stype/manifestitem#',
1612  'http://ns.adobe.com/xap/1.0/stype/resourceevent#',
1613  'http://ns.adobe.com/xap/1.0/stype/resourceref#',
1614  'http://ns.adobe.com/xap/1.0/t/pg/',
1615  'http://purl.org/dc/elements/1.1/',
1616  'http://purl.org/dc/elements/1.1',
1617  'http://schemas.microsoft.com/visio/2003/svgextensions/',
1618  'http://sodipodi.sourceforge.net/dtd/sodipodi-0.dtd',
1619  'http://taptrix.com/inkpad/svg_extensions',
1620  'http://web.resource.org/cc/',
1621  'http://www.freesoftware.fsf.org/bkchem/cdml',
1622  'http://www.inkscape.org/namespaces/inkscape',
1623  'http://www.opengis.net/gml',
1624  'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
1625  'http://www.w3.org/2000/svg',
1626  'http://www.w3.org/tr/rec-rdf-syntax/',
1627  'http://www.w3.org/2000/01/rdf-schema#',
1628  ];
1629 
1630  // Inkscape mangles namespace definitions created by Adobe Illustrator.
1631  // This is nasty but harmless. (T144827)
1632  $isBuggyInkscape = preg_match( '/^&(#38;)*ns_[a-z_]+;$/', $namespace );
1633 
1634  if ( !( $isBuggyInkscape || in_array( $namespace, $validNamespaces ) ) ) {
1635  wfDebug( __METHOD__ . ": Non-svg namespace '$namespace' in uploaded file." );
1637  $this->mSVGNSError = $namespace;
1638 
1639  return true;
1640  }
1641 
1642  /*
1643  * check for elements that can contain javascript
1644  */
1645  if ( $strippedElement == 'script' ) {
1646  wfDebug( __METHOD__ . ": Found script element '$element' in uploaded file." );
1647 
1648  return [ 'uploaded-script-svg', $strippedElement ];
1649  }
1650 
1651  # e.g., <svg xmlns="http://www.w3.org/2000/svg">
1652  # <handler xmlns:ev="http://www.w3.org/2001/xml-events" ev:event="load">alert(1)</handler> </svg>
1653  if ( $strippedElement == 'handler' ) {
1654  wfDebug( __METHOD__ . ": Found scriptable element '$element' in uploaded file." );
1655 
1656  return [ 'uploaded-script-svg', $strippedElement ];
1657  }
1658 
1659  # SVG reported in Feb '12 that used xml:stylesheet to generate javascript block
1660  if ( $strippedElement == 'stylesheet' ) {
1661  wfDebug( __METHOD__ . ": Found scriptable element '$element' in uploaded file." );
1662 
1663  return [ 'uploaded-script-svg', $strippedElement ];
1664  }
1665 
1666  # Block iframes, in case they pass the namespace check
1667  if ( $strippedElement == 'iframe' ) {
1668  wfDebug( __METHOD__ . ": iframe in uploaded file." );
1669 
1670  return [ 'uploaded-script-svg', $strippedElement ];
1671  }
1672 
1673  # Check <style> css
1674  if ( $strippedElement == 'style'
1675  && self::checkCssFragment( Sanitizer::normalizeCss( $data ) )
1676  ) {
1677  wfDebug( __METHOD__ . ": hostile css in style element." );
1678  return [ 'uploaded-hostile-svg' ];
1679  }
1680 
1681  foreach ( $attribs as $attrib => $value ) {
1682  $stripped = $this->stripXmlNamespace( $attrib );
1683  $value = strtolower( $value );
1684 
1685  if ( substr( $stripped, 0, 2 ) == 'on' ) {
1686  wfDebug( __METHOD__
1687  . ": Found event-handler attribute '$attrib'='$value' in uploaded file." );
1688 
1689  return [ 'uploaded-event-handler-on-svg', $attrib, $value ];
1690  }
1691 
1692  # Do not allow relative links, or unsafe url schemas.
1693  # For <a> tags, only data:, http: and https: and same-document
1694  # fragment links are allowed. For all other tags, only data:
1695  # and fragment are allowed.
1696  if ( $stripped == 'href'
1697  && $value !== ''
1698  && strpos( $value, 'data:' ) !== 0
1699  && strpos( $value, '#' ) !== 0
1700  ) {
1701  if ( !( $strippedElement === 'a'
1702  && preg_match( '!^https?://!i', $value ) )
1703  ) {
1704  wfDebug( __METHOD__ . ": Found href attribute <$strippedElement "
1705  . "'$attrib'='$value' in uploaded file." );
1706 
1707  return [ 'uploaded-href-attribute-svg', $strippedElement, $attrib, $value ];
1708  }
1709  }
1710 
1711  # only allow data: targets that should be safe. This prevents vectors like,
1712  # image/svg, text/xml, application/xml, and text/html, which can contain scripts
1713  if ( $stripped == 'href' && strncasecmp( 'data:', $value, 5 ) === 0 ) {
1714  // rfc2397 parameters. This is only slightly slower than (;[\w;]+)*.
1715  // phpcs:ignore Generic.Files.LineLength
1716  $parameters = '(?>;[a-zA-Z0-9\!#$&\'*+.^_`{|}~-]+=(?>[a-zA-Z0-9\!#$&\'*+.^_`{|}~-]+|"(?>[\0-\x0c\x0e-\x21\x23-\x5b\x5d-\x7f]+|\\\\[\0-\x7f])*"))*(?:;base64)?';
1717 
1718  if ( !preg_match( "!^data:\s*image/(gif|jpeg|jpg|png)$parameters,!i", $value ) ) {
1719  wfDebug( __METHOD__ . ": Found href to unwhitelisted data: uri "
1720  . "\"<$strippedElement '$attrib'='$value'...\" in uploaded file." );
1721  return [ 'uploaded-href-unsafe-target-svg', $strippedElement, $attrib, $value ];
1722  }
1723  }
1724 
1725  # Change href with animate from (http://html5sec.org/#137).
1726  if ( $stripped === 'attributename'
1727  && $strippedElement === 'animate'
1728  && $this->stripXmlNamespace( $value ) == 'href'
1729  ) {
1730  wfDebug( __METHOD__ . ": Found animate that might be changing href using from "
1731  . "\"<$strippedElement '$attrib'='$value'...\" in uploaded file." );
1732 
1733  return [ 'uploaded-animate-svg', $strippedElement, $attrib, $value ];
1734  }
1735 
1736  # use set/animate to add event-handler attribute to parent
1737  if ( ( $strippedElement == 'set' || $strippedElement == 'animate' )
1738  && $stripped == 'attributename'
1739  && substr( $value, 0, 2 ) == 'on'
1740  ) {
1741  wfDebug( __METHOD__ . ": Found svg setting event-handler attribute with "
1742  . "\"<$strippedElement $stripped='$value'...\" in uploaded file." );
1743 
1744  return [ 'uploaded-setting-event-handler-svg', $strippedElement, $stripped, $value ];
1745  }
1746 
1747  # use set to add href attribute to parent element
1748  if ( $strippedElement == 'set'
1749  && $stripped == 'attributename'
1750  && strpos( $value, 'href' ) !== false
1751  ) {
1752  wfDebug( __METHOD__ . ": Found svg setting href attribute '$value' in uploaded file." );
1753 
1754  return [ 'uploaded-setting-href-svg' ];
1755  }
1756 
1757  # use set to add a remote / data / script target to an element
1758  if ( $strippedElement == 'set'
1759  && $stripped == 'to'
1760  && preg_match( '!(http|https|data|script):!sim', $value )
1761  ) {
1762  wfDebug( __METHOD__ . ": Found svg setting attribute to '$value' in uploaded file." );
1763 
1764  return [ 'uploaded-wrong-setting-svg', $value ];
1765  }
1766 
1767  # use handler attribute with remote / data / script
1768  if ( $stripped == 'handler' && preg_match( '!(http|https|data|script):!sim', $value ) ) {
1769  wfDebug( __METHOD__ . ": Found svg setting handler with remote/data/script "
1770  . "'$attrib'='$value' in uploaded file." );
1771 
1772  return [ 'uploaded-setting-handler-svg', $attrib, $value ];
1773  }
1774 
1775  # use CSS styles to bring in remote code
1776  if ( $stripped == 'style'
1777  && self::checkCssFragment( Sanitizer::normalizeCss( $value ) )
1778  ) {
1779  wfDebug( __METHOD__ . ": Found svg setting a style with "
1780  . "remote url '$attrib'='$value' in uploaded file." );
1781  return [ 'uploaded-remote-url-svg', $attrib, $value ];
1782  }
1783 
1784  # Several attributes can include css, css character escaping isn't allowed
1785  $cssAttrs = [ 'font', 'clip-path', 'fill', 'filter', 'marker',
1786  'marker-end', 'marker-mid', 'marker-start', 'mask', 'stroke' ];
1787  if ( in_array( $stripped, $cssAttrs )
1788  && self::checkCssFragment( $value )
1789  ) {
1790  wfDebug( __METHOD__ . ": Found svg setting a style with "
1791  . "remote url '$attrib'='$value' in uploaded file." );
1792  return [ 'uploaded-remote-url-svg', $attrib, $value ];
1793  }
1794 
1795  # image filters can pull in url, which could be svg that executes scripts
1796  # Only allow url( "#foo" ). Do not allow url( http://example.com )
1797  if ( $strippedElement == 'image'
1798  && $stripped == 'filter'
1799  && preg_match( '!url\s*\‍(\s*["\']?[^#]!sim', $value )
1800  ) {
1801  wfDebug( __METHOD__ . ": Found image filter with url: "
1802  . "\"<$strippedElement $stripped='$value'...\" in uploaded file." );
1803 
1804  return [ 'uploaded-image-filter-svg', $strippedElement, $stripped, $value ];
1805  }
1806  }
1807 
1808  return false; // No scripts detected
1809  }
1810 
1817  private static function checkCssFragment( $value ) {
1818  # Forbid external stylesheets, for both reliability and to protect viewer's privacy
1819  if ( stripos( $value, '@import' ) !== false ) {
1820  return true;
1821  }
1822 
1823  # We allow @font-face to embed fonts with data: urls, so we snip the string
1824  # 'url' out so this case won't match when we check for urls below
1825  $pattern = '!(@font-face\s*{[^}]*src:)url(\‍("data:;base64,)!im';
1826  $value = preg_replace( $pattern, '$1$2', $value );
1827 
1828  # Check for remote and executable CSS. Unlike in Sanitizer::checkCss, the CSS
1829  # properties filter and accelerator don't seem to be useful for xss in SVG files.
1830  # Expression and -o-link don't seem to work either, but filtering them here in case.
1831  # Additionally, we catch remote urls like url("http:..., url('http:..., url(http:...,
1832  # but not local ones such as url("#..., url('#..., url(#....
1833  if ( preg_match( '!expression
1834  | -o-link\s*:
1835  | -o-link-source\s*:
1836  | -o-replace\s*:!imx', $value ) ) {
1837  return true;
1838  }
1839 
1840  if ( preg_match_all(
1841  "!(\s*(url|image|image-set)\s*\‍(\s*[\"']?\s*[^#]+.*?\‍))!sim",
1842  $value,
1843  $matches
1844  ) !== 0
1845  ) {
1846  # TODO: redo this in one regex. Until then, url("#whatever") matches the first
1847  foreach ( $matches[1] as $match ) {
1848  if ( !preg_match( "!\s*(url|image|image-set)\s*\‍(\s*(#|'#|\"#)!im", $match ) ) {
1849  return true;
1850  }
1851  }
1852  }
1853 
1854  if ( preg_match( '/[\000-\010\013\016-\037\177]/', $value ) ) {
1855  return true;
1856  }
1857 
1858  return false;
1859  }
1860 
1866  private static function splitXmlNamespace( $element ) {
1867  // 'http://www.w3.org/2000/svg:script' -> [ 'http://www.w3.org/2000/svg', 'script' ]
1868  $parts = explode( ':', strtolower( $element ) );
1869  $name = array_pop( $parts );
1870  $ns = implode( ':', $parts );
1871 
1872  return [ $ns, $name ];
1873  }
1874 
1879  private function stripXmlNamespace( $name ) {
1880  // 'http://www.w3.org/2000/svg:script' -> 'script'
1881  $parts = explode( ':', strtolower( $name ) );
1882 
1883  return array_pop( $parts );
1884  }
1885 
1896  public static function detectVirus( $file ) {
1898 
1899  if ( !$wgAntivirus ) {
1900  wfDebug( __METHOD__ . ": virus scanner disabled" );
1901 
1902  return null;
1903  }
1904 
1905  if ( !$wgAntivirusSetup[$wgAntivirus] ) {
1906  wfDebug( __METHOD__ . ": unknown virus scanner: $wgAntivirus" );
1907  $wgOut->wrapWikiMsg( "<div class=\"error\">\n$1\n</div>",
1908  [ 'virus-badscanner', $wgAntivirus ] );
1909 
1910  return wfMessage( 'virus-unknownscanner' )->text() . " $wgAntivirus";
1911  }
1912 
1913  # look up scanner configuration
1914  $command = $wgAntivirusSetup[$wgAntivirus]['command'];
1915  $exitCodeMap = $wgAntivirusSetup[$wgAntivirus]['codemap'];
1916  $msgPattern = $wgAntivirusSetup[$wgAntivirus]['messagepattern'] ?? null;
1917 
1918  if ( strpos( $command, "%f" ) === false ) {
1919  # simple pattern: append file to scan
1920  $command .= " " . Shell::escape( $file );
1921  } else {
1922  # complex pattern: replace "%f" with file to scan
1923  $command = str_replace( "%f", Shell::escape( $file ), $command );
1924  }
1925 
1926  wfDebug( __METHOD__ . ": running virus scan: $command " );
1927 
1928  # execute virus scanner
1929  $exitCode = false;
1930 
1931  # NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
1932  # that does not seem to be worth the pain.
1933  # Ask me (Duesentrieb) about it if it's ever needed.
1934  $output = wfShellExecWithStderr( $command, $exitCode );
1935 
1936  # map exit code to AV_xxx constants.
1937  $mappedCode = $exitCode;
1938  if ( $exitCodeMap ) {
1939  if ( isset( $exitCodeMap[$exitCode] ) ) {
1940  $mappedCode = $exitCodeMap[$exitCode];
1941  } elseif ( isset( $exitCodeMap["*"] ) ) {
1942  $mappedCode = $exitCodeMap["*"];
1943  }
1944  }
1945 
1946  /* NB: AV_NO_VIRUS is 0 but AV_SCAN_FAILED is false,
1947  * so we need the strict equalities === and thus can't use a switch here
1948  */
1949  if ( $mappedCode === AV_SCAN_FAILED ) {
1950  # scan failed (code was mapped to false by $exitCodeMap)
1951  wfDebug( __METHOD__ . ": failed to scan $file (code $exitCode)." );
1952 
1953  $output = $wgAntivirusRequired
1954  ? wfMessage( 'virus-scanfailed', [ $exitCode ] )->text()
1955  : null;
1956  } elseif ( $mappedCode === AV_SCAN_ABORTED ) {
1957  # scan failed because filetype is unknown (probably imune)
1958  wfDebug( __METHOD__ . ": unsupported file type $file (code $exitCode)." );
1959  $output = null;
1960  } elseif ( $mappedCode === AV_NO_VIRUS ) {
1961  # no virus found
1962  wfDebug( __METHOD__ . ": file passed virus scan." );
1963  $output = false;
1964  } else {
1965  $output = trim( $output );
1966 
1967  if ( !$output ) {
1968  $output = true; # if there's no output, return true
1969  } elseif ( $msgPattern ) {
1970  $groups = [];
1971  if ( preg_match( $msgPattern, $output, $groups ) && $groups[1] ) {
1972  $output = $groups[1];
1973  }
1974  }
1975 
1976  wfDebug( __METHOD__ . ": FOUND VIRUS! scanner feedback: $output" );
1977  }
1978 
1979  return $output;
1980  }
1981 
1990  private function checkOverwrite( $user ) {
1991  // First check whether the local file can be overwritten
1992  $file = $this->getLocalFile();
1993  $file->load( File::READ_LATEST );
1994  if ( $file->exists() ) {
1995  if ( !self::userCanReUpload( $user, $file ) ) {
1996  return [ 'fileexists-forbidden', $file->getName() ];
1997  } else {
1998  return true;
1999  }
2000  }
2001 
2002  $services = MediaWikiServices::getInstance();
2003 
2004  /* Check shared conflicts: if the local file does not exist, but
2005  * RepoGroup::findFile finds a file, it exists in a shared repository.
2006  */
2007  $file = $services->getRepoGroup()->findFile( $this->getTitle(), [ 'latest' => true ] );
2008  if ( $file && !$services->getPermissionManager()
2009  ->userHasRight( $user, 'reupload-shared' )
2010  ) {
2011  return [ 'fileexists-shared-forbidden', $file->getName() ];
2012  }
2013 
2014  return true;
2015  }
2016 
2024  public static function userCanReUpload( User $user, File $img ) {
2025  $permissionManager = MediaWikiServices::getInstance()->getPermissionManager();
2026  if ( $permissionManager->userHasRight( $user, 'reupload' ) ) {
2027  return true; // non-conditional
2028  } elseif ( !$permissionManager->userHasRight( $user, 'reupload-own' ) ) {
2029  return false;
2030  }
2031 
2032  if ( !( $img instanceof LocalFile ) ) {
2033  return false;
2034  }
2035 
2036  $img->load();
2037 
2038  return $user->getId() == $img->getUser( 'id' );
2039  }
2040 
2052  public static function getExistsWarning( $file ) {
2053  if ( $file->exists() ) {
2054  return [ 'warning' => 'exists', 'file' => $file ];
2055  }
2056 
2057  if ( $file->getTitle()->getArticleID() ) {
2058  return [ 'warning' => 'page-exists', 'file' => $file ];
2059  }
2060 
2061  if ( strpos( $file->getName(), '.' ) == false ) {
2062  $partname = $file->getName();
2063  $extension = '';
2064  } else {
2065  $n = strrpos( $file->getName(), '.' );
2066  $extension = substr( $file->getName(), $n + 1 );
2067  $partname = substr( $file->getName(), 0, $n );
2068  }
2069  $normalizedExtension = File::normalizeExtension( $extension );
2070  $localRepo = MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo();
2071 
2072  if ( $normalizedExtension != $extension ) {
2073  // We're not using the normalized form of the extension.
2074  // Normal form is lowercase, using most common of alternate
2075  // extensions (eg 'jpg' rather than 'JPEG').
2076 
2077  // Check for another file using the normalized form...
2078  $nt_lc = Title::makeTitle( NS_FILE, "{$partname}.{$normalizedExtension}" );
2079  $file_lc = $localRepo->newFile( $nt_lc );
2080 
2081  if ( $file_lc->exists() ) {
2082  return [
2083  'warning' => 'exists-normalized',
2084  'file' => $file,
2085  'normalizedFile' => $file_lc
2086  ];
2087  }
2088  }
2089 
2090  // Check for files with the same name but a different extension
2091  $similarFiles = $localRepo->findFilesByPrefix( "{$partname}.", 1 );
2092  if ( count( $similarFiles ) ) {
2093  return [
2094  'warning' => 'exists-normalized',
2095  'file' => $file,
2096  'normalizedFile' => $similarFiles[0],
2097  ];
2098  }
2099 
2100  if ( self::isThumbName( $file->getName() ) ) {
2101  # Check for filenames like 50px- or 180px-, these are mostly thumbnails
2102  $nt_thb = Title::newFromText(
2103  substr( $partname, strpos( $partname, '-' ) + 1 ) . '.' . $extension,
2104  NS_FILE
2105  );
2106  $file_thb = $localRepo->newFile( $nt_thb );
2107  if ( $file_thb->exists() ) {
2108  return [
2109  'warning' => 'thumb',
2110  'file' => $file,
2111  'thumbFile' => $file_thb
2112  ];
2113  } else {
2114  // File does not exist, but we just don't like the name
2115  return [
2116  'warning' => 'thumb-name',
2117  'file' => $file,
2118  'thumbFile' => $file_thb
2119  ];
2120  }
2121  }
2122 
2123  foreach ( self::getFilenamePrefixBlacklist() as $prefix ) {
2124  if ( substr( $partname, 0, strlen( $prefix ) ) == $prefix ) {
2125  return [
2126  'warning' => 'bad-prefix',
2127  'file' => $file,
2128  'prefix' => $prefix
2129  ];
2130  }
2131  }
2132 
2133  return false;
2134  }
2135 
2141  public static function isThumbName( $filename ) {
2142  $n = strrpos( $filename, '.' );
2143  $partname = $n ? substr( $filename, 0, $n ) : $filename;
2144 
2145  return (
2146  substr( $partname, 3, 3 ) == 'px-' ||
2147  substr( $partname, 2, 3 ) == 'px-'
2148  ) &&
2149  preg_match( "/[0-9]{2}/", substr( $partname, 0, 2 ) );
2150  }
2151 
2157  public static function getFilenamePrefixBlacklist() {
2158  $blacklist = [];
2159  $message = wfMessage( 'filename-prefix-blacklist' )->inContentLanguage();
2160  if ( !$message->isDisabled() ) {
2161  $lines = explode( "\n", $message->plain() );
2162  foreach ( $lines as $line ) {
2163  // Remove comment lines
2164  $comment = substr( trim( $line ), 0, 1 );
2165  if ( $comment == '#' || $comment == '' ) {
2166  continue;
2167  }
2168  // Remove additional comments after a prefix
2169  $comment = strpos( $line, '#' );
2170  if ( $comment > 0 ) {
2171  $line = substr( $line, 0, $comment - 1 );
2172  }
2173  $blacklist[] = trim( $line );
2174  }
2175  }
2176 
2177  return $blacklist;
2178  }
2179 
2191  public function getImageInfo( $result ) {
2192  $localFile = $this->getLocalFile();
2193  $stashFile = $this->getStashFile();
2194  // Calling a different API module depending on whether the file was stashed is less than optimal.
2195  // In fact, calling API modules here at all is less than optimal. Maybe it should be refactored.
2196  if ( $stashFile ) {
2198  $info = ApiQueryStashImageInfo::getInfo( $stashFile, array_flip( $imParam ), $result );
2199  } else {
2201  $info = ApiQueryImageInfo::getInfo( $localFile, array_flip( $imParam ), $result );
2202  }
2203 
2204  return $info;
2205  }
2206 
2211  public function convertVerifyErrorToStatus( $error ) {
2212  $code = $error['status'];
2213  unset( $code['status'] );
2214 
2215  return Status::newFatal( $this->getVerificationErrorCode( $code ), $error );
2216  }
2217 
2225  public static function getMaxUploadSize( $forType = null ) {
2226  global $wgMaxUploadSize;
2227 
2228  if ( is_array( $wgMaxUploadSize ) ) {
2229  if ( $forType !== null && isset( $wgMaxUploadSize[$forType] ) ) {
2230  return $wgMaxUploadSize[$forType];
2231  } else {
2232  return $wgMaxUploadSize['*'];
2233  }
2234  } else {
2235  return intval( $wgMaxUploadSize );
2236  }
2237  }
2238 
2246  public static function getMaxPhpUploadSize() {
2247  $phpMaxFileSize = wfShorthandToInteger(
2248  ini_get( 'upload_max_filesize' ),
2249  PHP_INT_MAX
2250  );
2251  $phpMaxPostSize = wfShorthandToInteger(
2252  ini_get( 'post_max_size' ),
2253  PHP_INT_MAX
2254  ) ?: PHP_INT_MAX;
2255  return min( $phpMaxFileSize, $phpMaxPostSize );
2256  }
2257 
2267  public static function getSessionStatus( User $user, $statusKey ) {
2268  $store = self::getUploadSessionStore();
2269  $key = self::getUploadSessionKey( $store, $user, $statusKey );
2270 
2271  return $store->get( $key );
2272  }
2273 
2286  public static function setSessionStatus( User $user, $statusKey, $value ) {
2287  $store = self::getUploadSessionStore();
2288  $key = self::getUploadSessionKey( $store, $user, $statusKey );
2289 
2290  if ( $value === false ) {
2291  $store->delete( $key );
2292  } else {
2293  $store->set( $key, $value, $store::TTL_DAY );
2294  }
2295  }
2296 
2303  private static function getUploadSessionKey( BagOStuff $store, User $user, $statusKey ) {
2304  return $store->makeKey(
2305  'uploadstatus',
2306  $user->getId() ?: md5( $user->getName() ),
2307  $statusKey
2308  );
2309  }
2310 
2314  private static function getUploadSessionStore() {
2315  return ObjectCache::getInstance( 'db-replicated' );
2316  }
2317 }
UploadBase
UploadBase and subclasses are the backend of MediaWiki's file uploads.
Definition: UploadBase.php:45
UploadBase\checkSvgExternalDTD
static checkSvgExternalDTD( $type, $publicId, $systemId)
Verify that DTD urls referenced are only the standard dtds.
Definition: UploadBase.php:1557
AV_NO_VIRUS
const AV_NO_VIRUS
Definition: Defines.php:100
LocalFile\getSha1
getSha1()
Stable to override.
Definition: LocalFile.php:2261
UploadBase\getRealPath
getRealPath( $srcPath)
Definition: UploadBase.php:331
File\wasDeleted
wasDeleted()
Was this file ever deleted from the wiki?
Definition: File.php:1988
$wgAllowJavaUploads
$wgAllowJavaUploads
Allow Java archive uploads.
Definition: DefaultSettings.php:1065
MediaWiki\Shell\Shell
Executes shell commands.
Definition: Shell.php:44
ApiQueryImageInfo\getPropertyNames
static getPropertyNames( $filter=[])
Returns all possible parameters to iiprop.
Definition: ApiQueryImageInfo.php:742
UploadBase\checkWarnings
checkWarnings( $user=null)
Check for non fatal problems with the file.
Definition: UploadBase.php:686
UploadBase\verifyTitlePermissions
verifyTitlePermissions( $user)
Check whether the user can edit, upload and create the image.
Definition: UploadBase.php:645
UploadBase\$mFileSize
int null $mFileSize
Definition: UploadBase.php:73
Title\newFromText
static newFromText( $text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:328
UploadBase\VERIFICATION_ERROR
const VERIFICATION_ERROR
Definition: UploadBase.php:108
ApiQueryStashImageInfo\getPropertyNames
static getPropertyNames( $filter=null)
Returns all possible parameters to siiprop.
Definition: ApiQueryStashImageInfo.php:87
UploadBase\$mBlackListedExtensions
string[] $mBlackListedExtensions
Definition: UploadBase.php:77
UploadBase\isAllowed
static isAllowed(UserIdentity $user)
Returns true if the user can use this upload module or else a string identifying the missing permissi...
Definition: UploadBase.php:155
UploadBase\$mJavaDetected
bool null $mJavaDetected
Definition: UploadBase.php:79
$wgFileBlacklist
$wgFileBlacklist
Files with these extensions will never be allowed as uploads.
Definition: DefaultSettings.php:1033
UploadBase\stashFile
stashFile(User $user=null)
If the user does not supply all necessary information in the first upload form submission (either by ...
Definition: UploadBase.php:1198
StatusValue\newFatal
static newFatal( $message,... $parameters)
Factory function for fatal errors.
Definition: StatusValue.php:70
User\getId
getId()
Get the user's ID.
Definition: User.php:1999
UploadBase\isThrottled
static isThrottled( $user)
Returns true if the user has surpassed the upload rate limit, false otherwise.
Definition: UploadBase.php:172
WatchAction\doWatch
static doWatch(Title $title, User $user, $checkRights=User::CHECK_USER_RIGHTS, ?string $expiry=null)
Watch a page.
Definition: WatchAction.php:256
UploadBase\makeWarningsSerializable
static makeWarningsSerializable( $warnings)
Convert the warnings array returned by checkWarnings() to something that can be serialized.
Definition: UploadBase.php:750
UploadBase\isThumbName
static isThumbName( $filename)
Helper function that checks whether the filename looks like a thumbnail.
Definition: UploadBase.php:2141
UploadBase\getSourceType
getSourceType()
Returns the upload type.
Definition: UploadBase.php:248
AV_SCAN_FAILED
const AV_SCAN_FAILED
Definition: Defines.php:103
UploadBase\FILE_TOO_LARGE
const FILE_TOO_LARGE
Definition: UploadBase.php:110
UploadBase\checkAgainstArchiveDupes
checkAgainstArchiveDupes( $hash, User $user)
Definition: UploadBase.php:898
UploadBase\MIN_LENGTH_PARTNAME
const MIN_LENGTH_PARTNAME
Definition: UploadBase.php:103
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:163
UploadBase\verifyUpload
verifyUpload()
Verify whether the upload is sane.
Definition: UploadBase.php:366
UploadBase\postProcessUpload
postProcessUpload()
Perform extra steps after a successful upload.
Definition: UploadBase.php:977
UploadBase\$mRemoveTempFile
string null $mRemoveTempFile
Definition: UploadBase.php:57
UploadBase\isEnabled
static isEnabled()
Returns true if uploads are enabled.
Definition: UploadBase.php:141
UploadBase\checkFileExtensionList
static checkFileExtensionList( $ext, $list)
Perform case-insensitive match against a list of file extensions.
Definition: UploadBase.php:1272
UploadBase\getTitle
getTitle()
Returns the title of the file to be uploaded.
Definition: UploadBase.php:986
$wgMaxUploadSize
$wgMaxUploadSize
Max size for uploads, in bytes.
Definition: DefaultSettings.php:951
UploadBase\$mTitle
Title bool $mTitle
Definition: UploadBase.php:61
UploadBase\getMaxPhpUploadSize
static getMaxPhpUploadSize()
Get the PHP maximum uploaded file size, based on ini settings.
Definition: UploadBase.php:2246
UploadBase\cleanupTempFile
cleanupTempFile()
If we've modified the upload file we need to manually remove it on exit to clean up.
Definition: UploadBase.php:1224
UploadBase\initializeFromRequest
initializeFromRequest(&$request)
Initialize from a WebRequest.
UploadBase\getLocalFile
getLocalFile()
Return the local file and initializes if necessary.
Definition: UploadBase.php:1120
UploadBase\checkBadFileName
checkBadFileName( $filename, $desiredFileName)
Check whether the resulting filename is different from the desired one, but ignore things like ucfirs...
Definition: UploadBase.php:775
$wgFileExtensions
$wgFileExtensions
This is the list of preferred extensions for uploading files.
Definition: DefaultSettings.php:1026
UploadBase\$mFinalExtension
string null $mFinalExtension
Definition: UploadBase.php:67
LocalFile\getHistory
getHistory( $limit=null, $start=null, $end=null, $inc=true)
purgeDescription inherited
Definition: LocalFile.php:1225
NS_FILE
const NS_FILE
Definition: Defines.php:75
$file
if(PHP_SAPI !='cli-server') if(!isset( $_SERVER['SCRIPT_FILENAME'])) $file
Item class for a filearchive table row.
Definition: router.php:42
UploadStashFile
Definition: UploadStashFile.php:24
UploadBase\setSessionStatus
static setSessionStatus(User $user, $statusKey, $value)
Set the current status of a chunked upload (used for polling)
Definition: UploadBase.php:2286
UploadBase\getFilenamePrefixBlacklist
static getFilenamePrefixBlacklist()
Get a list of blacklisted filename prefixes from [[MediaWiki:Filename-prefix-blacklist]].
Definition: UploadBase.php:2157
BagOStuff
Class representing a cache/ephemeral data store.
Definition: BagOStuff.php:71
$wgMimeTypeBlacklist
$wgMimeTypeBlacklist
Files with these MIME types will never be allowed as uploads if $wgVerifyMimeType is enabled.
Definition: DefaultSettings.php:1047
wfMessage
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
Definition: GlobalFunctions.php:1220
$wgVerifyMimeTypeIE
$wgVerifyMimeTypeIE
Determines whether extra checks for IE type detection should be applied.
Definition: DefaultSettings.php:1497
UploadBase\$uploadHandlers
static string[] $uploadHandlers
Upload handlers.
Definition: UploadBase.php:177
UploadBase\$tempFileObj
TempFSFile null $tempFileObj
Wrapper to handle deleting the temp file.
Definition: UploadBase.php:51
UploadBase\HOOK_ABORTED
const HOOK_ABORTED
Definition: UploadBase.php:109
UploadBase\checkAgainstExistingDupes
checkAgainstExistingDupes( $hash, $ignoreLocalDupes)
Definition: UploadBase.php:875
UploadBase\OK
const OK
Definition: UploadBase.php:101
UploadBase\stripXmlNamespace
stripXmlNamespace( $name)
Definition: UploadBase.php:1879
UploadBase\$mFilteredName
string null $mFilteredName
Definition: UploadBase.php:65
UploadBase\validateName
validateName()
Verify that the name is valid and, if necessary, that we can overwrite.
Definition: UploadBase.php:415
$wgStrictFileExtensions
$wgStrictFileExtensions
If this is turned off, users may override the warning for files not covered by $wgFileExtensions.
Definition: DefaultSettings.php:1080
ApiQueryImageInfo\getInfo
static getInfo( $file, $prop, $result, $thumbParams=null, $opts=false)
Get result information for an image revision.
Definition: ApiQueryImageInfo.php:375
UploadBase\isValidRequest
static isValidRequest( $request)
Check whether a request if valid for this handler.
Definition: UploadBase.php:231
MediaWiki\User\UserIdentity
Interface for objects representing user identity.
Definition: UserIdentity.php:32
UploadBase\EMPTY_FILE
const EMPTY_FILE
Definition: UploadBase.php:102
UploadBase\verifyPermissions
verifyPermissions( $user)
Alias for verifyTitlePermissions.
Definition: UploadBase.php:630
UploadBase\checkFileSize
checkFileSize( $fileSize)
Definition: UploadBase.php:816
AV_SCAN_ABORTED
const AV_SCAN_ABORTED
Definition: Defines.php:102
UploadBase\runUploadStashFileHook
runUploadStashFileHook(User $user)
Definition: UploadBase.php:1169
MediaWiki\MediaWikiServices\getInstance
static getInstance()
Returns the global default instance of the top level service locator.
Definition: MediaWikiServices.php:195
UploadBase\checkSvgScriptCallback
checkSvgScriptCallback( $element, $attribs, $data=null)
Definition: UploadBase.php:1584
File
Implements some public methods and some protected utility functions which are required by multiple ch...
Definition: File.php:63
Title\getDBkey
getDBkey()
Get the main part with underscores.
Definition: Title.php:1025
MWException
MediaWiki exception.
Definition: MWException.php:29
UploadBase\performUpload
performUpload( $comment, $pageText, $watch, $user, $tags=[], ?string $watchlistExpiry=null)
Really perform the upload.
Definition: UploadBase.php:928
wfStripIllegalFilenameChars
wfStripIllegalFilenameChars( $name)
Replace all invalid characters with '-'.
Definition: GlobalFunctions.php:2590
$wgUploadSizeWarning
$wgUploadSizeWarning
Warn if uploaded files are larger than this (in bytes), or false to disable.
Definition: DefaultSettings.php:1093
wfDeprecated
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Logs a warning that $function is deprecated.
Definition: GlobalFunctions.php:1027
$wgAntivirusRequired
$wgAntivirusRequired
Determines if a failed virus scan (AV_SCAN_FAILED) will cause the file to be rejected.
Definition: DefaultSettings.php:1482
UploadBase\verifyExtension
static verifyExtension( $mime, $extension)
Checks if the MIME type of the uploaded file matches the file extension.
Definition: UploadBase.php:1283
wfArrayDiff2
wfArrayDiff2( $a, $b)
Like array_diff( $a, $b ) except that it works with two-dimensional arrays.
Definition: GlobalFunctions.php:112
UploadBase\checkLocalFileWasDeleted
checkLocalFileWasDeleted(LocalFile $localFile)
Definition: UploadBase.php:865
FileBackend\isStoragePath
static isStoragePath( $path)
Check if a given path is a "mwstore://" path.
Definition: FileBackend.php:1528
UploadBase\WINDOWS_NONASCII_FILENAME
const WINDOWS_NONASCII_FILENAME
Definition: UploadBase.php:111
UploadBase\verifyMimeType
verifyMimeType( $mime)
Verify the MIME type.
Definition: UploadBase.php:445
$matches
$matches
Definition: NoLocalSettings.php:24
UploadBase\verifyFile
verifyFile()
Verifies that it's ok to include the uploaded file.
Definition: UploadBase.php:479
UploadBase\tryStashFile
tryStashFile(User $user, $isPartial=false)
Like stashFile(), but respects extensions' wishes to prevent the stashing.
Definition: UploadBase.php:1150
FSFile\getSha1Base36FromPath
static getSha1Base36FromPath( $path)
Get a SHA-1 hash of a file in the local filesystem, in base-36 lower case encoding,...
Definition: FSFile.php:225
UploadBase\getVerificationErrorCode
getVerificationErrorCode( $error)
Definition: UploadBase.php:118
UploadBase\getImageInfo
getImageInfo( $result)
Gets image info about the file just uploaded.
Definition: UploadBase.php:2191
$wgLang
$wgLang
Definition: Setup.php:778
$wgAntivirusSetup
$wgAntivirusSetup
Configuration for different virus scanners.
Definition: DefaultSettings.php:1464
MediaWiki
A helper class for throttling authentication attempts.
ObjectCache\getInstance
static getInstance( $id)
Get a cached instance of the specified type of cache object.
Definition: ObjectCache.php:78
UploadBase\getStashFile
getStashFile()
Definition: UploadBase.php:1134
UploadBase\zipEntryCallback
zipEntryCallback( $entry)
Callback for ZipDirectoryReader to detect Java class files.
Definition: UploadBase.php:601
UploadBase\detectVirus
static detectVirus( $file)
Generic wrapper function for a virus scanner program.
Definition: UploadBase.php:1896
UploadBase\getUploadSessionKey
static getUploadSessionKey(BagOStuff $store, User $user, $statusKey)
Definition: UploadBase.php:2303
$title
$title
Definition: testCompression.php:38
MWFileProps
MimeMagic helper wrapper.
Definition: MWFileProps.php:28
UploadBase\setTempFile
setTempFile( $tempPath, $fileSize=null)
Definition: UploadBase.php:280
UploadBase\getTempPath
getTempPath()
Definition: UploadBase.php:1232
Title\makeTitle
static makeTitle( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:591
UploadBase\$safeXmlEncodings
static $safeXmlEncodings
Definition: UploadBase.php:83
UploadBase\$mTitleError
int $mTitleError
Definition: UploadBase.php:63
wfDebug
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
Definition: GlobalFunctions.php:910
UploadBase\SUCCESS
const SUCCESS
Definition: UploadBase.php:100
LocalFile
Class to represent a local file in the wiki's own database.
Definition: LocalFile.php:59
UploadBase\checkFileExtension
static checkFileExtension( $ext, $list)
Perform case-insensitive match against a list of file extensions.
Definition: UploadBase.php:1260
$wgSVGMetadataCutoff
$wgSVGMetadataCutoff
Don't read SVG metadata beyond this point.
Definition: DefaultSettings.php:1310
UploadBase\detectScript
static detectScript( $file, $mime, $extension)
Heuristic for detecting files that could contain JavaScript instructions or things that may look like...
Definition: UploadBase.php:1336
Title\makeTitleSafe
static makeTitleSafe( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:617
Message\sizeParam
static sizeParam( $size)
Definition: Message.php:1079
UploadBase\splitXmlNamespace
static splitXmlNamespace( $element)
Divide the element name passed by the xml parser to the callback into URI and prifix.
Definition: UploadBase.php:1866
UploadBase\__construct
__construct()
Stable to call.
Definition: UploadBase.php:238
UploadBase\isEmptyFile
isEmptyFile()
Return true if the file is empty.
Definition: UploadBase.php:306
ArchivedFile
Class representing a row of the 'filearchive' table.
Definition: ArchivedFile.php:33
StatusValue\newGood
static newGood( $value=null)
Factory function for good results.
Definition: StatusValue.php:82
Hooks\runner
static runner()
Get a HookRunner instance for calling hooks using the new interfaces.
Definition: Hooks.php:172
UploadBase\checkOverwrite
checkOverwrite( $user)
Check if there's an overwrite conflict and, if so, if restrictions forbid this user from performing t...
Definition: UploadBase.php:1990
UploadBase\detectScriptInSvg
detectScriptInSvg( $filename, $partial)
Definition: UploadBase.php:1505
UploadBase\$mLocalFile
LocalFile null $mLocalFile
Definition: UploadBase.php:69
$line
$line
Definition: mcc.php:119
UploadBase\getUploadSessionStore
static getUploadSessionStore()
Definition: UploadBase.php:2314
TempFSFile
This class is used to hold the location and do limited manipulation of files stored temporarily (this...
Definition: TempFSFile.php:35
UploadBase\checkLocalFileExists
checkLocalFileExists(LocalFile $localFile, $hash)
Definition: UploadBase.php:841
UploadBase\getExistsWarning
static getExistsWarning( $file)
Helper function that does various existence checks for a file.
Definition: UploadBase.php:2052
XmlTypeCheck
Definition: XmlTypeCheck.php:28
UploadBase\FILENAME_TOO_LONG
const FILENAME_TOO_LONG
Definition: UploadBase.php:112
ZipDirectoryReader\read
static read( $fileName, $callback, $options=[])
Read a ZIP file and call a function for each file discovered in it.
Definition: ZipDirectoryReader.php:88
UploadBase\verifyPartialFile
verifyPartialFile()
A verification routine suitable for partial files.
Definition: UploadBase.php:540
UploadBase\$mSVGNSError
string null $mSVGNSError
Definition: UploadBase.php:81
RequestContext\getMain
static getMain()
Get the RequestContext object associated with the main request.
Definition: RequestContext.php:454
wfIniGetBool
wfIniGetBool( $setting)
Safety wrapper around ini_get() for boolean settings.
Definition: GlobalFunctions.php:1994
File\DELETE_SOURCE
const DELETE_SOURCE
Definition: File.php:80
UploadBase\getSessionStatus
static getSessionStatus(User $user, $statusKey)
Get the current status of a chunked upload (used for polling)
Definition: UploadBase.php:2267
$lines
if(!file_exists( $CREDITS)) $lines
Definition: updateCredits.php:49
UploadBase\OVERWRITE_EXISTING_FILE
const OVERWRITE_EXISTING_FILE
Definition: UploadBase.php:105
UploadBase\ILLEGAL_FILENAME
const ILLEGAL_FILENAME
Definition: UploadBase.php:104
UploadBase\getMaxUploadSize
static getMaxUploadSize( $forType=null)
Get MediaWiki's maximum uploaded file size for given type of upload, based on $wgMaxUploadSize.
Definition: UploadBase.php:2225
BagOStuff\makeKey
makeKey( $class,... $components)
Make a cache key, scoped to this instance's keyspace.
UploadBase\createFromRequest
static createFromRequest(&$request, $type=null)
Create a form of UploadBase depending on wpSourceType and initializes it.
Definition: UploadBase.php:186
UploadBase\convertVerifyErrorToStatus
convertVerifyErrorToStatus( $error)
Definition: UploadBase.php:2211
UploadBase\initializePathInfo
initializePathInfo( $name, $tempPath, $fileSize, $removeTempFile=false)
Definition: UploadBase.php:259
wfShorthandToInteger
wfShorthandToInteger( $string='', $default=-1)
Converts shorthand byte notation to integer form.
Definition: GlobalFunctions.php:2655
Title
Represents a title within MediaWiki.
Definition: Title.php:41
$command
$command
Definition: mcc.php:125
Sanitizer\normalizeCss
static normalizeCss( $value)
Normalize CSS into a format we can easily search for hostile input.
Definition: Sanitizer.php:562
UploadBase\splitExtensions
static splitExtensions( $filename)
Split a file into a base name and all dot-delimited 'extensions' on the end.
Definition: UploadBase.php:1245
UploadBase\$mSourceType
string null $mSourceType
Definition: UploadBase.php:59
$wgDisableUploadScriptChecks
$wgDisableUploadScriptChecks
Setting this to true will disable the upload system's checks for HTML/JavaScript.
Definition: DefaultSettings.php:1088
UploadBase\getTempFileSha1Base36
getTempFileSha1Base36()
Get the base 36 SHA1 of the file Stable to override.
Definition: UploadBase.php:323
UploadBase\$mDestName
string null $mDestName
Definition: UploadBase.php:55
Title\capitalize
static capitalize( $text, $ns=NS_MAIN)
Capitalize a text string for a title if it belongs to a namespace that capitalizes.
Definition: Title.php:3298
UploadBase\checkUnwantedFileExtensions
checkUnwantedFileExtensions( $fileExtension)
Definition: UploadBase.php:794
UploadBase\checkSvgPICallback
static checkSvgPICallback( $target, $data)
Callback to filter SVG Processing Instructions.
Definition: UploadBase.php:1537
$path
$path
Definition: NoLocalSettings.php:25
MediaHandler\getHandler
static getHandler( $type)
Get a MediaHandler for a given MIME type from the instance cache.
Definition: MediaHandler.php:53
$wgVerifyMimeType
$wgVerifyMimeType
Determines if the MIME type of uploaded files should be checked.
Definition: DefaultSettings.php:1487
UploadBase\$mTempPath
string $mTempPath
Local file system path to the file to upload (or a local copy)
Definition: UploadBase.php:49
FileRepo\isVirtualUrl
static isVirtualUrl( $url)
Determine if a string is an mwrepo:// URL.
Definition: FileRepo.php:283
UploadBase\fetchFile
fetchFile()
Fetch the file.
Definition: UploadBase.php:298
$wgEnableUploads
$wgEnableUploads
Allow users to upload files.
Definition: DefaultSettings.php:472
$ext
if(!is_readable( $file)) $ext
Definition: router.php:48
File\DELETED_FILE
const DELETED_FILE
Definition: File.php:67
User\IGNORE_USER_RIGHTS
const IGNORE_USER_RIGHTS
Definition: User.php:90
UploadBase\$mStashFile
UploadStashFile null $mStashFile
Definition: UploadBase.php:71
Sanitizer\decodeCharReferences
static decodeCharReferences( $text)
Decode any character references, numeric or named entities, in the text and return a UTF-8 string.
Definition: Sanitizer.php:1232
$mime
$mime
Definition: router.php:60
$wgAntivirus
$wgAntivirus
Internal name of virus scanner.
Definition: DefaultSettings.php:1428
$wgOut
$wgOut
Definition: Setup.php:783
User
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition: User.php:56
User\getName
getName()
Get the user name, or the IP of an anonymous user.
Definition: User.php:2028
UploadBase\getFileSize
getFileSize()
Return the file size.
Definition: UploadBase.php:314
LocalFile\exists
exists()
canRender inherited
Definition: LocalFile.php:1007
$wgCheckFileExtensions
$wgCheckFileExtensions
This is a flag to determine whether or not to check file extensions on upload.
Definition: DefaultSettings.php:1072
UploadBase\$mDesiredDestName
string null $mDesiredDestName
Definition: UploadBase.php:53
UploadBase\$mFileProps
array null $mFileProps
Definition: UploadBase.php:75
UploadStashException
@newable
Definition: UploadStashException.php:27
wfShellExecWithStderr
wfShellExecWithStderr( $cmd, &$retval=null, $environ=[], $limits=[])
Execute a shell command, returning both stdout and stderr.
Definition: GlobalFunctions.php:2112
UploadBase\doStashFile
doStashFile(User $user=null)
Implementation for stashFile() and tryStashFile().
Definition: UploadBase.php:1211
UploadBase\checkXMLEncodingMissmatch
static checkXMLEncodingMissmatch( $file)
Check a whitelist of xml encodings that are known not to be interpreted differently by the server's x...
Definition: UploadBase.php:1447
UploadBase\FILETYPE_MISSING
const FILETYPE_MISSING
Definition: UploadBase.php:106
$type
$type
Definition: testCompression.php:52
UploadBase\FILETYPE_BADTYPE
const FILETYPE_BADTYPE
Definition: UploadBase.php:107
UploadBase\checkCssFragment
static checkCssFragment( $value)
Check a block of CSS or CSS fragment for anything that looks like it is bringing in remote code.
Definition: UploadBase.php:1817