Localisation updates from https://translatewiki.net.
[mediawiki.git] / includes / upload / UploadBase.php
blobfccb5e1a3ade701b60825043eec2a175bc5301c9
1 <?php
2 /**
3 * Base class for the backend of file upload.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
20 * @file
21 * @ingroup Upload
24 /**
25 * @defgroup Upload Upload related
28 /**
29 * @ingroup Upload
31 * UploadBase and subclasses are the backend of MediaWiki's file uploads.
32 * The frontends are formed by ApiUpload and SpecialUpload.
34 * @author Brion Vibber
35 * @author Bryan Tong Minh
36 * @author Michael Dale
38 abstract class UploadBase {
39 protected $mTempPath;
40 protected $mDesiredDestName, $mDestName, $mRemoveTempFile, $mSourceType;
41 protected $mTitle = false, $mTitleError = 0;
42 protected $mFilteredName, $mFinalExtension;
43 protected $mLocalFile, $mFileSize, $mFileProps;
44 protected $mBlackListedExtensions;
45 protected $mJavaDetected, $mSVGNSError;
47 protected static $safeXmlEncodings = array(
48 'UTF-8',
49 'ISO-8859-1',
50 'ISO-8859-2',
51 'UTF-16',
52 'UTF-32'
55 const SUCCESS = 0;
56 const OK = 0;
57 const EMPTY_FILE = 3;
58 const MIN_LENGTH_PARTNAME = 4;
59 const ILLEGAL_FILENAME = 5;
60 const OVERWRITE_EXISTING_FILE = 7; # Not used anymore; handled by verifyTitlePermissions()
61 const FILETYPE_MISSING = 8;
62 const FILETYPE_BADTYPE = 9;
63 const VERIFICATION_ERROR = 10;
65 # HOOK_ABORTED is the new name of UPLOAD_VERIFICATION_ERROR
66 const UPLOAD_VERIFICATION_ERROR = 11;
67 const HOOK_ABORTED = 11;
68 const FILE_TOO_LARGE = 12;
69 const WINDOWS_NONASCII_FILENAME = 13;
70 const FILENAME_TOO_LONG = 14;
72 /**
73 * @param int $error
74 * @return string
76 public function getVerificationErrorCode( $error ) {
77 $code_to_status = array(
78 self::EMPTY_FILE => 'empty-file',
79 self::FILE_TOO_LARGE => 'file-too-large',
80 self::FILETYPE_MISSING => 'filetype-missing',
81 self::FILETYPE_BADTYPE => 'filetype-banned',
82 self::MIN_LENGTH_PARTNAME => 'filename-tooshort',
83 self::ILLEGAL_FILENAME => 'illegal-filename',
84 self::OVERWRITE_EXISTING_FILE => 'overwrite',
85 self::VERIFICATION_ERROR => 'verification-error',
86 self::HOOK_ABORTED => 'hookaborted',
87 self::WINDOWS_NONASCII_FILENAME => 'windows-nonascii-filename',
88 self::FILENAME_TOO_LONG => 'filename-toolong',
90 if ( isset( $code_to_status[$error] ) ) {
91 return $code_to_status[$error];
94 return 'unknown-error';
97 /**
98 * Returns true if uploads are enabled.
99 * Can be override by subclasses.
100 * @return bool
102 public static function isEnabled() {
103 global $wgEnableUploads;
105 if ( !$wgEnableUploads ) {
106 return false;
109 # Check php's file_uploads setting
110 return wfIsHHVM() || wfIniGetBool( 'file_uploads' );
114 * Returns true if the user can use this upload module or else a string
115 * identifying the missing permission.
116 * Can be overridden by subclasses.
118 * @param User $user
119 * @return bool|string
121 public static function isAllowed( $user ) {
122 foreach ( array( 'upload', 'edit' ) as $permission ) {
123 if ( !$user->isAllowed( $permission ) ) {
124 return $permission;
128 return true;
131 // Upload handlers. Should probably just be a global.
132 private static $uploadHandlers = array( 'Stash', 'File', 'Url' );
135 * Create a form of UploadBase depending on wpSourceType and initializes it
137 * @param WebRequest $request
138 * @param string|null $type
139 * @return null|UploadBase
141 public static function createFromRequest( &$request, $type = null ) {
142 $type = $type ? $type : $request->getVal( 'wpSourceType', 'File' );
144 if ( !$type ) {
145 return null;
148 // Get the upload class
149 $type = ucfirst( $type );
151 // Give hooks the chance to handle this request
152 $className = null;
153 Hooks::run( 'UploadCreateFromRequest', array( $type, &$className ) );
154 if ( is_null( $className ) ) {
155 $className = 'UploadFrom' . $type;
156 wfDebug( __METHOD__ . ": class name: $className\n" );
157 if ( !in_array( $type, self::$uploadHandlers ) ) {
158 return null;
162 // Check whether this upload class is enabled
163 if ( !call_user_func( array( $className, 'isEnabled' ) ) ) {
164 return null;
167 // Check whether the request is valid
168 if ( !call_user_func( array( $className, 'isValidRequest' ), $request ) ) {
169 return null;
172 /** @var UploadBase $handler */
173 $handler = new $className;
175 $handler->initializeFromRequest( $request );
177 return $handler;
181 * Check whether a request if valid for this handler
182 * @param WebRequest $request
183 * @return bool
185 public static function isValidRequest( $request ) {
186 return false;
189 public function __construct() {
193 * Returns the upload type. Should be overridden by child classes
195 * @since 1.18
196 * @return string
198 public function getSourceType() {
199 return null;
203 * Initialize the path information
204 * @param string $name The desired destination name
205 * @param string $tempPath The temporary path
206 * @param int $fileSize The file size
207 * @param bool $removeTempFile (false) remove the temporary file?
208 * @throws MWException
210 public function initializePathInfo( $name, $tempPath, $fileSize, $removeTempFile = false ) {
211 $this->mDesiredDestName = $name;
212 if ( FileBackend::isStoragePath( $tempPath ) ) {
213 throw new MWException( __METHOD__ . " given storage path `$tempPath`." );
215 $this->mTempPath = $tempPath;
216 $this->mFileSize = $fileSize;
217 $this->mRemoveTempFile = $removeTempFile;
221 * Initialize from a WebRequest. Override this in a subclass.
223 * @param WebRequest $request
225 abstract public function initializeFromRequest( &$request );
228 * Fetch the file. Usually a no-op
229 * @return Status
231 public function fetchFile() {
232 return Status::newGood();
236 * Return true if the file is empty
237 * @return bool
239 public function isEmptyFile() {
240 return empty( $this->mFileSize );
244 * Return the file size
245 * @return int
247 public function getFileSize() {
248 return $this->mFileSize;
252 * Get the base 36 SHA1 of the file
253 * @return string
255 public function getTempFileSha1Base36() {
256 return FSFile::getSha1Base36FromPath( $this->mTempPath );
260 * @param string $srcPath The source path
261 * @return string|bool The real path if it was a virtual URL Returns false on failure
263 function getRealPath( $srcPath ) {
264 $repo = RepoGroup::singleton()->getLocalRepo();
265 if ( $repo->isVirtualUrl( $srcPath ) ) {
266 /** @todo Just make uploads work with storage paths UploadFromStash
267 * loads files via virtual URLs.
269 $tmpFile = $repo->getLocalCopy( $srcPath );
270 if ( $tmpFile ) {
271 $tmpFile->bind( $this ); // keep alive with $this
273 $path = $tmpFile ? $tmpFile->getPath() : false;
274 } else {
275 $path = $srcPath;
278 return $path;
282 * Verify whether the upload is sane.
283 * @return mixed Const self::OK or else an array with error information
285 public function verifyUpload() {
288 * If there was no filename or a zero size given, give up quick.
290 if ( $this->isEmptyFile() ) {
292 return array( 'status' => self::EMPTY_FILE );
296 * Honor $wgMaxUploadSize
298 $maxSize = self::getMaxUploadSize( $this->getSourceType() );
299 if ( $this->mFileSize > $maxSize ) {
301 return array(
302 'status' => self::FILE_TOO_LARGE,
303 'max' => $maxSize,
308 * Look at the contents of the file; if we can recognize the
309 * type but it's corrupt or data of the wrong type, we should
310 * probably not accept it.
312 $verification = $this->verifyFile();
313 if ( $verification !== true ) {
315 return array(
316 'status' => self::VERIFICATION_ERROR,
317 'details' => $verification
322 * Make sure this file can be created
324 $result = $this->validateName();
325 if ( $result !== true ) {
327 return $result;
330 $error = '';
331 if ( !Hooks::run( 'UploadVerification',
332 array( $this->mDestName, $this->mTempPath, &$error ) )
335 return array( 'status' => self::HOOK_ABORTED, 'error' => $error );
338 return array( 'status' => self::OK );
342 * Verify that the name is valid and, if necessary, that we can overwrite
344 * @return mixed True if valid, otherwise and array with 'status'
345 * and other keys
347 public function validateName() {
348 $nt = $this->getTitle();
349 if ( is_null( $nt ) ) {
350 $result = array( 'status' => $this->mTitleError );
351 if ( $this->mTitleError == self::ILLEGAL_FILENAME ) {
352 $result['filtered'] = $this->mFilteredName;
354 if ( $this->mTitleError == self::FILETYPE_BADTYPE ) {
355 $result['finalExt'] = $this->mFinalExtension;
356 if ( count( $this->mBlackListedExtensions ) ) {
357 $result['blacklistedExt'] = $this->mBlackListedExtensions;
361 return $result;
363 $this->mDestName = $this->getLocalFile()->getName();
365 return true;
369 * Verify the MIME type.
371 * @note Only checks that it is not an evil MIME. The "does it have
372 * correct extension given its MIME type?" check is in verifyFile.
373 * in `verifyFile()` that MIME type and file extension correlate.
374 * @param string $mime Representing the MIME
375 * @return mixed True if the file is verified, an array otherwise
377 protected function verifyMimeType( $mime ) {
378 global $wgVerifyMimeType;
379 if ( $wgVerifyMimeType ) {
380 wfDebug( "mime: <$mime> extension: <{$this->mFinalExtension}>\n" );
381 global $wgMimeTypeBlacklist;
382 if ( $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
384 return array( 'filetype-badmime', $mime );
387 # Check what Internet Explorer would detect
388 $fp = fopen( $this->mTempPath, 'rb' );
389 $chunk = fread( $fp, 256 );
390 fclose( $fp );
392 $magic = MimeMagic::singleton();
393 $extMime = $magic->guessTypesForExtension( $this->mFinalExtension );
394 $ieTypes = $magic->getIEMimeTypes( $this->mTempPath, $chunk, $extMime );
395 foreach ( $ieTypes as $ieType ) {
396 if ( $this->checkFileExtension( $ieType, $wgMimeTypeBlacklist ) ) {
398 return array( 'filetype-bad-ie-mime', $ieType );
403 return true;
407 * Verifies that it's ok to include the uploaded file
409 * @return mixed True of the file is verified, array otherwise.
411 protected function verifyFile() {
412 global $wgVerifyMimeType, $wgDisableUploadScriptChecks;
414 $status = $this->verifyPartialFile();
415 if ( $status !== true ) {
417 return $status;
420 $this->mFileProps = FSFile::getPropsFromPath( $this->mTempPath, $this->mFinalExtension );
421 $mime = $this->mFileProps['mime'];
423 if ( $wgVerifyMimeType ) {
424 # XXX: Missing extension will be caught by validateName() via getTitle()
425 if ( $this->mFinalExtension != '' && !$this->verifyExtension( $mime, $this->mFinalExtension ) ) {
427 return array( 'filetype-mime-mismatch', $this->mFinalExtension, $mime );
431 # check for htmlish code and javascript
432 if ( !$wgDisableUploadScriptChecks ) {
433 if ( $this->mFinalExtension == 'svg' || $mime == 'image/svg+xml' ) {
434 $svgStatus = $this->detectScriptInSvg( $this->mTempPath, false );
435 if ( $svgStatus !== false ) {
437 return $svgStatus;
442 $handler = MediaHandler::getHandler( $mime );
443 if ( $handler ) {
444 $handlerStatus = $handler->verifyUpload( $this->mTempPath );
445 if ( !$handlerStatus->isOK() ) {
446 $errors = $handlerStatus->getErrorsArray();
448 return reset( $errors );
452 Hooks::run( 'UploadVerifyFile', array( $this, $mime, &$status ) );
453 if ( $status !== true ) {
455 return $status;
458 wfDebug( __METHOD__ . ": all clear; passing.\n" );
460 return true;
464 * A verification routine suitable for partial files
466 * Runs the blacklist checks, but not any checks that may
467 * assume the entire file is present.
469 * @return mixed True for valid or array with error message key.
471 protected function verifyPartialFile() {
472 global $wgAllowJavaUploads, $wgDisableUploadScriptChecks;
474 # getTitle() sets some internal parameters like $this->mFinalExtension
475 $this->getTitle();
477 $this->mFileProps = FSFile::getPropsFromPath( $this->mTempPath, $this->mFinalExtension );
479 # check MIME type, if desired
480 $mime = $this->mFileProps['file-mime'];
481 $status = $this->verifyMimeType( $mime );
482 if ( $status !== true ) {
484 return $status;
487 # check for htmlish code and javascript
488 if ( !$wgDisableUploadScriptChecks ) {
489 if ( self::detectScript( $this->mTempPath, $mime, $this->mFinalExtension ) ) {
491 return array( 'uploadscripted' );
493 if ( $this->mFinalExtension == 'svg' || $mime == 'image/svg+xml' ) {
494 $svgStatus = $this->detectScriptInSvg( $this->mTempPath, true );
495 if ( $svgStatus !== false ) {
497 return $svgStatus;
502 # Check for Java applets, which if uploaded can bypass cross-site
503 # restrictions.
504 if ( !$wgAllowJavaUploads ) {
505 $this->mJavaDetected = false;
506 $zipStatus = ZipDirectoryReader::read( $this->mTempPath,
507 array( $this, 'zipEntryCallback' ) );
508 if ( !$zipStatus->isOK() ) {
509 $errors = $zipStatus->getErrorsArray();
510 $error = reset( $errors );
511 if ( $error[0] !== 'zip-wrong-format' ) {
513 return $error;
516 if ( $this->mJavaDetected ) {
518 return array( 'uploadjava' );
522 # Scan the uploaded file for viruses
523 $virus = $this->detectVirus( $this->mTempPath );
524 if ( $virus ) {
526 return array( 'uploadvirus', $virus );
529 return true;
533 * Callback for ZipDirectoryReader to detect Java class files.
535 * @param array $entry
537 function zipEntryCallback( $entry ) {
538 $names = array( $entry['name'] );
540 // If there is a null character, cut off the name at it, because JDK's
541 // ZIP_GetEntry() uses strcmp() if the name hashes match. If a file name
542 // were constructed which had ".class\0" followed by a string chosen to
543 // make the hash collide with the truncated name, that file could be
544 // returned in response to a request for the .class file.
545 $nullPos = strpos( $entry['name'], "\000" );
546 if ( $nullPos !== false ) {
547 $names[] = substr( $entry['name'], 0, $nullPos );
550 // If there is a trailing slash in the file name, we have to strip it,
551 // because that's what ZIP_GetEntry() does.
552 if ( preg_grep( '!\.class/?$!', $names ) ) {
553 $this->mJavaDetected = true;
558 * Alias for verifyTitlePermissions. The function was originally
559 * 'verifyPermissions', but that suggests it's checking the user, when it's
560 * really checking the title + user combination.
562 * @param User $user User object to verify the permissions against
563 * @return mixed An array as returned by getUserPermissionsErrors or true
564 * in case the user has proper permissions.
566 public function verifyPermissions( $user ) {
567 return $this->verifyTitlePermissions( $user );
571 * Check whether the user can edit, upload and create the image. This
572 * checks only against the current title; if it returns errors, it may
573 * very well be that another title will not give errors. Therefore
574 * isAllowed() should be called as well for generic is-user-blocked or
575 * can-user-upload checking.
577 * @param User $user User object to verify the permissions against
578 * @return mixed An array as returned by getUserPermissionsErrors or true
579 * in case the user has proper permissions.
581 public function verifyTitlePermissions( $user ) {
583 * If the image is protected, non-sysop users won't be able
584 * to modify it by uploading a new revision.
586 $nt = $this->getTitle();
587 if ( is_null( $nt ) ) {
588 return true;
590 $permErrors = $nt->getUserPermissionsErrors( 'edit', $user );
591 $permErrorsUpload = $nt->getUserPermissionsErrors( 'upload', $user );
592 if ( !$nt->exists() ) {
593 $permErrorsCreate = $nt->getUserPermissionsErrors( 'create', $user );
594 } else {
595 $permErrorsCreate = array();
597 if ( $permErrors || $permErrorsUpload || $permErrorsCreate ) {
598 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsUpload, $permErrors ) );
599 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsCreate, $permErrors ) );
601 return $permErrors;
604 $overwriteError = $this->checkOverwrite( $user );
605 if ( $overwriteError !== true ) {
606 return array( $overwriteError );
609 return true;
613 * Check for non fatal problems with the file.
615 * This should not assume that mTempPath is set.
617 * @return array Array of warnings
619 public function checkWarnings() {
620 global $wgLang;
622 $warnings = array();
624 $localFile = $this->getLocalFile();
625 $filename = $localFile->getName();
628 * Check whether the resulting filename is different from the desired one,
629 * but ignore things like ucfirst() and spaces/underscore things
631 $comparableName = str_replace( ' ', '_', $this->mDesiredDestName );
632 $comparableName = Title::capitalize( $comparableName, NS_FILE );
634 if ( $this->mDesiredDestName != $filename && $comparableName != $filename ) {
635 $warnings['badfilename'] = $filename;
636 // Debugging for bug 62241
637 wfDebugLog( 'upload', "Filename: '$filename', mDesiredDestName: "
638 . "'$this->mDesiredDestName', comparableName: '$comparableName'" );
641 // Check whether the file extension is on the unwanted list
642 global $wgCheckFileExtensions, $wgFileExtensions;
643 if ( $wgCheckFileExtensions ) {
644 $extensions = array_unique( $wgFileExtensions );
645 if ( !$this->checkFileExtension( $this->mFinalExtension, $extensions ) ) {
646 $warnings['filetype-unwanted-type'] = array( $this->mFinalExtension,
647 $wgLang->commaList( $extensions ), count( $extensions ) );
651 global $wgUploadSizeWarning;
652 if ( $wgUploadSizeWarning && ( $this->mFileSize > $wgUploadSizeWarning ) ) {
653 $warnings['large-file'] = array( $wgUploadSizeWarning, $this->mFileSize );
656 if ( $this->mFileSize == 0 ) {
657 $warnings['emptyfile'] = true;
660 $exists = self::getExistsWarning( $localFile );
661 if ( $exists !== false ) {
662 $warnings['exists'] = $exists;
665 // Check dupes against existing files
666 $hash = $this->getTempFileSha1Base36();
667 $dupes = RepoGroup::singleton()->findBySha1( $hash );
668 $title = $this->getTitle();
669 // Remove all matches against self
670 foreach ( $dupes as $key => $dupe ) {
671 if ( $title->equals( $dupe->getTitle() ) ) {
672 unset( $dupes[$key] );
675 if ( $dupes ) {
676 $warnings['duplicate'] = $dupes;
679 // Check dupes against archives
680 $archivedFile = new ArchivedFile( null, 0, '', $hash );
681 if ( $archivedFile->getID() > 0 ) {
682 if ( $archivedFile->userCan( File::DELETED_FILE ) ) {
683 $warnings['duplicate-archive'] = $archivedFile->getName();
684 } else {
685 $warnings['duplicate-archive'] = '';
689 return $warnings;
693 * Really perform the upload. Stores the file in the local repo, watches
694 * if necessary and runs the UploadComplete hook.
696 * @param string $comment
697 * @param string $pageText
698 * @param bool $watch
699 * @param User $user
701 * @return Status Indicating the whether the upload succeeded.
703 public function performUpload( $comment, $pageText, $watch, $user ) {
705 $status = $this->getLocalFile()->upload(
706 $this->mTempPath,
707 $comment,
708 $pageText,
709 File::DELETE_SOURCE,
710 $this->mFileProps,
711 false,
712 $user
715 if ( $status->isGood() ) {
716 if ( $watch ) {
717 WatchAction::doWatch(
718 $this->getLocalFile()->getTitle(),
719 $user,
720 WatchedItem::IGNORE_USER_RIGHTS
723 Hooks::run( 'UploadComplete', array( &$this ) );
725 $this->postProcessUpload();
728 return $status;
732 * Perform extra steps after a successful upload.
734 * @since 1.25
736 public function postProcessUpload() {
737 global $wgUploadThumbnailRenderMap;
739 $jobs = array();
741 $sizes = $wgUploadThumbnailRenderMap;
742 rsort( $sizes );
744 $file = $this->getLocalFile();
746 foreach ( $sizes as $size ) {
747 if ( $file->isVectorized()
748 || $file->getWidth() > $size ) {
749 $jobs[] = new ThumbnailRenderJob( $file->getTitle(), array(
750 'transformParams' => array( 'width' => $size ),
751 ) );
755 if ( $jobs ) {
756 JobQueueGroup::singleton()->push( $jobs );
761 * Returns the title of the file to be uploaded. Sets mTitleError in case
762 * the name was illegal.
764 * @return Title The title of the file or null in case the name was illegal
766 public function getTitle() {
767 if ( $this->mTitle !== false ) {
768 return $this->mTitle;
770 /* Assume that if a user specified File:Something.jpg, this is an error
771 * and that the namespace prefix needs to be stripped of.
773 $title = Title::newFromText( $this->mDesiredDestName );
774 if ( $title && $title->getNamespace() == NS_FILE ) {
775 $this->mFilteredName = $title->getDBkey();
776 } else {
777 $this->mFilteredName = $this->mDesiredDestName;
780 # oi_archive_name is max 255 bytes, which include a timestamp and an
781 # exclamation mark, so restrict file name to 240 bytes.
782 if ( strlen( $this->mFilteredName ) > 240 ) {
783 $this->mTitleError = self::FILENAME_TOO_LONG;
784 $this->mTitle = null;
786 return $this->mTitle;
790 * Chop off any directories in the given filename. Then
791 * filter out illegal characters, and try to make a legible name
792 * out of it. We'll strip some silently that Title would die on.
794 $this->mFilteredName = wfStripIllegalFilenameChars( $this->mFilteredName );
795 /* Normalize to title form before we do any further processing */
796 $nt = Title::makeTitleSafe( NS_FILE, $this->mFilteredName );
797 if ( is_null( $nt ) ) {
798 $this->mTitleError = self::ILLEGAL_FILENAME;
799 $this->mTitle = null;
801 return $this->mTitle;
803 $this->mFilteredName = $nt->getDBkey();
806 * We'll want to blacklist against *any* 'extension', and use
807 * only the final one for the whitelist.
809 list( $partname, $ext ) = $this->splitExtensions( $this->mFilteredName );
811 if ( count( $ext ) ) {
812 $this->mFinalExtension = trim( $ext[count( $ext ) - 1] );
813 } else {
814 $this->mFinalExtension = '';
816 # No extension, try guessing one
817 $magic = MimeMagic::singleton();
818 $mime = $magic->guessMimeType( $this->mTempPath );
819 if ( $mime !== 'unknown/unknown' ) {
820 # Get a space separated list of extensions
821 $extList = $magic->getExtensionsForType( $mime );
822 if ( $extList ) {
823 # Set the extension to the canonical extension
824 $this->mFinalExtension = strtok( $extList, ' ' );
826 # Fix up the other variables
827 $this->mFilteredName .= ".{$this->mFinalExtension}";
828 $nt = Title::makeTitleSafe( NS_FILE, $this->mFilteredName );
829 $ext = array( $this->mFinalExtension );
834 /* Don't allow users to override the blacklist (check file extension) */
835 global $wgCheckFileExtensions, $wgStrictFileExtensions;
836 global $wgFileExtensions, $wgFileBlacklist;
838 $blackListedExtensions = $this->checkFileExtensionList( $ext, $wgFileBlacklist );
840 if ( $this->mFinalExtension == '' ) {
841 $this->mTitleError = self::FILETYPE_MISSING;
842 $this->mTitle = null;
844 return $this->mTitle;
845 } elseif ( $blackListedExtensions ||
846 ( $wgCheckFileExtensions && $wgStrictFileExtensions &&
847 !$this->checkFileExtension( $this->mFinalExtension, $wgFileExtensions ) )
849 $this->mBlackListedExtensions = $blackListedExtensions;
850 $this->mTitleError = self::FILETYPE_BADTYPE;
851 $this->mTitle = null;
853 return $this->mTitle;
856 // Windows may be broken with special characters, see bug 1780
857 if ( !preg_match( '/^[\x0-\x7f]*$/', $nt->getText() )
858 && !RepoGroup::singleton()->getLocalRepo()->backendSupportsUnicodePaths()
860 $this->mTitleError = self::WINDOWS_NONASCII_FILENAME;
861 $this->mTitle = null;
863 return $this->mTitle;
866 # If there was more than one "extension", reassemble the base
867 # filename to prevent bogus complaints about length
868 if ( count( $ext ) > 1 ) {
869 $iterations = count( $ext ) - 1;
870 for ( $i = 0; $i < $iterations; $i++ ) {
871 $partname .= '.' . $ext[$i];
875 if ( strlen( $partname ) < 1 ) {
876 $this->mTitleError = self::MIN_LENGTH_PARTNAME;
877 $this->mTitle = null;
879 return $this->mTitle;
882 $this->mTitle = $nt;
884 return $this->mTitle;
888 * Return the local file and initializes if necessary.
890 * @return LocalFile|UploadStashFile|null
892 public function getLocalFile() {
893 if ( is_null( $this->mLocalFile ) ) {
894 $nt = $this->getTitle();
895 $this->mLocalFile = is_null( $nt ) ? null : wfLocalFile( $nt );
898 return $this->mLocalFile;
902 * If the user does not supply all necessary information in the first upload
903 * form submission (either by accident or by design) then we may want to
904 * stash the file temporarily, get more information, and publish the file
905 * later.
907 * This method will stash a file in a temporary directory for later
908 * processing, and save the necessary descriptive info into the database.
909 * This method returns the file object, which also has a 'fileKey' property
910 * which can be passed through a form or API request to find this stashed
911 * file again.
913 * @param User $user
914 * @return UploadStashFile Stashed file
916 public function stashFile( User $user = null ) {
917 // was stashSessionFile
919 $stash = RepoGroup::singleton()->getLocalRepo()->getUploadStash( $user );
920 $file = $stash->stashFile( $this->mTempPath, $this->getSourceType() );
921 $this->mLocalFile = $file;
923 return $file;
927 * Stash a file in a temporary directory, returning a key which can be used
928 * to find the file again. See stashFile().
930 * @return string File key
932 public function stashFileGetKey() {
933 return $this->stashFile()->getFileKey();
937 * alias for stashFileGetKey, for backwards compatibility
939 * @return string File key
941 public function stashSession() {
942 return $this->stashFileGetKey();
946 * If we've modified the upload file we need to manually remove it
947 * on exit to clean up.
949 public function cleanupTempFile() {
950 if ( $this->mRemoveTempFile && $this->mTempPath && file_exists( $this->mTempPath ) ) {
951 wfDebug( __METHOD__ . ": Removing temporary file {$this->mTempPath}\n" );
952 unlink( $this->mTempPath );
956 public function getTempPath() {
957 return $this->mTempPath;
961 * Split a file into a base name and all dot-delimited 'extensions'
962 * on the end. Some web server configurations will fall back to
963 * earlier pseudo-'extensions' to determine type and execute
964 * scripts, so the blacklist needs to check them all.
966 * @param string $filename
967 * @return array
969 public static function splitExtensions( $filename ) {
970 $bits = explode( '.', $filename );
971 $basename = array_shift( $bits );
973 return array( $basename, $bits );
977 * Perform case-insensitive match against a list of file extensions.
978 * Returns true if the extension is in the list.
980 * @param string $ext
981 * @param array $list
982 * @return bool
984 public static function checkFileExtension( $ext, $list ) {
985 return in_array( strtolower( $ext ), $list );
989 * Perform case-insensitive match against a list of file extensions.
990 * Returns an array of matching extensions.
992 * @param array $ext
993 * @param array $list
994 * @return bool
996 public static function checkFileExtensionList( $ext, $list ) {
997 return array_intersect( array_map( 'strtolower', $ext ), $list );
1001 * Checks if the MIME type of the uploaded file matches the file extension.
1003 * @param string $mime The MIME type of the uploaded file
1004 * @param string $extension The filename extension that the file is to be served with
1005 * @return bool
1007 public static function verifyExtension( $mime, $extension ) {
1008 $magic = MimeMagic::singleton();
1010 if ( !$mime || $mime == 'unknown' || $mime == 'unknown/unknown' ) {
1011 if ( !$magic->isRecognizableExtension( $extension ) ) {
1012 wfDebug( __METHOD__ . ": passing file with unknown detected mime type; " .
1013 "unrecognized extension '$extension', can't verify\n" );
1015 return true;
1016 } else {
1017 wfDebug( __METHOD__ . ": rejecting file with unknown detected mime type; " .
1018 "recognized extension '$extension', so probably invalid file\n" );
1020 return false;
1024 $match = $magic->isMatchingExtension( $extension, $mime );
1026 if ( $match === null ) {
1027 if ( $magic->getTypesForExtension( $extension ) !== null ) {
1028 wfDebug( __METHOD__ . ": No extension known for $mime, but we know a mime for $extension\n" );
1030 return false;
1031 } else {
1032 wfDebug( __METHOD__ . ": no file extension known for mime type $mime, passing file\n" );
1034 return true;
1036 } elseif ( $match === true ) {
1037 wfDebug( __METHOD__ . ": mime type $mime matches extension $extension, passing file\n" );
1039 /** @todo If it's a bitmap, make sure PHP or ImageMagick resp. can handle it! */
1040 return true;
1041 } else {
1042 wfDebug( __METHOD__
1043 . ": mime type $mime mismatches file extension $extension, rejecting file\n" );
1045 return false;
1050 * Heuristic for detecting files that *could* contain JavaScript instructions or
1051 * things that may look like HTML to a browser and are thus
1052 * potentially harmful. The present implementation will produce false
1053 * positives in some situations.
1055 * @param string $file Pathname to the temporary upload file
1056 * @param string $mime The MIME type of the file
1057 * @param string $extension The extension of the file
1058 * @return bool True if the file contains something looking like embedded scripts
1060 public static function detectScript( $file, $mime, $extension ) {
1061 global $wgAllowTitlesInSVG;
1063 # ugly hack: for text files, always look at the entire file.
1064 # For binary field, just check the first K.
1066 if ( strpos( $mime, 'text/' ) === 0 ) {
1067 $chunk = file_get_contents( $file );
1068 } else {
1069 $fp = fopen( $file, 'rb' );
1070 $chunk = fread( $fp, 1024 );
1071 fclose( $fp );
1074 $chunk = strtolower( $chunk );
1076 if ( !$chunk ) {
1078 return false;
1081 # decode from UTF-16 if needed (could be used for obfuscation).
1082 if ( substr( $chunk, 0, 2 ) == "\xfe\xff" ) {
1083 $enc = 'UTF-16BE';
1084 } elseif ( substr( $chunk, 0, 2 ) == "\xff\xfe" ) {
1085 $enc = 'UTF-16LE';
1086 } else {
1087 $enc = null;
1090 if ( $enc ) {
1091 $chunk = iconv( $enc, "ASCII//IGNORE", $chunk );
1094 $chunk = trim( $chunk );
1096 /** @todo FIXME: Convert from UTF-16 if necessary! */
1097 wfDebug( __METHOD__ . ": checking for embedded scripts and HTML stuff\n" );
1099 # check for HTML doctype
1100 if ( preg_match( "/<!DOCTYPE *X?HTML/i", $chunk ) ) {
1102 return true;
1105 // Some browsers will interpret obscure xml encodings as UTF-8, while
1106 // PHP/expat will interpret the given encoding in the xml declaration (bug 47304)
1107 if ( $extension == 'svg' || strpos( $mime, 'image/svg' ) === 0 ) {
1108 if ( self::checkXMLEncodingMissmatch( $file ) ) {
1110 return true;
1115 * Internet Explorer for Windows performs some really stupid file type
1116 * autodetection which can cause it to interpret valid image files as HTML
1117 * and potentially execute JavaScript, creating a cross-site scripting
1118 * attack vectors.
1120 * Apple's Safari browser also performs some unsafe file type autodetection
1121 * which can cause legitimate files to be interpreted as HTML if the
1122 * web server is not correctly configured to send the right content-type
1123 * (or if you're really uploading plain text and octet streams!)
1125 * Returns true if IE is likely to mistake the given file for HTML.
1126 * Also returns true if Safari would mistake the given file for HTML
1127 * when served with a generic content-type.
1129 $tags = array(
1130 '<a href',
1131 '<body',
1132 '<head',
1133 '<html', #also in safari
1134 '<img',
1135 '<pre',
1136 '<script', #also in safari
1137 '<table'
1140 if ( !$wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
1141 $tags[] = '<title';
1144 foreach ( $tags as $tag ) {
1145 if ( false !== strpos( $chunk, $tag ) ) {
1146 wfDebug( __METHOD__ . ": found something that may make it be mistaken for html: $tag\n" );
1148 return true;
1153 * look for JavaScript
1156 # resolve entity-refs to look at attributes. may be harsh on big files... cache result?
1157 $chunk = Sanitizer::decodeCharReferences( $chunk );
1159 # look for script-types
1160 if ( preg_match( '!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim', $chunk ) ) {
1161 wfDebug( __METHOD__ . ": found script types\n" );
1163 return true;
1166 # look for html-style script-urls
1167 if ( preg_match( '!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
1168 wfDebug( __METHOD__ . ": found html-style script urls\n" );
1170 return true;
1173 # look for css-style script-urls
1174 if ( preg_match( '!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
1175 wfDebug( __METHOD__ . ": found css-style script urls\n" );
1177 return true;
1180 wfDebug( __METHOD__ . ": no scripts found\n" );
1182 return false;
1186 * Check a whitelist of xml encodings that are known not to be interpreted differently
1187 * by the server's xml parser (expat) and some common browsers.
1189 * @param string $file Pathname to the temporary upload file
1190 * @return bool True if the file contains an encoding that could be misinterpreted
1192 public static function checkXMLEncodingMissmatch( $file ) {
1193 global $wgSVGMetadataCutoff;
1194 $contents = file_get_contents( $file, false, null, -1, $wgSVGMetadataCutoff );
1195 $encodingRegex = '!encoding[ \t\n\r]*=[ \t\n\r]*[\'"](.*?)[\'"]!si';
1197 if ( preg_match( "!<\?xml\b(.*?)\?>!si", $contents, $matches ) ) {
1198 if ( preg_match( $encodingRegex, $matches[1], $encMatch )
1199 && !in_array( strtoupper( $encMatch[1] ), self::$safeXmlEncodings )
1201 wfDebug( __METHOD__ . ": Found unsafe XML encoding '{$encMatch[1]}'\n" );
1203 return true;
1205 } elseif ( preg_match( "!<\?xml\b!si", $contents ) ) {
1206 // Start of XML declaration without an end in the first $wgSVGMetadataCutoff
1207 // bytes. There shouldn't be a legitimate reason for this to happen.
1208 wfDebug( __METHOD__ . ": Unmatched XML declaration start\n" );
1210 return true;
1211 } elseif ( substr( $contents, 0, 4 ) == "\x4C\x6F\xA7\x94" ) {
1212 // EBCDIC encoded XML
1213 wfDebug( __METHOD__ . ": EBCDIC Encoded XML\n" );
1215 return true;
1218 // It's possible the file is encoded with multi-byte encoding, so re-encode attempt to
1219 // detect the encoding in case is specifies an encoding not whitelisted in self::$safeXmlEncodings
1220 $attemptEncodings = array( 'UTF-16', 'UTF-16BE', 'UTF-32', 'UTF-32BE' );
1221 foreach ( $attemptEncodings as $encoding ) {
1222 wfSuppressWarnings();
1223 $str = iconv( $encoding, 'UTF-8', $contents );
1224 wfRestoreWarnings();
1225 if ( $str != '' && preg_match( "!<\?xml\b(.*?)\?>!si", $str, $matches ) ) {
1226 if ( preg_match( $encodingRegex, $matches[1], $encMatch )
1227 && !in_array( strtoupper( $encMatch[1] ), self::$safeXmlEncodings )
1229 wfDebug( __METHOD__ . ": Found unsafe XML encoding '{$encMatch[1]}'\n" );
1231 return true;
1233 } elseif ( $str != '' && preg_match( "!<\?xml\b!si", $str ) ) {
1234 // Start of XML declaration without an end in the first $wgSVGMetadataCutoff
1235 // bytes. There shouldn't be a legitimate reason for this to happen.
1236 wfDebug( __METHOD__ . ": Unmatched XML declaration start\n" );
1238 return true;
1242 return false;
1246 * @param string $filename
1247 * @param bool $partial
1248 * @return mixed False of the file is verified (does not contain scripts), array otherwise.
1250 protected function detectScriptInSvg( $filename, $partial ) {
1251 $this->mSVGNSError = false;
1252 $check = new XmlTypeCheck(
1253 $filename,
1254 array( $this, 'checkSvgScriptCallback' ),
1255 true,
1256 array( 'processing_instruction_handler' => 'UploadBase::checkSvgPICallback' )
1258 if ( $check->wellFormed !== true ) {
1259 // Invalid xml (bug 58553)
1260 // But only when non-partial (bug 65724)
1261 return $partial ? false : array( 'uploadinvalidxml' );
1262 } elseif ( $check->filterMatch ) {
1263 if ( $this->mSVGNSError ) {
1264 return array( 'uploadscriptednamespace', $this->mSVGNSError );
1267 return array( 'uploadscripted' );
1270 return false;
1274 * Callback to filter SVG Processing Instructions.
1275 * @param string $target Processing instruction name
1276 * @param string $data Processing instruction attribute and value
1277 * @return bool (true if the filter identified something bad)
1279 public static function checkSvgPICallback( $target, $data ) {
1280 // Don't allow external stylesheets (bug 57550)
1281 if ( preg_match( '/xml-stylesheet/i', $target ) ) {
1282 return true;
1285 return false;
1289 * @todo Replace this with a whitelist filter!
1290 * @param string $element
1291 * @param array $attribs
1292 * @return bool
1294 public function checkSvgScriptCallback( $element, $attribs, $data = null ) {
1296 list( $namespace, $strippedElement ) = $this->splitXmlNamespace( $element );
1298 // We specifically don't include:
1299 // http://www.w3.org/1999/xhtml (bug 60771)
1300 static $validNamespaces = array(
1302 'adobe:ns:meta/',
1303 'http://creativecommons.org/ns#',
1304 'http://inkscape.sourceforge.net/dtd/sodipodi-0.dtd',
1305 'http://ns.adobe.com/adobeillustrator/10.0/',
1306 'http://ns.adobe.com/adobesvgviewerextensions/3.0/',
1307 'http://ns.adobe.com/extensibility/1.0/',
1308 'http://ns.adobe.com/flows/1.0/',
1309 'http://ns.adobe.com/illustrator/1.0/',
1310 'http://ns.adobe.com/imagereplacement/1.0/',
1311 'http://ns.adobe.com/pdf/1.3/',
1312 'http://ns.adobe.com/photoshop/1.0/',
1313 'http://ns.adobe.com/saveforweb/1.0/',
1314 'http://ns.adobe.com/variables/1.0/',
1315 'http://ns.adobe.com/xap/1.0/',
1316 'http://ns.adobe.com/xap/1.0/g/',
1317 'http://ns.adobe.com/xap/1.0/g/img/',
1318 'http://ns.adobe.com/xap/1.0/mm/',
1319 'http://ns.adobe.com/xap/1.0/rights/',
1320 'http://ns.adobe.com/xap/1.0/stype/dimensions#',
1321 'http://ns.adobe.com/xap/1.0/stype/font#',
1322 'http://ns.adobe.com/xap/1.0/stype/manifestitem#',
1323 'http://ns.adobe.com/xap/1.0/stype/resourceevent#',
1324 'http://ns.adobe.com/xap/1.0/stype/resourceref#',
1325 'http://ns.adobe.com/xap/1.0/t/pg/',
1326 'http://purl.org/dc/elements/1.1/',
1327 'http://purl.org/dc/elements/1.1',
1328 'http://schemas.microsoft.com/visio/2003/svgextensions/',
1329 'http://sodipodi.sourceforge.net/dtd/sodipodi-0.dtd',
1330 'http://taptrix.com/inkpad/svg_extensions',
1331 'http://web.resource.org/cc/',
1332 'http://www.freesoftware.fsf.org/bkchem/cdml',
1333 'http://www.inkscape.org/namespaces/inkscape',
1334 'http://www.opengis.net/gml',
1335 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
1336 'http://www.w3.org/2000/svg',
1337 'http://www.w3.org/tr/rec-rdf-syntax/',
1340 if ( !in_array( $namespace, $validNamespaces ) ) {
1341 wfDebug( __METHOD__ . ": Non-svg namespace '$namespace' in uploaded file.\n" );
1342 /** @todo Return a status object to a closure in XmlTypeCheck, for MW1.21+ */
1343 $this->mSVGNSError = $namespace;
1345 return true;
1349 * check for elements that can contain javascript
1351 if ( $strippedElement == 'script' ) {
1352 wfDebug( __METHOD__ . ": Found script element '$element' in uploaded file.\n" );
1354 return true;
1357 # e.g., <svg xmlns="http://www.w3.org/2000/svg">
1358 # <handler xmlns:ev="http://www.w3.org/2001/xml-events" ev:event="load">alert(1)</handler> </svg>
1359 if ( $strippedElement == 'handler' ) {
1360 wfDebug( __METHOD__ . ": Found scriptable element '$element' in uploaded file.\n" );
1362 return true;
1365 # SVG reported in Feb '12 that used xml:stylesheet to generate javascript block
1366 if ( $strippedElement == 'stylesheet' ) {
1367 wfDebug( __METHOD__ . ": Found scriptable element '$element' in uploaded file.\n" );
1369 return true;
1372 # Block iframes, in case they pass the namespace check
1373 if ( $strippedElement == 'iframe' ) {
1374 wfDebug( __METHOD__ . ": iframe in uploaded file.\n" );
1376 return true;
1379 # Check <style> css
1380 if ( $strippedElement == 'style'
1381 && self::checkCssFragment( Sanitizer::normalizeCss( $data ) )
1383 wfDebug( __METHOD__ . ": hostile css in style element.\n" );
1384 return true;
1387 foreach ( $attribs as $attrib => $value ) {
1388 $stripped = $this->stripXmlNamespace( $attrib );
1389 $value = strtolower( $value );
1391 if ( substr( $stripped, 0, 2 ) == 'on' ) {
1392 wfDebug( __METHOD__
1393 . ": Found event-handler attribute '$attrib'='$value' in uploaded file.\n" );
1395 return true;
1398 # href with non-local target (don't allow http://, javascript:, etc)
1399 if ( $stripped == 'href'
1400 && strpos( $value, 'data:' ) !== 0
1401 && strpos( $value, '#' ) !== 0
1403 if ( !( $strippedElement === 'a'
1404 && preg_match( '!^https?://!im', $value ) )
1406 wfDebug( __METHOD__ . ": Found href attribute <$strippedElement "
1407 . "'$attrib'='$value' in uploaded file.\n" );
1409 return true;
1413 # href with embedded svg as target
1414 if ( $stripped == 'href' && preg_match( '!data:[^,]*image/svg[^,]*,!sim', $value ) ) {
1415 wfDebug( __METHOD__ . ": Found href to embedded svg "
1416 . "\"<$strippedElement '$attrib'='$value'...\" in uploaded file.\n" );
1418 return true;
1421 # href with embedded (text/xml) svg as target
1422 if ( $stripped == 'href' && preg_match( '!data:[^,]*text/xml[^,]*,!sim', $value ) ) {
1423 wfDebug( __METHOD__ . ": Found href to embedded svg "
1424 . "\"<$strippedElement '$attrib'='$value'...\" in uploaded file.\n" );
1426 return true;
1429 # Change href with animate from (http://html5sec.org/#137). This doesn't seem
1430 # possible without embedding the svg, but filter here in case.
1431 if ( $stripped == 'from'
1432 && $strippedElement === 'animate'
1433 && !preg_match( '!^https?://!im', $value )
1435 wfDebug( __METHOD__ . ": Found animate that might be changing href using from "
1436 . "\"<$strippedElement '$attrib'='$value'...\" in uploaded file.\n" );
1438 return true;
1441 # use set/animate to add event-handler attribute to parent
1442 if ( ( $strippedElement == 'set' || $strippedElement == 'animate' )
1443 && $stripped == 'attributename'
1444 && substr( $value, 0, 2 ) == 'on'
1446 wfDebug( __METHOD__ . ": Found svg setting event-handler attribute with "
1447 . "\"<$strippedElement $stripped='$value'...\" in uploaded file.\n" );
1449 return true;
1452 # use set to add href attribute to parent element
1453 if ( $strippedElement == 'set'
1454 && $stripped == 'attributename'
1455 && strpos( $value, 'href' ) !== false
1457 wfDebug( __METHOD__ . ": Found svg setting href attribute '$value' in uploaded file.\n" );
1459 return true;
1462 # use set to add a remote / data / script target to an element
1463 if ( $strippedElement == 'set'
1464 && $stripped == 'to'
1465 && preg_match( '!(http|https|data|script):!sim', $value )
1467 wfDebug( __METHOD__ . ": Found svg setting attribute to '$value' in uploaded file.\n" );
1469 return true;
1472 # use handler attribute with remote / data / script
1473 if ( $stripped == 'handler' && preg_match( '!(http|https|data|script):!sim', $value ) ) {
1474 wfDebug( __METHOD__ . ": Found svg setting handler with remote/data/script "
1475 . "'$attrib'='$value' in uploaded file.\n" );
1477 return true;
1480 # use CSS styles to bring in remote code
1481 if ( $stripped == 'style'
1482 && self::checkCssFragment( Sanitizer::normalizeCss( $value ) )
1484 wfDebug( __METHOD__ . ": Found svg setting a style with "
1485 . "remote url '$attrib'='$value' in uploaded file.\n" );
1486 return true;
1489 # Several attributes can include css, css character escaping isn't allowed
1490 $cssAttrs = array( 'font', 'clip-path', 'fill', 'filter', 'marker',
1491 'marker-end', 'marker-mid', 'marker-start', 'mask', 'stroke' );
1492 if ( in_array( $stripped, $cssAttrs )
1493 && self::checkCssFragment( $value )
1495 wfDebug( __METHOD__ . ": Found svg setting a style with "
1496 . "remote url '$attrib'='$value' in uploaded file.\n" );
1497 return true;
1500 # image filters can pull in url, which could be svg that executes scripts
1501 if ( $strippedElement == 'image'
1502 && $stripped == 'filter'
1503 && preg_match( '!url\s*\(!sim', $value )
1505 wfDebug( __METHOD__ . ": Found image filter with url: "
1506 . "\"<$strippedElement $stripped='$value'...\" in uploaded file.\n" );
1508 return true;
1512 return false; //No scripts detected
1516 * Check a block of CSS or CSS fragment for anything that looks like
1517 * it is bringing in remote code.
1518 * @param string $value a string of CSS
1519 * @param bool $propOnly only check css properties (start regex with :)
1520 * @return bool true if the CSS contains an illegal string, false if otherwise
1522 private static function checkCssFragment( $value ) {
1524 # Forbid external stylesheets, for both reliability and to protect viewer's privacy
1525 if ( strpos( $value, '@import' ) !== false ) {
1526 return true;
1529 # We allow @font-face to embed fonts with data: urls, so we snip the string
1530 # 'url' out so this case won't match when we check for urls below
1531 $pattern = '!(@font-face\s*{[^}]*src:)url(\("data:;base64,)!im';
1532 $value = preg_replace( $pattern, '$1$2', $value );
1534 # Check for remote and executable CSS. Unlike in Sanitizer::checkCss, the CSS
1535 # properties filter and accelerator don't seem to be useful for xss in SVG files.
1536 # Expression and -o-link don't seem to work either, but filtering them here in case.
1537 # Additionally, we catch remote urls like url("http:..., url('http:..., url(http:...,
1538 # but not local ones such as url("#..., url('#..., url(#....
1539 if ( preg_match( '!expression
1540 | -o-link\s*:
1541 | -o-link-source\s*:
1542 | -o-replace\s*:!imx', $value ) ) {
1543 return true;
1546 if ( preg_match_all(
1547 "!(\s*(url|image|image-set)\s*\(\s*[\"']?\s*[^#]+.*?\))!sim",
1548 $value,
1549 $matches
1550 ) !== 0
1552 # TODO: redo this in one regex. Until then, url("#whatever") matches the first
1553 foreach ( $matches[1] as $match ) {
1554 if ( !preg_match( "!\s*(url|image|image-set)\s*\(\s*(#|'#|\"#)!im", $match ) ) {
1555 return true;
1560 if ( preg_match( '/[\000-\010\013\016-\037\177]/', $value ) ) {
1561 return true;
1564 return false;
1568 * Divide the element name passed by the xml parser to the callback into URI and prifix.
1569 * @param string $element
1570 * @return array Containing the namespace URI and prefix
1572 private static function splitXmlNamespace( $element ) {
1573 // 'http://www.w3.org/2000/svg:script' -> array( 'http://www.w3.org/2000/svg', 'script' )
1574 $parts = explode( ':', strtolower( $element ) );
1575 $name = array_pop( $parts );
1576 $ns = implode( ':', $parts );
1578 return array( $ns, $name );
1582 * @param string $name
1583 * @return string
1585 private function stripXmlNamespace( $name ) {
1586 // 'http://www.w3.org/2000/svg:script' -> 'script'
1587 $parts = explode( ':', strtolower( $name ) );
1589 return array_pop( $parts );
1593 * Generic wrapper function for a virus scanner program.
1594 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
1595 * $wgAntivirusRequired may be used to deny upload if the scan fails.
1597 * @param string $file Pathname to the temporary upload file
1598 * @return mixed False if not virus is found, null if the scan fails or is disabled,
1599 * or a string containing feedback from the virus scanner if a virus was found.
1600 * If textual feedback is missing but a virus was found, this function returns true.
1602 public static function detectVirus( $file ) {
1603 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
1605 if ( !$wgAntivirus ) {
1606 wfDebug( __METHOD__ . ": virus scanner disabled\n" );
1608 return null;
1611 if ( !$wgAntivirusSetup[$wgAntivirus] ) {
1612 wfDebug( __METHOD__ . ": unknown virus scanner: $wgAntivirus\n" );
1613 $wgOut->wrapWikiMsg( "<div class=\"error\">\n$1\n</div>",
1614 array( 'virus-badscanner', $wgAntivirus ) );
1616 return wfMessage( 'virus-unknownscanner' )->text() . " $wgAntivirus";
1619 # look up scanner configuration
1620 $command = $wgAntivirusSetup[$wgAntivirus]['command'];
1621 $exitCodeMap = $wgAntivirusSetup[$wgAntivirus]['codemap'];
1622 $msgPattern = isset( $wgAntivirusSetup[$wgAntivirus]['messagepattern'] ) ?
1623 $wgAntivirusSetup[$wgAntivirus]['messagepattern'] : null;
1625 if ( strpos( $command, "%f" ) === false ) {
1626 # simple pattern: append file to scan
1627 $command .= " " . wfEscapeShellArg( $file );
1628 } else {
1629 # complex pattern: replace "%f" with file to scan
1630 $command = str_replace( "%f", wfEscapeShellArg( $file ), $command );
1633 wfDebug( __METHOD__ . ": running virus scan: $command \n" );
1635 # execute virus scanner
1636 $exitCode = false;
1638 # NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
1639 # that does not seem to be worth the pain.
1640 # Ask me (Duesentrieb) about it if it's ever needed.
1641 $output = wfShellExecWithStderr( $command, $exitCode );
1643 # map exit code to AV_xxx constants.
1644 $mappedCode = $exitCode;
1645 if ( $exitCodeMap ) {
1646 if ( isset( $exitCodeMap[$exitCode] ) ) {
1647 $mappedCode = $exitCodeMap[$exitCode];
1648 } elseif ( isset( $exitCodeMap["*"] ) ) {
1649 $mappedCode = $exitCodeMap["*"];
1653 /* NB: AV_NO_VIRUS is 0 but AV_SCAN_FAILED is false,
1654 * so we need the strict equalities === and thus can't use a switch here
1656 if ( $mappedCode === AV_SCAN_FAILED ) {
1657 # scan failed (code was mapped to false by $exitCodeMap)
1658 wfDebug( __METHOD__ . ": failed to scan $file (code $exitCode).\n" );
1660 $output = $wgAntivirusRequired
1661 ? wfMessage( 'virus-scanfailed', array( $exitCode ) )->text()
1662 : null;
1663 } elseif ( $mappedCode === AV_SCAN_ABORTED ) {
1664 # scan failed because filetype is unknown (probably imune)
1665 wfDebug( __METHOD__ . ": unsupported file type $file (code $exitCode).\n" );
1666 $output = null;
1667 } elseif ( $mappedCode === AV_NO_VIRUS ) {
1668 # no virus found
1669 wfDebug( __METHOD__ . ": file passed virus scan.\n" );
1670 $output = false;
1671 } else {
1672 $output = trim( $output );
1674 if ( !$output ) {
1675 $output = true; #if there's no output, return true
1676 } elseif ( $msgPattern ) {
1677 $groups = array();
1678 if ( preg_match( $msgPattern, $output, $groups ) ) {
1679 if ( $groups[1] ) {
1680 $output = $groups[1];
1685 wfDebug( __METHOD__ . ": FOUND VIRUS! scanner feedback: $output \n" );
1688 return $output;
1692 * Check if there's an overwrite conflict and, if so, if restrictions
1693 * forbid this user from performing the upload.
1695 * @param User $user
1697 * @return mixed True on success, array on failure
1699 private function checkOverwrite( $user ) {
1700 // First check whether the local file can be overwritten
1701 $file = $this->getLocalFile();
1702 if ( $file->exists() ) {
1703 if ( !self::userCanReUpload( $user, $file ) ) {
1704 return array( 'fileexists-forbidden', $file->getName() );
1705 } else {
1706 return true;
1710 /* Check shared conflicts: if the local file does not exist, but
1711 * wfFindFile finds a file, it exists in a shared repository.
1713 $file = wfFindFile( $this->getTitle() );
1714 if ( $file && !$user->isAllowed( 'reupload-shared' ) ) {
1715 return array( 'fileexists-shared-forbidden', $file->getName() );
1718 return true;
1722 * Check if a user is the last uploader
1724 * @param User $user
1725 * @param string $img Image name
1726 * @return bool
1728 public static function userCanReUpload( User $user, $img ) {
1729 if ( $user->isAllowed( 'reupload' ) ) {
1730 return true; // non-conditional
1732 if ( !$user->isAllowed( 'reupload-own' ) ) {
1733 return false;
1735 if ( is_string( $img ) ) {
1736 $img = wfLocalFile( $img );
1738 if ( !( $img instanceof LocalFile ) ) {
1739 return false;
1742 return $user->getId() == $img->getUser( 'id' );
1746 * Helper function that does various existence checks for a file.
1747 * The following checks are performed:
1748 * - The file exists
1749 * - Article with the same name as the file exists
1750 * - File exists with normalized extension
1751 * - The file looks like a thumbnail and the original exists
1753 * @param File $file The File object to check
1754 * @return mixed False if the file does not exists, else an array
1756 public static function getExistsWarning( $file ) {
1757 if ( $file->exists() ) {
1758 return array( 'warning' => 'exists', 'file' => $file );
1761 if ( $file->getTitle()->getArticleID() ) {
1762 return array( 'warning' => 'page-exists', 'file' => $file );
1765 if ( $file->wasDeleted() && !$file->exists() ) {
1766 return array( 'warning' => 'was-deleted', 'file' => $file );
1769 if ( strpos( $file->getName(), '.' ) == false ) {
1770 $partname = $file->getName();
1771 $extension = '';
1772 } else {
1773 $n = strrpos( $file->getName(), '.' );
1774 $extension = substr( $file->getName(), $n + 1 );
1775 $partname = substr( $file->getName(), 0, $n );
1777 $normalizedExtension = File::normalizeExtension( $extension );
1779 if ( $normalizedExtension != $extension ) {
1780 // We're not using the normalized form of the extension.
1781 // Normal form is lowercase, using most common of alternate
1782 // extensions (eg 'jpg' rather than 'JPEG').
1784 // Check for another file using the normalized form...
1785 $nt_lc = Title::makeTitle( NS_FILE, "{$partname}.{$normalizedExtension}" );
1786 $file_lc = wfLocalFile( $nt_lc );
1788 if ( $file_lc->exists() ) {
1789 return array(
1790 'warning' => 'exists-normalized',
1791 'file' => $file,
1792 'normalizedFile' => $file_lc
1797 // Check for files with the same name but a different extension
1798 $similarFiles = RepoGroup::singleton()->getLocalRepo()->findFilesByPrefix(
1799 "{$partname}.", 1 );
1800 if ( count( $similarFiles ) ) {
1801 return array(
1802 'warning' => 'exists-normalized',
1803 'file' => $file,
1804 'normalizedFile' => $similarFiles[0],
1808 if ( self::isThumbName( $file->getName() ) ) {
1809 # Check for filenames like 50px- or 180px-, these are mostly thumbnails
1810 $nt_thb = Title::newFromText(
1811 substr( $partname, strpos( $partname, '-' ) + 1 ) . '.' . $extension,
1812 NS_FILE
1814 $file_thb = wfLocalFile( $nt_thb );
1815 if ( $file_thb->exists() ) {
1816 return array(
1817 'warning' => 'thumb',
1818 'file' => $file,
1819 'thumbFile' => $file_thb
1821 } else {
1822 // File does not exist, but we just don't like the name
1823 return array(
1824 'warning' => 'thumb-name',
1825 'file' => $file,
1826 'thumbFile' => $file_thb
1831 foreach ( self::getFilenamePrefixBlacklist() as $prefix ) {
1832 if ( substr( $partname, 0, strlen( $prefix ) ) == $prefix ) {
1833 return array(
1834 'warning' => 'bad-prefix',
1835 'file' => $file,
1836 'prefix' => $prefix
1841 return false;
1845 * Helper function that checks whether the filename looks like a thumbnail
1846 * @param string $filename
1847 * @return bool
1849 public static function isThumbName( $filename ) {
1850 $n = strrpos( $filename, '.' );
1851 $partname = $n ? substr( $filename, 0, $n ) : $filename;
1853 return (
1854 substr( $partname, 3, 3 ) == 'px-' ||
1855 substr( $partname, 2, 3 ) == 'px-'
1856 ) &&
1857 preg_match( "/[0-9]{2}/", substr( $partname, 0, 2 ) );
1861 * Get a list of blacklisted filename prefixes from [[MediaWiki:Filename-prefix-blacklist]]
1863 * @return array List of prefixes
1865 public static function getFilenamePrefixBlacklist() {
1866 $blacklist = array();
1867 $message = wfMessage( 'filename-prefix-blacklist' )->inContentLanguage();
1868 if ( !$message->isDisabled() ) {
1869 $lines = explode( "\n", $message->plain() );
1870 foreach ( $lines as $line ) {
1871 // Remove comment lines
1872 $comment = substr( trim( $line ), 0, 1 );
1873 if ( $comment == '#' || $comment == '' ) {
1874 continue;
1876 // Remove additional comments after a prefix
1877 $comment = strpos( $line, '#' );
1878 if ( $comment > 0 ) {
1879 $line = substr( $line, 0, $comment - 1 );
1881 $blacklist[] = trim( $line );
1885 return $blacklist;
1889 * Gets image info about the file just uploaded.
1891 * Also has the effect of setting metadata to be an 'indexed tag name' in
1892 * returned API result if 'metadata' was requested. Oddly, we have to pass
1893 * the "result" object down just so it can do that with the appropriate
1894 * format, presumably.
1896 * @param ApiResult $result
1897 * @return array Image info
1899 public function getImageInfo( $result ) {
1900 $file = $this->getLocalFile();
1901 /** @todo This cries out for refactoring.
1902 * We really want to say $file->getAllInfo(); here.
1903 * Perhaps "info" methods should be moved into files, and the API should
1904 * just wrap them in queries.
1906 if ( $file instanceof UploadStashFile ) {
1907 $imParam = ApiQueryStashImageInfo::getPropertyNames();
1908 $info = ApiQueryStashImageInfo::getInfo( $file, array_flip( $imParam ), $result );
1909 } else {
1910 $imParam = ApiQueryImageInfo::getPropertyNames();
1911 $info = ApiQueryImageInfo::getInfo( $file, array_flip( $imParam ), $result );
1914 return $info;
1918 * @param array $error
1919 * @return Status
1921 public function convertVerifyErrorToStatus( $error ) {
1922 $code = $error['status'];
1923 unset( $code['status'] );
1925 return Status::newFatal( $this->getVerificationErrorCode( $code ), $error );
1929 * @param null|string $forType
1930 * @return int
1932 public static function getMaxUploadSize( $forType = null ) {
1933 global $wgMaxUploadSize;
1935 if ( is_array( $wgMaxUploadSize ) ) {
1936 if ( !is_null( $forType ) && isset( $wgMaxUploadSize[$forType] ) ) {
1937 return $wgMaxUploadSize[$forType];
1938 } else {
1939 return $wgMaxUploadSize['*'];
1941 } else {
1942 return intval( $wgMaxUploadSize );
1947 * Get the current status of a chunked upload (used for polling)
1949 * The value will be read from cache.
1951 * @param User $user
1952 * @param string $statusKey
1953 * @return Status[]|bool
1955 public static function getSessionStatus( User $user, $statusKey ) {
1956 $key = wfMemcKey( 'uploadstatus', $user->getId() ?: md5( $user->getName() ), $statusKey );
1958 return wfGetCache( CACHE_ANYTHING )->get( $key );
1962 * Set the current status of a chunked upload (used for polling)
1964 * The value will be set in cache for 1 day
1966 * @param User $user
1967 * @param string $statusKey
1968 * @param array|bool $value
1969 * @return void
1971 public static function setSessionStatus( User $user, $statusKey, $value ) {
1972 $key = wfMemcKey( 'uploadstatus', $user->getId() ?: md5( $user->getName() ), $statusKey );
1974 $cache = wfGetCache( CACHE_ANYTHING );
1975 if ( $value === false ) {
1976 $cache->delete( $key );
1977 } else {
1978 $cache->set( $key, $value, 86400 );