24 use MediaWiki\HookContainer\ProtectedHookAccessorTrait;
46 use ProtectedHookAccessorTrait;
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',
132 return $code_to_status[$error] ??
'unknown-error';
156 $permissionManager = MediaWikiServices::getInstance()->getPermissionManager();
157 foreach ( [
'upload',
'edit' ] as $permission ) {
158 if ( !$permissionManager->userHasRight( $user, $permission ) ) {
173 return $user->pingLimiter(
'upload' );
187 $type =
$type ?: $request->getVal(
'wpSourceType',
'File' );
200 if ( $className ===
null ) {
201 $className =
'UploadFrom' .
$type;
202 wfDebug( __METHOD__ .
": class name: $className" );
203 if ( !in_array(
$type, self::$uploadHandlers ) ) {
209 if ( !$className::isEnabled() ) {
214 if ( !$className::isValidRequest( $request ) ) {
219 $handler =
new $className;
221 $handler->initializeFromRequest( $request );
260 $this->mDesiredDestName = $name;
262 throw new MWException( __METHOD__ .
" given storage path `$tempPath`." );
266 $this->mRemoveTempFile = $removeTempFile;
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 );
286 $this->mFileSize = filesize( $this->mTempPath );
289 $this->tempFileObj =
null;
307 return empty( $this->mFileSize );
332 $repo = MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo();
337 $tmpFile = $repo->getLocalCopy( $srcPath );
339 $tmpFile->bind( $this );
341 $path = $tmpFile ? $tmpFile->getPath() :
false;
378 if ( $this->mFileSize > $maxSize ) {
391 if ( $verification !==
true ) {
394 'details' => $verification
402 if ( $result !==
true ) {
417 if ( $nt ===
null ) {
419 if ( $this->mTitleError == self::ILLEGAL_FILENAME ) {
422 if ( $this->mTitleError == self::FILETYPE_BADTYPE ) {
424 if ( count( $this->mBlackListedExtensions ) ) {
448 wfDebug(
"mime: <$mime> extension: <{$this->mFinalExtension}>" );
451 return [
'filetype-badmime',
$mime ];
455 # Check what Internet Explorer would detect
456 $fp = fopen( $this->mTempPath,
'rb' );
457 $chunk = fread( $fp, 256 );
461 $extMime = $magic->getMimeTypeFromExtensionOrNull( (
string)$this->mFinalExtension ) ??
'';
462 $ieTypes = $magic->getIEMimeTypes( $this->mTempPath, $chunk, $extMime );
463 foreach ( $ieTypes as $ieType ) {
465 return [
'filetype-bad-ie-mime', $ieType ];
483 if ( $status !==
true ) {
488 $this->mFileProps = $mwProps->getPropsFromPath( $this->mTempPath, $this->mFinalExtension );
489 $mime = $this->mFileProps[
'mime'];
492 # XXX: Missing extension will be caught by validateName() via getTitle()
493 if ( (
string)$this->mFinalExtension !==
'' &&
500 # check for htmlish code and javascript
502 if ( $this->mFinalExtension ==
'svg' ||
$mime ==
'image/svg+xml' ) {
504 if ( $svgStatus !==
false ) {
512 $handlerStatus = $handler->verifyUpload( $this->mTempPath );
513 if ( !$handlerStatus->isOK() ) {
514 $errors = $handlerStatus->getErrorsArray();
516 return reset( $errors );
521 $this->getHookRunner()->onUploadVerifyFile( $this,
$mime, $error );
522 if ( $error !==
true ) {
523 if ( !is_array( $error ) ) {
529 wfDebug( __METHOD__ .
": all clear; passing." );
545 # getTitle() sets some internal parameters like $this->mFinalExtension
549 $this->mFileProps = $mwProps->getPropsFromPath( $this->mTempPath, $this->mFinalExtension );
551 # check MIME type, if desired
552 $mime = $this->mFileProps[
'file-mime'];
554 if ( $status !==
true ) {
558 # check for htmlish code and javascript
560 if ( self::detectScript( $this->mTempPath,
$mime, $this->mFinalExtension ) ) {
561 return [
'uploadscripted' ];
563 if ( $this->mFinalExtension ==
'svg' ||
$mime ==
'image/svg+xml' ) {
565 if ( $svgStatus !==
false ) {
571 # Check for Java applets, which if uploaded can bypass cross-site
574 $this->mJavaDetected =
false;
576 [ $this,
'zipEntryCallback' ] );
577 if ( !$zipStatus->isOK() ) {
578 $errors = $zipStatus->getErrorsArray();
579 $error = reset( $errors );
580 if ( $error[0] !==
'zip-wrong-format' ) {
584 if ( $this->mJavaDetected ) {
585 return [
'uploadjava' ];
589 # Scan the uploaded file for viruses
592 return [
'uploadvirus', $virus ];
604 $names = [ $entry[
'name'] ];
611 $nullPos = strpos( $entry[
'name'],
"\000" );
612 if ( $nullPos !==
false ) {
613 $names[] = substr( $entry[
'name'], 0, $nullPos );
618 if ( preg_grep(
'!\.class/?$!', $names ) ) {
619 $this->mJavaDetected =
true;
653 if ( $nt ===
null ) {
656 $permManager = MediaWikiServices::getInstance()->getPermissionManager();
657 $permErrors = $permManager->getPermissionErrors(
'edit', $user, $nt );
658 $permErrorsUpload = $permManager->getPermissionErrors(
'upload', $user, $nt );
659 if ( !$nt->exists() ) {
660 $permErrorsCreate = $permManager->getPermissionErrors(
'create', $user, $nt );
662 $permErrorsCreate = [];
664 if ( $permErrors || $permErrorsUpload || $permErrorsCreate ) {
665 $permErrors = array_merge( $permErrors,
wfArrayDiff2( $permErrorsUpload, $permErrors ) );
666 $permErrors = array_merge( $permErrors,
wfArrayDiff2( $permErrorsCreate, $permErrors ) );
672 if ( $overwriteError !==
true ) {
673 return [ $overwriteError ];
689 if ( $user ===
null ) {
697 $localFile->load( File::READ_LATEST );
698 $filename = $localFile->getName();
701 $badFileName = $this->
checkBadFileName( $filename, $this->mDesiredDestName );
702 if ( $badFileName !==
null ) {
703 $warnings[
'badfilename'] = $badFileName;
707 if ( $unwantedFileExtensionDetails !==
null ) {
708 $warnings[
'filetype-unwanted-type'] = $unwantedFileExtensionDetails;
711 $fileSizeWarnings = $this->
checkFileSize( $this->mFileSize );
712 if ( $fileSizeWarnings ) {
713 $warnings = array_merge( $warnings, $fileSizeWarnings );
717 if ( $localFileExistsWarnings ) {
718 $warnings = array_merge( $warnings, $localFileExistsWarnings );
722 $warnings[
'was-deleted'] = $filename;
727 $ignoreLocalDupes = isset( $warnings[
'exists'] );
730 $warnings[
'duplicate'] = $dupes;
734 if ( $archivedDupes !==
null ) {
735 $warnings[
'duplicate-archive'] = $archivedDupes;
753 array_walk_recursive( $warnings,
static function ( &$param, $key ) {
754 if ( $param instanceof
File ) {
756 'fileName' => $param->getName(),
757 'timestamp' => $param->getTimestamp()
759 } elseif ( is_object( $param ) ) {
760 throw new InvalidArgumentException(
761 'UploadBase::makeWarningsSerializable: ' .
762 'Unexpected object of class ' . get_class( $param ) );
778 $comparableName = str_replace(
' ',
'_', $desiredFileName );
781 if ( $desiredFileName != $filename && $comparableName != $filename ) {
804 $wgLang->commaList( $extensions ),
824 $warnings[
'large-file'] = [
830 if ( $fileSize == 0 ) {
831 $warnings[
'empty-file'] =
true;
847 if ( $exists !==
false ) {
848 $warnings[
'exists'] = $exists;
851 if ( $hash === $localFile->
getSha1() ) {
852 $warnings[
'no-change'] = $localFile;
857 foreach ( $history as $oldFile ) {
858 if ( $hash === $oldFile->getSha1() ) {
859 $warnings[
'duplicate-version'][] = $oldFile;
878 $dupes = MediaWikiServices::getInstance()->getRepoGroup()->findBySha1( $hash );
880 foreach ( $dupes as $key => $dupe ) {
884 $title->equals( $dupe->getTitle() )
886 unset( $dupes[$key] );
902 if ( $archivedFile->getID() > 0 ) {
904 return $archivedFile->getName();
931 $comment, $pageText, $watch, $user, $tags = [], ?
string $watchlistExpiry =
null
937 $this->getHookRunner()->onUploadVerifyUpload( $this, $user, $props, $comment, $pageText, $error );
939 if ( !is_array( $error ) ) {
956 if ( $status->isGood() ) {
965 $this->getHookRunner()->onUploadComplete( $this );
989 if ( $this->mTitle !==
false ) {
992 if ( !is_string( $this->mDesiredDestName ) ) {
994 $this->mTitle =
null;
1003 $this->mFilteredName =
$title->getDBkey();
1008 # oi_archive_name is max 255 bytes, which include a timestamp and an
1009 # exclamation mark, so restrict file name to 240 bytes.
1010 if ( strlen( $this->mFilteredName ) > 240 ) {
1012 $this->mTitle =
null;
1025 if ( $nt ===
null ) {
1027 $this->mTitle =
null;
1031 $this->mFilteredName = $nt->
getDBkey();
1039 if (
$ext !== [] ) {
1040 $this->mFinalExtension = trim( end(
$ext ) );
1042 $this->mFinalExtension =
'';
1047 if ( $this->mTempPath !==
null ) {
1049 $mime = $magic->guessMimeType( $this->mTempPath );
1050 if (
$mime !==
'unknown/unknown' ) {
1051 # Get a space separated list of extensions
1052 $mimeExt = $magic->getExtensionFromMimeTypeOrNull(
$mime );
1053 if ( $mimeExt !==
null ) {
1054 # Set the extension to the canonical extension
1055 $this->mFinalExtension = $mimeExt;
1057 # Fix up the other variables
1058 $this->mFilteredName .=
".{$this->mFinalExtension}";
1072 if ( $this->mFinalExtension ==
'' ) {
1074 $this->mTitle =
null;
1077 } elseif ( $blackListedExtensions ||
1081 $this->mBlackListedExtensions = $blackListedExtensions;
1083 $this->mTitle =
null;
1089 if ( !preg_match(
'/^[\x0-\x7f]*$/', $nt->getText() )
1090 && !MediaWikiServices::getInstance()->getRepoGroup()
1091 ->getLocalRepo()->backendSupportsUnicodePaths()
1094 $this->mTitle =
null;
1099 # If there was more than one "extension", reassemble the base
1100 # filename to prevent bogus complaints about length
1101 if ( count(
$ext ) > 1 ) {
1102 $iterations = count(
$ext ) - 1;
1103 for ( $i = 0; $i < $iterations; $i++ ) {
1104 $partname .=
'.' .
$ext[$i];
1108 if ( strlen( $partname ) < 1 ) {
1110 $this->mTitle =
null;
1115 $this->mTitle = $nt;
1127 if ( $this->mLocalFile ===
null ) {
1129 $this->mLocalFile = $nt ===
null
1131 : MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo()->newFile( $nt );
1157 if ( !$isPartial ) {
1167 return Status::newFatal(
'uploadstash-exception', get_class( $e ), $e->getMessage() );
1178 $this->getHookRunner()->onUploadStashFile( $this, $user, $props, $error );
1179 if ( $error && !is_array( $error ) ) {
1180 $error = [ $error ];
1218 $stash = MediaWikiServices::getInstance()->getRepoGroup()
1219 ->getLocalRepo()->getUploadStash( $user );
1221 $this->mStashFile =
$file;
1231 if ( $this->mRemoveTempFile && $this->tempFileObj ) {
1233 wfDebug( __METHOD__ .
": Marked temporary file '{$this->mTempPath}' for removal" );
1234 $this->tempFileObj->autocollect();
1252 $bits = explode(
'.', $filename );
1253 $basename = array_shift( $bits );
1255 return [ $basename, $bits ];
1267 return in_array( strtolower(
$ext ), $list );
1279 return array_intersect( array_map(
'strtolower',
$ext ), $list );
1293 if ( !$magic->isRecognizableExtension( $extension ) ) {
1294 wfDebug( __METHOD__ .
": passing file with unknown detected mime type; " .
1295 "unrecognized extension '$extension', can't verify" );
1299 wfDebug( __METHOD__ .
": rejecting file with unknown detected mime type; " .
1300 "recognized extension '$extension', so probably invalid file" );
1306 $match = $magic->isMatchingExtension( $extension,
$mime );
1308 if ( $match ===
null ) {
1309 if ( $magic->getMimeTypesFromExtension( $extension ) !== [] ) {
1310 wfDebug( __METHOD__ .
": No extension known for $mime, but we know a mime for $extension" );
1314 wfDebug( __METHOD__ .
": no file extension known for mime type $mime, passing file" );
1318 } elseif ( $match ===
true ) {
1319 wfDebug( __METHOD__ .
": mime type $mime matches extension $extension, passing file" );
1325 .
": mime type $mime mismatches file extension $extension, rejecting file" );
1343 # ugly hack: for text files, always look at the entire file.
1344 # For binary field, just check the first K.
1346 $isText = strpos(
$mime,
'text/' ) === 0;
1348 $chunk = file_get_contents(
$file );
1350 $fp = fopen(
$file,
'rb' );
1351 $chunk = fread( $fp, 1024 );
1355 $chunk = strtolower( $chunk );
1361 # decode from UTF-16 if needed (could be used for obfuscation).
1362 if ( substr( $chunk, 0, 2 ) ==
"\xfe\xff" ) {
1364 } elseif ( substr( $chunk, 0, 2 ) ==
"\xff\xfe" ) {
1370 if ( $enc !==
null ) {
1371 $chunk = iconv( $enc,
"ASCII//IGNORE", $chunk );
1374 $chunk = trim( $chunk );
1377 wfDebug( __METHOD__ .
": checking for embedded scripts and HTML stuff" );
1379 # check for HTML doctype
1380 if ( preg_match(
"/<!DOCTYPE *X?HTML/i", $chunk ) ) {
1386 if ( $extension ==
'svg' || strpos(
$mime,
'image/svg' ) === 0 ) {
1387 if ( self::checkXMLEncodingMissmatch(
$file ) ) {
1401 '<html', # also in safari
1402 '<script', # also in safari
1405 foreach ( $tags as $tag ) {
1406 if ( strpos( $chunk, $tag ) !==
false ) {
1407 wfDebug( __METHOD__ .
": found something that may make it be mistaken for html: $tag" );
1417 # resolve entity-refs to look at attributes. may be harsh on big files... cache result?
1420 # look for script-types
1421 if ( preg_match(
'!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim', $chunk ) ) {
1422 wfDebug( __METHOD__ .
": found script types" );
1427 # look for html-style script-urls
1428 if ( preg_match(
'!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
1429 wfDebug( __METHOD__ .
": found html-style script urls" );
1434 # look for css-style script-urls
1435 if ( preg_match(
'!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
1436 wfDebug( __METHOD__ .
": found css-style script urls" );
1441 wfDebug( __METHOD__ .
": no scripts found" );
1456 $encodingRegex =
'!encoding[ \t\n\r]*=[ \t\n\r]*[\'"](.*?)[\'"]!si';
1458 if ( preg_match(
"!<\?xml\b(.*?)\?>!si", $contents,
$matches ) ) {
1459 if ( preg_match( $encodingRegex,
$matches[1], $encMatch )
1460 && !in_array( strtoupper( $encMatch[1] ), self::$safeXmlEncodings )
1462 wfDebug( __METHOD__ .
": Found unsafe XML encoding '{$encMatch[1]}'" );
1466 } elseif ( preg_match(
"!<\?xml\b!si", $contents ) ) {
1469 wfDebug( __METHOD__ .
": Unmatched XML declaration start" );
1472 } elseif ( substr( $contents, 0, 4 ) ==
"\x4C\x6F\xA7\x94" ) {
1474 wfDebug( __METHOD__ .
": EBCDIC Encoded XML" );
1481 $attemptEncodings = [
'UTF-16',
'UTF-16BE',
'UTF-32',
'UTF-32BE' ];
1482 foreach ( $attemptEncodings as $encoding ) {
1483 Wikimedia\suppressWarnings();
1484 $str = iconv( $encoding,
'UTF-8', $contents );
1485 Wikimedia\restoreWarnings();
1486 if ( $str !=
'' && preg_match(
"!<\?xml\b(.*?)\?>!si", $str,
$matches ) ) {
1487 if ( preg_match( $encodingRegex,
$matches[1], $encMatch )
1488 && !in_array( strtoupper( $encMatch[1] ), self::$safeXmlEncodings )
1490 wfDebug( __METHOD__ .
": Found unsafe XML encoding '{$encMatch[1]}'" );
1494 } elseif ( $str !=
'' && preg_match(
"!<\?xml\b!si", $str ) ) {
1497 wfDebug( __METHOD__ .
": Unmatched XML declaration start" );
1512 $this->mSVGNSError =
false;
1515 [ $this,
'checkSvgScriptCallback' ],
1518 'processing_instruction_handler' => [ __CLASS__,
'checkSvgPICallback' ],
1519 'external_dtd_handler' => [ __CLASS__,
'checkSvgExternalDTD' ],
1522 if ( $check->wellFormed !==
true ) {
1525 return $partial ? false : [
'uploadinvalidxml' ];
1526 } elseif ( $check->filterMatch ) {
1527 if ( $this->mSVGNSError ) {
1531 return $check->filterMatchType;
1545 if ( preg_match(
'/xml-stylesheet/i', $target ) ) {
1546 return [
'upload-scripted-pi-callback' ];
1567 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd',
1568 'http://www.w3.org/TR/2001/REC-SVG-20010904/DTD/svg10.dtd',
1569 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11-basic.dtd',
1570 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11-tiny.dtd',
1572 'http://www.w3.org/TR/2001/PR-SVG-20010719/DTD/svg10.dtd',
1574 if (
$type !==
'PUBLIC'
1575 || !in_array( $systemId, $allowedDTDs )
1576 || strpos( $publicId,
"-//W3C//" ) !== 0
1578 return [
'upload-scripted-dtd' ];
1595 static $validNamespaces = [
1598 'http://creativecommons.org/ns#',
1599 'http://inkscape.sourceforge.net/dtd/sodipodi-0.dtd',
1600 'http://ns.adobe.com/adobeillustrator/10.0/',
1601 'http://ns.adobe.com/adobesvgviewerextensions/3.0/',
1602 'http://ns.adobe.com/extensibility/1.0/',
1603 'http://ns.adobe.com/flows/1.0/',
1604 'http://ns.adobe.com/illustrator/1.0/',
1605 'http://ns.adobe.com/imagereplacement/1.0/',
1606 'http://ns.adobe.com/pdf/1.3/',
1607 'http://ns.adobe.com/photoshop/1.0/',
1608 'http://ns.adobe.com/saveforweb/1.0/',
1609 'http://ns.adobe.com/variables/1.0/',
1610 'http://ns.adobe.com/xap/1.0/',
1611 'http://ns.adobe.com/xap/1.0/g/',
1612 'http://ns.adobe.com/xap/1.0/g/img/',
1613 'http://ns.adobe.com/xap/1.0/mm/',
1614 'http://ns.adobe.com/xap/1.0/rights/',
1615 'http://ns.adobe.com/xap/1.0/stype/dimensions#',
1616 'http://ns.adobe.com/xap/1.0/stype/font#',
1617 'http://ns.adobe.com/xap/1.0/stype/manifestitem#',
1618 'http://ns.adobe.com/xap/1.0/stype/resourceevent#',
1619 'http://ns.adobe.com/xap/1.0/stype/resourceref#',
1620 'http://ns.adobe.com/xap/1.0/t/pg/',
1621 'http://purl.org/dc/elements/1.1/',
1622 'http://purl.org/dc/elements/1.1',
1623 'http://schemas.microsoft.com/visio/2003/svgextensions/',
1624 'http://sodipodi.sourceforge.net/dtd/sodipodi-0.dtd',
1625 'http://taptrix.com/inkpad/svg_extensions',
1626 'http://web.resource.org/cc/',
1627 'http://www.freesoftware.fsf.org/bkchem/cdml',
1628 'http://www.inkscape.org/namespaces/inkscape',
1629 'http://www.opengis.net/gml',
1630 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
1631 'http://www.w3.org/2000/svg',
1632 'http://www.w3.org/tr/rec-rdf-syntax/',
1633 'http://www.w3.org/2000/01/rdf-schema#',
1638 $isBuggyInkscape = preg_match(
'/^&(#38;)*ns_[a-z_]+;$/', $namespace );
1640 if ( !( $isBuggyInkscape || in_array( $namespace, $validNamespaces ) ) ) {
1641 wfDebug( __METHOD__ .
": Non-svg namespace '$namespace' in uploaded file." );
1643 $this->mSVGNSError = $namespace;
1651 if ( $strippedElement ==
'script' ) {
1652 wfDebug( __METHOD__ .
": Found script element '$element' in uploaded file." );
1654 return [
'uploaded-script-svg', $strippedElement ];
1657 # e.g., <svg xmlns="http://www.w3.org/2000/svg">
1658 # <handler xmlns:ev="http://www.w3.org/2001/xml-events" ev:event="load">alert(1)</handler> </svg>
1659 if ( $strippedElement ==
'handler' ) {
1660 wfDebug( __METHOD__ .
": Found scriptable element '$element' in uploaded file." );
1662 return [
'uploaded-script-svg', $strippedElement ];
1665 # SVG reported in Feb '12 that used xml:stylesheet to generate javascript block
1666 if ( $strippedElement ==
'stylesheet' ) {
1667 wfDebug( __METHOD__ .
": Found scriptable element '$element' in uploaded file." );
1669 return [
'uploaded-script-svg', $strippedElement ];
1672 # Block iframes, in case they pass the namespace check
1673 if ( $strippedElement ==
'iframe' ) {
1674 wfDebug( __METHOD__ .
": iframe in uploaded file." );
1676 return [
'uploaded-script-svg', $strippedElement ];
1680 if ( $strippedElement ==
'style'
1683 wfDebug( __METHOD__ .
": hostile css in style element." );
1684 return [
'uploaded-hostile-svg' ];
1687 foreach ( $attribs as $attrib => $value ) {
1689 $value = strtolower( $value );
1691 if ( substr( $stripped, 0, 2 ) ==
'on' ) {
1693 .
": Found event-handler attribute '$attrib'='$value' in uploaded file." );
1695 return [
'uploaded-event-handler-on-svg', $attrib, $value ];
1698 # Do not allow relative links, or unsafe url schemas.
1699 # For <a> tags, only data:, http: and https: and same-document
1700 # fragment links are allowed. For all other tags, only data:
1701 # and fragment are allowed.
1702 if ( $stripped ==
'href'
1704 && strpos( $value,
'data:' ) !== 0
1705 && strpos( $value,
'#' ) !== 0
1707 if ( !( $strippedElement ===
'a'
1708 && preg_match(
'!^https?://!i', $value ) )
1710 wfDebug( __METHOD__ .
": Found href attribute <$strippedElement "
1711 .
"'$attrib'='$value' in uploaded file." );
1713 return [
'uploaded-href-attribute-svg', $strippedElement, $attrib, $value ];
1717 # only allow data: targets that should be safe. This prevents vectors like,
1718 # image/svg, text/xml, application/xml, and text/html, which can contain scripts
1719 if ( $stripped ==
'href' && strncasecmp(
'data:', $value, 5 ) === 0 ) {
1722 $parameters =
'(?>;[a-zA-Z0-9\!#$&\'*+.^_`{|}~-]+=(?>[a-zA-Z0-9\!#$&\'*+.^_`{|}~-]+|"(?>[\0-\x0c\x0e-\x21\x23-\x5b\x5d-\x7f]+|\\\\[\0-\x7f])*"))*(?:;base64)?';
1724 if ( !preg_match(
"!^data:\s*image/(gif|jpeg|jpg|png)$parameters,!i", $value ) ) {
1725 wfDebug( __METHOD__ .
": Found href to unwhitelisted data: uri "
1726 .
"\"<$strippedElement '$attrib'='$value'...\" in uploaded file." );
1727 return [
'uploaded-href-unsafe-target-svg', $strippedElement, $attrib, $value ];
1731 # Change href with animate from (http://html5sec.org/#137).
1732 if ( $stripped ===
'attributename'
1733 && $strippedElement ===
'animate'
1736 wfDebug( __METHOD__ .
": Found animate that might be changing href using from "
1737 .
"\"<$strippedElement '$attrib'='$value'...\" in uploaded file." );
1739 return [
'uploaded-animate-svg', $strippedElement, $attrib, $value ];
1742 # use set/animate to add event-handler attribute to parent
1743 if ( ( $strippedElement ==
'set' || $strippedElement ==
'animate' )
1744 && $stripped ==
'attributename'
1745 && substr( $value, 0, 2 ) ==
'on'
1747 wfDebug( __METHOD__ .
": Found svg setting event-handler attribute with "
1748 .
"\"<$strippedElement $stripped='$value'...\" in uploaded file." );
1750 return [
'uploaded-setting-event-handler-svg', $strippedElement, $stripped, $value ];
1753 # use set to add href attribute to parent element
1754 if ( $strippedElement ==
'set'
1755 && $stripped ==
'attributename'
1756 && strpos( $value,
'href' ) !==
false
1758 wfDebug( __METHOD__ .
": Found svg setting href attribute '$value' in uploaded file." );
1760 return [
'uploaded-setting-href-svg' ];
1763 # use set to add a remote / data / script target to an element
1764 if ( $strippedElement ==
'set'
1765 && $stripped ==
'to'
1766 && preg_match(
'!(http|https|data|script):!sim', $value )
1768 wfDebug( __METHOD__ .
": Found svg setting attribute to '$value' in uploaded file." );
1770 return [
'uploaded-wrong-setting-svg', $value ];
1773 # use handler attribute with remote / data / script
1774 if ( $stripped ==
'handler' && preg_match(
'!(http|https|data|script):!sim', $value ) ) {
1775 wfDebug( __METHOD__ .
": Found svg setting handler with remote/data/script "
1776 .
"'$attrib'='$value' in uploaded file." );
1778 return [
'uploaded-setting-handler-svg', $attrib, $value ];
1781 # use CSS styles to bring in remote code
1782 if ( $stripped ==
'style'
1785 wfDebug( __METHOD__ .
": Found svg setting a style with "
1786 .
"remote url '$attrib'='$value' in uploaded file." );
1787 return [
'uploaded-remote-url-svg', $attrib, $value ];
1790 # Several attributes can include css, css character escaping isn't allowed
1791 $cssAttrs = [
'font',
'clip-path',
'fill',
'filter',
'marker',
1792 'marker-end',
'marker-mid',
'marker-start',
'mask',
'stroke' ];
1793 if ( in_array( $stripped, $cssAttrs )
1794 && self::checkCssFragment( $value )
1796 wfDebug( __METHOD__ .
": Found svg setting a style with "
1797 .
"remote url '$attrib'='$value' in uploaded file." );
1798 return [
'uploaded-remote-url-svg', $attrib, $value ];
1801 # image filters can pull in url, which could be svg that executes scripts
1802 # Only allow url( "#foo" ). Do not allow url( http://example.com )
1803 if ( $strippedElement ==
'image'
1804 && $stripped ==
'filter'
1805 && preg_match(
'!url\s*\(\s*["\']?[^#]!sim', $value )
1807 wfDebug( __METHOD__ .
": Found image filter with url: "
1808 .
"\"<$strippedElement $stripped='$value'...\" in uploaded file." );
1810 return [
'uploaded-image-filter-svg', $strippedElement, $stripped, $value ];
1824 # Forbid external stylesheets, for both reliability and to protect viewer's privacy
1825 if ( stripos( $value,
'@import' ) !==
false ) {
1829 # We allow @font-face to embed fonts with data: urls, so we snip the string
1830 # 'url' out so this case won't match when we check for urls below
1831 $pattern =
'!(@font-face\s*{[^}]*src:)url(\("data:;base64,)!im';
1832 $value = preg_replace( $pattern,
'$1$2', $value );
1834 # Check for remote and executable CSS. Unlike in Sanitizer::checkCss, the CSS
1835 # properties filter and accelerator don't seem to be useful for xss in SVG files.
1836 # Expression and -o-link don't seem to work either, but filtering them here in case.
1837 # Additionally, we catch remote urls like url("http:..., url('http:..., url(http:...,
1838 # but not local ones such as url("#..., url('#..., url(#....
1839 if ( preg_match(
'!expression
1841 | -o-link-source\s*:
1842 | -o-replace\s*:!imx', $value ) ) {
1846 if ( preg_match_all(
1847 "!(\s*(url|image|image-set)\s*\(\s*[\"']?\s*[^#]+.*?\))!sim",
1852 # TODO: redo this in one regex. Until then, url("#whatever") matches the first
1853 foreach (
$matches[1] as $match ) {
1854 if ( !preg_match(
"!\s*(url|image|image-set)\s*\(\s*(#|'#|\"#)!im", $match ) ) {
1860 if ( preg_match(
'/[\000-\010\013\016-\037\177]/', $value ) ) {
1874 $parts = explode(
':', strtolower( $element ) );
1875 $name = array_pop( $parts );
1876 $ns = implode(
':', $parts );
1878 return [ $ns, $name ];
1887 $parts = explode(
':', strtolower( $name ) );
1889 return array_pop( $parts );
1906 wfDebug( __METHOD__ .
": virus scanner disabled" );
1912 wfDebug( __METHOD__ .
": unknown virus scanner: $wgAntivirus" );
1913 $wgOut->wrapWikiMsg(
"<div class=\"error\">\n$1\n</div>",
1916 return wfMessage(
'virus-unknownscanner' )->text() .
" $wgAntivirus";
1919 # look up scanner configuration
1924 if ( strpos(
$command,
"%f" ) ===
false ) {
1925 # simple pattern: append file to scan
1928 # complex pattern: replace "%f" with file to scan
1932 wfDebug( __METHOD__ .
": running virus scan: $command " );
1934 # execute virus scanner
1937 # NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
1938 # that does not seem to be worth the pain.
1939 # Ask me (Duesentrieb) about it if it's ever needed.
1942 # map exit code to AV_xxx constants.
1943 $mappedCode = $exitCode;
1944 if ( $exitCodeMap ) {
1945 if ( isset( $exitCodeMap[$exitCode] ) ) {
1946 $mappedCode = $exitCodeMap[$exitCode];
1947 } elseif ( isset( $exitCodeMap[
"*"] ) ) {
1948 $mappedCode = $exitCodeMap[
"*"];
1956 # scan failed (code was mapped to false by $exitCodeMap)
1957 wfDebug( __METHOD__ .
": failed to scan $file (code $exitCode)." );
1960 ?
wfMessage(
'virus-scanfailed', [ $exitCode ] )->text()
1963 # scan failed because filetype is unknown (probably imune)
1964 wfDebug( __METHOD__ .
": unsupported file type $file (code $exitCode)." );
1968 wfDebug( __METHOD__ .
": file passed virus scan." );
1971 $output = trim( $output );
1974 $output =
true; #
if there
's no output, return true
1975 } elseif ( $msgPattern ) {
1977 if ( preg_match( $msgPattern, $output, $groups ) && $groups[1] ) {
1978 $output = $groups[1];
1982 wfDebug( __METHOD__ . ": FOUND VIRUS! scanner feedback: $output" );
1996 private function checkOverwrite( $user ) {
1997 // First check whether the local file can be overwritten
1998 $file = $this->getLocalFile();
1999 $file->load( File::READ_LATEST );
2000 if ( $file->exists() ) {
2001 if ( !self::userCanReUpload( $user, $file ) ) {
2002 return [ 'fileexists-forbidden
', $file->getName() ];
2008 $services = MediaWikiServices::getInstance();
2010 /* Check shared conflicts: if the local file does not exist, but
2011 * RepoGroup::findFile finds a file, it exists in a shared repository.
2013 $file = $services->getRepoGroup()->findFile( $this->getTitle(), [ 'latest
' => true ] );
2014 if ( $file && !$services->getPermissionManager()
2015 ->userHasRight( $user, 'reupload-shared
' )
2017 return [ 'fileexists-shared-forbidden
', $file->getName() ];
2030 public static function userCanReUpload( User $user, File $img ) {
2031 $permissionManager = MediaWikiServices::getInstance()->getPermissionManager();
2032 if ( $permissionManager->userHasRight( $user, 'reupload
' ) ) {
2033 return true; // non-conditional
2034 } elseif ( !$permissionManager->userHasRight( $user, 'reupload-own
' ) ) {
2038 if ( !( $img instanceof LocalFile ) ) {
2044 return $user->getId() == $img->getUser( 'id' );
2058 public static function getExistsWarning( $file ) {
2059 if ( $file->exists() ) {
2060 return [ 'warning
' => 'exists
', 'file
' => $file ];
2063 if ( $file->getTitle()->getArticleID() ) {
2064 return [ 'warning
' => 'page-exists
', 'file
' => $file ];
2067 if ( strpos( $file->getName(), '.
' ) == false ) {
2068 $partname = $file->getName();
2071 $n = strrpos( $file->getName(), '.
' );
2072 $extension = substr( $file->getName(), $n + 1 );
2073 $partname = substr( $file->getName(), 0, $n );
2075 $normalizedExtension = File::normalizeExtension( $extension );
2076 $localRepo = MediaWikiServices::getInstance()->getRepoGroup()->getLocalRepo();
2078 if ( $normalizedExtension != $extension ) {
2079 // We're not
using the normalized form of the extension.
2085 $file_lc = $localRepo->newFile( $nt_lc );
2087 if ( $file_lc->exists() ) {
2089 'warning' =>
'exists-normalized',
2091 'normalizedFile' => $file_lc
2097 $similarFiles = $localRepo->findFilesByPrefix(
"{$partname}.", 1 );
2098 if ( count( $similarFiles ) ) {
2100 'warning' =>
'exists-normalized',
2102 'normalizedFile' => $similarFiles[0],
2106 if ( self::isThumbName(
$file->getName() ) ) {
2107 # Check for filenames like 50px- or 180px-, these are mostly thumbnails
2109 substr( $partname, strpos( $partname,
'-' ) + 1 ) .
'.' . $extension,
2112 $file_thb = $localRepo->newFile( $nt_thb );
2113 if ( $file_thb->exists() ) {
2115 'warning' =>
'thumb',
2117 'thumbFile' => $file_thb
2122 'warning' =>
'thumb-name',
2124 'thumbFile' => $file_thb
2129 foreach ( self::getFilenamePrefixBlacklist() as $prefix ) {
2130 if ( substr( $partname, 0, strlen( $prefix ) ) == $prefix ) {
2132 'warning' =>
'bad-prefix',
2148 $n = strrpos( $filename,
'.' );
2149 $partname = $n ? substr( $filename, 0, $n ) : $filename;
2152 substr( $partname, 3, 3 ) ==
'px-' ||
2153 substr( $partname, 2, 3 ) ==
'px-'
2155 preg_match(
"/[0-9]{2}/", substr( $partname, 0, 2 ) );
2165 $message =
wfMessage(
'filename-prefix-blacklist' )->inContentLanguage();
2166 if ( !$message->isDisabled() ) {
2167 $lines = explode(
"\n", $message->plain() );
2170 $comment = substr( trim(
$line ), 0, 1 );
2171 if ( $comment ==
'#' || $comment ==
'' ) {
2175 $comment = strpos(
$line,
'#' );
2176 if ( $comment > 0 ) {
2179 $blacklist[] = trim(
$line );
2218 $code = $error[
'status'];
2219 unset( $code[
'status'] );
2254 ini_get(
'upload_max_filesize' ),
2258 ini_get(
'post_max_size' ),
2261 return min( $phpMaxFileSize, $phpMaxPostSize );
2277 return $store->get( $key );
2296 if ( $value ===
false ) {
2297 $store->delete( $key );
2299 $store->set( $key, $value, $store::TTL_DAY );