4 * @addtogroup SpecialPage
11 function wfSpecialUpload() {
13 $form = new UploadForm( $wgRequest );
18 * implements Special:Upload
19 * @addtogroup SpecialPage
23 const BEFORE_PROCESSING
= 1;
24 const LARGE_FILE_SERVER
= 2;
26 const MIN_LENGHT_PARTNAME
= 4;
27 const ILLEGAL_FILENAME
= 5;
28 const PROTECTED_PAGE
= 6;
29 const OVERWRITE_EXISTING_FILE
= 7;
30 const FILETYPE_MISSING
= 8;
31 const FILETYPE_BADTYPE
= 9;
32 const VERIFICATION_ERROR
= 10;
33 const UPLOAD_VERIFICATION_ERROR
= 11;
34 const UPLOAD_WARNING
= 12;
35 const INTERNAL_ERROR
= 13;
40 var $mComment, $mLicense, $mIgnoreWarning, $mCurlError;
41 var $mDestName, $mTempPath, $mFileSize, $mFileProps;
42 var $mCopyrightStatus, $mCopyrightSource, $mReUpload, $mAction, $mUploadClicked;
43 var $mSrcName, $mSessionKey, $mStashed, $mDesiredDestName, $mRemoveTempFile, $mSourceType;
44 var $mDestWarningAck, $mCurlDestHandle;
47 # Placeholders for text injection by hooks (must be HTML)
48 # extensions should take care to _append_ to the present value
49 var $uploadFormTextTop;
50 var $uploadFormTextAfterSummary;
52 const SESSION_VERSION
= 1;
56 * Constructor : initialise object
57 * Get data POSTed through the form and assign them to the object
58 * @param $request Data posted.
60 function UploadForm( &$request ) {
61 global $wgAllowCopyUploads;
62 $this->mDesiredDestName
= $request->getText( 'wpDestFile' );
63 $this->mIgnoreWarning
= $request->getCheck( 'wpIgnoreWarning' );
64 $this->mComment
= $request->getText( 'wpUploadDescription' );
66 if( !$request->wasPosted() ) {
67 # GET requests just give the main form; no data except destination
68 # filename and description
72 # Placeholders for text injection by hooks (empty per default)
73 $this->uploadFormTextTop
= "";
74 $this->uploadFormTextAfterSummary
= "";
76 $this->mReUpload
= $request->getCheck( 'wpReUpload' );
77 $this->mUploadClicked
= $request->getCheck( 'wpUpload' );
79 $this->mLicense
= $request->getText( 'wpLicense' );
80 $this->mCopyrightStatus
= $request->getText( 'wpUploadCopyStatus' );
81 $this->mCopyrightSource
= $request->getText( 'wpUploadSource' );
82 $this->mWatchthis
= $request->getBool( 'wpWatchthis' );
83 $this->mSourceType
= $request->getText( 'wpSourceType' );
84 $this->mDestWarningAck
= $request->getText( 'wpDestFileWarningAck' );
86 $this->mAction
= $request->getVal( 'action' );
88 $this->mSessionKey
= $request->getInt( 'wpSessionKey' );
89 if( !empty( $this->mSessionKey
) &&
90 isset( $_SESSION['wsUploadData'][$this->mSessionKey
]['version'] ) &&
91 $_SESSION['wsUploadData'][$this->mSessionKey
]['version'] == self
::SESSION_VERSION
) {
93 * Confirming a temporarily stashed upload.
94 * We don't want path names to be forged, so we keep
95 * them in the session on the server and just give
96 * an opaque key to the user agent.
98 $data = $_SESSION['wsUploadData'][$this->mSessionKey
];
99 $this->mTempPath
= $data['mTempPath'];
100 $this->mFileSize
= $data['mFileSize'];
101 $this->mSrcName
= $data['mSrcName'];
102 $this->mFileProps
= $data['mFileProps'];
103 $this->mCurlError
= 0/*UPLOAD_ERR_OK*/;
104 $this->mStashed
= true;
105 $this->mRemoveTempFile
= false;
108 *Check for a newly uploaded file.
110 if( $wgAllowCopyUploads && $this->mSourceType
== 'web' ) {
111 $this->initializeFromUrl( $request );
113 $this->initializeFromUpload( $request );
119 * Initialize the uploaded file from PHP data
122 function initializeFromUpload( $request ) {
123 $this->mTempPath
= $request->getFileTempName( 'wpUploadFile' );
124 $this->mFileSize
= $request->getFileSize( 'wpUploadFile' );
125 $this->mSrcName
= $request->getFileName( 'wpUploadFile' );
126 $this->mCurlError
= $request->getUploadError( 'wpUploadFile' );
127 $this->mSessionKey
= false;
128 $this->mStashed
= false;
129 $this->mRemoveTempFile
= false; // PHP will handle this
133 * Copy a web file to a temporary file
136 function initializeFromUrl( $request ) {
137 global $wgTmpDirectory;
138 $url = $request->getText( 'wpUploadFileURL' );
139 $local_file = tempnam( $wgTmpDirectory, 'WEBUPLOAD' );
141 $this->mTempPath
= $local_file;
142 $this->mFileSize
= 0; # Will be set by curlCopy
143 $this->mCurlError
= $this->curlCopy( $url, $local_file );
144 $this->mSrcName
= array_pop( explode( '/', $url ) );
145 $this->mSessionKey
= false;
146 $this->mStashed
= false;
148 // PHP won't auto-cleanup the file
149 $this->mRemoveTempFile
= file_exists( $local_file );
154 * Returns true if there was an error, false otherwise
156 private function curlCopy( $url, $dest ) {
157 global $wgUser, $wgOut;
159 if( !$wgUser->isAllowed( 'upload_by_url' ) ) {
160 $wgOut->permissionRequired( 'upload_by_url' );
164 # Maybe remove some pasting blanks :-)
166 if( stripos($url, 'http://') !== 0 && stripos($url, 'ftp://') !== 0 ) {
167 # Only HTTP or FTP URLs
168 $wgOut->errorPage( 'upload-proto-error', 'upload-proto-error-text' );
172 # Open temporary file
173 $this->mCurlDestHandle
= @fopen
( $this->mTempPath
, "wb" );
174 if( $this->mCurlDestHandle
=== false ) {
175 # Could not open temporary file to write in
176 $wgOut->errorPage( 'upload-file-error', 'upload-file-error-text');
181 curl_setopt( $ch, CURLOPT_HTTP_VERSION
, 1.0); # Probably not needed, but apparently can work around some bug
182 curl_setopt( $ch, CURLOPT_TIMEOUT
, 10); # 10 seconds timeout
183 curl_setopt( $ch, CURLOPT_LOW_SPEED_LIMIT
, 512); # 0.5KB per second minimum transfer speed
184 curl_setopt( $ch, CURLOPT_URL
, $url);
185 curl_setopt( $ch, CURLOPT_WRITEFUNCTION
, array( $this, 'uploadCurlCallback' ) );
187 $error = curl_errno( $ch ) ?
true : false;
188 $errornum = curl_errno( $ch );
189 // if ( $error ) print curl_error ( $ch ) ; # Debugging output
192 fclose( $this->mCurlDestHandle
);
193 unset( $this->mCurlDestHandle
);
196 if( wfEmptyMsg( "upload-curl-error$errornum", wfMsg("upload-curl-error$errornum") ) )
197 $wgOut->errorPage( 'upload-misc-error', 'upload-misc-error-text' );
199 $wgOut->errorPage( "upload-curl-error$errornum", "upload-curl-error$errornum-text" );
206 * Callback function for CURL-based web transfer
207 * Write data to file unless we've passed the length limit;
208 * if so, abort immediately.
211 function uploadCurlCallback( $ch, $data ) {
212 global $wgMaxUploadSize;
213 $length = strlen( $data );
214 $this->mFileSize +
= $length;
215 if( $this->mFileSize
> $wgMaxUploadSize ) {
218 fwrite( $this->mCurlDestHandle
, $data );
227 global $wgUser, $wgOut;
228 global $wgEnableUploads;
230 # Check uploading enabled
231 if( !$wgEnableUploads ) {
232 $wgOut->showErrorPage( 'uploaddisabled', 'uploaddisabledtext', array( $this->mDesiredDestName
) );
237 if( !$wgUser->isAllowed( 'upload' ) ) {
238 if( !$wgUser->isLoggedIn() ) {
239 $wgOut->showErrorPage( 'uploadnologin', 'uploadnologintext' );
241 $wgOut->permissionRequired( 'upload' );
247 if( $wgUser->isBlocked() ) {
248 $wgOut->blockedPage();
253 $wgOut->readOnlyPage();
257 if( $this->mReUpload
) {
258 if( !$this->unsaveUploadedFile() ) {
261 $this->mainUploadForm();
262 } else if( 'submit' == $this->mAction ||
$this->mUploadClicked
) {
263 $this->processUpload();
265 $this->mainUploadForm();
268 $this->cleanupTempFile();
273 * Checks are made in SpecialUpload::execute()
277 function processUpload(){
278 global $wgUser, $wgOut, $wgFileExtensions;
281 $value = $this->internalProcessUpload( $details );
285 $wgOut->redirect( $this->mLocalFile
->getTitle()->getFullURL() );
288 case self
::BEFORE_PROCESSING
:
291 case self
::LARGE_FILE_SERVER
:
292 $this->mainUploadForm( wfMsgHtml( 'largefileserver' ) );
295 case self
::EMPTY_FILE
:
296 $this->mainUploadForm( wfMsgHtml( 'emptyfile' ) );
299 case self
::MIN_LENGHT_PARTNAME
:
300 $this->mainUploadForm( wfMsgHtml( 'minlength1' ) );
303 case self
::ILLEGAL_FILENAME
:
304 $filtered = $details['filtered'];
305 $this->uploadError( wfMsgWikiHtml( 'illegalfilename', htmlspecialchars( $filtered ) ) );
308 case self
::PROTECTED_PAGE
:
309 $this->uploadError( wfMsgWikiHtml( 'protectedpage' ) );
312 case self
::OVERWRITE_EXISTING_FILE
:
313 $errorText = $details['overwrite'];
314 $overwrite = new WikiError( $wgOut->parse( $errorText ) );
315 $this->uploadError( $overwrite->toString() );
318 case self
::FILETYPE_MISSING
:
319 $this->uploadError( wfMsgExt( 'filetype-missing', array ( 'parseinline' ) ) );
322 case self
::FILETYPE_BADTYPE
:
323 $finalExt = $details['finalExt'];
325 wfMsgExt( 'filetype-banned-type',
326 array( 'parseinline' ),
327 htmlspecialchars( $finalExt ),
329 wfMsgExt( 'filetype-separator', array( 'escapenoentities' ) ),
336 case self
::VERIFICATION_ERROR
:
337 $veri = $details['veri'];
338 $this->uploadError( $veri->toString() );
341 case self
::UPLOAD_VERIFICATION_ERROR
:
342 $error = $details['error'];
343 $this->uploadError( $error );
346 case self
::UPLOAD_WARNING
:
347 $warning = $details['warning'];
348 $this->uploadWarning( $warning );
351 case self
::INTERNAL_ERROR
:
352 $internal = $details['internal'];
353 $this->showError( $internal );
357 throw new MWException( __METHOD__
. ": Unknown value `{$value}`" );
362 * Really do the upload
363 * Checks are made in SpecialUpload::execute()
365 * @param array $resultDetails contains result-specific dict of additional values
369 function internalProcessUpload( &$resultDetails ) {
372 if( !wfRunHooks( 'UploadForm:BeforeProcessing', array( &$this ) ) )
374 wfDebug( "Hook 'UploadForm:BeforeProcessing' broke processing the file." );
375 return self
::BEFORE_PROCESSING
;
378 /* Check for PHP error if any, requires php 4.2 or newer */
379 if( $this->mCurlError
== 1/*UPLOAD_ERR_INI_SIZE*/ ) {
380 return self
::LARGE_FILE_SERVER
;
384 * If there was no filename or a zero size given, give up quick.
386 if( trim( $this->mSrcName
) == '' ||
empty( $this->mFileSize
) ) {
387 return self
::EMPTY_FILE
;
390 # Chop off any directories in the given filename
391 if( $this->mDesiredDestName
) {
392 $basename = $this->mDesiredDestName
;
394 $basename = $this->mSrcName
;
396 $filtered = wfBaseName( $basename );
399 * We'll want to blacklist against *any* 'extension', and use
400 * only the final one for the whitelist.
402 list( $partname, $ext ) = $this->splitExtensions( $filtered );
404 if( count( $ext ) ) {
405 $finalExt = $ext[count( $ext ) - 1];
410 # If there was more than one "extension", reassemble the base
411 # filename to prevent bogus complaints about length
412 if( count( $ext ) > 1 ) {
413 for( $i = 0; $i < count( $ext ) - 1; $i++
)
414 $partname .= '.' . $ext[$i];
417 if( strlen( $partname ) < 1 ) {
418 return self
::MIN_LENGHT_PARTNAME
;
422 * Filter out illegal characters, and try to make a legible name
423 * out of it. We'll strip some silently that Title would die on.
425 $filtered = preg_replace ( "/[^".Title
::legalChars()."]|:/", '-', $filtered );
426 $nt = Title
::makeTitleSafe( NS_IMAGE
, $filtered );
427 if( is_null( $nt ) ) {
428 $resultDetails = array( 'filtered' => $filtered );
429 return self
::ILLEGAL_FILENAME
;
431 $this->mLocalFile
= wfLocalFile( $nt );
432 $this->mDestName
= $this->mLocalFile
->getName();
435 * If the image is protected, non-sysop users won't be able
436 * to modify it by uploading a new revision.
438 if( !$nt->userCan( 'edit' ) ) {
439 return self
::PROTECTED_PAGE
;
443 * In some cases we may forbid overwriting of existing files.
445 $overwrite = $this->checkOverwrite( $this->mDestName
);
446 if( $overwrite !== true ) {
447 $resultDetails = array( 'overwrite' => $overwrite );
448 return self
::OVERWRITE_EXISTING_FILE
;
451 /* Don't allow users to override the blacklist (check file extension) */
452 global $wgStrictFileExtensions;
453 global $wgFileExtensions, $wgFileBlacklist;
454 if ($finalExt == '') {
455 return self
::FILETYPE_MISSING
;
456 } elseif ( $this->checkFileExtensionList( $ext, $wgFileBlacklist ) ||
457 ($wgStrictFileExtensions && !$this->checkFileExtension( $finalExt, $wgFileExtensions ) ) ) {
458 $resultDetails = array( 'finalExt' => $finalExt );
459 return self
::FILETYPE_BADTYPE
;
463 * Look at the contents of the file; if we can recognize the
464 * type but it's corrupt or data of the wrong type, we should
465 * probably not accept it.
467 if( !$this->mStashed
) {
468 $this->mFileProps
= File
::getPropsFromPath( $this->mTempPath
, $finalExt );
469 $this->checkMacBinary();
470 $veri = $this->verify( $this->mTempPath
, $finalExt );
472 if( $veri !== true ) { //it's a wiki error...
473 $resultDetails = array( 'veri' => $veri );
474 return self
::VERIFICATION_ERROR
;
478 * Provide an opportunity for extensions to add further checks
481 if( !wfRunHooks( 'UploadVerification',
482 array( $this->mDestName
, $this->mTempPath
, &$error ) ) ) {
483 $resultDetails = array( 'error' => $error );
484 return self
::UPLOAD_VERIFICATION_ERROR
;
490 * Check for non-fatal conditions
492 if ( ! $this->mIgnoreWarning
) {
495 global $wgCapitalLinks;
496 if( $wgCapitalLinks ) {
497 $filtered = ucfirst( $filtered );
499 if( $basename != $filtered ) {
500 $warning .= '<li>'.wfMsgHtml( 'badfilename', htmlspecialchars( $this->mDestName
) ).'</li>';
503 global $wgCheckFileExtensions;
504 if ( $wgCheckFileExtensions ) {
505 if ( !$this->checkFileExtension( $finalExt, $wgFileExtensions ) ) {
507 wfMsgExt( 'filetype-unwanted-type',
508 array( 'parseinline' ),
509 htmlspecialchars( $finalExt ),
511 wfMsgExt( 'filetype-separator', array( 'escapenoentities' ) ),
518 global $wgUploadSizeWarning;
519 if ( $wgUploadSizeWarning && ( $this->mFileSize
> $wgUploadSizeWarning ) ) {
520 $skin = $wgUser->getSkin();
521 $wsize = $skin->formatSize( $wgUploadSizeWarning );
522 $asize = $skin->formatSize( $this->mFileSize
);
523 $warning .= '<li>' . wfMsgHtml( 'large-file', $wsize, $asize ) . '</li>';
525 if ( $this->mFileSize
== 0 ) {
526 $warning .= '<li>'.wfMsgHtml( 'emptyfile' ).'</li>';
529 if ( !$this->mDestWarningAck
) {
530 $warning .= self
::getExistsWarning( $this->mLocalFile
);
532 if( $warning != '' ) {
534 * Stash the file in a temporary location; the user can choose
535 * to let it through and we'll complete the upload then.
537 $resultDetails = array( 'warning' => $warning );
538 return self
::UPLOAD_WARNING
;
543 * Try actually saving the thing...
544 * It will show an error form on failure.
546 $pageText = self
::getInitialPageText( $this->mComment
, $this->mLicense
,
547 $this->mCopyrightStatus
, $this->mCopyrightSource
);
549 $status = $this->mLocalFile
->upload( $this->mTempPath
, $this->mComment
, $pageText,
550 File
::DELETE_SOURCE
, $this->mFileProps
);
551 if ( !$status->isGood() ) {
552 $resultDetails = array( 'internal' => $status->getWikiText() );
553 return self
::INTERNAL_ERROR
;
555 if ( $this->mWatchthis
) {
557 $wgUser->addWatch( $this->mLocalFile
->getTitle() );
559 // Success, redirect to description page
560 $img = null; // @todo: added to avoid passing a ref to null - should this be defined somewhere?
561 wfRunHooks( 'UploadComplete', array( &$img ) );
562 return self
::SUCCESS
;
567 * Do existence checks on a file and produce a warning
568 * This check is static and can be done pre-upload via AJAX
569 * Returns an HTML fragment consisting of one or more LI elements if there is a warning
570 * Returns an empty string if there is no warning
572 static function getExistsWarning( $file ) {
574 // Check for uppercase extension. We allow these filenames but check if an image
575 // with lowercase extension exists already
578 if( strpos( $file->getName(), '.' ) == false ) {
579 $partname = $file->getName();
582 list( $partname, $rawExtension ) = explode( '.', $file->getName(), 2 );
584 $sk = $wgUser->getSkin();
586 if ( $rawExtension != $file->getExtension() ) {
587 // We're not using the normalized form of the extension.
588 // Normal form is lowercase, using most common of alternate
589 // extensions (eg 'jpg' rather than 'JPEG').
591 // Check for another file using the normalized form...
592 $nt_lc = Title
::newFromText( $partname . '.' . $file->getExtension() );
593 $file_lc = wfLocalFile( $nt_lc );
598 if( $file->exists() ) {
599 $dlink = $sk->makeKnownLinkObj( $file->getTitle() );
600 if ( $file->allowInlineDisplay() ) {
601 $dlink2 = $sk->makeImageLinkObj( $file->getTitle(), wfMsgExt( 'fileexists-thumb', 'parseinline', $dlink ),
602 $file->getName(), 'right', array(), false, true );
603 } elseif ( !$file->allowInlineDisplay() && $file->isSafeFile() ) {
604 $icon = $file->iconThumb();
605 $dlink2 = '<div style="float:right" id="mw-media-icon">' .
606 $icon->toHtml( array( 'desc-link' => true ) ) . '<br />' . $dlink . '</div>';
611 $warning .= '<li>' . wfMsgExt( 'fileexists', 'parseline', $dlink ) . '</li>' . $dlink2;
613 } elseif ( $file_lc && $file_lc->exists() ) {
614 # Check if image with lowercase extension exists.
615 # It's not forbidden but in 99% it makes no sense to upload the same filename with uppercase extension
616 $dlink = $sk->makeKnownLinkObj( $nt_lc );
617 if ( $file_lc->allowInlineDisplay() ) {
618 $dlink2 = $sk->makeImageLinkObj( $nt_lc, wfMsgExt( 'fileexists-thumb', 'parseinline', $dlink ),
619 $nt_lc->getText(), 'right', array(), false, true );
620 } elseif ( !$file_lc->allowInlineDisplay() && $file_lc->isSafeFile() ) {
621 $icon = $file_lc->iconThumb();
622 $dlink2 = '<div style="float:right" id="mw-media-icon">' .
623 $icon->toHtml( array( 'desc-link' => true ) ) . '<br />' . $dlink . '</div>';
628 $warning .= '<li>' . wfMsgExt( 'fileexists-extension', 'parsemag', $file->getName(), $dlink ) . '</li>' . $dlink2;
630 } elseif ( ( substr( $partname , 3, 3 ) == 'px-' ||
substr( $partname , 2, 3 ) == 'px-' )
631 && ereg( "[0-9]{2}" , substr( $partname , 0, 2) ) )
633 # Check for filenames like 50px- or 180px-, these are mostly thumbnails
634 $nt_thb = Title
::newFromText( substr( $partname , strpos( $partname , '-' ) +
1 ) . '.' . $rawExtension );
635 $file_thb = wfLocalFile( $nt_thb );
636 if ($file_thb->exists() ) {
637 # Check if an image without leading '180px-' (or similiar) exists
638 $dlink = $sk->makeKnownLinkObj( $nt_thb);
639 if ( $file_thb->allowInlineDisplay() ) {
640 $dlink2 = $sk->makeImageLinkObj( $nt_thb,
641 wfMsgExt( 'fileexists-thumb', 'parseinline', $dlink ),
642 $nt_thb->getText(), 'right', array(), false, true );
643 } elseif ( !$file_thb->allowInlineDisplay() && $file_thb->isSafeFile() ) {
644 $icon = $file_thb->iconThumb();
645 $dlink2 = '<div style="float:right" id="mw-media-icon">' .
646 $icon->toHtml( array( 'desc-link' => true ) ) . '<br />' .
652 $warning .= '<li>' . wfMsgExt( 'fileexists-thumbnail-yes', 'parsemag', $dlink ) .
655 # Image w/o '180px-' does not exists, but we do not like these filenames
656 $warning .= '<li>' . wfMsgExt( 'file-thumbnail-no', 'parseinline' ,
657 substr( $partname , 0, strpos( $partname , '-' ) +
1 ) ) . '</li>';
661 $filenamePrefixBlacklist = self
::getFilenamePrefixBlacklist();
663 foreach( $filenamePrefixBlacklist as $prefix ) {
664 if ( substr( $partname, 0, strlen( $prefix ) ) == $prefix ) {
665 $warning .= '<li>' . wfMsgExt( 'filename-bad-prefix', 'parseinline', $prefix ) . '</li>';
670 if ( $file->wasDeleted() && !$file->exists() ) {
671 # If the file existed before and was deleted, warn the user of this
672 # Don't bother doing so if the file exists now, however
673 $ltitle = SpecialPage
::getTitleFor( 'Log' );
674 $llink = $sk->makeKnownLinkObj( $ltitle, wfMsgHtml( 'deletionlog' ),
675 'type=delete&page=' . $file->getTitle()->getPrefixedUrl() );
676 $warning .= '<li>' . wfMsgWikiHtml( 'filewasdeleted', $llink ) . '</li>';
682 * Get a list of warnings
684 * @param string local filename, e.g. 'file exists', 'non-descriptive filename'
685 * @return array list of warning messages
687 static function ajaxGetExistsWarning( $filename ) {
688 $file = wfFindFile( $filename );
690 // Force local file so we have an object to do further checks against
691 // if there isn't an exact match...
692 $file = wfLocalFile( $filename );
696 $warning = self
::getExistsWarning( $file );
697 if ( $warning !== '' ) {
698 $s = "<ul>$warning</ul>";
705 * Render a preview of a given license for the AJAX preview on upload
707 * @param string $license
710 public static function ajaxGetLicensePreview( $license ) {
711 global $wgParser, $wgUser;
712 $text = '{{' . $license . '}}';
713 $title = Title
::makeTitle( NS_IMAGE
, 'Sample.jpg' );
714 $options = ParserOptions
::newFromUser( $wgUser );
716 // Expand subst: first, then live templates...
717 $text = $wgParser->preSaveTransform( $text, $title, $wgUser, $options );
718 $output = $wgParser->parse( $text, $title, $options );
720 return $output->getText();
724 * Get a list of blacklisted filename prefixes from [[MediaWiki:filename-prefix-blacklist]]
726 * @return array list of prefixes
728 public static function getFilenamePrefixBlacklist() {
729 $blacklist = array();
730 $message = wfMsgForContent( 'filename-prefix-blacklist' );
731 if( $message && !( wfEmptyMsg( 'filename-prefix-blacklist', $message ) ||
$message == '-' ) ) {
732 $lines = explode( "\n", $message );
733 foreach( $lines as $line ) {
734 // Remove comment lines
735 $comment = substr( trim( $line ), 0, 1 );
736 if ( $comment == '#' ||
$comment == '' ) {
739 // Remove additional comments after a prefix
740 $comment = strpos( $line, '#' );
741 if ( $comment > 0 ) {
742 $line = substr( $line, 0, $comment-1 );
744 $blacklist[] = trim( $line );
751 * Stash a file in a temporary directory for later processing
752 * after the user has confirmed it.
754 * If the user doesn't explicitly cancel or accept, these files
755 * can accumulate in the temp directory.
757 * @param string $saveName - the destination filename
758 * @param string $tempName - the source temporary file to save
759 * @return string - full path the stashed file, or false on failure
762 function saveTempUploadedFile( $saveName, $tempName ) {
764 $repo = RepoGroup
::singleton()->getLocalRepo();
765 $status = $repo->storeTemp( $saveName, $tempName );
766 if ( !$status->isGood() ) {
767 $this->showError( $status->getWikiText() );
770 return $status->value
;
775 * Stash a file in a temporary directory for later processing,
776 * and save the necessary descriptive info into the session.
777 * Returns a key value which will be passed through a form
778 * to pick up the path info on a later invocation.
783 function stashSession() {
784 $stash = $this->saveTempUploadedFile( $this->mDestName
, $this->mTempPath
);
787 # Couldn't save the file.
791 $key = mt_rand( 0, 0x7fffffff );
792 $_SESSION['wsUploadData'][$key] = array(
793 'mTempPath' => $stash,
794 'mFileSize' => $this->mFileSize
,
795 'mSrcName' => $this->mSrcName
,
796 'mFileProps' => $this->mFileProps
,
797 'version' => self
::SESSION_VERSION
,
803 * Remove a temporarily kept file stashed by saveTempUploadedFile().
807 function unsaveUploadedFile() {
809 $repo = RepoGroup
::singleton()->getLocalRepo();
810 $success = $repo->freeTemp( $this->mTempPath
);
812 $wgOut->showFileDeleteError( $this->mTempPath
);
819 /* -------------------------------------------------------------- */
822 * @param string $error as HTML
825 function uploadError( $error ) {
827 $wgOut->addHTML( "<h2>" . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
828 $wgOut->addHTML( "<span class='error'>{$error}</span>\n" );
832 * There's something wrong with this file, not enough to reject it
833 * totally but we require manual intervention to save it for real.
834 * Stash it away, then present a form asking to confirm or cancel.
836 * @param string $warning as HTML
839 function uploadWarning( $warning ) {
840 global $wgOut, $wgContLang;
841 global $wgUseCopyrightUpload;
843 $this->mSessionKey
= $this->stashSession();
844 if( !$this->mSessionKey
) {
845 # Couldn't save file; an error has been displayed so let's go.
849 $wgOut->addHTML( "<h2>" . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
850 $wgOut->addHTML( "<ul class='warning'>{$warning}</ul><br />\n" );
852 $save = wfMsgHtml( 'savefile' );
853 $reupload = wfMsgHtml( 'reupload' );
854 $iw = wfMsgWikiHtml( 'ignorewarning' );
855 $reup = wfMsgWikiHtml( 'reuploaddesc' );
856 $titleObj = SpecialPage
::getTitleFor( 'Upload' );
857 $action = $titleObj->escapeLocalURL( 'action=submit' );
858 $align1 = $wgContLang->isRTL() ?
'left' : 'right';
859 $align2 = $wgContLang->isRTL() ?
'right' : 'left';
861 if ( $wgUseCopyrightUpload )
864 <input type='hidden' name='wpUploadCopyStatus' value=\"" . htmlspecialchars( $this->mCopyrightStatus
) . "\" />
865 <input type='hidden' name='wpUploadSource' value=\"" . htmlspecialchars( $this->mCopyrightSource
) . "\" />
872 <form id='uploadwarning' method='post' enctype='multipart/form-data' action='$action'>
873 <input type='hidden' name='wpIgnoreWarning' value='1' />
874 <input type='hidden' name='wpSessionKey' value=\"" . htmlspecialchars( $this->mSessionKey
) . "\" />
875 <input type='hidden' name='wpUploadDescription' value=\"" . htmlspecialchars( $this->mComment
) . "\" />
876 <input type='hidden' name='wpLicense' value=\"" . htmlspecialchars( $this->mLicense
) . "\" />
877 <input type='hidden' name='wpDestFile' value=\"" . htmlspecialchars( $this->mDesiredDestName
) . "\" />
878 <input type='hidden' name='wpWatchthis' value=\"" . htmlspecialchars( intval( $this->mWatchthis
) ) . "\" />
884 <input tabindex='2' type='submit' name='wpUpload' value=\"$save\" />
886 <td align='$align2'>$iw</td>
890 <input tabindex='2' type='submit' name='wpReUpload' value=\"{$reupload}\" />
892 <td align='$align2'>$reup</td>
895 </table></form>\n" );
899 * Displays the main upload form, optionally with a highlighted
900 * error message up at the top.
902 * @param string $msg as HTML
905 function mainUploadForm( $msg='' ) {
906 global $wgOut, $wgUser, $wgContLang;
907 global $wgUseCopyrightUpload, $wgUseAjax, $wgAjaxUploadDestCheck, $wgAjaxLicensePreview;
908 global $wgRequest, $wgAllowCopyUploads;
909 global $wgStylePath, $wgStyleVersion;
911 $useAjaxDestCheck = $wgUseAjax && $wgAjaxUploadDestCheck;
912 $useAjaxLicensePreview = $wgUseAjax && $wgAjaxLicensePreview;
914 $adc = wfBoolToStr( $useAjaxDestCheck );
915 $alp = wfBoolToStr( $useAjaxLicensePreview );
917 $wgOut->addScript( "<script type=\"text/javascript\">
918 wgAjaxUploadDestCheck = {$adc};
919 wgAjaxLicensePreview = {$alp};
921 <script type=\"text/javascript\" src=\"{$wgStylePath}/common/upload.js?{$wgStyleVersion}\"></script>
924 if( !wfRunHooks( 'UploadForm:initial', array( &$this ) ) )
926 wfDebug( "Hook 'UploadForm:initial' broke output of the upload form" );
930 if( $this->mDesiredDestName
) {
931 $title = Title
::makeTitleSafe( NS_IMAGE
, $this->mDesiredDestName
);
932 // Show a subtitle link to deleted revisions (to sysops et al only)
933 if( $title instanceof Title
&& ( $count = $title->isDeleted() ) > 0 && $wgUser->isAllowed( 'deletedhistory' ) ) {
935 $wgUser->isAllowed( 'delete' ) ?
'thisisdeleted' : 'viewdeleted',
936 array( 'parse', 'replaceafter' ),
937 $wgUser->getSkin()->makeKnownLinkObj(
938 SpecialPage
::getTitleFor( 'Undelete', $title->getPrefixedText() ),
939 wfMsgExt( 'restorelink', array( 'parsemag', 'escape' ), $count )
942 $wgOut->addHtml( "<div id=\"contentSub2\">{$link}</div>" );
945 // Show the relevant lines from deletion log (for still deleted files only)
946 if( $title instanceof Title
&& $title->isDeleted() > 0 && !$title->exists() ) {
947 $this->showDeletionLog( $wgOut, $title->getPrefixedText() );
951 $cols = intval($wgUser->getOption( 'cols' ));
953 if( $wgUser->getOption( 'editwidth' ) ) {
954 $width = " style=\"width:100%\"";
960 $sub = wfMsgHtml( 'uploaderror' );
961 $wgOut->addHTML( "<h2>{$sub}</h2>\n" .
962 "<span class='error'>{$msg}</span>\n" );
964 $wgOut->addHTML( '<div id="uploadtext">' );
965 $wgOut->addWikiText( wfMsgNoTrans( 'uploadtext', $this->mDesiredDestName
) );
966 $wgOut->addHTML( "</div>\n" );
968 # Print a list of allowed file extensions, if so configured. We ignore
969 # MIME type here, it's incomprehensible to most people and too long.
970 global $wgCheckFileExtensions, $wgStrictFileExtensions,
971 $wgFileExtensions, $wgFileBlacklist;
972 if( $wgCheckFileExtensions ) {
973 $delim = wfMsgExt( 'filetype-separator', array( 'escapenoentities' ) );
974 if( $wgStrictFileExtensions ) {
975 # Everything not permitted is banned
977 '<div id="mw-upload-permitted">' .
978 wfMsgWikiHtml( 'upload-permitted', implode( $wgFileExtensions, $delim ) ) .
982 # We have to list both preferred and prohibited
984 '<div id="mw-upload-preferred">' .
985 wfMsgWikiHtml( 'upload-preferred', implode( $wgFileExtensions, $delim ) ) .
987 '<div id="mw-upload-prohibited">' .
988 wfMsgWikiHtml( 'upload-prohibited', implode( $wgFileBlacklist, $delim ) ) .
994 $sourcefilename = wfMsgHtml( 'sourcefilename' );
995 $destfilename = wfMsgHtml( 'destfilename' );
996 $summary = wfMsgExt( 'fileuploadsummary', 'parseinline' );
998 $licenses = new Licenses();
999 $license = wfMsgExt( 'license', array( 'parseinline' ) );
1000 $nolicense = wfMsgHtml( 'nolicense' );
1001 $licenseshtml = $licenses->getHtml();
1003 $ulb = wfMsgHtml( 'uploadbtn' );
1006 $titleObj = SpecialPage
::getTitleFor( 'Upload' );
1007 $action = $titleObj->escapeLocalURL();
1009 $encDestName = htmlspecialchars( $this->mDesiredDestName
);
1012 ( $wgUser->getOption( 'watchdefault' ) ||
1013 ( $wgUser->getOption( 'watchcreations' ) && $this->mDesiredDestName
== '' ) )
1014 ?
'checked="checked"'
1016 $warningChecked = $this->mIgnoreWarning ?
'checked' : '';
1018 // Prepare form for upload or upload/copy
1019 if( $wgAllowCopyUploads && $wgUser->isAllowed( 'upload_by_url' ) ) {
1021 "<input type='radio' id='wpSourceTypeFile' name='wpSourceType' value='file' " .
1022 "onchange='toggle_element_activation(\"wpUploadFileURL\",\"wpUploadFile\")' checked />" .
1023 "<input tabindex='1' type='file' name='wpUploadFile' id='wpUploadFile' " .
1025 "toggle_element_activation(\"wpUploadFileURL\",\"wpUploadFile\");" .
1026 "toggle_element_check(\"wpSourceTypeFile\",\"wpSourceTypeURL\")'" .
1027 ($this->mDesiredDestName?
"":"onchange='fillDestFilename(\"wpUploadFile\")' ") . "size='40' />" .
1028 wfMsgHTML( 'upload_source_file' ) . "<br/>" .
1029 "<input type='radio' id='wpSourceTypeURL' name='wpSourceType' value='web' " .
1030 "onchange='toggle_element_activation(\"wpUploadFile\",\"wpUploadFileURL\")' />" .
1031 "<input tabindex='1' type='text' name='wpUploadFileURL' id='wpUploadFileURL' " .
1033 "toggle_element_activation(\"wpUploadFile\",\"wpUploadFileURL\");" .
1034 "toggle_element_check(\"wpSourceTypeURL\",\"wpSourceTypeFile\")'" .
1035 ($this->mDesiredDestName?
"":"onchange='fillDestFilename(\"wpUploadFileURL\")' ") . "size='40' DISABLED />" .
1036 wfMsgHtml( 'upload_source_url' ) ;
1039 "<input tabindex='1' type='file' name='wpUploadFile' id='wpUploadFile' " .
1040 ($this->mDesiredDestName?
"":"onchange='fillDestFilename(\"wpUploadFile\")' ") .
1042 "<input type='hidden' name='wpSourceType' value='file' />" ;
1044 if ( $useAjaxDestCheck ) {
1045 $warningRow = "<tr><td colspan='2' id='wpDestFile-warning'> </td></tr>";
1046 $destOnkeyup = 'onkeyup="wgUploadWarningObj.keypress();"';
1052 $encComment = htmlspecialchars( $this->mComment
);
1053 $align1 = $wgContLang->isRTL() ?
'left' : 'right';
1054 $align2 = $wgContLang->isRTL() ?
'right' : 'left';
1056 $wgOut->addHTML( <<<EOT
1057 <form id='upload' method='post' enctype='multipart/form-data' action="$action">
1060 {$this->uploadFormTextTop}
1061 <td align='$align1' valign='top'><label for='wpUploadFile'>{$sourcefilename}:</label></td>
1062 <td align='$align2'>
1067 <td align='$align1'><label for='wpDestFile'>{$destfilename}:</label></td>
1068 <td align='$align2'>
1069 <input tabindex='2' type='text' name='wpDestFile' id='wpDestFile' size='40'
1070 value="$encDestName" $destOnkeyup />
1074 <td align='$align1'><label for='wpUploadDescription'>{$summary}</label></td>
1075 <td align='$align2'>
1076 <textarea tabindex='3' name='wpUploadDescription' id='wpUploadDescription' rows='6'
1077 cols='{$cols}'{$width}>$encComment</textarea>
1078 {$this->uploadFormTextAfterSummary}
1085 if ( $licenseshtml != '' ) {
1086 global $wgStylePath;
1088 <td align='$align1'><label for='wpLicense'>$license:</label></td>
1089 <td align='$align2'>
1090 <select name='wpLicense' id='wpLicense' tabindex='4'
1091 onchange='licenseSelectorCheck()'>
1092 <option value=''>$nolicense</option>
1098 if( $useAjaxLicensePreview ) {
1101 <td id=\"mw-license-preview\"></td>
1107 if ( $wgUseCopyrightUpload ) {
1108 $filestatus = wfMsgHtml ( 'filestatus' );
1109 $copystatus = htmlspecialchars( $this->mCopyrightStatus
);
1110 $filesource = wfMsgHtml ( 'filesource' );
1111 $uploadsource = htmlspecialchars( $this->mCopyrightSource
);
1114 <td align='$align1' nowrap='nowrap'><label for='wpUploadCopyStatus'>$filestatus:</label></td>
1115 <td><input tabindex='5' type='text' name='wpUploadCopyStatus' id='wpUploadCopyStatus'
1116 value=\"$copystatus\" size='40' /></td>
1119 <td align='$align1'><label for='wpUploadCopyStatus'>$filesource:</label></td>
1120 <td><input tabindex='6' type='text' name='wpUploadSource' id='wpUploadCopyStatus'
1121 value=\"$uploadsource\" size='40' /></td>
1130 <input tabindex='7' type='checkbox' name='wpWatchthis' id='wpWatchthis' $watchChecked value='true' />
1131 <label for='wpWatchthis'>" . wfMsgHtml( 'watchthisupload' ) . "</label>
1132 <input tabindex='8' type='checkbox' name='wpIgnoreWarning' id='wpIgnoreWarning' value='true' $warningChecked/>
1133 <label for='wpIgnoreWarning'>" . wfMsgHtml( 'ignorewarnings' ) . "</label>
1139 <td align='$align2'><input tabindex='9' type='submit' name='wpUpload' value=\"{$ulb}\"" . $wgUser->getSkin()->tooltipAndAccesskey( 'upload' ) . " /></td>
1143 <td align='$align2'>
1145 $wgOut->addWikiText( wfMsgForContent( 'edittools' ) );
1151 <input type='hidden' name='wpDestFileWarningAck' id='wpDestFileWarningAck' value=''/>
1155 /* -------------------------------------------------------------- */
1158 * Split a file into a base name and all dot-delimited 'extensions'
1159 * on the end. Some web server configurations will fall back to
1160 * earlier pseudo-'extensions' to determine type and execute
1161 * scripts, so the blacklist needs to check them all.
1165 function splitExtensions( $filename ) {
1166 $bits = explode( '.', $filename );
1167 $basename = array_shift( $bits );
1168 return array( $basename, $bits );
1172 * Perform case-insensitive match against a list of file extensions.
1173 * Returns true if the extension is in the list.
1175 * @param string $ext
1176 * @param array $list
1179 function checkFileExtension( $ext, $list ) {
1180 return in_array( strtolower( $ext ), $list );
1184 * Perform case-insensitive match against a list of file extensions.
1185 * Returns true if any of the extensions are in the list.
1188 * @param array $list
1191 function checkFileExtensionList( $ext, $list ) {
1192 foreach( $ext as $e ) {
1193 if( in_array( strtolower( $e ), $list ) ) {
1201 * Verifies that it's ok to include the uploaded file
1203 * @param string $tmpfile the full path of the temporary file to verify
1204 * @param string $extension The filename extension that the file is to be served with
1205 * @return mixed true of the file is verified, a WikiError object otherwise.
1207 function verify( $tmpfile, $extension ) {
1208 #magically determine mime type
1209 $magic=& MimeMagic
::singleton();
1210 $mime= $magic->guessMimeType($tmpfile,false);
1212 #check mime type, if desired
1213 global $wgVerifyMimeType;
1214 if ($wgVerifyMimeType) {
1216 wfDebug ( "\n\nmime: <$mime> extension: <$extension>\n\n");
1217 #check mime type against file extension
1218 if( !$this->verifyExtension( $mime, $extension ) ) {
1219 return new WikiErrorMsg( 'uploadcorrupt' );
1222 #check mime type blacklist
1223 global $wgMimeTypeBlacklist;
1224 if( isset($wgMimeTypeBlacklist) && !is_null($wgMimeTypeBlacklist)
1225 && $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
1226 return new WikiErrorMsg( 'filetype-badmime', htmlspecialchars( $mime ) );
1230 #check for htmlish code and javascript
1231 if( $this->detectScript ( $tmpfile, $mime, $extension ) ) {
1232 return new WikiErrorMsg( 'uploadscripted' );
1236 * Scan the uploaded file for viruses
1238 $virus= $this->detectVirus($tmpfile);
1240 return new WikiErrorMsg( 'uploadvirus', htmlspecialchars($virus) );
1243 wfDebug( __METHOD__
.": all clear; passing.\n" );
1248 * Checks if the mime type of the uploaded file matches the file extension.
1250 * @param string $mime the mime type of the uploaded file
1251 * @param string $extension The filename extension that the file is to be served with
1254 function verifyExtension( $mime, $extension ) {
1255 $magic =& MimeMagic
::singleton();
1257 if ( ! $mime ||
$mime == 'unknown' ||
$mime == 'unknown/unknown' )
1258 if ( ! $magic->isRecognizableExtension( $extension ) ) {
1259 wfDebug( __METHOD__
.": passing file with unknown detected mime type; " .
1260 "unrecognized extension '$extension', can't verify\n" );
1263 wfDebug( __METHOD__
.": rejecting file with unknown detected mime type; ".
1264 "recognized extension '$extension', so probably invalid file\n" );
1268 $match= $magic->isMatchingExtension($extension,$mime);
1270 if ($match===NULL) {
1271 wfDebug( __METHOD__
.": no file extension known for mime type $mime, passing file\n" );
1273 } elseif ($match===true) {
1274 wfDebug( __METHOD__
.": mime type $mime matches extension $extension, passing file\n" );
1276 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
1280 wfDebug( __METHOD__
.": mime type $mime mismatches file extension $extension, rejecting file\n" );
1286 * Heuristic for detecting files that *could* contain JavaScript instructions or
1287 * things that may look like HTML to a browser and are thus
1288 * potentially harmful. The present implementation will produce false positives in some situations.
1290 * @param string $file Pathname to the temporary upload file
1291 * @param string $mime The mime type of the file
1292 * @param string $extension The extension of the file
1293 * @return bool true if the file contains something looking like embedded scripts
1295 function detectScript($file, $mime, $extension) {
1296 global $wgAllowTitlesInSVG;
1298 #ugly hack: for text files, always look at the entire file.
1299 #For binarie field, just check the first K.
1301 if (strpos($mime,'text/')===0) $chunk = file_get_contents( $file );
1303 $fp = fopen( $file, 'rb' );
1304 $chunk = fread( $fp, 1024 );
1308 $chunk= strtolower( $chunk );
1310 if (!$chunk) return false;
1312 #decode from UTF-16 if needed (could be used for obfuscation).
1313 if (substr($chunk,0,2)=="\xfe\xff") $enc= "UTF-16BE";
1314 elseif (substr($chunk,0,2)=="\xff\xfe") $enc= "UTF-16LE";
1317 if ($enc) $chunk= iconv($enc,"ASCII//IGNORE",$chunk);
1319 $chunk= trim($chunk);
1321 #FIXME: convert from UTF-16 if necessarry!
1323 wfDebug("SpecialUpload::detectScript: checking for embedded scripts and HTML stuff\n");
1325 #check for HTML doctype
1326 if (eregi("<!DOCTYPE *X?HTML",$chunk)) return true;
1329 * Internet Explorer for Windows performs some really stupid file type
1330 * autodetection which can cause it to interpret valid image files as HTML
1331 * and potentially execute JavaScript, creating a cross-site scripting
1334 * Apple's Safari browser also performs some unsafe file type autodetection
1335 * which can cause legitimate files to be interpreted as HTML if the
1336 * web server is not correctly configured to send the right content-type
1337 * (or if you're really uploading plain text and octet streams!)
1339 * Returns true if IE is likely to mistake the given file for HTML.
1340 * Also returns true if Safari would mistake the given file for HTML
1341 * when served with a generic content-type.
1347 '<html', #also in safari
1350 '<script', #also in safari
1353 if( ! $wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
1357 foreach( $tags as $tag ) {
1358 if( false !== strpos( $chunk, $tag ) ) {
1364 * look for javascript
1367 #resolve entity-refs to look at attributes. may be harsh on big files... cache result?
1368 $chunk = Sanitizer
::decodeCharReferences( $chunk );
1370 #look for script-types
1371 if (preg_match('!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim',$chunk)) return true;
1373 #look for html-style script-urls
1374 if (preg_match('!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim',$chunk)) return true;
1376 #look for css-style script-urls
1377 if (preg_match('!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim',$chunk)) return true;
1379 wfDebug("SpecialUpload::detectScript: no scripts found\n");
1384 * Generic wrapper function for a virus scanner program.
1385 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
1386 * $wgAntivirusRequired may be used to deny upload if the scan fails.
1388 * @param string $file Pathname to the temporary upload file
1389 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
1390 * or a string containing feedback from the virus scanner if a virus was found.
1391 * If textual feedback is missing but a virus was found, this function returns true.
1393 function detectVirus($file) {
1394 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
1396 if ( !$wgAntivirus ) {
1397 wfDebug( __METHOD__
.": virus scanner disabled\n");
1401 if ( !$wgAntivirusSetup[$wgAntivirus] ) {
1402 wfDebug( __METHOD__
.": unknown virus scanner: $wgAntivirus\n" );
1404 $wgOut->addHTML( "<div class='error'>Bad configuration: unknown virus scanner: <i>$wgAntivirus</i></div>\n" );
1405 return "unknown antivirus: $wgAntivirus";
1408 # look up scanner configuration
1409 $command = $wgAntivirusSetup[$wgAntivirus]["command"];
1410 $exitCodeMap = $wgAntivirusSetup[$wgAntivirus]["codemap"];
1411 $msgPattern = isset( $wgAntivirusSetup[$wgAntivirus]["messagepattern"] ) ?
1412 $wgAntivirusSetup[$wgAntivirus]["messagepattern"] : null;
1414 if ( strpos( $command,"%f" ) === false ) {
1415 # simple pattern: append file to scan
1416 $command .= " " . wfEscapeShellArg( $file );
1418 # complex pattern: replace "%f" with file to scan
1419 $command = str_replace( "%f", wfEscapeShellArg( $file ), $command );
1422 wfDebug( __METHOD__
.": running virus scan: $command \n" );
1424 # execute virus scanner
1427 #NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
1428 # that does not seem to be worth the pain.
1429 # Ask me (Duesentrieb) about it if it's ever needed.
1431 if ( wfIsWindows() ) {
1432 exec( "$command", $output, $exitCode );
1434 exec( "$command 2>&1", $output, $exitCode );
1437 # map exit code to AV_xxx constants.
1438 $mappedCode = $exitCode;
1439 if ( $exitCodeMap ) {
1440 if ( isset( $exitCodeMap[$exitCode] ) ) {
1441 $mappedCode = $exitCodeMap[$exitCode];
1442 } elseif ( isset( $exitCodeMap["*"] ) ) {
1443 $mappedCode = $exitCodeMap["*"];
1447 if ( $mappedCode === AV_SCAN_FAILED
) {
1448 # scan failed (code was mapped to false by $exitCodeMap)
1449 wfDebug( __METHOD__
.": failed to scan $file (code $exitCode).\n" );
1451 if ( $wgAntivirusRequired ) {
1452 return "scan failed (code $exitCode)";
1456 } else if ( $mappedCode === AV_SCAN_ABORTED
) {
1457 # scan failed because filetype is unknown (probably imune)
1458 wfDebug( __METHOD__
.": unsupported file type $file (code $exitCode).\n" );
1460 } else if ( $mappedCode === AV_NO_VIRUS
) {
1462 wfDebug( __METHOD__
.": file passed virus scan.\n" );
1465 $output = join( "\n", $output );
1466 $output = trim( $output );
1469 $output = true; #if there's no output, return true
1470 } elseif ( $msgPattern ) {
1472 if ( preg_match( $msgPattern, $output, $groups ) ) {
1474 $output = $groups[1];
1479 wfDebug( __METHOD__
.": FOUND VIRUS! scanner feedback: $output" );
1485 * Check if the temporary file is MacBinary-encoded, as some uploads
1486 * from Internet Explorer on Mac OS Classic and Mac OS X will be.
1487 * If so, the data fork will be extracted to a second temporary file,
1488 * which will then be checked for validity and either kept or discarded.
1492 function checkMacBinary() {
1493 $macbin = new MacBinary( $this->mTempPath
);
1494 if( $macbin->isValid() ) {
1495 $dataFile = tempnam( wfTempDir(), "WikiMacBinary" );
1496 $dataHandle = fopen( $dataFile, 'wb' );
1498 wfDebug( "SpecialUpload::checkMacBinary: Extracting MacBinary data fork to $dataFile\n" );
1499 $macbin->extractData( $dataHandle );
1501 $this->mTempPath
= $dataFile;
1502 $this->mFileSize
= $macbin->dataForkLength();
1504 // We'll have to manually remove the new file if it's not kept.
1505 $this->mRemoveTempFile
= true;
1511 * If we've modified the upload file we need to manually remove it
1512 * on exit to clean up.
1515 function cleanupTempFile() {
1516 if ( $this->mRemoveTempFile
&& file_exists( $this->mTempPath
) ) {
1517 wfDebug( "SpecialUpload::cleanupTempFile: Removing temporary file {$this->mTempPath}\n" );
1518 unlink( $this->mTempPath
);
1523 * Check if there's an overwrite conflict and, if so, if restrictions
1524 * forbid this user from performing the upload.
1526 * @return mixed true on success, WikiError on failure
1529 function checkOverwrite( $name ) {
1530 $img = wfFindFile( $name );
1534 global $wgUser, $wgOut;
1535 if( $img->isLocal() ) {
1536 if( !self
::userCanReUpload( $wgUser, $img->name
) ) {
1537 $error = 'fileexists-forbidden';
1540 if( !$wgUser->isAllowed( 'reupload' ) ||
1541 !$wgUser->isAllowed( 'reupload-shared' ) ) {
1542 $error = "fileexists-shared-forbidden";
1548 $errorText = wfMsg( $error, wfEscapeWikiText( $img->getName() ) );
1552 // Rockin', go ahead and upload
1557 * Check if a user is the last uploader
1560 * @param string $img, image name
1563 public static function userCanReUpload( User
$user, $img ) {
1564 if( $user->isAllowed( 'reupload' ) )
1565 return true; // non-conditional
1566 if( !$user->isAllowed( 'reupload-own' ) )
1569 $dbr = wfGetDB( DB_SLAVE
);
1570 $row = $dbr->selectRow('image',
1571 /* SELECT */ 'img_user',
1572 /* WHERE */ array( 'img_name' => $img )
1577 return $user->getID() == $row->img_user
;
1581 * Display an error with a wikitext description
1583 function showError( $description ) {
1585 $wgOut->setPageTitle( wfMsg( "internalerror" ) );
1586 $wgOut->setRobotpolicy( "noindex,nofollow" );
1587 $wgOut->setArticleRelated( false );
1588 $wgOut->enableClientCache( false );
1589 $wgOut->addWikiText( $description );
1593 * Get the initial image page text based on a comment and optional file status information
1595 static function getInitialPageText( $comment, $license, $copyStatus, $source ) {
1596 global $wgUseCopyrightUpload;
1597 if ( $wgUseCopyrightUpload ) {
1598 if ( $license != '' ) {
1599 $licensetxt = '== ' . wfMsgForContent( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1601 $pageText = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $comment . "\n" .
1602 '== ' . wfMsgForContent ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
1604 '== ' . wfMsgForContent ( 'filesource' ) . " ==\n" . $source ;
1606 if ( $license != '' ) {
1607 $filedesc = $comment == '' ?
'' : '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $comment . "\n";
1608 $pageText = $filedesc .
1609 '== ' . wfMsgForContent ( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1611 $pageText = $comment;
1618 * If there are rows in the deletion log for this file, show them,
1619 * along with a nice little note for the user
1621 * @param OutputPage $out
1622 * @param string filename
1624 private function showDeletionLog( $out, $filename ) {
1625 $reader = new LogReader(
1628 'page' => $filename,
1633 if( $reader->hasRows() ) {
1634 $out->addHtml( '<div id="mw-upload-deleted-warn">' );
1635 $out->addWikiText( wfMsg( 'upload-wasdeleted' ) );
1636 $viewer = new LogViewer( $reader );
1637 $viewer->showList( $out );
1638 $out->addHtml( '</div>' );