* (bug 22876) Avoid possible PHP Notice if $wgDefaultUserOptions is not correctly set
[mediawiki.git] / includes / upload / UploadBase.php
blob94fda9b0753fc3bde87e74d5da96b7727cb77041
1 <?php
2 /**
3 * @file
4 * @ingroup upload
6 * UploadBase and subclasses are the backend of MediaWiki's file uploads.
7 * The frontends are formed by ApiUpload and SpecialUpload.
9 * See also includes/docs/upload.txt
11 * @author Brion Vibber
12 * @author Bryan Tong Minh
13 * @author Michael Dale
16 abstract class UploadBase {
17 protected $mTempPath;
18 protected $mDesiredDestName, $mDestName, $mRemoveTempFile, $mSourceType;
19 protected $mTitle = false, $mTitleError = 0;
20 protected $mFilteredName, $mFinalExtension;
21 protected $mLocalFile;
23 const SUCCESS = 0;
24 const OK = 0;
25 const EMPTY_FILE = 3;
26 const MIN_LENGTH_PARTNAME = 4;
27 const ILLEGAL_FILENAME = 5;
28 const OVERWRITE_EXISTING_FILE = 7;
29 const FILETYPE_MISSING = 8;
30 const FILETYPE_BADTYPE = 9;
31 const VERIFICATION_ERROR = 10;
32 const UPLOAD_VERIFICATION_ERROR = 11;
33 const HOOK_ABORTED = 11;
35 const SESSION_VERSION = 2;
37 /**
38 * Returns true if uploads are enabled.
39 * Can be override by subclasses.
41 public static function isEnabled() {
42 global $wgEnableUploads;
43 if ( !$wgEnableUploads ) {
44 return false;
47 # Check php's file_uploads setting
48 if( !wfIniGetBool( 'file_uploads' ) ) {
49 return false;
51 return true;
54 /**
55 * Returns true if the user can use this upload module or else a string
56 * identifying the missing permission.
57 * Can be overriden by subclasses.
59 public static function isAllowed( $user ) {
60 if( !$user->isAllowed( 'upload' ) ) {
61 return 'upload';
63 return true;
66 // Upload handlers. Should probably just be a global.
67 static $uploadHandlers = array( 'Stash', 'File', 'Url' );
69 /**
70 * Create a form of UploadBase depending on wpSourceType and initializes it
72 public static function createFromRequest( &$request, $type = null ) {
73 $type = $type ? $type : $request->getVal( 'wpSourceType', 'File' );
75 if( !$type ) {
76 return null;
79 // Get the upload class
80 $type = ucfirst( $type );
82 // Give hooks the chance to handle this request
83 $className = null;
84 wfRunHooks( 'UploadCreateFromRequest', array( $type, &$className ) );
85 if ( is_null( $className ) ) {
86 $className = 'UploadFrom' . $type;
87 wfDebug( __METHOD__ . ": class name: $className\n" );
88 if( !in_array( $type, self::$uploadHandlers ) ) {
89 return null;
93 // Check whether this upload class is enabled
94 if( !call_user_func( array( $className, 'isEnabled' ) ) ) {
95 return null;
98 // Check whether the request is valid
99 if( !call_user_func( array( $className, 'isValidRequest' ), $request ) ) {
100 return null;
103 $handler = new $className;
105 $handler->initializeFromRequest( $request );
106 return $handler;
110 * Check whether a request if valid for this handler
112 public static function isValidRequest( $request ) {
113 return false;
116 public function __construct() {}
119 * Initialize the path information
120 * @param $name string the desired destination name
121 * @param $tempPath string the temporary path
122 * @param $fileSize int the file size
123 * @param $removeTempFile bool (false) remove the temporary file?
124 * @return null
126 public function initializePathInfo( $name, $tempPath, $fileSize, $removeTempFile = false ) {
127 $this->mDesiredDestName = $name;
128 $this->mTempPath = $tempPath;
129 $this->mFileSize = $fileSize;
130 $this->mRemoveTempFile = $removeTempFile;
134 * Initialize from a WebRequest. Override this in a subclass.
136 public abstract function initializeFromRequest( &$request );
139 * Fetch the file. Usually a no-op
141 public function fetchFile() {
142 return Status::newGood();
146 * Return the file size
148 public function isEmptyFile() {
149 return empty( $this->mFileSize );
153 * @param $srcPath String: the source path
154 * @return the real path if it was a virtual URL
156 function getRealPath( $srcPath ) {
157 $repo = RepoGroup::singleton()->getLocalRepo();
158 if ( $repo->isVirtualUrl( $srcPath ) ) {
159 return $repo->resolveVirtualUrl( $srcPath );
161 return $srcPath;
165 * Verify whether the upload is sane.
166 * Returns self::OK or else an array with error information
168 public function verifyUpload() {
170 * If there was no filename or a zero size given, give up quick.
172 if( $this->isEmptyFile() ) {
173 return array( 'status' => self::EMPTY_FILE );
177 * Look at the contents of the file; if we can recognize the
178 * type but it's corrupt or data of the wrong type, we should
179 * probably not accept it.
181 $verification = $this->verifyFile();
182 if( $verification !== true ) {
183 if( !is_array( $verification ) ) {
184 $verification = array( $verification );
186 return array(
187 'status' => self::VERIFICATION_ERROR,
188 'details' => $verification
192 $nt = $this->getTitle();
193 if( is_null( $nt ) ) {
194 $result = array( 'status' => $this->mTitleError );
195 if( $this->mTitleError == self::ILLEGAL_FILENAME ) {
196 $result['filtered'] = $this->mFilteredName;
198 if ( $this->mTitleError == self::FILETYPE_BADTYPE ) {
199 $result['finalExt'] = $this->mFinalExtension;
201 return $result;
203 $this->mDestName = $this->getLocalFile()->getName();
206 * In some cases we may forbid overwriting of existing files.
208 $overwrite = $this->checkOverwrite();
209 if( $overwrite !== true ) {
210 return array(
211 'status' => self::OVERWRITE_EXISTING_FILE,
212 'overwrite' => $overwrite
216 $error = '';
217 if( !wfRunHooks( 'UploadVerification',
218 array( $this->mDestName, $this->mTempPath, &$error ) ) ) {
219 // This status needs another name...
220 return array( 'status' => self::HOOK_ABORTED, 'error' => $error );
223 return array( 'status' => self::OK );
227 * Verifies that it's ok to include the uploaded file
229 * @return mixed true of the file is verified, a string or array otherwise.
231 protected function verifyFile() {
232 $this->mFileProps = File::getPropsFromPath( $this->mTempPath, $this->mFinalExtension );
233 $this->checkMacBinary();
235 # magically determine mime type
236 $magic = MimeMagic::singleton();
237 $mime = $magic->guessMimeType( $this->mTempPath, false );
239 # check mime type, if desired
240 global $wgVerifyMimeType;
241 if ( $wgVerifyMimeType ) {
242 wfDebug ( "\n\nmime: <$mime> extension: <{$this->mFinalExtension}>\n\n");
243 if ( !$this->verifyExtension( $mime, $this->mFinalExtension ) ) {
244 return array( 'filetype-mime-mismatch' );
247 global $wgMimeTypeBlacklist;
248 if ( $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
249 return array( 'filetype-badmime', $mime );
252 # Check IE type
253 $fp = fopen( $this->mTempPath, 'rb' );
254 $chunk = fread( $fp, 256 );
255 fclose( $fp );
256 $extMime = $magic->guessTypesForExtension( $this->mFinalExtension );
257 $ieTypes = $magic->getIEMimeTypes( $this->mTempPath, $chunk, $extMime );
258 foreach ( $ieTypes as $ieType ) {
259 if ( $this->checkFileExtension( $ieType, $wgMimeTypeBlacklist ) ) {
260 return array( 'filetype-bad-ie-mime', $ieType );
265 # check for htmlish code and javascript
266 if( self::detectScript( $this->mTempPath, $mime, $this->mFinalExtension ) ) {
267 return 'uploadscripted';
269 if( $this->mFinalExtension == 'svg' || $mime == 'image/svg+xml' ) {
270 if( self::detectScriptInSvg( $this->mTempPath ) ) {
271 return 'uploadscripted';
276 * Scan the uploaded file for viruses
278 $virus = $this->detectVirus( $this->mTempPath );
279 if ( $virus ) {
280 return array( 'uploadvirus', $virus );
282 wfDebug( __METHOD__ . ": all clear; passing.\n" );
283 return true;
287 * Check whether the user can edit, upload and create the image.
289 * @param $user the User object to verify the permissions against
290 * @return mixed An array as returned by getUserPermissionsErrors or true
291 * in case the user has proper permissions.
293 public function verifyPermissions( $user ) {
295 * If the image is protected, non-sysop users won't be able
296 * to modify it by uploading a new revision.
298 $nt = $this->getTitle();
299 if( is_null( $nt ) ) {
300 return true;
302 $permErrors = $nt->getUserPermissionsErrors( 'edit', $user );
303 $permErrorsUpload = $nt->getUserPermissionsErrors( 'upload', $user );
304 $permErrorsCreate = ( $nt->exists() ? array() : $nt->getUserPermissionsErrors( 'create', $user ) );
305 if( $permErrors || $permErrorsUpload || $permErrorsCreate ) {
306 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsUpload, $permErrors ) );
307 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsCreate, $permErrors ) );
308 return $permErrors;
310 return true;
314 * Check for non fatal problems with the file
316 * @return Array of warnings
318 public function checkWarnings() {
319 $warnings = array();
321 $localFile = $this->getLocalFile();
322 $filename = $localFile->getName();
323 $n = strrpos( $filename, '.' );
324 $partname = $n ? substr( $filename, 0, $n ) : $filename;
327 * Check whether the resulting filename is different from the desired one,
328 * but ignore things like ucfirst() and spaces/underscore things
330 $comparableName = str_replace( ' ', '_', $this->mDesiredDestName );
331 $comparableName = Title::capitalize( $comparableName, NS_FILE );
333 if( $this->mDesiredDestName != $filename && $comparableName != $filename ) {
334 $warnings['badfilename'] = $filename;
337 // Check whether the file extension is on the unwanted list
338 global $wgCheckFileExtensions, $wgFileExtensions;
339 if ( $wgCheckFileExtensions ) {
340 if ( !$this->checkFileExtension( $this->mFinalExtension, $wgFileExtensions ) ) {
341 $warnings['filetype-unwanted-type'] = $this->mFinalExtension;
345 global $wgUploadSizeWarning;
346 if ( $wgUploadSizeWarning && ( $this->mFileSize > $wgUploadSizeWarning ) ) {
347 $warnings['large-file'] = $wgUploadSizeWarning;
350 if ( $this->mFileSize == 0 ) {
351 $warnings['emptyfile'] = true;
354 $exists = self::getExistsWarning( $localFile );
355 if( $exists !== false ) {
356 $warnings['exists'] = $exists;
359 // Check dupes against existing files
360 $hash = File::sha1Base36( $this->mTempPath );
361 $dupes = RepoGroup::singleton()->findBySha1( $hash );
362 $title = $this->getTitle();
363 // Remove all matches against self
364 foreach ( $dupes as $key => $dupe ) {
365 if( $title->equals( $dupe->getTitle() ) ) {
366 unset( $dupes[$key] );
369 if( $dupes ) {
370 $warnings['duplicate'] = $dupes;
373 // Check dupes against archives
374 $archivedImage = new ArchivedFile( null, 0, "{$hash}.{$this->mFinalExtension}" );
375 if ( $archivedImage->getID() > 0 ) {
376 $warnings['duplicate-archive'] = $archivedImage->getName();
379 return $warnings;
383 * Really perform the upload. Stores the file in the local repo, watches
384 * if necessary and runs the UploadComplete hook.
386 * @return mixed Status indicating the whether the upload succeeded.
388 public function performUpload( $comment, $pageText, $watch, $user ) {
389 wfDebug( "\n\n\performUpload: sum:" . $comment . ' c: ' . $pageText . ' w:' . $watch );
390 $status = $this->getLocalFile()->upload( $this->mTempPath, $comment, $pageText,
391 File::DELETE_SOURCE, $this->mFileProps, false, $user );
393 if( $status->isGood() ) {
394 if ( $watch ) {
395 $user->addWatch( $this->getLocalFile()->getTitle() );
398 wfRunHooks( 'UploadComplete', array( &$this ) );
401 return $status;
405 * Returns the title of the file to be uploaded. Sets mTitleError in case
406 * the name was illegal.
408 * @return Title The title of the file or null in case the name was illegal
410 public function getTitle() {
411 if ( $this->mTitle !== false ) {
412 return $this->mTitle;
416 * Chop off any directories in the given filename. Then
417 * filter out illegal characters, and try to make a legible name
418 * out of it. We'll strip some silently that Title would die on.
420 $this->mFilteredName = wfStripIllegalFilenameChars( $this->mDesiredDestName );
421 /* Normalize to title form before we do any further processing */
422 $nt = Title::makeTitleSafe( NS_FILE, $this->mFilteredName );
423 if( is_null( $nt ) ) {
424 $this->mTitleError = self::ILLEGAL_FILENAME;
425 return $this->mTitle = null;
427 $this->mFilteredName = $nt->getDBkey();
430 * We'll want to blacklist against *any* 'extension', and use
431 * only the final one for the whitelist.
433 list( $partname, $ext ) = $this->splitExtensions( $this->mFilteredName );
435 if( count( $ext ) ) {
436 $this->mFinalExtension = trim( $ext[count( $ext ) - 1] );
437 } else {
438 $this->mFinalExtension = '';
441 /* Don't allow users to override the blacklist (check file extension) */
442 global $wgCheckFileExtensions, $wgStrictFileExtensions;
443 global $wgFileExtensions, $wgFileBlacklist;
444 if ( $this->mFinalExtension == '' ) {
445 $this->mTitleError = self::FILETYPE_MISSING;
446 return $this->mTitle = null;
447 } elseif ( $this->checkFileExtensionList( $ext, $wgFileBlacklist ) ||
448 ( $wgCheckFileExtensions && $wgStrictFileExtensions &&
449 !$this->checkFileExtension( $this->mFinalExtension, $wgFileExtensions ) ) ) {
450 $this->mTitleError = self::FILETYPE_BADTYPE;
451 return $this->mTitle = null;
454 # If there was more than one "extension", reassemble the base
455 # filename to prevent bogus complaints about length
456 if( count( $ext ) > 1 ) {
457 for( $i = 0; $i < count( $ext ) - 1; $i++ ) {
458 $partname .= '.' . $ext[$i];
462 if( strlen( $partname ) < 1 ) {
463 $this->mTitleError = self::MIN_LENGTH_PARTNAME;
464 return $this->mTitle = null;
467 return $this->mTitle = $nt;
471 * Return the local file and initializes if necessary.
473 public function getLocalFile() {
474 if( is_null( $this->mLocalFile ) ) {
475 $nt = $this->getTitle();
476 $this->mLocalFile = is_null( $nt ) ? null : wfLocalFile( $nt );
478 return $this->mLocalFile;
482 * Stash a file in a temporary directory for later processing
483 * after the user has confirmed it.
485 * If the user doesn't explicitly cancel or accept, these files
486 * can accumulate in the temp directory.
488 * @param $saveName String: the destination filename
489 * @param $tempSrc String: the source temporary file to save
490 * @return String: full path the stashed file, or false on failure
492 protected function saveTempUploadedFile( $saveName, $tempSrc ) {
493 $repo = RepoGroup::singleton()->getLocalRepo();
494 $status = $repo->storeTemp( $saveName, $tempSrc );
495 return $status;
499 * Stash a file in a temporary directory for later processing,
500 * and save the necessary descriptive info into the session.
501 * Returns a key value which will be passed through a form
502 * to pick up the path info on a later invocation.
504 * @return Integer: session key
506 public function stashSession() {
507 $status = $this->saveTempUploadedFile( $this->mDestName, $this->mTempPath );
508 if( !$status->isOK() ) {
509 # Couldn't save the file.
510 return false;
513 $key = $this->getSessionKey();
514 $_SESSION['wsUploadData'][$key] = array(
515 'mTempPath' => $status->value,
516 'mFileSize' => $this->mFileSize,
517 'mFileProps' => $this->mFileProps,
518 'version' => self::SESSION_VERSION,
520 return $key;
524 * Generate a random session key from stash in cases where we want to start an upload without much information
526 protected function getSessionKey() {
527 $key = mt_rand( 0, 0x7fffffff );
528 $_SESSION['wsUploadData'][$key] = array();
529 return $key;
533 * If we've modified the upload file we need to manually remove it
534 * on exit to clean up.
536 public function cleanupTempFile() {
537 if ( $this->mRemoveTempFile && $this->mTempPath && file_exists( $this->mTempPath ) ) {
538 wfDebug( __METHOD__ . ": Removing temporary file {$this->mTempPath}\n" );
539 unlink( $this->mTempPath );
543 public function getTempPath() {
544 return $this->mTempPath;
548 * Split a file into a base name and all dot-delimited 'extensions'
549 * on the end. Some web server configurations will fall back to
550 * earlier pseudo-'extensions' to determine type and execute
551 * scripts, so the blacklist needs to check them all.
553 * @return array
555 public static function splitExtensions( $filename ) {
556 $bits = explode( '.', $filename );
557 $basename = array_shift( $bits );
558 return array( $basename, $bits );
562 * Perform case-insensitive match against a list of file extensions.
563 * Returns true if the extension is in the list.
565 * @param $ext String
566 * @param $list Array
567 * @return Boolean
569 public static function checkFileExtension( $ext, $list ) {
570 return in_array( strtolower( $ext ), $list );
574 * Perform case-insensitive match against a list of file extensions.
575 * Returns true if any of the extensions are in the list.
577 * @param $ext Array
578 * @param $list Array
579 * @return Boolean
581 public static function checkFileExtensionList( $ext, $list ) {
582 foreach( $ext as $e ) {
583 if( in_array( strtolower( $e ), $list ) ) {
584 return true;
587 return false;
591 * Checks if the mime type of the uploaded file matches the file extension.
593 * @param $mime String: the mime type of the uploaded file
594 * @param $extension String: the filename extension that the file is to be served with
595 * @return Boolean
597 public static function verifyExtension( $mime, $extension ) {
598 $magic = MimeMagic::singleton();
600 if ( !$mime || $mime == 'unknown' || $mime == 'unknown/unknown' )
601 if ( !$magic->isRecognizableExtension( $extension ) ) {
602 wfDebug( __METHOD__ . ": passing file with unknown detected mime type; " .
603 "unrecognized extension '$extension', can't verify\n" );
604 return true;
605 } else {
606 wfDebug( __METHOD__ . ": rejecting file with unknown detected mime type; ".
607 "recognized extension '$extension', so probably invalid file\n" );
608 return false;
611 $match = $magic->isMatchingExtension( $extension, $mime );
613 if ( $match === null ) {
614 wfDebug( __METHOD__ . ": no file extension known for mime type $mime, passing file\n" );
615 return true;
616 } elseif( $match === true ) {
617 wfDebug( __METHOD__ . ": mime type $mime matches extension $extension, passing file\n" );
619 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
620 return true;
622 } else {
623 wfDebug( __METHOD__ . ": mime type $mime mismatches file extension $extension, rejecting file\n" );
624 return false;
629 * Heuristic for detecting files that *could* contain JavaScript instructions or
630 * things that may look like HTML to a browser and are thus
631 * potentially harmful. The present implementation will produce false
632 * positives in some situations.
634 * @param $file String: pathname to the temporary upload file
635 * @param $mime String: the mime type of the file
636 * @param $extension String: the extension of the file
637 * @return Boolean: true if the file contains something looking like embedded scripts
639 public static function detectScript( $file, $mime, $extension ) {
640 global $wgAllowTitlesInSVG;
642 # ugly hack: for text files, always look at the entire file.
643 # For binary field, just check the first K.
645 if( strpos( $mime,'text/' ) === 0 ) {
646 $chunk = file_get_contents( $file );
647 } else {
648 $fp = fopen( $file, 'rb' );
649 $chunk = fread( $fp, 1024 );
650 fclose( $fp );
653 $chunk = strtolower( $chunk );
655 if( !$chunk ) {
656 return false;
659 # decode from UTF-16 if needed (could be used for obfuscation).
660 if( substr( $chunk, 0, 2 ) == "\xfe\xff" ) {
661 $enc = 'UTF-16BE';
662 } elseif( substr( $chunk, 0, 2 ) == "\xff\xfe" ) {
663 $enc = 'UTF-16LE';
664 } else {
665 $enc = null;
668 if( $enc ) {
669 $chunk = iconv( $enc, "ASCII//IGNORE", $chunk );
672 $chunk = trim( $chunk );
674 # FIXME: convert from UTF-16 if necessarry!
675 wfDebug( __METHOD__ . ": checking for embedded scripts and HTML stuff\n" );
677 # check for HTML doctype
678 if ( preg_match( "/<!DOCTYPE *X?HTML/i", $chunk ) ) {
679 return true;
683 * Internet Explorer for Windows performs some really stupid file type
684 * autodetection which can cause it to interpret valid image files as HTML
685 * and potentially execute JavaScript, creating a cross-site scripting
686 * attack vectors.
688 * Apple's Safari browser also performs some unsafe file type autodetection
689 * which can cause legitimate files to be interpreted as HTML if the
690 * web server is not correctly configured to send the right content-type
691 * (or if you're really uploading plain text and octet streams!)
693 * Returns true if IE is likely to mistake the given file for HTML.
694 * Also returns true if Safari would mistake the given file for HTML
695 * when served with a generic content-type.
697 $tags = array(
698 '<a href',
699 '<body',
700 '<head',
701 '<html', #also in safari
702 '<img',
703 '<pre',
704 '<script', #also in safari
705 '<table'
708 if( !$wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
709 $tags[] = '<title';
712 foreach( $tags as $tag ) {
713 if( false !== strpos( $chunk, $tag ) ) {
714 return true;
719 * look for JavaScript
722 # resolve entity-refs to look at attributes. may be harsh on big files... cache result?
723 $chunk = Sanitizer::decodeCharReferences( $chunk );
725 # look for script-types
726 if( preg_match( '!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim', $chunk ) ) {
727 return true;
730 # look for html-style script-urls
731 if( preg_match( '!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
732 return true;
735 # look for css-style script-urls
736 if( preg_match( '!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim', $chunk ) ) {
737 return true;
740 wfDebug( __METHOD__ . ": no scripts found\n" );
741 return false;
744 protected function detectScriptInSvg( $filename ) {
745 $check = new XmlTypeCheck( $filename, array( $this, 'checkSvgScriptCallback' ) );
746 return $check->filterMatch;
750 * @todo Replace this with a whitelist filter!
752 public function checkSvgScriptCallback( $element, $attribs ) {
753 $stripped = $this->stripXmlNamespace( $element );
755 if( $stripped == 'script' ) {
756 wfDebug( __METHOD__ . ": Found script element '$element' in uploaded file.\n" );
757 return true;
760 foreach( $attribs as $attrib => $value ) {
761 $stripped = $this->stripXmlNamespace( $attrib );
762 if( substr( $stripped, 0, 2 ) == 'on' ) {
763 wfDebug( __METHOD__ . ": Found script attribute '$attrib'='value' in uploaded file.\n" );
764 return true;
766 if( $stripped == 'href' && strpos( strtolower( $value ), 'javascript:' ) !== false ) {
767 wfDebug( __METHOD__ . ": Found script href attribute '$attrib'='$value' in uploaded file.\n" );
768 return true;
773 private function stripXmlNamespace( $name ) {
774 // 'http://www.w3.org/2000/svg:script' -> 'script'
775 $parts = explode( ':', strtolower( $name ) );
776 return array_pop( $parts );
780 * Generic wrapper function for a virus scanner program.
781 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
782 * $wgAntivirusRequired may be used to deny upload if the scan fails.
784 * @param $file String: pathname to the temporary upload file
785 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
786 * or a string containing feedback from the virus scanner if a virus was found.
787 * If textual feedback is missing but a virus was found, this function returns true.
789 public static function detectVirus( $file ) {
790 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
792 if ( !$wgAntivirus ) {
793 wfDebug( __METHOD__ . ": virus scanner disabled\n" );
794 return null;
797 if ( !$wgAntivirusSetup[$wgAntivirus] ) {
798 wfDebug( __METHOD__ . ": unknown virus scanner: $wgAntivirus\n" );
799 $wgOut->wrapWikiMsg( "<div class=\"error\">\n$1</div>", array( 'virus-badscanner', $wgAntivirus ) );
800 return wfMsg( 'virus-unknownscanner' ) . " $wgAntivirus";
803 # look up scanner configuration
804 $command = $wgAntivirusSetup[$wgAntivirus]['command'];
805 $exitCodeMap = $wgAntivirusSetup[$wgAntivirus]['codemap'];
806 $msgPattern = isset( $wgAntivirusSetup[$wgAntivirus]['messagepattern'] ) ?
807 $wgAntivirusSetup[$wgAntivirus]['messagepattern'] : null;
809 if ( strpos( $command, "%f" ) === false ) {
810 # simple pattern: append file to scan
811 $command .= " " . wfEscapeShellArg( $file );
812 } else {
813 # complex pattern: replace "%f" with file to scan
814 $command = str_replace( "%f", wfEscapeShellArg( $file ), $command );
817 wfDebug( __METHOD__ . ": running virus scan: $command \n" );
819 # execute virus scanner
820 $exitCode = false;
822 # NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
823 # that does not seem to be worth the pain.
824 # Ask me (Duesentrieb) about it if it's ever needed.
825 $output = wfShellExec( "$command 2>&1", $exitCode );
827 # map exit code to AV_xxx constants.
828 $mappedCode = $exitCode;
829 if ( $exitCodeMap ) {
830 if ( isset( $exitCodeMap[$exitCode] ) ) {
831 $mappedCode = $exitCodeMap[$exitCode];
832 } elseif ( isset( $exitCodeMap["*"] ) ) {
833 $mappedCode = $exitCodeMap["*"];
837 if ( $mappedCode === AV_SCAN_FAILED ) {
838 # scan failed (code was mapped to false by $exitCodeMap)
839 wfDebug( __METHOD__ . ": failed to scan $file (code $exitCode).\n" );
841 if ( $wgAntivirusRequired ) {
842 return wfMsg( 'virus-scanfailed', array( $exitCode ) );
843 } else {
844 return null;
846 } elseif ( $mappedCode === AV_SCAN_ABORTED ) {
847 # scan failed because filetype is unknown (probably imune)
848 wfDebug( __METHOD__ . ": unsupported file type $file (code $exitCode).\n" );
849 return null;
850 } elseif ( $mappedCode === AV_NO_VIRUS ) {
851 # no virus found
852 wfDebug( __METHOD__ . ": file passed virus scan.\n" );
853 return false;
854 } else {
855 $output = trim( $output );
857 if ( !$output ) {
858 $output = true; #if there's no output, return true
859 } elseif ( $msgPattern ) {
860 $groups = array();
861 if ( preg_match( $msgPattern, $output, $groups ) ) {
862 if ( $groups[1] ) {
863 $output = $groups[1];
868 wfDebug( __METHOD__ . ": FOUND VIRUS! scanner feedback: $output \n" );
869 return $output;
874 * Check if the temporary file is MacBinary-encoded, as some uploads
875 * from Internet Explorer on Mac OS Classic and Mac OS X will be.
876 * If so, the data fork will be extracted to a second temporary file,
877 * which will then be checked for validity and either kept or discarded.
879 private function checkMacBinary() {
880 $macbin = new MacBinary( $this->mTempPath );
881 if( $macbin->isValid() ) {
882 $dataFile = tempnam( wfTempDir(), 'WikiMacBinary' );
883 $dataHandle = fopen( $dataFile, 'wb' );
885 wfDebug( __METHOD__ . ": Extracting MacBinary data fork to $dataFile\n" );
886 $macbin->extractData( $dataHandle );
888 $this->mTempPath = $dataFile;
889 $this->mFileSize = $macbin->dataForkLength();
891 // We'll have to manually remove the new file if it's not kept.
892 $this->mRemoveTempFile = true;
894 $macbin->close();
898 * Check if there's an overwrite conflict and, if so, if restrictions
899 * forbid this user from performing the upload.
901 * @return mixed true on success, error string on failure
903 private function checkOverwrite() {
904 global $wgUser;
905 // First check whether the local file can be overwritten
906 $file = $this->getLocalFile();
907 if( $file->exists() ) {
908 if( !self::userCanReUpload( $wgUser, $file ) ) {
909 return 'fileexists-forbidden';
910 } else {
911 return true;
915 /* Check shared conflicts: if the local file does not exist, but
916 * wfFindFile finds a file, it exists in a shared repository.
918 $file = wfFindFile( $this->getTitle() );
919 if ( $file && !$wgUser->isAllowed( 'reupload-shared' ) ) {
920 return 'fileexists-shared-forbidden';
923 return true;
927 * Check if a user is the last uploader
929 * @param $user User object
930 * @param $img String: image name
931 * @return Boolean
933 public static function userCanReUpload( User $user, $img ) {
934 if( $user->isAllowed( 'reupload' ) ) {
935 return true; // non-conditional
937 if( !$user->isAllowed( 'reupload-own' ) ) {
938 return false;
940 if( is_string( $img ) ) {
941 $img = wfLocalFile( $img );
943 if ( !( $img instanceof LocalFile ) ) {
944 return false;
947 return $user->getId() == $img->getUser( 'id' );
951 * Helper function that does various existence checks for a file.
952 * The following checks are performed:
953 * - The file exists
954 * - Article with the same name as the file exists
955 * - File exists with normalized extension
956 * - The file looks like a thumbnail and the original exists
958 * @param $file The File object to check
959 * @return mixed False if the file does not exists, else an array
961 public static function getExistsWarning( $file ) {
962 if( $file->exists() ) {
963 return array( 'warning' => 'exists', 'file' => $file );
966 if( $file->getTitle()->getArticleID() ) {
967 return array( 'warning' => 'page-exists', 'file' => $file );
970 if ( $file->wasDeleted() && !$file->exists() ) {
971 return array( 'warning' => 'was-deleted', 'file' => $file );
974 if( strpos( $file->getName(), '.' ) == false ) {
975 $partname = $file->getName();
976 $extension = '';
977 } else {
978 $n = strrpos( $file->getName(), '.' );
979 $extension = substr( $file->getName(), $n + 1 );
980 $partname = substr( $file->getName(), 0, $n );
982 $normalizedExtension = File::normalizeExtension( $extension );
984 if ( $normalizedExtension != $extension ) {
985 // We're not using the normalized form of the extension.
986 // Normal form is lowercase, using most common of alternate
987 // extensions (eg 'jpg' rather than 'JPEG').
989 // Check for another file using the normalized form...
990 $nt_lc = Title::makeTitle( NS_FILE, "{$partname}.{$normalizedExtension}" );
991 $file_lc = wfLocalFile( $nt_lc );
993 if( $file_lc->exists() ) {
994 return array(
995 'warning' => 'exists-normalized',
996 'file' => $file,
997 'normalizedFile' => $file_lc
1002 if ( self::isThumbName( $file->getName() ) ) {
1003 # Check for filenames like 50px- or 180px-, these are mostly thumbnails
1004 $nt_thb = Title::newFromText( substr( $partname , strpos( $partname , '-' ) +1 ) . '.' . $extension, NS_FILE );
1005 $file_thb = wfLocalFile( $nt_thb );
1006 if( $file_thb->exists() ) {
1007 return array(
1008 'warning' => 'thumb',
1009 'file' => $file,
1010 'thumbFile' => $file_thb
1012 } else {
1013 // File does not exist, but we just don't like the name
1014 return array(
1015 'warning' => 'thumb-name',
1016 'file' => $file,
1017 'thumbFile' => $file_thb
1023 foreach( self::getFilenamePrefixBlacklist() as $prefix ) {
1024 if ( substr( $partname, 0, strlen( $prefix ) ) == $prefix ) {
1025 return array(
1026 'warning' => 'bad-prefix',
1027 'file' => $file,
1028 'prefix' => $prefix
1033 return false;
1037 * Helper function that checks whether the filename looks like a thumbnail
1039 public static function isThumbName( $filename ) {
1040 $n = strrpos( $filename, '.' );
1041 $partname = $n ? substr( $filename, 0, $n ) : $filename;
1042 return (
1043 substr( $partname , 3, 3 ) == 'px-' ||
1044 substr( $partname , 2, 3 ) == 'px-'
1045 ) &&
1046 preg_match( "/[0-9]{2}/" , substr( $partname , 0, 2 ) );
1050 * Get a list of blacklisted filename prefixes from [[MediaWiki:Filename-prefix-blacklist]]
1052 * @return array list of prefixes
1054 public static function getFilenamePrefixBlacklist() {
1055 $blacklist = array();
1056 $message = wfMsgForContent( 'filename-prefix-blacklist' );
1057 if( $message && !( wfEmptyMsg( 'filename-prefix-blacklist', $message ) || $message == '-' ) ) {
1058 $lines = explode( "\n", $message );
1059 foreach( $lines as $line ) {
1060 // Remove comment lines
1061 $comment = substr( trim( $line ), 0, 1 );
1062 if ( $comment == '#' || $comment == '' ) {
1063 continue;
1065 // Remove additional comments after a prefix
1066 $comment = strpos( $line, '#' );
1067 if ( $comment > 0 ) {
1068 $line = substr( $line, 0, $comment-1 );
1070 $blacklist[] = trim( $line );
1073 return $blacklist;
1076 public function getImageInfo( $result ) {
1077 $file = $this->getLocalFile();
1078 $imParam = ApiQueryImageInfo::getPropertyNames();
1079 return ApiQueryImageInfo::getInfo( $file, array_flip( $imParam ), $result );