MediaWiki  master
UploadBase.php
Go to the documentation of this file.
1 <?php
27 
42 abstract class UploadBase {
44  protected $mTempPath;
46  protected $tempFileObj;
48  protected $mDesiredDestName;
50  protected $mDestName;
52  protected $mRemoveTempFile;
54  protected $mSourceType;
56  protected $mTitle = false;
58  protected $mTitleError = 0;
60  protected $mFilteredName;
62  protected $mFinalExtension;
64  protected $mLocalFile;
66  protected $mStashFile;
68  protected $mFileSize;
70  protected $mFileProps;
72  protected $mBlackListedExtensions;
74  protected $mJavaDetected;
76  protected $mSVGNSError;
77 
78  protected static $safeXmlEncodings = [
79  'UTF-8',
80  'ISO-8859-1',
81  'ISO-8859-2',
82  'UTF-16',
83  'UTF-32',
84  'WINDOWS-1250',
85  'WINDOWS-1251',
86  'WINDOWS-1252',
87  'WINDOWS-1253',
88  'WINDOWS-1254',
89  'WINDOWS-1255',
90  'WINDOWS-1256',
91  'WINDOWS-1257',
92  'WINDOWS-1258',
93  ];
94 
95  public const SUCCESS = 0;
96  public const OK = 0;
97  public const EMPTY_FILE = 3;
98  public const MIN_LENGTH_PARTNAME = 4;
99  public const ILLEGAL_FILENAME = 5;
100  public const OVERWRITE_EXISTING_FILE = 7; # Not used anymore; handled by verifyTitlePermissions()
101  public const FILETYPE_MISSING = 8;
102  public const FILETYPE_BADTYPE = 9;
103  public const VERIFICATION_ERROR = 10;
104  public const HOOK_ABORTED = 11;
105  public const FILE_TOO_LARGE = 12;
106  public const WINDOWS_NONASCII_FILENAME = 13;
107  public const FILENAME_TOO_LONG = 14;
108 
113  public function getVerificationErrorCode( $error ) {
114  $code_to_status = [
115  self::EMPTY_FILE => 'empty-file',
116  self::FILE_TOO_LARGE => 'file-too-large',
117  self::FILETYPE_MISSING => 'filetype-missing',
118  self::FILETYPE_BADTYPE => 'filetype-banned',
119  self::MIN_LENGTH_PARTNAME => 'filename-tooshort',
120  self::ILLEGAL_FILENAME => 'illegal-filename',
121  self::OVERWRITE_EXISTING_FILE => 'overwrite',
122  self::VERIFICATION_ERROR => 'verification-error',
123  self::HOOK_ABORTED => 'hookaborted',
124  self::WINDOWS_NONASCII_FILENAME => 'windows-nonascii-filename',
125  self::FILENAME_TOO_LONG => 'filename-toolong',
126  ];
127  return $code_to_status[$error] ?? 'unknown-error';
128  }
129 
135  public static function isEnabled() {
136  global $wgEnableUploads;
137 
138  return $wgEnableUploads && wfIniGetBool( 'file_uploads' );
139  }
140 
149  public static function isAllowed( UserIdentity $user ) {
150  $permissionManager = MediaWikiServices::getInstance()->getPermissionManager();
151  foreach ( [ 'upload', 'edit' ] as $permission ) {
152  if ( !$permissionManager->userHasRight( $user, $permission ) ) {
153  return $permission;
154  }
155  }
156 
157  return true;
158  }
159 
166  public static function isThrottled( $user ) {
167  return $user->pingLimiter( 'upload' );
168  }
169 
170  // Upload handlers. Should probably just be a global.
171  private static $uploadHandlers = [ 'Stash', 'File', 'Url' ];
172 
180  public static function createFromRequest( &$request, $type = null ) {
181  $type = $type ?: $request->getVal( 'wpSourceType', 'File' );
182 
183  if ( !$type ) {
184  return null;
185  }
186 
187  // Get the upload class
188  $type = ucfirst( $type );
189 
190  // Give hooks the chance to handle this request
191  $className = null;
192  Hooks::run( 'UploadCreateFromRequest', [ $type, &$className ] );
193  if ( $className === null ) {
194  $className = 'UploadFrom' . $type;
195  wfDebug( __METHOD__ . ": class name: $className\n" );
196  if ( !in_array( $type, self::$uploadHandlers ) ) {
197  return null;
198  }
199  }
200 
201  // Check whether this upload class is enabled
202  if ( !call_user_func( [ $className, 'isEnabled' ] ) ) {
203  return null;
204  }
205 
206  // Check whether the request is valid
207  if ( !call_user_func( [ $className, 'isValidRequest' ], $request ) ) {
208  return null;
209  }
210 
212  $handler = new $className;
213 
214  $handler->initializeFromRequest( $request );
215 
216  return $handler;
217  }
218 
224  public static function isValidRequest( $request ) {
225  return false;
226  }
227 
228  public function __construct() {
229  }
230 
237  public function getSourceType() {
238  return null;
239  }
240 
248  public function initializePathInfo( $name, $tempPath, $fileSize, $removeTempFile = false ) {
249  $this->mDesiredDestName = $name;
250  if ( FileBackend::isStoragePath( $tempPath ) ) {
251  throw new MWException( __METHOD__ . " given storage path `$tempPath`." );
252  }
253 
254  $this->setTempFile( $tempPath, $fileSize );
255  $this->mRemoveTempFile = $removeTempFile;
256  }
257 
263  abstract public function initializeFromRequest( &$request );
264 
269  protected function setTempFile( $tempPath, $fileSize = null ) {
270  $this->mTempPath = $tempPath;
271  $this->mFileSize = $fileSize ?: null;
272  if ( strlen( $this->mTempPath ) && file_exists( $this->mTempPath ) ) {
273  $this->tempFileObj = new TempFSFile( $this->mTempPath );
274  if ( !$fileSize ) {
275  $this->mFileSize = filesize( $this->mTempPath );
276  }
277  } else {
278  $this->tempFileObj = null;
279  }
280  }
281 
286  public function fetchFile() {
287  return Status::newGood();
288  }
289 
294  public function isEmptyFile() {
295  return empty( $this->mFileSize );
296  }
297 
302  public function getFileSize() {
303  return $this->mFileSize;
304  }
305 
310  public function getTempFileSha1Base36() {
311  return FSFile::getSha1Base36FromPath( $this->mTempPath );
312  }
313 
318  public function getRealPath( $srcPath ) {
319  $repo = RepoGroup::singleton()->getLocalRepo();
320  if ( FileRepo::isVirtualUrl( $srcPath ) ) {
324  $tmpFile = $repo->getLocalCopy( $srcPath );
325  if ( $tmpFile ) {
326  $tmpFile->bind( $this ); // keep alive with $this
327  }
328  $path = $tmpFile ? $tmpFile->getPath() : false;
329  } else {
330  $path = $srcPath;
331  }
332 
333  return $path;
334  }
335 
352  public function verifyUpload() {
356  if ( $this->isEmptyFile() ) {
357  return [ 'status' => self::EMPTY_FILE ];
358  }
359 
363  $maxSize = self::getMaxUploadSize( $this->getSourceType() );
364  if ( $this->mFileSize > $maxSize ) {
365  return [
366  'status' => self::FILE_TOO_LARGE,
367  'max' => $maxSize,
368  ];
369  }
370 
376  $verification = $this->verifyFile();
377  if ( $verification !== true ) {
378  return [
379  'status' => self::VERIFICATION_ERROR,
380  'details' => $verification
381  ];
382  }
383 
387  $result = $this->validateName();
388  if ( $result !== true ) {
389  return $result;
390  }
391 
392  return [ 'status' => self::OK ];
393  }
394 
401  public function validateName() {
402  $nt = $this->getTitle();
403  if ( $nt === null ) {
404  $result = [ 'status' => $this->mTitleError ];
405  if ( $this->mTitleError == self::ILLEGAL_FILENAME ) {
406  $result['filtered'] = $this->mFilteredName;
407  }
408  if ( $this->mTitleError == self::FILETYPE_BADTYPE ) {
409  $result['finalExt'] = $this->mFinalExtension;
410  if ( count( $this->mBlackListedExtensions ) ) {
411  $result['blacklistedExt'] = $this->mBlackListedExtensions;
412  }
413  }
414 
415  return $result;
416  }
417  $this->mDestName = $this->getLocalFile()->getName();
418 
419  return true;
420  }
421 
431  protected function verifyMimeType( $mime ) {
433  if ( $wgVerifyMimeType ) {
434  wfDebug( "mime: <$mime> extension: <{$this->mFinalExtension}>\n" );
435  global $wgMimeTypeBlacklist;
436  if ( $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
437  return [ 'filetype-badmime', $mime ];
438  }
439 
440  if ( $wgVerifyMimeTypeIE ) {
441  # Check what Internet Explorer would detect
442  $fp = fopen( $this->mTempPath, 'rb' );
443  $chunk = fread( $fp, 256 );
444  fclose( $fp );
445 
446  $magic = MediaWiki\MediaWikiServices::getInstance()->getMimeAnalyzer();
447  $extMime = $magic->guessTypesForExtension( $this->mFinalExtension );
448  $ieTypes = $magic->getIEMimeTypes( $this->mTempPath, $chunk, $extMime );
449  foreach ( $ieTypes as $ieType ) {
450  if ( $this->checkFileExtension( $ieType, $wgMimeTypeBlacklist ) ) {
451  return [ 'filetype-bad-ie-mime', $ieType ];
452  }
453  }
454  }
455  }
456 
457  return true;
458  }
459 
465  protected function verifyFile() {
467 
468  $status = $this->verifyPartialFile();
469  if ( $status !== true ) {
470  return $status;
471  }
472 
473  $mwProps = new MWFileProps( MediaWiki\MediaWikiServices::getInstance()->getMimeAnalyzer() );
474  $this->mFileProps = $mwProps->getPropsFromPath( $this->mTempPath, $this->mFinalExtension );
475  $mime = $this->mFileProps['mime'];
476 
477  if ( $wgVerifyMimeType ) {
478  # XXX: Missing extension will be caught by validateName() via getTitle()
479  if ( $this->mFinalExtension != '' && !$this->verifyExtension( $mime, $this->mFinalExtension ) ) {
480  return [ 'filetype-mime-mismatch', $this->mFinalExtension, $mime ];
481  }
482  }
483 
484  # check for htmlish code and javascript
486  if ( $this->mFinalExtension == 'svg' || $mime == 'image/svg+xml' ) {
487  $svgStatus = $this->detectScriptInSvg( $this->mTempPath, false );
488  if ( $svgStatus !== false ) {
489  return $svgStatus;
490  }
491  }
492  }
493 
494  $handler = MediaHandler::getHandler( $mime );
495  if ( $handler ) {
496  $handlerStatus = $handler->verifyUpload( $this->mTempPath );
497  if ( !$handlerStatus->isOK() ) {
498  $errors = $handlerStatus->getErrorsArray();
499 
500  return reset( $errors );
501  }
502  }
503 
504  $error = true;
505  Hooks::run( 'UploadVerifyFile', [ $this, $mime, &$error ] );
506  if ( $error !== true ) {
507  if ( !is_array( $error ) ) {
508  $error = [ $error ];
509  }
510  return $error;
511  }
512 
513  wfDebug( __METHOD__ . ": all clear; passing.\n" );
514 
515  return true;
516  }
517 
526  protected function verifyPartialFile() {
528 
529  # getTitle() sets some internal parameters like $this->mFinalExtension
530  $this->getTitle();
531 
532  $mwProps = new MWFileProps( MediaWiki\MediaWikiServices::getInstance()->getMimeAnalyzer() );
533  $this->mFileProps = $mwProps->getPropsFromPath( $this->mTempPath, $this->mFinalExtension );
534 
535  # check MIME type, if desired
536  $mime = $this->mFileProps['file-mime'];
537  $status = $this->verifyMimeType( $mime );
538  if ( $status !== true ) {
539  return $status;
540  }
541 
542  # check for htmlish code and javascript
544  if ( self::detectScript( $this->mTempPath, $mime, $this->mFinalExtension ) ) {
545  return [ 'uploadscripted' ];
546  }
547  if ( $this->mFinalExtension == 'svg' || $mime == 'image/svg+xml' ) {
548  $svgStatus = $this->detectScriptInSvg( $this->mTempPath, true );
549  if ( $svgStatus !== false ) {
550  return $svgStatus;
551  }
552  }
553  }
554 
555  # Check for Java applets, which if uploaded can bypass cross-site
556  # restrictions.
557  if ( !$wgAllowJavaUploads ) {
558  $this->mJavaDetected = false;
559  $zipStatus = ZipDirectoryReader::read( $this->mTempPath,
560  [ $this, 'zipEntryCallback' ] );
561  if ( !$zipStatus->isOK() ) {
562  $errors = $zipStatus->getErrorsArray();
563  $error = reset( $errors );
564  if ( $error[0] !== 'zip-wrong-format' ) {
565  return $error;
566  }
567  }
568  if ( $this->mJavaDetected ) {
569  return [ 'uploadjava' ];
570  }
571  }
572 
573  # Scan the uploaded file for viruses
574  $virus = $this->detectVirus( $this->mTempPath );
575  if ( $virus ) {
576  return [ 'uploadvirus', $virus ];
577  }
578 
579  return true;
580  }
581 
587  public function zipEntryCallback( $entry ) {
588  $names = [ $entry['name'] ];
589 
590  // If there is a null character, cut off the name at it, because JDK's
591  // ZIP_GetEntry() uses strcmp() if the name hashes match. If a file name
592  // were constructed which had ".class\0" followed by a string chosen to
593  // make the hash collide with the truncated name, that file could be
594  // returned in response to a request for the .class file.
595  $nullPos = strpos( $entry['name'], "\000" );
596  if ( $nullPos !== false ) {
597  $names[] = substr( $entry['name'], 0, $nullPos );
598  }
599 
600  // If there is a trailing slash in the file name, we have to strip it,
601  // because that's what ZIP_GetEntry() does.
602  if ( preg_grep( '!\.class/?$!', $names ) ) {
603  $this->mJavaDetected = true;
604  }
605  }
606 
616  public function verifyPermissions( $user ) {
617  return $this->verifyTitlePermissions( $user );
618  }
619 
631  public function verifyTitlePermissions( $user ) {
636  $nt = $this->getTitle();
637  if ( $nt === null ) {
638  return true;
639  }
640  $permErrors = $nt->getUserPermissionsErrors( 'edit', $user );
641  $permErrorsUpload = $nt->getUserPermissionsErrors( 'upload', $user );
642  if ( !$nt->exists() ) {
643  $permErrorsCreate = $nt->getUserPermissionsErrors( 'create', $user );
644  } else {
645  $permErrorsCreate = [];
646  }
647  if ( $permErrors || $permErrorsUpload || $permErrorsCreate ) {
648  $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsUpload, $permErrors ) );
649  $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsCreate, $permErrors ) );
650 
651  return $permErrors;
652  }
653 
654  $overwriteError = $this->checkOverwrite( $user );
655  if ( $overwriteError !== true ) {
656  return [ $overwriteError ];
657  }
658 
659  return true;
660  }
661 
669  public function checkWarnings() {
670  $warnings = [];
671 
672  $localFile = $this->getLocalFile();
673  $localFile->load( File::READ_LATEST );
674  $filename = $localFile->getName();
675  $hash = $this->getTempFileSha1Base36();
676 
677  $badFileName = $this->checkBadFileName( $filename, $this->mDesiredDestName );
678  if ( $badFileName !== null ) {
679  $warnings['badfilename'] = $badFileName;
680  }
681 
682  $unwantedFileExtensionDetails = $this->checkUnwantedFileExtensions( $this->mFinalExtension );
683  if ( $unwantedFileExtensionDetails !== null ) {
684  $warnings['filetype-unwanted-type'] = $unwantedFileExtensionDetails;
685  }
686 
687  $fileSizeWarnings = $this->checkFileSize( $this->mFileSize );
688  if ( $fileSizeWarnings ) {
689  $warnings = array_merge( $warnings, $fileSizeWarnings );
690  }
691 
692  $localFileExistsWarnings = $this->checkLocalFileExists( $localFile, $hash );
693  if ( $localFileExistsWarnings ) {
694  $warnings = array_merge( $warnings, $localFileExistsWarnings );
695  }
696 
697  if ( $this->checkLocalFileWasDeleted( $localFile ) ) {
698  $warnings['was-deleted'] = $filename;
699  }
700 
701  // If a file with the same name exists locally then the local file has already been tested
702  // for duplication of content
703  $ignoreLocalDupes = isset( $warnings[ 'exists '] );
704  $dupes = $this->checkAgainstExistingDupes( $hash, $ignoreLocalDupes );
705  if ( $dupes ) {
706  $warnings['duplicate'] = $dupes;
707  }
708 
709  $archivedDupes = $this->checkAgainstArchiveDupes( $hash );
710  if ( $archivedDupes !== null ) {
711  $warnings['duplicate-archive'] = $archivedDupes;
712  }
713 
714  return $warnings;
715  }
716 
728  public static function makeWarningsSerializable( $warnings ) {
729  array_walk_recursive( $warnings, function ( &$param, $key ) {
730  if ( $param instanceof File ) {
731  $param = [
732  'fileName' => $param->getName(),
733  'timestamp' => $param->getTimestamp()
734  ];
735  } elseif ( is_object( $param ) ) {
736  throw new InvalidArgumentException(
737  'UploadBase::makeWarningsSerializable: ' .
738  'Unexpected object of class ' . get_class( $param ) );
739  }
740  } );
741  return $warnings;
742  }
743 
753  private function checkBadFileName( $filename, $desiredFileName ) {
754  $comparableName = str_replace( ' ', '_', $desiredFileName );
755  $comparableName = Title::capitalize( $comparableName, NS_FILE );
756 
757  if ( $desiredFileName != $filename && $comparableName != $filename ) {
758  return $filename;
759  }
760 
761  return null;
762  }
763 
772  private function checkUnwantedFileExtensions( $fileExtension ) {
774 
775  if ( $wgCheckFileExtensions ) {
776  $extensions = array_unique( $wgFileExtensions );
777  if ( !$this->checkFileExtension( $fileExtension, $extensions ) ) {
778  return [
779  $fileExtension,
780  $wgLang->commaList( $extensions ),
781  count( $extensions )
782  ];
783  }
784  }
785 
786  return null;
787  }
788 
794  private function checkFileSize( $fileSize ) {
795  global $wgUploadSizeWarning;
796 
797  $warnings = [];
798 
799  if ( $wgUploadSizeWarning && ( $fileSize > $wgUploadSizeWarning ) ) {
800  $warnings['large-file'] = [ $wgUploadSizeWarning, $fileSize ];
801  }
802 
803  if ( $fileSize == 0 ) {
804  $warnings['empty-file'] = true;
805  }
806 
807  return $warnings;
808  }
809 
816  private function checkLocalFileExists( LocalFile $localFile, $hash ) {
817  $warnings = [];
818 
819  $exists = self::getExistsWarning( $localFile );
820  if ( $exists !== false ) {
821  $warnings['exists'] = $exists;
822 
823  // check if file is an exact duplicate of current file version
824  if ( $hash === $localFile->getSha1() ) {
825  $warnings['no-change'] = $localFile;
826  }
827 
828  // check if file is an exact duplicate of older versions of this file
829  $history = $localFile->getHistory();
830  foreach ( $history as $oldFile ) {
831  if ( $hash === $oldFile->getSha1() ) {
832  $warnings['duplicate-version'][] = $oldFile;
833  }
834  }
835  }
836 
837  return $warnings;
838  }
839 
840  private function checkLocalFileWasDeleted( LocalFile $localFile ) {
841  return $localFile->wasDeleted() && !$localFile->exists();
842  }
843 
850  private function checkAgainstExistingDupes( $hash, $ignoreLocalDupes ) {
851  $dupes = RepoGroup::singleton()->findBySha1( $hash );
852  $title = $this->getTitle();
853  foreach ( $dupes as $key => $dupe ) {
854  if (
855  ( $dupe instanceof LocalFile ) &&
856  $ignoreLocalDupes &&
857  $title->equals( $dupe->getTitle() )
858  ) {
859  unset( $dupes[$key] );
860  }
861  }
862 
863  return $dupes;
864  }
865 
872  private function checkAgainstArchiveDupes( $hash ) {
873  $archivedFile = new ArchivedFile( null, 0, '', $hash );
874  if ( $archivedFile->getID() > 0 ) {
875  if ( $archivedFile->userCan( File::DELETED_FILE ) ) {
876  return $archivedFile->getName();
877  } else {
878  return '';
879  }
880  }
881 
882  return null;
883  }
884 
898  public function performUpload( $comment, $pageText, $watch, $user, $tags = [] ) {
899  $this->getLocalFile()->load( File::READ_LATEST );
900  $props = $this->mFileProps;
901 
902  $error = null;
903  Hooks::run( 'UploadVerifyUpload', [ $this, $user, $props, $comment, $pageText, &$error ] );
904  if ( $error ) {
905  if ( !is_array( $error ) ) {
906  $error = [ $error ];
907  }
908  return Status::newFatal( ...$error );
909  }
910 
911  $status = $this->getLocalFile()->upload(
912  $this->mTempPath,
913  $comment,
914  $pageText,
916  $props,
917  false,
918  $user,
919  $tags
920  );
921 
922  if ( $status->isGood() ) {
923  if ( $watch ) {
925  $this->getLocalFile()->getTitle(),
926  $user,
928  );
929  }
930  // Avoid PHP 7.1 warning of passing $this by reference
931  $uploadBase = $this;
932  Hooks::run( 'UploadComplete', [ &$uploadBase ] );
933 
934  $this->postProcessUpload();
935  }
936 
937  return $status;
938  }
939 
945  public function postProcessUpload() {
946  }
947 
954  public function getTitle() {
955  if ( $this->mTitle !== false ) {
956  return $this->mTitle;
957  }
958  if ( !is_string( $this->mDesiredDestName ) ) {
959  $this->mTitleError = self::ILLEGAL_FILENAME;
960  $this->mTitle = null;
961 
962  return $this->mTitle;
963  }
964  /* Assume that if a user specified File:Something.jpg, this is an error
965  * and that the namespace prefix needs to be stripped of.
966  */
967  $title = Title::newFromText( $this->mDesiredDestName );
968  if ( $title && $title->getNamespace() == NS_FILE ) {
969  $this->mFilteredName = $title->getDBkey();
970  } else {
971  $this->mFilteredName = $this->mDesiredDestName;
972  }
973 
974  # oi_archive_name is max 255 bytes, which include a timestamp and an
975  # exclamation mark, so restrict file name to 240 bytes.
976  if ( strlen( $this->mFilteredName ) > 240 ) {
977  $this->mTitleError = self::FILENAME_TOO_LONG;
978  $this->mTitle = null;
979 
980  return $this->mTitle;
981  }
982 
988  $this->mFilteredName = wfStripIllegalFilenameChars( $this->mFilteredName );
989  /* Normalize to title form before we do any further processing */
990  $nt = Title::makeTitleSafe( NS_FILE, $this->mFilteredName );
991  if ( $nt === null ) {
992  $this->mTitleError = self::ILLEGAL_FILENAME;
993  $this->mTitle = null;
994 
995  return $this->mTitle;
996  }
997  $this->mFilteredName = $nt->getDBkey();
998 
1003  list( $partname, $ext ) = $this->splitExtensions( $this->mFilteredName );
1004 
1005  if ( $ext !== [] ) {
1006  $this->mFinalExtension = trim( end( $ext ) );
1007  } else {
1008  $this->mFinalExtension = '';
1009 
1010  # No extension, try guessing one
1011  $magic = MediaWiki\MediaWikiServices::getInstance()->getMimeAnalyzer();
1012  $mime = $magic->guessMimeType( $this->mTempPath );
1013  if ( $mime !== 'unknown/unknown' ) {
1014  # Get a space separated list of extensions
1015  $extList = $magic->getExtensionsForType( $mime );
1016  if ( $extList ) {
1017  # Set the extension to the canonical extension
1018  $this->mFinalExtension = strtok( $extList, ' ' );
1019 
1020  # Fix up the other variables
1021  $this->mFilteredName .= ".{$this->mFinalExtension}";
1022  $nt = Title::makeTitleSafe( NS_FILE, $this->mFilteredName );
1023  $ext = [ $this->mFinalExtension ];
1024  }
1025  }
1026  }
1027 
1028  /* Don't allow users to override the blacklist (check file extension) */
1031 
1032  $blackListedExtensions = $this->checkFileExtensionList( $ext, $wgFileBlacklist );
1033 
1034  if ( $this->mFinalExtension == '' ) {
1035  $this->mTitleError = self::FILETYPE_MISSING;
1036  $this->mTitle = null;
1037 
1038  return $this->mTitle;
1039  } elseif ( $blackListedExtensions ||
1041  !$this->checkFileExtension( $this->mFinalExtension, $wgFileExtensions ) )
1042  ) {
1043  $this->mBlackListedExtensions = $blackListedExtensions;
1044  $this->mTitleError = self::FILETYPE_BADTYPE;
1045  $this->mTitle = null;
1046 
1047  return $this->mTitle;
1048  }
1049 
1050  // Windows may be broken with special characters, see T3780
1051  if ( !preg_match( '/^[\x0-\x7f]*$/', $nt->getText() )
1052  && !RepoGroup::singleton()->getLocalRepo()->backendSupportsUnicodePaths()
1053  ) {
1054  $this->mTitleError = self::WINDOWS_NONASCII_FILENAME;
1055  $this->mTitle = null;
1056 
1057  return $this->mTitle;
1058  }
1059 
1060  # If there was more than one "extension", reassemble the base
1061  # filename to prevent bogus complaints about length
1062  if ( count( $ext ) > 1 ) {
1063  $iterations = count( $ext ) - 1;
1064  for ( $i = 0; $i < $iterations; $i++ ) {
1065  $partname .= '.' . $ext[$i];
1066  }
1067  }
1068 
1069  if ( strlen( $partname ) < 1 ) {
1070  $this->mTitleError = self::MIN_LENGTH_PARTNAME;
1071  $this->mTitle = null;
1072 
1073  return $this->mTitle;
1074  }
1075 
1076  $this->mTitle = $nt;
1077 
1078  return $this->mTitle;
1079  }
1080 
1086  public function getLocalFile() {
1087  if ( $this->mLocalFile === null ) {
1088  $nt = $this->getTitle();
1089  $this->mLocalFile = $nt === null ? null : wfLocalFile( $nt );
1090  }
1091 
1092  return $this->mLocalFile;
1093  }
1094 
1098  public function getStashFile() {
1099  return $this->mStashFile;
1100  }
1101 
1113  public function tryStashFile( User $user, $isPartial = false ) {
1114  if ( !$isPartial ) {
1115  $error = $this->runUploadStashFileHook( $user );
1116  if ( $error ) {
1117  return Status::newFatal( ...$error );
1118  }
1119  }
1120  try {
1121  $file = $this->doStashFile( $user );
1122  return Status::newGood( $file );
1123  } catch ( UploadStashException $e ) {
1124  return Status::newFatal( 'uploadstash-exception', get_class( $e ), $e->getMessage() );
1125  }
1126  }
1127 
1132  protected function runUploadStashFileHook( User $user ) {
1133  $props = $this->mFileProps;
1134  $error = null;
1135  Hooks::run( 'UploadStashFile', [ $this, $user, $props, &$error ] );
1136  if ( $error && !is_array( $error ) ) {
1137  $error = [ $error ];
1138  }
1139  return $error;
1140  }
1141 
1161  public function stashFile( User $user = null ) {
1162  wfDeprecated( __METHOD__, '1.28' );
1163 
1164  return $this->doStashFile( $user );
1165  }
1166 
1173  protected function doStashFile( User $user = null ) {
1174  $stash = RepoGroup::singleton()->getLocalRepo()->getUploadStash( $user );
1175  $file = $stash->stashFile( $this->mTempPath, $this->getSourceType() );
1176  $this->mStashFile = $file;
1177 
1178  return $file;
1179  }
1180 
1185  public function cleanupTempFile() {
1186  if ( $this->mRemoveTempFile && $this->tempFileObj ) {
1187  // Delete when all relevant TempFSFile handles go out of scope
1188  wfDebug( __METHOD__ . ": Marked temporary file '{$this->mTempPath}' for removal\n" );
1189  $this->tempFileObj->autocollect();
1190  }
1191  }
1192 
1193  public function getTempPath() {
1194  return $this->mTempPath;
1195  }
1196 
1206  public static function splitExtensions( $filename ) {
1207  $bits = explode( '.', $filename );
1208  $basename = array_shift( $bits );
1209 
1210  return [ $basename, $bits ];
1211  }
1212 
1221  public static function checkFileExtension( $ext, $list ) {
1222  return in_array( strtolower( $ext ), $list );
1223  }
1224 
1233  public static function checkFileExtensionList( $ext, $list ) {
1234  return array_intersect( array_map( 'strtolower', $ext ), $list );
1235  }
1236 
1244  public static function verifyExtension( $mime, $extension ) {
1245  $magic = MediaWiki\MediaWikiServices::getInstance()->getMimeAnalyzer();
1246 
1247  if ( !$mime || $mime == 'unknown' || $mime == 'unknown/unknown' ) {
1248  if ( !$magic->isRecognizableExtension( $extension ) ) {
1249  wfDebug( __METHOD__ . ": passing file with unknown detected mime type; " .
1250  "unrecognized extension '$extension', can't verify\n" );
1251 
1252  return true;
1253  } else {
1254  wfDebug( __METHOD__ . ": rejecting file with unknown detected mime type; " .
1255  "recognized extension '$extension', so probably invalid file\n" );
1256 
1257  return false;
1258  }
1259  }
1260 
1261  $match = $magic->isMatchingExtension( $extension, $mime );
1262 
1263  if ( $match === null ) {
1264  if ( $magic->getTypesForExtension( $extension ) !== null ) {
1265  wfDebug( __METHOD__ . ": No extension known for $mime, but we know a mime for $extension\n" );
1266 
1267  return false;
1268  } else {
1269  wfDebug( __METHOD__ . ": no file extension known for mime type $mime, passing file\n" );
1270 
1271  return true;
1272  }
1273  } elseif ( $match === true ) {
1274  wfDebug( __METHOD__ . ": mime type $mime matches extension $extension, passing file\n" );
1275 
1277  return true;
1278  } else {
1279  wfDebug( __METHOD__
1280  . ": mime type $mime mismatches file extension $extension, rejecting file\n" );
1281 
1282  return false;
1283  }
1284  }
1285 
1297  public static function detectScript( $file, $mime, $extension ) {
1298  # ugly hack: for text files, always look at the entire file.
1299  # For binary field, just check the first K.
1300 
1301  $isText = strpos( $mime, 'text/' ) === 0;
1302  if ( $isText ) {
1303  $chunk = file_get_contents( $file );
1304  } else {
1305  $fp = fopen( $file, 'rb' );
1306  $chunk = fread( $fp, 1024 );
1307  fclose( $fp );
1308  }
1309 
1310  $chunk = strtolower( $chunk );
1311 
1312  if ( !$chunk ) {
1313  return false;
1314  }
1315 
1316  # decode from UTF-16 if needed (could be used for obfuscation).
1317  if ( substr( $chunk, 0, 2 ) == "\xfe\xff" ) {
1318  $enc = 'UTF-16BE';
1319  } elseif ( substr( $chunk, 0, 2 ) == "\xff\xfe" ) {
1320  $enc = 'UTF-16LE';
1321  } else {
1322  $enc = null;
1323  }
1324 
1325  if ( $enc !== null ) {
1326  $chunk = iconv( $enc, "ASCII//IGNORE", $chunk );
1327  }
1328 
1329  $chunk = trim( $chunk );
1330 
1332  wfDebug( __METHOD__ . ": checking for embedded scripts and HTML stuff\n" );
1333 
1334  # check for HTML doctype
1335  if ( preg_match( "/<!DOCTYPE *X?HTML/i", $chunk ) ) {
1336  return true;
1337  }
1338 
1339  // Some browsers will interpret obscure xml encodings as UTF-8, while
1340  // PHP/expat will interpret the given encoding in the xml declaration (T49304)
1341  if ( $extension == 'svg' || strpos( $mime, 'image/svg' ) === 0 ) {
1342  if ( self::checkXMLEncodingMissmatch( $file ) ) {
1343  return true;
1344  }
1345  }
1346 
1347  // Quick check for HTML heuristics in old IE and Safari.
1348  //
1349  // The exact heuristics IE uses are checked separately via verifyMimeType(), so we
1350  // don't need them all here as it can cause many false positives.
1351  //
1352  // Check for `<script` and such still to forbid script tags and embedded HTML in SVG:
1353  $tags = [
1354  '<body',
1355  '<head',
1356  '<html', # also in safari
1357  '<script', # also in safari
1358  ];
1359 
1360  foreach ( $tags as $tag ) {
1361  if ( strpos( $chunk, $tag ) !== false ) {
1362  wfDebug( __METHOD__ . ": found something that may make it be mistaken for html: $tag\n" );
1363 
1364  return true;
1365  }
1366  }
1367 
1368  /*
1369  * look for JavaScript
1370  */
1371 
1372  # resolve entity-refs to look at attributes. may be harsh on big files... cache result?
1373  $chunk = Sanitizer::decodeCharReferences( $chunk );
1374 
1375  # look for script-types
1376  if ( preg_match( '!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim', $chunk ) ) {
1377  wfDebug( __METHOD__ . ": found script types\n" );
1378 
1379  return true;
1380  }
1381 
1382  # look for html-style script-urls
1383  if ( preg_match( '!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
1384  wfDebug( __METHOD__ . ": found html-style script urls\n" );
1385 
1386  return true;
1387  }
1388 
1389  # look for css-style script-urls
1390  if ( preg_match( '!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
1391  wfDebug( __METHOD__ . ": found css-style script urls\n" );
1392 
1393  return true;
1394  }
1395 
1396  wfDebug( __METHOD__ . ": no scripts found\n" );
1397 
1398  return false;
1399  }
1400 
1408  public static function checkXMLEncodingMissmatch( $file ) {
1409  global $wgSVGMetadataCutoff;
1410  $contents = file_get_contents( $file, false, null, 0, $wgSVGMetadataCutoff );
1411  $encodingRegex = '!encoding[ \t\n\r]*=[ \t\n\r]*[\'"](.*?)[\'"]!si';
1412 
1413  if ( preg_match( "!<\?xml\b(.*?)\?>!si", $contents, $matches ) ) {
1414  if ( preg_match( $encodingRegex, $matches[1], $encMatch )
1415  && !in_array( strtoupper( $encMatch[1] ), self::$safeXmlEncodings )
1416  ) {
1417  wfDebug( __METHOD__ . ": Found unsafe XML encoding '{$encMatch[1]}'\n" );
1418 
1419  return true;
1420  }
1421  } elseif ( preg_match( "!<\?xml\b!si", $contents ) ) {
1422  // Start of XML declaration without an end in the first $wgSVGMetadataCutoff
1423  // bytes. There shouldn't be a legitimate reason for this to happen.
1424  wfDebug( __METHOD__ . ": Unmatched XML declaration start\n" );
1425 
1426  return true;
1427  } elseif ( substr( $contents, 0, 4 ) == "\x4C\x6F\xA7\x94" ) {
1428  // EBCDIC encoded XML
1429  wfDebug( __METHOD__ . ": EBCDIC Encoded XML\n" );
1430 
1431  return true;
1432  }
1433 
1434  // It's possible the file is encoded with multi-byte encoding, so re-encode attempt to
1435  // detect the encoding in case is specifies an encoding not whitelisted in self::$safeXmlEncodings
1436  $attemptEncodings = [ 'UTF-16', 'UTF-16BE', 'UTF-32', 'UTF-32BE' ];
1437  foreach ( $attemptEncodings as $encoding ) {
1438  Wikimedia\suppressWarnings();
1439  $str = iconv( $encoding, 'UTF-8', $contents );
1440  Wikimedia\restoreWarnings();
1441  if ( $str != '' && preg_match( "!<\?xml\b(.*?)\?>!si", $str, $matches ) ) {
1442  if ( preg_match( $encodingRegex, $matches[1], $encMatch )
1443  && !in_array( strtoupper( $encMatch[1] ), self::$safeXmlEncodings )
1444  ) {
1445  wfDebug( __METHOD__ . ": Found unsafe XML encoding '{$encMatch[1]}'\n" );
1446 
1447  return true;
1448  }
1449  } elseif ( $str != '' && preg_match( "!<\?xml\b!si", $str ) ) {
1450  // Start of XML declaration without an end in the first $wgSVGMetadataCutoff
1451  // bytes. There shouldn't be a legitimate reason for this to happen.
1452  wfDebug( __METHOD__ . ": Unmatched XML declaration start\n" );
1453 
1454  return true;
1455  }
1456  }
1457 
1458  return false;
1459  }
1460 
1466  protected function detectScriptInSvg( $filename, $partial ) {
1467  $this->mSVGNSError = false;
1468  $check = new XmlTypeCheck(
1469  $filename,
1470  [ $this, 'checkSvgScriptCallback' ],
1471  true,
1472  [
1473  'processing_instruction_handler' => 'UploadBase::checkSvgPICallback',
1474  'external_dtd_handler' => 'UploadBase::checkSvgExternalDTD',
1475  ]
1476  );
1477  if ( $check->wellFormed !== true ) {
1478  // Invalid xml (T60553)
1479  // But only when non-partial (T67724)
1480  return $partial ? false : [ 'uploadinvalidxml' ];
1481  } elseif ( $check->filterMatch ) {
1482  if ( $this->mSVGNSError ) {
1483  return [ 'uploadscriptednamespace', $this->mSVGNSError ];
1484  }
1485 
1486  return $check->filterMatchType;
1487  }
1488 
1489  return false;
1490  }
1491 
1498  public static function checkSvgPICallback( $target, $data ) {
1499  // Don't allow external stylesheets (T59550)
1500  if ( preg_match( '/xml-stylesheet/i', $target ) ) {
1501  return [ 'upload-scripted-pi-callback' ];
1502  }
1503 
1504  return false;
1505  }
1506 
1518  public static function checkSvgExternalDTD( $type, $publicId, $systemId ) {
1519  // This doesn't include the XHTML+MathML+SVG doctype since we don't
1520  // allow XHTML anyways.
1521  $allowedDTDs = [
1522  'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd',
1523  'http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd',
1524  'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11-basic.dtd',
1525  'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11-tiny.dtd',
1526  // https://phabricator.wikimedia.org/T168856
1527  'http://www.w3.org/TR/2001/PR-SVG-20010719/DTD/svg10.dtd',
1528  ];
1529  if ( $type !== 'PUBLIC'
1530  || !in_array( $systemId, $allowedDTDs )
1531  || strpos( $publicId, "-//W3C//" ) !== 0
1532  ) {
1533  return [ 'upload-scripted-dtd' ];
1534  }
1535  return false;
1536  }
1537 
1545  public function checkSvgScriptCallback( $element, $attribs, $data = null ) {
1546  list( $namespace, $strippedElement ) = $this->splitXmlNamespace( $element );
1547 
1548  // We specifically don't include:
1549  // http://www.w3.org/1999/xhtml (T62771)
1550  static $validNamespaces = [
1551  '',
1552  'adobe:ns:meta/',
1553  'http://creativecommons.org/ns#',
1554  'http://inkscape.sourceforge.net/dtd/sodipodi-0.dtd',
1555  'http://ns.adobe.com/adobeillustrator/10.0/',
1556  'http://ns.adobe.com/adobesvgviewerextensions/3.0/',
1557  'http://ns.adobe.com/extensibility/1.0/',
1558  'http://ns.adobe.com/flows/1.0/',
1559  'http://ns.adobe.com/illustrator/1.0/',
1560  'http://ns.adobe.com/imagereplacement/1.0/',
1561  'http://ns.adobe.com/pdf/1.3/',
1562  'http://ns.adobe.com/photoshop/1.0/',
1563  'http://ns.adobe.com/saveforweb/1.0/',
1564  'http://ns.adobe.com/variables/1.0/',
1565  'http://ns.adobe.com/xap/1.0/',
1566  'http://ns.adobe.com/xap/1.0/g/',
1567  'http://ns.adobe.com/xap/1.0/g/img/',
1568  'http://ns.adobe.com/xap/1.0/mm/',
1569  'http://ns.adobe.com/xap/1.0/rights/',
1570  'http://ns.adobe.com/xap/1.0/stype/dimensions#',
1571  'http://ns.adobe.com/xap/1.0/stype/font#',
1572  'http://ns.adobe.com/xap/1.0/stype/manifestitem#',
1573  'http://ns.adobe.com/xap/1.0/stype/resourceevent#',
1574  'http://ns.adobe.com/xap/1.0/stype/resourceref#',
1575  'http://ns.adobe.com/xap/1.0/t/pg/',
1576  'http://purl.org/dc/elements/1.1/',
1577  'http://purl.org/dc/elements/1.1',
1578  'http://schemas.microsoft.com/visio/2003/svgextensions/',
1579  'http://sodipodi.sourceforge.net/dtd/sodipodi-0.dtd',
1580  'http://taptrix.com/inkpad/svg_extensions',
1581  'http://web.resource.org/cc/',
1582  'http://www.freesoftware.fsf.org/bkchem/cdml',
1583  'http://www.inkscape.org/namespaces/inkscape',
1584  'http://www.opengis.net/gml',
1585  'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
1586  'http://www.w3.org/2000/svg',
1587  'http://www.w3.org/tr/rec-rdf-syntax/',
1588  'http://www.w3.org/2000/01/rdf-schema#',
1589  ];
1590 
1591  // Inkscape mangles namespace definitions created by Adobe Illustrator.
1592  // This is nasty but harmless. (T144827)
1593  $isBuggyInkscape = preg_match( '/^&(#38;)*ns_[a-z_]+;$/', $namespace );
1594 
1595  if ( !( $isBuggyInkscape || in_array( $namespace, $validNamespaces ) ) ) {
1596  wfDebug( __METHOD__ . ": Non-svg namespace '$namespace' in uploaded file.\n" );
1598  $this->mSVGNSError = $namespace;
1599 
1600  return true;
1601  }
1602 
1603  /*
1604  * check for elements that can contain javascript
1605  */
1606  if ( $strippedElement == 'script' ) {
1607  wfDebug( __METHOD__ . ": Found script element '$element' in uploaded file.\n" );
1608 
1609  return [ 'uploaded-script-svg', $strippedElement ];
1610  }
1611 
1612  # e.g., <svg xmlns="http://www.w3.org/2000/svg">
1613  # <handler xmlns:ev="http://www.w3.org/2001/xml-events" ev:event="load">alert(1)</handler> </svg>
1614  if ( $strippedElement == 'handler' ) {
1615  wfDebug( __METHOD__ . ": Found scriptable element '$element' in uploaded file.\n" );
1616 
1617  return [ 'uploaded-script-svg', $strippedElement ];
1618  }
1619 
1620  # SVG reported in Feb '12 that used xml:stylesheet to generate javascript block
1621  if ( $strippedElement == 'stylesheet' ) {
1622  wfDebug( __METHOD__ . ": Found scriptable element '$element' in uploaded file.\n" );
1623 
1624  return [ 'uploaded-script-svg', $strippedElement ];
1625  }
1626 
1627  # Block iframes, in case they pass the namespace check
1628  if ( $strippedElement == 'iframe' ) {
1629  wfDebug( __METHOD__ . ": iframe in uploaded file.\n" );
1630 
1631  return [ 'uploaded-script-svg', $strippedElement ];
1632  }
1633 
1634  # Check <style> css
1635  if ( $strippedElement == 'style'
1636  && self::checkCssFragment( Sanitizer::normalizeCss( $data ) )
1637  ) {
1638  wfDebug( __METHOD__ . ": hostile css in style element.\n" );
1639  return [ 'uploaded-hostile-svg' ];
1640  }
1641 
1642  foreach ( $attribs as $attrib => $value ) {
1643  $stripped = $this->stripXmlNamespace( $attrib );
1644  $value = strtolower( $value );
1645 
1646  if ( substr( $stripped, 0, 2 ) == 'on' ) {
1647  wfDebug( __METHOD__
1648  . ": Found event-handler attribute '$attrib'='$value' in uploaded file.\n" );
1649 
1650  return [ 'uploaded-event-handler-on-svg', $attrib, $value ];
1651  }
1652 
1653  # Do not allow relative links, or unsafe url schemas.
1654  # For <a> tags, only data:, http: and https: and same-document
1655  # fragment links are allowed. For all other tags, only data:
1656  # and fragment are allowed.
1657  if ( $stripped == 'href'
1658  && $value !== ''
1659  && strpos( $value, 'data:' ) !== 0
1660  && strpos( $value, '#' ) !== 0
1661  ) {
1662  if ( !( $strippedElement === 'a'
1663  && preg_match( '!^https?://!i', $value ) )
1664  ) {
1665  wfDebug( __METHOD__ . ": Found href attribute <$strippedElement "
1666  . "'$attrib'='$value' in uploaded file.\n" );
1667 
1668  return [ 'uploaded-href-attribute-svg', $strippedElement, $attrib, $value ];
1669  }
1670  }
1671 
1672  # only allow data: targets that should be safe. This prevents vectors like,
1673  # image/svg, text/xml, application/xml, and text/html, which can contain scripts
1674  if ( $stripped == 'href' && strncasecmp( 'data:', $value, 5 ) === 0 ) {
1675  // rfc2397 parameters. This is only slightly slower than (;[\w;]+)*.
1676  // phpcs:ignore Generic.Files.LineLength
1677  $parameters = '(?>;[a-zA-Z0-9\!#$&\'*+.^_`{|}~-]+=(?>[a-zA-Z0-9\!#$&\'*+.^_`{|}~-]+|"(?>[\0-\x0c\x0e-\x21\x23-\x5b\x5d-\x7f]+|\\\\[\0-\x7f])*"))*(?:;base64)?';
1678 
1679  if ( !preg_match( "!^data:\s*image/(gif|jpeg|jpg|png)$parameters,!i", $value ) ) {
1680  wfDebug( __METHOD__ . ": Found href to unwhitelisted data: uri "
1681  . "\"<$strippedElement '$attrib'='$value'...\" in uploaded file.\n" );
1682  return [ 'uploaded-href-unsafe-target-svg', $strippedElement, $attrib, $value ];
1683  }
1684  }
1685 
1686  # Change href with animate from (http://html5sec.org/#137).
1687  if ( $stripped === 'attributename'
1688  && $strippedElement === 'animate'
1689  && $this->stripXmlNamespace( $value ) == 'href'
1690  ) {
1691  wfDebug( __METHOD__ . ": Found animate that might be changing href using from "
1692  . "\"<$strippedElement '$attrib'='$value'...\" in uploaded file.\n" );
1693 
1694  return [ 'uploaded-animate-svg', $strippedElement, $attrib, $value ];
1695  }
1696 
1697  # use set/animate to add event-handler attribute to parent
1698  if ( ( $strippedElement == 'set' || $strippedElement == 'animate' )
1699  && $stripped == 'attributename'
1700  && substr( $value, 0, 2 ) == 'on'
1701  ) {
1702  wfDebug( __METHOD__ . ": Found svg setting event-handler attribute with "
1703  . "\"<$strippedElement $stripped='$value'...\" in uploaded file.\n" );
1704 
1705  return [ 'uploaded-setting-event-handler-svg', $strippedElement, $stripped, $value ];
1706  }
1707 
1708  # use set to add href attribute to parent element
1709  if ( $strippedElement == 'set'
1710  && $stripped == 'attributename'
1711  && strpos( $value, 'href' ) !== false
1712  ) {
1713  wfDebug( __METHOD__ . ": Found svg setting href attribute '$value' in uploaded file.\n" );
1714 
1715  return [ 'uploaded-setting-href-svg' ];
1716  }
1717 
1718  # use set to add a remote / data / script target to an element
1719  if ( $strippedElement == 'set'
1720  && $stripped == 'to'
1721  && preg_match( '!(http|https|data|script):!sim', $value )
1722  ) {
1723  wfDebug( __METHOD__ . ": Found svg setting attribute to '$value' in uploaded file.\n" );
1724 
1725  return [ 'uploaded-wrong-setting-svg', $value ];
1726  }
1727 
1728  # use handler attribute with remote / data / script
1729  if ( $stripped == 'handler' && preg_match( '!(http|https|data|script):!sim', $value ) ) {
1730  wfDebug( __METHOD__ . ": Found svg setting handler with remote/data/script "
1731  . "'$attrib'='$value' in uploaded file.\n" );
1732 
1733  return [ 'uploaded-setting-handler-svg', $attrib, $value ];
1734  }
1735 
1736  # use CSS styles to bring in remote code
1737  if ( $stripped == 'style'
1738  && self::checkCssFragment( Sanitizer::normalizeCss( $value ) )
1739  ) {
1740  wfDebug( __METHOD__ . ": Found svg setting a style with "
1741  . "remote url '$attrib'='$value' in uploaded file.\n" );
1742  return [ 'uploaded-remote-url-svg', $attrib, $value ];
1743  }
1744 
1745  # Several attributes can include css, css character escaping isn't allowed
1746  $cssAttrs = [ 'font', 'clip-path', 'fill', 'filter', 'marker',
1747  'marker-end', 'marker-mid', 'marker-start', 'mask', 'stroke' ];
1748  if ( in_array( $stripped, $cssAttrs )
1749  && self::checkCssFragment( $value )
1750  ) {
1751  wfDebug( __METHOD__ . ": Found svg setting a style with "
1752  . "remote url '$attrib'='$value' in uploaded file.\n" );
1753  return [ 'uploaded-remote-url-svg', $attrib, $value ];
1754  }
1755 
1756  # image filters can pull in url, which could be svg that executes scripts
1757  # Only allow url( "#foo" ). Do not allow url( http://example.com )
1758  if ( $strippedElement == 'image'
1759  && $stripped == 'filter'
1760  && preg_match( '!url\s*\(\s*["\']?[^#]!sim', $value )
1761  ) {
1762  wfDebug( __METHOD__ . ": Found image filter with url: "
1763  . "\"<$strippedElement $stripped='$value'...\" in uploaded file.\n" );
1764 
1765  return [ 'uploaded-image-filter-svg', $strippedElement, $stripped, $value ];
1766  }
1767  }
1768 
1769  return false; // No scripts detected
1770  }
1771 
1778  private static function checkCssFragment( $value ) {
1779  # Forbid external stylesheets, for both reliability and to protect viewer's privacy
1780  if ( stripos( $value, '@import' ) !== false ) {
1781  return true;
1782  }
1783 
1784  # We allow @font-face to embed fonts with data: urls, so we snip the string
1785  # 'url' out so this case won't match when we check for urls below
1786  $pattern = '!(@font-face\s*{[^}]*src:)url(\("data:;base64,)!im';
1787  $value = preg_replace( $pattern, '$1$2', $value );
1788 
1789  # Check for remote and executable CSS. Unlike in Sanitizer::checkCss, the CSS
1790  # properties filter and accelerator don't seem to be useful for xss in SVG files.
1791  # Expression and -o-link don't seem to work either, but filtering them here in case.
1792  # Additionally, we catch remote urls like url("http:..., url('http:..., url(http:...,
1793  # but not local ones such as url("#..., url('#..., url(#....
1794  if ( preg_match( '!expression
1795  | -o-link\s*:
1796  | -o-link-source\s*:
1797  | -o-replace\s*:!imx', $value ) ) {
1798  return true;
1799  }
1800 
1801  if ( preg_match_all(
1802  "!(\s*(url|image|image-set)\s*\(\s*[\"']?\s*[^#]+.*?\))!sim",
1803  $value,
1804  $matches
1805  ) !== 0
1806  ) {
1807  # TODO: redo this in one regex. Until then, url("#whatever") matches the first
1808  foreach ( $matches[1] as $match ) {
1809  if ( !preg_match( "!\s*(url|image|image-set)\s*\(\s*(#|'#|\"#)!im", $match ) ) {
1810  return true;
1811  }
1812  }
1813  }
1814 
1815  if ( preg_match( '/[\000-\010\013\016-\037\177]/', $value ) ) {
1816  return true;
1817  }
1818 
1819  return false;
1820  }
1821 
1827  private static function splitXmlNamespace( $element ) {
1828  // 'http://www.w3.org/2000/svg:script' -> [ 'http://www.w3.org/2000/svg', 'script' ]
1829  $parts = explode( ':', strtolower( $element ) );
1830  $name = array_pop( $parts );
1831  $ns = implode( ':', $parts );
1832 
1833  return [ $ns, $name ];
1834  }
1835 
1840  private function stripXmlNamespace( $name ) {
1841  // 'http://www.w3.org/2000/svg:script' -> 'script'
1842  $parts = explode( ':', strtolower( $name ) );
1843 
1844  return array_pop( $parts );
1845  }
1846 
1857  public static function detectVirus( $file ) {
1859 
1860  if ( !$wgAntivirus ) {
1861  wfDebug( __METHOD__ . ": virus scanner disabled\n" );
1862 
1863  return null;
1864  }
1865 
1866  if ( !$wgAntivirusSetup[$wgAntivirus] ) {
1867  wfDebug( __METHOD__ . ": unknown virus scanner: $wgAntivirus\n" );
1868  $wgOut->wrapWikiMsg( "<div class=\"error\">\n$1\n</div>",
1869  [ 'virus-badscanner', $wgAntivirus ] );
1870 
1871  return wfMessage( 'virus-unknownscanner' )->text() . " $wgAntivirus";
1872  }
1873 
1874  # look up scanner configuration
1875  $command = $wgAntivirusSetup[$wgAntivirus]['command'];
1876  $exitCodeMap = $wgAntivirusSetup[$wgAntivirus]['codemap'];
1877  $msgPattern = $wgAntivirusSetup[$wgAntivirus]['messagepattern'] ?? null;
1878 
1879  if ( strpos( $command, "%f" ) === false ) {
1880  # simple pattern: append file to scan
1881  $command .= " " . Shell::escape( $file );
1882  } else {
1883  # complex pattern: replace "%f" with file to scan
1884  $command = str_replace( "%f", Shell::escape( $file ), $command );
1885  }
1886 
1887  wfDebug( __METHOD__ . ": running virus scan: $command \n" );
1888 
1889  # execute virus scanner
1890  $exitCode = false;
1891 
1892  # NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
1893  # that does not seem to be worth the pain.
1894  # Ask me (Duesentrieb) about it if it's ever needed.
1895  $output = wfShellExecWithStderr( $command, $exitCode );
1896 
1897  # map exit code to AV_xxx constants.
1898  $mappedCode = $exitCode;
1899  if ( $exitCodeMap ) {
1900  if ( isset( $exitCodeMap[$exitCode] ) ) {
1901  $mappedCode = $exitCodeMap[$exitCode];
1902  } elseif ( isset( $exitCodeMap["*"] ) ) {
1903  $mappedCode = $exitCodeMap["*"];
1904  }
1905  }
1906 
1907  /* NB: AV_NO_VIRUS is 0 but AV_SCAN_FAILED is false,
1908  * so we need the strict equalities === and thus can't use a switch here
1909  */
1910  if ( $mappedCode === AV_SCAN_FAILED ) {
1911  # scan failed (code was mapped to false by $exitCodeMap)
1912  wfDebug( __METHOD__ . ": failed to scan $file (code $exitCode).\n" );
1913 
1914  $output = $wgAntivirusRequired
1915  ? wfMessage( 'virus-scanfailed', [ $exitCode ] )->text()
1916  : null;
1917  } elseif ( $mappedCode === AV_SCAN_ABORTED ) {
1918  # scan failed because filetype is unknown (probably imune)
1919  wfDebug( __METHOD__ . ": unsupported file type $file (code $exitCode).\n" );
1920  $output = null;
1921  } elseif ( $mappedCode === AV_NO_VIRUS ) {
1922  # no virus found
1923  wfDebug( __METHOD__ . ": file passed virus scan.\n" );
1924  $output = false;
1925  } else {
1926  $output = trim( $output );
1927 
1928  if ( !$output ) {
1929  $output = true; # if there's no output, return true
1930  } elseif ( $msgPattern ) {
1931  $groups = [];
1932  if ( preg_match( $msgPattern, $output, $groups ) && $groups[1] ) {
1933  $output = $groups[1];
1934  }
1935  }
1936 
1937  wfDebug( __METHOD__ . ": FOUND VIRUS! scanner feedback: $output \n" );
1938  }
1939 
1940  return $output;
1941  }
1942 
1951  private function checkOverwrite( $user ) {
1952  // First check whether the local file can be overwritten
1953  $file = $this->getLocalFile();
1954  $file->load( File::READ_LATEST );
1955  if ( $file->exists() ) {
1956  if ( !self::userCanReUpload( $user, $file ) ) {
1957  return [ 'fileexists-forbidden', $file->getName() ];
1958  } else {
1959  return true;
1960  }
1961  }
1962 
1963  /* Check shared conflicts: if the local file does not exist, but
1964  * wfFindFile finds a file, it exists in a shared repository.
1965  */
1966  $file = wfFindFile( $this->getTitle(), [ 'latest' => true ] );
1967  if ( $file && !MediaWikiServices::getInstance()
1968  ->getPermissionManager()
1969  ->userHasRight( $user, 'reupload-shared' )
1970  ) {
1971  return [ 'fileexists-shared-forbidden', $file->getName() ];
1972  }
1973 
1974  return true;
1975  }
1976 
1984  public static function userCanReUpload( User $user, File $img ) {
1985  $permissionManager = MediaWikiServices::getInstance()->getPermissionManager();
1986  if ( $permissionManager->userHasRight( $user, 'reupload' ) ) {
1987  return true; // non-conditional
1988  } elseif ( !$permissionManager->userHasRight( $user, 'reupload-own' ) ) {
1989  return false;
1990  }
1991 
1992  if ( !( $img instanceof LocalFile ) ) {
1993  return false;
1994  }
1995 
1996  $img->load();
1997 
1998  return $user->getId() == $img->getUser( 'id' );
1999  }
2000 
2012  public static function getExistsWarning( $file ) {
2013  if ( $file->exists() ) {
2014  return [ 'warning' => 'exists', 'file' => $file ];
2015  }
2016 
2017  if ( $file->getTitle()->getArticleID() ) {
2018  return [ 'warning' => 'page-exists', 'file' => $file ];
2019  }
2020 
2021  if ( strpos( $file->getName(), '.' ) == false ) {
2022  $partname = $file->getName();
2023  $extension = '';
2024  } else {
2025  $n = strrpos( $file->getName(), '.' );
2026  $extension = substr( $file->getName(), $n + 1 );
2027  $partname = substr( $file->getName(), 0, $n );
2028  }
2029  $normalizedExtension = File::normalizeExtension( $extension );
2030 
2031  if ( $normalizedExtension != $extension ) {
2032  // We're not using the normalized form of the extension.
2033  // Normal form is lowercase, using most common of alternate
2034  // extensions (eg 'jpg' rather than 'JPEG').
2035 
2036  // Check for another file using the normalized form...
2037  $nt_lc = Title::makeTitle( NS_FILE, "{$partname}.{$normalizedExtension}" );
2038  $file_lc = wfLocalFile( $nt_lc );
2039 
2040  if ( $file_lc->exists() ) {
2041  return [
2042  'warning' => 'exists-normalized',
2043  'file' => $file,
2044  'normalizedFile' => $file_lc
2045  ];
2046  }
2047  }
2048 
2049  // Check for files with the same name but a different extension
2050  $similarFiles = RepoGroup::singleton()->getLocalRepo()->findFilesByPrefix(
2051  "{$partname}.", 1 );
2052  if ( count( $similarFiles ) ) {
2053  return [
2054  'warning' => 'exists-normalized',
2055  'file' => $file,
2056  'normalizedFile' => $similarFiles[0],
2057  ];
2058  }
2059 
2060  if ( self::isThumbName( $file->getName() ) ) {
2061  # Check for filenames like 50px- or 180px-, these are mostly thumbnails
2062  $nt_thb = Title::newFromText(
2063  substr( $partname, strpos( $partname, '-' ) + 1 ) . '.' . $extension,
2064  NS_FILE
2065  );
2066  $file_thb = wfLocalFile( $nt_thb );
2067  if ( $file_thb->exists() ) {
2068  return [
2069  'warning' => 'thumb',
2070  'file' => $file,
2071  'thumbFile' => $file_thb
2072  ];
2073  } else {
2074  // File does not exist, but we just don't like the name
2075  return [
2076  'warning' => 'thumb-name',
2077  'file' => $file,
2078  'thumbFile' => $file_thb
2079  ];
2080  }
2081  }
2082 
2083  foreach ( self::getFilenamePrefixBlacklist() as $prefix ) {
2084  if ( substr( $partname, 0, strlen( $prefix ) ) == $prefix ) {
2085  return [
2086  'warning' => 'bad-prefix',
2087  'file' => $file,
2088  'prefix' => $prefix
2089  ];
2090  }
2091  }
2092 
2093  return false;
2094  }
2095 
2101  public static function isThumbName( $filename ) {
2102  $n = strrpos( $filename, '.' );
2103  $partname = $n ? substr( $filename, 0, $n ) : $filename;
2104 
2105  return (
2106  substr( $partname, 3, 3 ) == 'px-' ||
2107  substr( $partname, 2, 3 ) == 'px-'
2108  ) &&
2109  preg_match( "/[0-9]{2}/", substr( $partname, 0, 2 ) );
2110  }
2111 
2117  public static function getFilenamePrefixBlacklist() {
2118  $blacklist = [];
2119  $message = wfMessage( 'filename-prefix-blacklist' )->inContentLanguage();
2120  if ( !$message->isDisabled() ) {
2121  $lines = explode( "\n", $message->plain() );
2122  foreach ( $lines as $line ) {
2123  // Remove comment lines
2124  $comment = substr( trim( $line ), 0, 1 );
2125  if ( $comment == '#' || $comment == '' ) {
2126  continue;
2127  }
2128  // Remove additional comments after a prefix
2129  $comment = strpos( $line, '#' );
2130  if ( $comment > 0 ) {
2131  $line = substr( $line, 0, $comment - 1 );
2132  }
2133  $blacklist[] = trim( $line );
2134  }
2135  }
2136 
2137  return $blacklist;
2138  }
2139 
2151  public function getImageInfo( $result ) {
2152  $localFile = $this->getLocalFile();
2153  $stashFile = $this->getStashFile();
2154  // Calling a different API module depending on whether the file was stashed is less than optimal.
2155  // In fact, calling API modules here at all is less than optimal. Maybe it should be refactored.
2156  if ( $stashFile ) {
2158  $info = ApiQueryStashImageInfo::getInfo( $stashFile, array_flip( $imParam ), $result );
2159  } else {
2161  $info = ApiQueryImageInfo::getInfo( $localFile, array_flip( $imParam ), $result );
2162  }
2163 
2164  return $info;
2165  }
2166 
2171  public function convertVerifyErrorToStatus( $error ) {
2172  $code = $error['status'];
2173  unset( $code['status'] );
2174 
2175  return Status::newFatal( $this->getVerificationErrorCode( $code ), $error );
2176  }
2177 
2185  public static function getMaxUploadSize( $forType = null ) {
2186  global $wgMaxUploadSize;
2187 
2188  if ( is_array( $wgMaxUploadSize ) ) {
2189  if ( $forType !== null && isset( $wgMaxUploadSize[$forType] ) ) {
2190  return $wgMaxUploadSize[$forType];
2191  } else {
2192  return $wgMaxUploadSize['*'];
2193  }
2194  } else {
2195  return intval( $wgMaxUploadSize );
2196  }
2197  }
2198 
2206  public static function getMaxPhpUploadSize() {
2207  $phpMaxFileSize = wfShorthandToInteger(
2208  ini_get( 'upload_max_filesize' ),
2209  PHP_INT_MAX
2210  );
2211  $phpMaxPostSize = wfShorthandToInteger(
2212  ini_get( 'post_max_size' ),
2213  PHP_INT_MAX
2214  ) ?: PHP_INT_MAX;
2215  return min( $phpMaxFileSize, $phpMaxPostSize );
2216  }
2217 
2227  public static function getSessionStatus( User $user, $statusKey ) {
2228  $store = self::getUploadSessionStore();
2229  $key = self::getUploadSessionKey( $store, $user, $statusKey );
2230 
2231  return $store->get( $key );
2232  }
2233 
2246  public static function setSessionStatus( User $user, $statusKey, $value ) {
2247  $store = self::getUploadSessionStore();
2248  $key = self::getUploadSessionKey( $store, $user, $statusKey );
2249 
2250  if ( $value === false ) {
2251  $store->delete( $key );
2252  } else {
2253  $store->set( $key, $value, $store::TTL_DAY );
2254  }
2255  }
2256 
2263  private static function getUploadSessionKey( BagOStuff $store, User $user, $statusKey ) {
2264  return $store->makeKey(
2265  'uploadstatus',
2266  $user->getId() ?: md5( $user->getName() ),
2267  $statusKey
2268  );
2269  }
2270 
2274  private static function getUploadSessionStore() {
2275  return ObjectCache::getInstance( 'db-replicated' );
2276  }
2277 }
AV_NO_VIRUS
const AV_NO_VIRUS
Definition: Defines.php:91
LocalFile\getSha1
getSha1()
Definition: LocalFile.php:2154
File\wasDeleted
wasDeleted()
Was this file ever deleted from the wiki?
Definition: File.php:1958
$wgAllowJavaUploads
$wgAllowJavaUploads
Allow Java archive uploads.
Definition: DefaultSettings.php:981
MediaWiki\Shell\Shell
Executes shell commands.
Definition: Shell.php:44
ApiQueryImageInfo\getPropertyNames
static getPropertyNames( $filter=[])
Returns all possible parameters to iiprop.
Definition: ApiQueryImageInfo.php:734
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:317
ApiQueryStashImageInfo\getPropertyNames
static getPropertyNames( $filter=null)
Returns all possible parameters to siiprop.
Definition: ApiQueryStashImageInfo.php:84
RepoGroup\singleton
static singleton()
Definition: RepoGroup.php:60
$wgFileBlacklist
$wgFileBlacklist
Files with these extensions will never be allowed as uploads.
Definition: DefaultSettings.php:949
StatusValue\newFatal
static newFatal( $message,... $parameters)
Factory function for fatal errors.
Definition: StatusValue.php:69
User\getId
getId()
Get the user's ID.
Definition: User.php:2255
AV_SCAN_FAILED
const AV_SCAN_FAILED
Definition: Defines.php:94
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:130
$wgMaxUploadSize
$wgMaxUploadSize
Max size for uploads, in bytes.
Definition: DefaultSettings.php:868
$wgFileExtensions
$wgFileExtensions
This is the list of preferred extensions for uploading files.
Definition: DefaultSettings.php:942
LocalFile\getHistory
getHistory( $limit=null, $start=null, $end=null, $inc=true)
purgeDescription inherited
Definition: LocalFile.php:1169
NS_FILE
const NS_FILE
Definition: Defines.php:66
$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
BagOStuff
Class representing a cache/ephemeral data store.
Definition: BagOStuff.php:63
$wgMimeTypeBlacklist
$wgMimeTypeBlacklist
Files with these MIME types will never be allowed as uploads if $wgVerifyMimeType is enabled.
Definition: DefaultSettings.php:963
wfMessage
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
Definition: GlobalFunctions.php:1263
$wgVerifyMimeTypeIE
$wgVerifyMimeTypeIE
Determines whether extra checks for IE type detection should be applied.
Definition: DefaultSettings.php:1406
$wgStrictFileExtensions
$wgStrictFileExtensions
If this is turned off, users may override the warning for files not covered by $wgFileExtensions.
Definition: DefaultSettings.php:996
ApiQueryImageInfo\getInfo
static getInfo( $file, $prop, $result, $thumbParams=null, $opts=false)
Get result information for an image revision.
Definition: ApiQueryImageInfo.php:374
MediaWiki\User\UserIdentity
Interface for objects representing user identity.
Definition: UserIdentity.php:32
AV_SCAN_ABORTED
const AV_SCAN_ABORTED
Definition: Defines.php:93
MediaWiki\MediaWikiServices\getInstance
static getInstance()
Returns the global default instance of the top level service locator.
Definition: MediaWikiServices.php:161
WatchAction\doWatch
static doWatch(Title $title, User $user, $checkRights=User::CHECK_USER_RIGHTS)
Watch a page.
Definition: WatchAction.php:116
File
Implements some public methods and some protected utility functions which are required by multiple ch...
Definition: File.php:61
Title\getDBkey
getDBkey()
Get the main part with underscores.
Definition: Title.php:1014
BagOStuff\get
get( $key, $flags=0)
Get an item with the given key.
$mTitle
Title null $mTitle
Definition: RevisionSearchResultTrait.php:26
MWException
MediaWiki exception.
Definition: MWException.php:26
wfStripIllegalFilenameChars
wfStripIllegalFilenameChars( $name)
Replace all invalid characters with '-'.
Definition: GlobalFunctions.php:2740
$wgUploadSizeWarning
$wgUploadSizeWarning
Warn if uploaded files are larger than this (in bytes), or false to disable.
Definition: DefaultSettings.php:1009
wfDeprecated
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
Definition: GlobalFunctions.php:1044
$wgAntivirusRequired
$wgAntivirusRequired
Determines if a failed virus scan (AV_SCAN_FAILED) will cause the file to be rejected.
Definition: DefaultSettings.php:1391
wfArrayDiff2
wfArrayDiff2( $a, $b)
Like array_diff( $a, $b ) except that it works with two-dimensional arrays.
Definition: GlobalFunctions.php:113
FileBackend\isStoragePath
static isStoragePath( $path)
Check if a given path is a "mwstore://" path.
Definition: FileBackend.php:1519
$matches
$matches
Definition: NoLocalSettings.php:24
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
$wgLang
$wgLang
Definition: Setup.php:846
$wgAntivirusSetup
$wgAntivirusSetup
Configuration for different virus scanners.
Definition: DefaultSettings.php:1373
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
$lines
$lines
Definition: router.php:61
$title
$title
Definition: testCompression.php:36
MWFileProps
MimeMagic helper wrapper.
Definition: MWFileProps.php:28
Title\makeTitle
static makeTitle( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:584
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:913
LocalFile
Class to represent a local file in the wiki's own database.
Definition: LocalFile.php:56
$wgSVGMetadataCutoff
$wgSVGMetadataCutoff
Don't read SVG metadata beyond this point.
Definition: DefaultSettings.php:1224
Title\makeTitleSafe
static makeTitleSafe( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:610
ArchivedFile
Class representing a row of the 'filearchive' table.
Definition: ArchivedFile.php:31
StatusValue\newGood
static newGood( $value=null)
Factory function for good results.
Definition: StatusValue.php:81
LocalFile\load
load( $flags=0)
Load file metadata from cache or DB, unless already loaded.
Definition: LocalFile.php:620
$line
$line
Definition: mcc.php:119
TempFSFile
This class is used to hold the location and do limited manipulation of files stored temporarily (this...
Definition: TempFSFile.php:35
XmlTypeCheck
Definition: XmlTypeCheck.php:28
File\getName
getName()
Return the name of this file.
Definition: File.php:307
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
wfIniGetBool
wfIniGetBool( $setting)
Safety wrapper around ini_get() for boolean settings.
Definition: GlobalFunctions.php:2064
File\DELETE_SOURCE
const DELETE_SOURCE
Definition: File.php:76
BagOStuff\makeKey
makeKey( $class,... $components)
Make a cache key, scoped to this instance's keyspace.
wfShorthandToInteger
wfShorthandToInteger( $string='', $default=-1)
Converts shorthand byte notation to integer form.
Definition: GlobalFunctions.php:2805
Title
Represents a title within MediaWiki.
Definition: Title.php:42
$command
$command
Definition: mcc.php:125
$wgDisableUploadScriptChecks
$wgDisableUploadScriptChecks
Setting this to true will disable the upload system's checks for HTML/JavaScript.
Definition: DefaultSettings.php:1004
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:3311
$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:46
$wgVerifyMimeType
$wgVerifyMimeType
Determines if the MIME type of uploaded files should be checked.
Definition: DefaultSettings.php:1396
getTitle
getTitle()
Definition: RevisionSearchResultTrait.php:74
FileRepo\isVirtualUrl
static isVirtualUrl( $url)
Determine if a string is an mwrepo:// URL.
Definition: FileRepo.php:281
$wgEnableUploads
$wgEnableUploads
Allow users to upload files.
Definition: DefaultSettings.php:402
$ext
if(!is_readable( $file)) $ext
Definition: router.php:48
File\DELETED_FILE
const DELETED_FILE
Definition: File.php:63
BagOStuff\set
set( $key, $value, $exptime=0, $flags=0)
Set an item.
User\IGNORE_USER_RIGHTS
const IGNORE_USER_RIGHTS
Definition: User.php:84
$wgAntivirus
$wgAntivirus
Internal name of virus scanner.
Definition: DefaultSettings.php:1337
$wgOut
$wgOut
Definition: Setup.php:851
User
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition: User.php:52
wfLocalFile
wfLocalFile( $title)
Get an object referring to a locally registered file.
Definition: GlobalFunctions.php:2603
Hooks\run
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:200
User\getName
getName()
Get the user name, or the IP of an anonymous user.
Definition: User.php:2284
LocalFile\exists
exists()
canRender inherited
Definition: LocalFile.php:969
BagOStuff\delete
delete( $key, $flags=0)
Delete an item.
$wgCheckFileExtensions
$wgCheckFileExtensions
This is a flag to determine whether or not to check file extensions on upload.
Definition: DefaultSettings.php:988
UploadStashException
Definition: UploadStashException.php:26
wfShellExecWithStderr
wfShellExecWithStderr( $cmd, &$retval=null, $environ=[], $limits=[])
Execute a shell command, returning both stdout and stderr.
Definition: GlobalFunctions.php:2182
$type
$type
Definition: testCompression.php:50