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 $pathParts = explode( '/', $url );
145 $this->mSrcName
= array_pop( $pathParts );
146 $this->mSessionKey
= false;
147 $this->mStashed
= false;
149 // PHP won't auto-cleanup the file
150 $this->mRemoveTempFile
= file_exists( $local_file );
155 * Returns true if there was an error, false otherwise
157 private function curlCopy( $url, $dest ) {
158 global $wgUser, $wgOut;
160 if( !$wgUser->isAllowed( 'upload_by_url' ) ) {
161 $wgOut->permissionRequired( 'upload_by_url' );
165 # Maybe remove some pasting blanks :-)
167 if( stripos($url, 'http://') !== 0 && stripos($url, 'ftp://') !== 0 ) {
168 # Only HTTP or FTP URLs
169 $wgOut->showErrorPage( 'upload-proto-error', 'upload-proto-error-text' );
173 # Open temporary file
174 $this->mCurlDestHandle
= @fopen
( $this->mTempPath
, "wb" );
175 if( $this->mCurlDestHandle
=== false ) {
176 # Could not open temporary file to write in
177 $wgOut->showErrorPage( 'upload-file-error', 'upload-file-error-text');
182 curl_setopt( $ch, CURLOPT_HTTP_VERSION
, 1.0); # Probably not needed, but apparently can work around some bug
183 curl_setopt( $ch, CURLOPT_TIMEOUT
, 10); # 10 seconds timeout
184 curl_setopt( $ch, CURLOPT_LOW_SPEED_LIMIT
, 512); # 0.5KB per second minimum transfer speed
185 curl_setopt( $ch, CURLOPT_URL
, $url);
186 curl_setopt( $ch, CURLOPT_WRITEFUNCTION
, array( $this, 'uploadCurlCallback' ) );
188 $error = curl_errno( $ch ) ?
true : false;
189 $errornum = curl_errno( $ch );
190 // if ( $error ) print curl_error ( $ch ) ; # Debugging output
193 fclose( $this->mCurlDestHandle
);
194 unset( $this->mCurlDestHandle
);
197 if( wfEmptyMsg( "upload-curl-error$errornum", wfMsg("upload-curl-error$errornum") ) )
198 $wgOut->showErrorPage( 'upload-misc-error', 'upload-misc-error-text' );
200 $wgOut->showErrorPage( "upload-curl-error$errornum", "upload-curl-error$errornum-text" );
207 * Callback function for CURL-based web transfer
208 * Write data to file unless we've passed the length limit;
209 * if so, abort immediately.
212 function uploadCurlCallback( $ch, $data ) {
213 global $wgMaxUploadSize;
214 $length = strlen( $data );
215 $this->mFileSize +
= $length;
216 if( $this->mFileSize
> $wgMaxUploadSize ) {
219 fwrite( $this->mCurlDestHandle
, $data );
228 global $wgUser, $wgOut;
229 global $wgEnableUploads;
231 # Check uploading enabled
232 if( !$wgEnableUploads ) {
233 $wgOut->showErrorPage( 'uploaddisabled', 'uploaddisabledtext', array( $this->mDesiredDestName
) );
238 if( !$wgUser->isAllowed( 'upload' ) ) {
239 if( !$wgUser->isLoggedIn() ) {
240 $wgOut->showErrorPage( 'uploadnologin', 'uploadnologintext' );
242 $wgOut->permissionRequired( 'upload' );
248 if( $wgUser->isBlocked() ) {
249 $wgOut->blockedPage();
254 $wgOut->readOnlyPage();
258 if( $this->mReUpload
) {
259 if( !$this->unsaveUploadedFile() ) {
262 $this->mainUploadForm();
263 } else if( 'submit' == $this->mAction ||
$this->mUploadClicked
) {
264 $this->processUpload();
266 $this->mainUploadForm();
269 $this->cleanupTempFile();
274 * Checks are made in SpecialUpload::execute()
278 function processUpload(){
279 global $wgUser, $wgOut, $wgFileExtensions;
282 $value = $this->internalProcessUpload( $details );
286 $wgOut->redirect( $this->mLocalFile
->getTitle()->getFullURL() );
289 case self
::BEFORE_PROCESSING
:
292 case self
::LARGE_FILE_SERVER
:
293 $this->mainUploadForm( wfMsgHtml( 'largefileserver' ) );
296 case self
::EMPTY_FILE
:
297 $this->mainUploadForm( wfMsgHtml( 'emptyfile' ) );
300 case self
::MIN_LENGHT_PARTNAME
:
301 $this->mainUploadForm( wfMsgHtml( 'minlength1' ) );
304 case self
::ILLEGAL_FILENAME
:
305 $filtered = $details['filtered'];
306 $this->uploadError( wfMsgWikiHtml( 'illegalfilename', htmlspecialchars( $filtered ) ) );
309 case self
::PROTECTED_PAGE
:
310 $this->uploadError( wfMsgWikiHtml( 'protectedpage' ) );
313 case self
::OVERWRITE_EXISTING_FILE
:
314 $errorText = $details['overwrite'];
315 $overwrite = new WikiError( $wgOut->parse( $errorText ) );
316 $this->uploadError( $overwrite->toString() );
319 case self
::FILETYPE_MISSING
:
320 $this->uploadError( wfMsgExt( 'filetype-missing', array ( 'parseinline' ) ) );
323 case self
::FILETYPE_BADTYPE
:
324 $finalExt = $details['finalExt'];
326 wfMsgExt( 'filetype-banned-type',
327 array( 'parseinline' ),
328 htmlspecialchars( $finalExt ),
330 wfMsgExt( 'comma-separator', array( 'escapenoentities' ) ),
337 case self
::VERIFICATION_ERROR
:
338 $veri = $details['veri'];
339 $this->uploadError( $veri->toString() );
342 case self
::UPLOAD_VERIFICATION_ERROR
:
343 $error = $details['error'];
344 $this->uploadError( $error );
347 case self
::UPLOAD_WARNING
:
348 $warning = $details['warning'];
349 $this->uploadWarning( $warning );
352 case self
::INTERNAL_ERROR
:
353 $internal = $details['internal'];
354 $this->showError( $internal );
358 throw new MWException( __METHOD__
. ": Unknown value `{$value}`" );
363 * Really do the upload
364 * Checks are made in SpecialUpload::execute()
366 * @param array $resultDetails contains result-specific dict of additional values
370 function internalProcessUpload( &$resultDetails ) {
373 if( !wfRunHooks( 'UploadForm:BeforeProcessing', array( &$this ) ) )
375 wfDebug( "Hook 'UploadForm:BeforeProcessing' broke processing the file." );
376 return self
::BEFORE_PROCESSING
;
380 * If there was no filename or a zero size given, give up quick.
382 if( trim( $this->mSrcName
) == '' ||
empty( $this->mFileSize
) ) {
383 return self
::EMPTY_FILE
;
386 /* Check for curl error */
387 if( $this->mCurlError
) {
388 return self
::BEFORE_PROCESSING
;
391 # Chop off any directories in the given filename
392 if( $this->mDesiredDestName
) {
393 $basename = $this->mDesiredDestName
;
395 $basename = $this->mSrcName
;
397 $filtered = wfBaseName( $basename );
400 * We'll want to blacklist against *any* 'extension', and use
401 * only the final one for the whitelist.
403 list( $partname, $ext ) = $this->splitExtensions( $filtered );
405 if( count( $ext ) ) {
406 $finalExt = $ext[count( $ext ) - 1];
411 # If there was more than one "extension", reassemble the base
412 # filename to prevent bogus complaints about length
413 if( count( $ext ) > 1 ) {
414 for( $i = 0; $i < count( $ext ) - 1; $i++
)
415 $partname .= '.' . $ext[$i];
418 if( strlen( $partname ) < 1 ) {
419 return self
::MIN_LENGHT_PARTNAME
;
423 * Filter out illegal characters, and try to make a legible name
424 * out of it. We'll strip some silently that Title would die on.
426 $filtered = preg_replace ( "/[^".Title
::legalChars()."]|:/", '-', $filtered );
427 $nt = Title
::makeTitleSafe( NS_IMAGE
, $filtered );
428 if( is_null( $nt ) ) {
429 $resultDetails = array( 'filtered' => $filtered );
430 return self
::ILLEGAL_FILENAME
;
432 $this->mLocalFile
= wfLocalFile( $nt );
433 $this->mDestName
= $this->mLocalFile
->getName();
436 * If the image is protected, non-sysop users won't be able
437 * to modify it by uploading a new revision.
439 if( !$nt->userCan( 'edit' ) ||
!$nt->userCan( 'create' ) ) {
440 return self
::PROTECTED_PAGE
;
444 * In some cases we may forbid overwriting of existing files.
446 $overwrite = $this->checkOverwrite( $this->mDestName
);
447 if( $overwrite !== true ) {
448 $resultDetails = array( 'overwrite' => $overwrite );
449 return self
::OVERWRITE_EXISTING_FILE
;
452 /* Don't allow users to override the blacklist (check file extension) */
453 global $wgStrictFileExtensions;
454 global $wgFileExtensions, $wgFileBlacklist;
455 if ($finalExt == '') {
456 return self
::FILETYPE_MISSING
;
457 } elseif ( $this->checkFileExtensionList( $ext, $wgFileBlacklist ) ||
458 ($wgStrictFileExtensions && !$this->checkFileExtension( $finalExt, $wgFileExtensions ) ) ) {
459 $resultDetails = array( 'finalExt' => $finalExt );
460 return self
::FILETYPE_BADTYPE
;
464 * Look at the contents of the file; if we can recognize the
465 * type but it's corrupt or data of the wrong type, we should
466 * probably not accept it.
468 if( !$this->mStashed
) {
469 $this->mFileProps
= File
::getPropsFromPath( $this->mTempPath
, $finalExt );
470 $this->checkMacBinary();
471 $veri = $this->verify( $this->mTempPath
, $finalExt );
473 if( $veri !== true ) { //it's a wiki error...
474 $resultDetails = array( 'veri' => $veri );
475 return self
::VERIFICATION_ERROR
;
479 * Provide an opportunity for extensions to add further checks
482 if( !wfRunHooks( 'UploadVerification',
483 array( $this->mDestName
, $this->mTempPath
, &$error ) ) ) {
484 $resultDetails = array( 'error' => $error );
485 return self
::UPLOAD_VERIFICATION_ERROR
;
491 * Check for non-fatal conditions
493 if ( ! $this->mIgnoreWarning
) {
496 global $wgCapitalLinks;
497 if( $wgCapitalLinks ) {
498 $filtered = ucfirst( $filtered );
500 if( $basename != $filtered ) {
501 $warning .= '<li>'.wfMsgHtml( 'badfilename', htmlspecialchars( $this->mDestName
) ).'</li>';
504 global $wgCheckFileExtensions;
505 if ( $wgCheckFileExtensions ) {
506 if ( !$this->checkFileExtension( $finalExt, $wgFileExtensions ) ) {
508 wfMsgExt( 'filetype-unwanted-type',
509 array( 'parseinline' ),
510 htmlspecialchars( $finalExt ),
512 wfMsgExt( 'comma-separator', array( 'escapenoentities' ) ),
519 global $wgUploadSizeWarning;
520 if ( $wgUploadSizeWarning && ( $this->mFileSize
> $wgUploadSizeWarning ) ) {
521 $skin = $wgUser->getSkin();
522 $wsize = $skin->formatSize( $wgUploadSizeWarning );
523 $asize = $skin->formatSize( $this->mFileSize
);
524 $warning .= '<li>' . wfMsgHtml( 'large-file', $wsize, $asize ) . '</li>';
526 if ( $this->mFileSize
== 0 ) {
527 $warning .= '<li>'.wfMsgHtml( 'emptyfile' ).'</li>';
530 if ( !$this->mDestWarningAck
) {
531 $warning .= self
::getExistsWarning( $this->mLocalFile
);
533 if( $warning != '' ) {
535 * Stash the file in a temporary location; the user can choose
536 * to let it through and we'll complete the upload then.
538 $resultDetails = array( 'warning' => $warning );
539 return self
::UPLOAD_WARNING
;
544 * Try actually saving the thing...
545 * It will show an error form on failure.
547 $pageText = self
::getInitialPageText( $this->mComment
, $this->mLicense
,
548 $this->mCopyrightStatus
, $this->mCopyrightSource
);
550 $status = $this->mLocalFile
->upload( $this->mTempPath
, $this->mComment
, $pageText,
551 File
::DELETE_SOURCE
, $this->mFileProps
);
552 if ( !$status->isGood() ) {
553 $resultDetails = array( 'internal' => $status->getWikiText() );
554 return self
::INTERNAL_ERROR
;
556 if ( $this->mWatchthis
) {
558 $wgUser->addWatch( $this->mLocalFile
->getTitle() );
560 // Success, redirect to description page
561 $img = null; // @todo: added to avoid passing a ref to null - should this be defined somewhere?
562 wfRunHooks( 'UploadComplete', array( &$this ) );
563 return self
::SUCCESS
;
568 * Do existence checks on a file and produce a warning
569 * This check is static and can be done pre-upload via AJAX
570 * Returns an HTML fragment consisting of one or more LI elements if there is a warning
571 * Returns an empty string if there is no warning
573 static function getExistsWarning( $file ) {
574 global $wgUser, $wgContLang;
575 // Check for uppercase extension. We allow these filenames but check if an image
576 // with lowercase extension exists already
578 $align = $wgContLang->isRtl() ?
'left' : 'right';
580 if( strpos( $file->getName(), '.' ) == false ) {
581 $partname = $file->getName();
584 $n = strrpos( $file->getName(), '.' );
585 $rawExtension = substr( $file->getName(), $n +
1 );
586 $partname = substr( $file->getName(), 0, $n );
589 $sk = $wgUser->getSkin();
591 if ( $rawExtension != $file->getExtension() ) {
592 // We're not using the normalized form of the extension.
593 // Normal form is lowercase, using most common of alternate
594 // extensions (eg 'jpg' rather than 'JPEG').
596 // Check for another file using the normalized form...
597 $nt_lc = Title
::newFromText( $partname . '.' . $file->getExtension() );
598 $file_lc = wfLocalFile( $nt_lc );
603 if( $file->exists() ) {
604 $dlink = $sk->makeKnownLinkObj( $file->getTitle() );
605 if ( $file->allowInlineDisplay() ) {
606 $dlink2 = $sk->makeImageLinkObj( $file->getTitle(), wfMsgExt( 'fileexists-thumb', 'parseinline' ),
607 $file->getName(), $align, array(), false, true );
608 } elseif ( !$file->allowInlineDisplay() && $file->isSafeFile() ) {
609 $icon = $file->iconThumb();
610 $dlink2 = '<div style="float:' . $align . '" id="mw-media-icon">' .
611 $icon->toHtml( array( 'desc-link' => true ) ) . '<br />' . $dlink . '</div>';
616 $warning .= '<li>' . wfMsgExt( 'fileexists', array('parseinline','replaceafter'), $dlink ) . '</li>' . $dlink2;
618 } elseif( $file->getTitle()->getArticleID() ) {
619 $lnk = $sk->makeKnownLinkObj( $file->getTitle(), '', 'redirect=no' );
620 $warning .= '<li>' . wfMsgExt( 'filepageexists', array( 'parseinline', 'replaceafter' ), $lnk ) . '</li>';
621 } elseif ( $file_lc && $file_lc->exists() ) {
622 # Check if image with lowercase extension exists.
623 # It's not forbidden but in 99% it makes no sense to upload the same filename with uppercase extension
624 $dlink = $sk->makeKnownLinkObj( $nt_lc );
625 if ( $file_lc->allowInlineDisplay() ) {
626 $dlink2 = $sk->makeImageLinkObj( $nt_lc, wfMsgExt( 'fileexists-thumb', 'parseinline' ),
627 $nt_lc->getText(), $align, array(), false, true );
628 } elseif ( !$file_lc->allowInlineDisplay() && $file_lc->isSafeFile() ) {
629 $icon = $file_lc->iconThumb();
630 $dlink2 = '<div style="float:' . $align . '" id="mw-media-icon">' .
631 $icon->toHtml( array( 'desc-link' => true ) ) . '<br />' . $dlink . '</div>';
636 $warning .= '<li>' . wfMsgExt( 'fileexists-extension', 'parsemag', $file->getName(), $dlink ) . '</li>' . $dlink2;
638 } elseif ( ( substr( $partname , 3, 3 ) == 'px-' ||
substr( $partname , 2, 3 ) == 'px-' )
639 && ereg( "[0-9]{2}" , substr( $partname , 0, 2) ) )
641 # Check for filenames like 50px- or 180px-, these are mostly thumbnails
642 $nt_thb = Title
::newFromText( substr( $partname , strpos( $partname , '-' ) +
1 ) . '.' . $rawExtension );
643 $file_thb = wfLocalFile( $nt_thb );
644 if ($file_thb->exists() ) {
645 # Check if an image without leading '180px-' (or similiar) exists
646 $dlink = $sk->makeKnownLinkObj( $nt_thb);
647 if ( $file_thb->allowInlineDisplay() ) {
648 $dlink2 = $sk->makeImageLinkObj( $nt_thb,
649 wfMsgExt( 'fileexists-thumb', 'parseinline' ),
650 $nt_thb->getText(), $align, array(), false, true );
651 } elseif ( !$file_thb->allowInlineDisplay() && $file_thb->isSafeFile() ) {
652 $icon = $file_thb->iconThumb();
653 $dlink2 = '<div style="float:' . $align . '" id="mw-media-icon">' .
654 $icon->toHtml( array( 'desc-link' => true ) ) . '<br />' .
660 $warning .= '<li>' . wfMsgExt( 'fileexists-thumbnail-yes', 'parsemag', $dlink ) .
663 # Image w/o '180px-' does not exists, but we do not like these filenames
664 $warning .= '<li>' . wfMsgExt( 'file-thumbnail-no', 'parseinline' ,
665 substr( $partname , 0, strpos( $partname , '-' ) +
1 ) ) . '</li>';
669 $filenamePrefixBlacklist = self
::getFilenamePrefixBlacklist();
671 foreach( $filenamePrefixBlacklist as $prefix ) {
672 if ( substr( $partname, 0, strlen( $prefix ) ) == $prefix ) {
673 $warning .= '<li>' . wfMsgExt( 'filename-bad-prefix', 'parseinline', $prefix ) . '</li>';
678 if ( $file->wasDeleted() && !$file->exists() ) {
679 # If the file existed before and was deleted, warn the user of this
680 # Don't bother doing so if the file exists now, however
681 $ltitle = SpecialPage
::getTitleFor( 'Log' );
682 $llink = $sk->makeKnownLinkObj( $ltitle, wfMsgHtml( 'deletionlog' ),
683 'type=delete&page=' . $file->getTitle()->getPrefixedUrl() );
684 $warning .= '<li>' . wfMsgWikiHtml( 'filewasdeleted', $llink ) . '</li>';
690 * Get a list of warnings
692 * @param string local filename, e.g. 'file exists', 'non-descriptive filename'
693 * @return array list of warning messages
695 static function ajaxGetExistsWarning( $filename ) {
696 $file = wfFindFile( $filename );
698 // Force local file so we have an object to do further checks against
699 // if there isn't an exact match...
700 $file = wfLocalFile( $filename );
704 $warning = self
::getExistsWarning( $file );
705 if ( $warning !== '' ) {
706 $s = "<ul>$warning</ul>";
713 * Render a preview of a given license for the AJAX preview on upload
715 * @param string $license
718 public static function ajaxGetLicensePreview( $license ) {
719 global $wgParser, $wgUser;
720 $text = '{{' . $license . '}}';
721 $title = Title
::makeTitle( NS_IMAGE
, 'Sample.jpg' );
722 $options = ParserOptions
::newFromUser( $wgUser );
724 // Expand subst: first, then live templates...
725 $text = $wgParser->preSaveTransform( $text, $title, $wgUser, $options );
726 $output = $wgParser->parse( $text, $title, $options );
728 return $output->getText();
732 * Get a list of blacklisted filename prefixes from [[MediaWiki:filename-prefix-blacklist]]
734 * @return array list of prefixes
736 public static function getFilenamePrefixBlacklist() {
737 $blacklist = array();
738 $message = wfMsgForContent( 'filename-prefix-blacklist' );
739 if( $message && !( wfEmptyMsg( 'filename-prefix-blacklist', $message ) ||
$message == '-' ) ) {
740 $lines = explode( "\n", $message );
741 foreach( $lines as $line ) {
742 // Remove comment lines
743 $comment = substr( trim( $line ), 0, 1 );
744 if ( $comment == '#' ||
$comment == '' ) {
747 // Remove additional comments after a prefix
748 $comment = strpos( $line, '#' );
749 if ( $comment > 0 ) {
750 $line = substr( $line, 0, $comment-1 );
752 $blacklist[] = trim( $line );
759 * Stash a file in a temporary directory for later processing
760 * after the user has confirmed it.
762 * If the user doesn't explicitly cancel or accept, these files
763 * can accumulate in the temp directory.
765 * @param string $saveName - the destination filename
766 * @param string $tempName - the source temporary file to save
767 * @return string - full path the stashed file, or false on failure
770 function saveTempUploadedFile( $saveName, $tempName ) {
772 $repo = RepoGroup
::singleton()->getLocalRepo();
773 $status = $repo->storeTemp( $saveName, $tempName );
774 if ( !$status->isGood() ) {
775 $this->showError( $status->getWikiText() );
778 return $status->value
;
783 * Stash a file in a temporary directory for later processing,
784 * and save the necessary descriptive info into the session.
785 * Returns a key value which will be passed through a form
786 * to pick up the path info on a later invocation.
791 function stashSession() {
792 $stash = $this->saveTempUploadedFile( $this->mDestName
, $this->mTempPath
);
795 # Couldn't save the file.
799 $key = mt_rand( 0, 0x7fffffff );
800 $_SESSION['wsUploadData'][$key] = array(
801 'mTempPath' => $stash,
802 'mFileSize' => $this->mFileSize
,
803 'mSrcName' => $this->mSrcName
,
804 'mFileProps' => $this->mFileProps
,
805 'version' => self
::SESSION_VERSION
,
811 * Remove a temporarily kept file stashed by saveTempUploadedFile().
815 function unsaveUploadedFile() {
817 $repo = RepoGroup
::singleton()->getLocalRepo();
818 $success = $repo->freeTemp( $this->mTempPath
);
820 $wgOut->showFileDeleteError( $this->mTempPath
);
827 /* -------------------------------------------------------------- */
830 * @param string $error as HTML
833 function uploadError( $error ) {
835 $wgOut->addHTML( Xml
::element( 'h2', null, wfMsg( 'uploadwarning' ) . "\n" ) );
836 $wgOut->addHTML( Xml
::tags( 'span', array( 'class' => 'error' ), $error ) );
840 * There's something wrong with this file, not enough to reject it
841 * totally but we require manual intervention to save it for real.
842 * Stash it away, then present a form asking to confirm or cancel.
844 * @param string $warning as HTML
847 function uploadWarning( $warning ) {
849 global $wgUseCopyrightUpload;
851 $this->mSessionKey
= $this->stashSession();
852 if( !$this->mSessionKey
) {
853 # Couldn't save file; an error has been displayed so let's go.
857 $wgOut->addHTML( Xml
::element( 'h2', null, wfMsg( 'uploadwarning' ) ) . "\n" );
858 $wgOut->addHTML( Xml
::tags( 'ul', array( 'class' => 'warning' ), $warning ) . "\n" );
860 $titleObj = SpecialPage
::getTitleFor( 'Upload' );
862 if ( $wgUseCopyrightUpload ) {
863 $copyright = Xml
::hidden( 'wpUploadCopyStatus', $this->mCopyrightStatus
) . "\n" .
864 Xml
::hidden( 'wpUploadSource', $this->mCopyrightSource
) . "\n";
870 Xml
::openElement( 'form', array( 'method' => 'post', 'action' => $titleObj->getLocalURL( 'action=submit' ),
871 'enctype' => 'multipart/form-data', 'id' => 'uploadwarning' ) ) . "\n" .
872 Xml
::hidden( 'wpIgnoreWarning', '1' ) . "\n" .
873 Xml
::hidden( 'wpSessionKey', $this->mSessionKey
) . "\n" .
874 Xml
::hidden( 'wpUploadDescription', $this->mComment
) . "\n" .
875 Xml
::hidden( 'wpLicense', $this->mLicense
) . "\n" .
876 Xml
::hidden( 'wpDestFile', $this->mDesiredDestName
) . "\n" .
877 Xml
::hidden( 'wpWatchthis', $this->mWatchthis
) . "\n" .
878 "{$copyright}<br />" .
879 Xml
::submitButton( wfMsg( 'ignorewarning' ), array ( 'name' => 'wpUpload', 'id' => 'wpUpload', 'checked' => 'checked' ) ) . ' ' .
880 Xml
::submitButton( wfMsg( 'reuploaddesc' ), array ( 'name' => 'wpReUpload', 'id' => 'wpReUpload' ) ) .
881 Xml
::closeElement( 'form' ) . "\n"
886 * Displays the main upload form, optionally with a highlighted
887 * error message up at the top.
889 * @param string $msg as HTML
892 function mainUploadForm( $msg='' ) {
893 global $wgOut, $wgUser, $wgLang, $wgMaxUploadSize;
894 global $wgUseCopyrightUpload, $wgUseAjax, $wgAjaxUploadDestCheck, $wgAjaxLicensePreview;
895 global $wgRequest, $wgAllowCopyUploads;
896 global $wgStylePath, $wgStyleVersion;
898 $useAjaxDestCheck = $wgUseAjax && $wgAjaxUploadDestCheck;
899 $useAjaxLicensePreview = $wgUseAjax && $wgAjaxLicensePreview;
901 $adc = wfBoolToStr( $useAjaxDestCheck );
902 $alp = wfBoolToStr( $useAjaxLicensePreview );
903 $autofill = wfBoolToStr( $this->mDesiredDestName
== '' );
905 $wgOut->addScript( "<script type=\"text/javascript\">
906 wgAjaxUploadDestCheck = {$adc};
907 wgAjaxLicensePreview = {$alp};
908 wgUploadAutoFill = {$autofill};
910 <script type=\"text/javascript\" src=\"{$wgStylePath}/common/upload.js?{$wgStyleVersion}\"></script>
913 if( !wfRunHooks( 'UploadForm:initial', array( &$this ) ) )
915 wfDebug( "Hook 'UploadForm:initial' broke output of the upload form" );
919 if( $this->mDesiredDestName
) {
920 $title = Title
::makeTitleSafe( NS_IMAGE
, $this->mDesiredDestName
);
921 // Show a subtitle link to deleted revisions (to sysops et al only)
922 if( $title instanceof Title
&& ( $count = $title->isDeleted() ) > 0 && $wgUser->isAllowed( 'deletedhistory' ) ) {
924 $wgUser->isAllowed( 'delete' ) ?
'thisisdeleted' : 'viewdeleted',
925 array( 'parse', 'replaceafter' ),
926 $wgUser->getSkin()->makeKnownLinkObj(
927 SpecialPage
::getTitleFor( 'Undelete', $title->getPrefixedText() ),
928 wfMsgExt( 'restorelink', array( 'parsemag', 'escape' ), $count )
931 $wgOut->addHtml( "<div id=\"contentSub2\">{$link}</div>" );
934 // Show the relevant lines from deletion log (for still deleted files only)
935 if( $title instanceof Title
&& $title->isDeleted() > 0 && !$title->exists() ) {
936 $this->showDeletionLog( $wgOut, $title->getPrefixedText() );
940 $cols = intval($wgUser->getOption( 'cols' ));
942 if( $wgUser->getOption( 'editwidth' ) ) {
943 $width = " style=\"width:100%\"";
949 $sub = wfMsgHtml( 'uploaderror' );
950 $wgOut->addHTML( "<h2>{$sub}</h2>\n" .
951 "<span class='error'>{$msg}</span>\n" );
953 $wgOut->addHTML( '<div id="uploadtext">' );
954 $wgOut->addWikiMsg( 'uploadtext', $this->mDesiredDestName
);
955 $wgOut->addHTML( "</div>\n" );
957 # Print a list of allowed file extensions, if so configured. We ignore
958 # MIME type here, it's incomprehensible to most people and too long.
959 global $wgCheckFileExtensions, $wgStrictFileExtensions,
960 $wgFileExtensions, $wgFileBlacklist;
962 $allowedExtensions = '';
963 if( $wgCheckFileExtensions ) {
964 $delim = wfMsgExt( 'comma-separator', array( 'escapenoentities' ) );
965 if( $wgStrictFileExtensions ) {
966 # Everything not permitted is banned
968 '<div id="mw-upload-permitted">' .
969 wfMsgWikiHtml( 'upload-permitted', implode( $wgFileExtensions, $delim ) ) .
972 # We have to list both preferred and prohibited
974 '<div id="mw-upload-preferred">' .
975 wfMsgWikiHtml( 'upload-preferred', implode( $wgFileExtensions, $delim ) ) .
977 '<div id="mw-upload-prohibited">' .
978 wfMsgWikiHtml( 'upload-prohibited', implode( $wgFileBlacklist, $delim ) ) .
983 # Get the maximum file size from php.ini as $wgMaxUploadSize works for uploads from URL via CURL only
984 # See http://www.php.net/manual/en/ini.core.php#ini.upload-max-filesize for possible values of upload_max_filesize
985 $val = trim( ini_get( 'upload_max_filesize' ) );
986 $last = strtoupper( ( substr( $val, -1 ) ) );
989 $val2 = substr( $val, 0, -1 ) * 1024 * 1024 * 1024;
992 $val2 = substr( $val, 0, -1 ) * 1024 * 1024;
995 $val2 = substr( $val, 0, -1 ) * 1024;
1000 $val2 = $wgAllowCopyUploads ?
min( $wgMaxUploadSize, $val2 ) : $val2;
1001 $maxUploadSize = wfMsgExt( 'upload-maxfilesize', array( 'parseinline', 'escapenoentities' ), $wgLang->formatSize( $val2 ) );
1003 $sourcefilename = wfMsgExt( 'sourcefilename', 'escapenoentities' );
1004 $destfilename = wfMsgExt( 'destfilename', 'escapenoentities' );
1005 $summary = wfMsgExt( 'fileuploadsummary', 'parseinline' );
1007 $licenses = new Licenses();
1008 $license = wfMsgExt( 'license', array( 'parseinline' ) );
1009 $nolicense = wfMsgHtml( 'nolicense' );
1010 $licenseshtml = $licenses->getHtml();
1012 $ulb = wfMsgHtml( 'uploadbtn' );
1015 $titleObj = SpecialPage
::getTitleFor( 'Upload' );
1017 $encDestName = htmlspecialchars( $this->mDesiredDestName
);
1020 ( $wgUser->getOption( 'watchdefault' ) ||
$wgUser->getOption( 'watchcreations' ) )
1021 ?
'checked="checked"'
1023 $warningChecked = $this->mIgnoreWarning ?
'checked' : '';
1025 // Prepare form for upload or upload/copy
1026 if( $wgAllowCopyUploads && $wgUser->isAllowed( 'upload_by_url' ) ) {
1028 "<input type='radio' id='wpSourceTypeFile' name='wpSourceType' value='file' " .
1029 "onchange='toggle_element_activation(\"wpUploadFileURL\",\"wpUploadFile\")' checked='checked' />" .
1030 "<input tabindex='1' type='file' name='wpUploadFile' id='wpUploadFile' " .
1032 "toggle_element_activation(\"wpUploadFileURL\",\"wpUploadFile\");" .
1033 "toggle_element_check(\"wpSourceTypeFile\",\"wpSourceTypeURL\")' " .
1034 "onchange='fillDestFilename(\"wpUploadFile\")' size='60' />" .
1035 wfMsgHTML( 'upload_source_file' ) . "<br/>" .
1036 "<input type='radio' id='wpSourceTypeURL' name='wpSourceType' value='web' " .
1037 "onchange='toggle_element_activation(\"wpUploadFile\",\"wpUploadFileURL\")' />" .
1038 "<input tabindex='1' type='text' name='wpUploadFileURL' id='wpUploadFileURL' " .
1040 "toggle_element_activation(\"wpUploadFile\",\"wpUploadFileURL\");" .
1041 "toggle_element_check(\"wpSourceTypeURL\",\"wpSourceTypeFile\")' " .
1042 "onchange='fillDestFilename(\"wpUploadFileURL\")' size='60' disabled='disabled' />" .
1043 wfMsgHtml( 'upload_source_url' ) ;
1046 "<input tabindex='1' type='file' name='wpUploadFile' id='wpUploadFile' " .
1047 ($this->mDesiredDestName?
"":"onchange='fillDestFilename(\"wpUploadFile\")' ") .
1049 "<input type='hidden' name='wpSourceType' value='file' />" ;
1051 if ( $useAjaxDestCheck ) {
1052 $warningRow = "<tr><td colspan='2' id='wpDestFile-warning'> </td></tr>";
1053 $destOnkeyup = 'onkeyup="wgUploadWarningObj.keypress();"';
1059 $encComment = htmlspecialchars( $this->mComment
);
1062 Xml
::openElement( 'form', array( 'method' => 'post', 'action' => $titleObj->getLocalURL(),
1063 'enctype' => 'multipart/form-data', 'id' => 'mw-upload-form' ) ) .
1064 Xml
::openElement( 'fieldset' ) .
1065 Xml
::element( 'legend', null, wfMsg( 'upload' ) ) .
1066 Xml
::openElement( 'table', array( 'border' => '0', 'id' => 'mw-upload-table' ) ) .
1068 {$this->uploadFormTextTop}
1069 <td class='mw-label'>
1070 <label for='wpUploadFile'>{$sourcefilename}</label>
1072 <td class='mw-input'>
1084 <td class='mw-label'>
1085 <label for='wpDestFile'>{$destfilename}</label>
1087 <td class='mw-input'>
1088 <input tabindex='2' type='text' name='wpDestFile' id='wpDestFile' size='60'
1089 value=\"{$encDestName}\" onchange='toggleFilenameFiller()' $destOnkeyup />
1093 <td class='mw-label'>
1094 <label for='wpUploadDescription'>{$summary}</label>
1096 <td class='mw-input'>
1097 <textarea tabindex='3' name='wpUploadDescription' id='wpUploadDescription' rows='6'
1098 cols='{$cols}'{$width}>$encComment</textarea>
1099 {$this->uploadFormTextAfterSummary}
1105 if ( $licenseshtml != '' ) {
1106 global $wgStylePath;
1108 <td class='mw-label'>
1109 <label for='wpLicense'>$license</label>
1111 <td class='mw-input'>
1112 <select name='wpLicense' id='wpLicense' tabindex='4'
1113 onchange='licenseSelectorCheck()'>
1114 <option value=''>$nolicense</option>
1121 if( $useAjaxLicensePreview ) {
1124 <td id=\"mw-license-preview\"></td>
1131 if ( $wgUseCopyrightUpload ) {
1132 $filestatus = wfMsgExt( 'filestatus', 'escapenoentities' );
1133 $copystatus = htmlspecialchars( $this->mCopyrightStatus
);
1134 $filesource = wfMsgExt( 'filesource', 'escapenoentities' );
1135 $uploadsource = htmlspecialchars( $this->mCopyrightSource
);
1138 <td class='mw-label' style='white-space: nowrap;'>
1139 <label for='wpUploadCopyStatus'>$filestatus</label></td>
1140 <td class='mw-input'>
1141 <input tabindex='5' type='text' name='wpUploadCopyStatus' id='wpUploadCopyStatus'
1142 value=\"$copystatus\" size='60' />
1146 <td class='mw-label'>
1147 <label for='wpUploadCopyStatus'>$filesource</label>
1149 <td class='mw-input'>
1150 <input tabindex='6' type='text' name='wpUploadSource' id='wpUploadCopyStatus'
1151 value=\"$uploadsource\" size='60' />
1161 <input tabindex='7' type='checkbox' name='wpWatchthis' id='wpWatchthis' $watchChecked value='true' />
1162 <label for='wpWatchthis'>" . wfMsgHtml( 'watchthisupload' ) . "</label>
1163 <input tabindex='8' type='checkbox' name='wpIgnoreWarning' id='wpIgnoreWarning' value='true' $warningChecked/>
1164 <label for='wpIgnoreWarning'>" . wfMsgHtml( 'ignorewarnings' ) . "</label>
1170 <td class='mw-input'>
1171 <input tabindex='9' type='submit' name='wpUpload' value=\"{$ulb}\"" . $wgUser->getSkin()->tooltipAndAccesskey( 'upload' ) . " />
1176 <td class='mw-input'>"
1178 $wgOut->addWikiText( wfMsgForContent( 'edittools' ) );
1182 Xml
::closeElement( 'table' ) .
1183 Xml
::hidden( 'wpDestFileWarningAck', '', array( 'id' => 'wpDestFileWarningAck' ) ) .
1184 Xml
::closeElement( 'fieldset' ) .
1185 Xml
::closeElement( 'form' )
1187 $uploadfooter = wfMsgNoTrans( 'uploadfooter' );
1188 if( $uploadfooter != '-' && !wfEmptyMsg( 'uploadfooter', $uploadfooter ) ){
1189 $wgOut->addWikiText( Xml
::tags( 'div',
1190 array( 'id' => 'mw-upload-footer-message' ), $uploadfooter ) );
1194 /* -------------------------------------------------------------- */
1197 * Split a file into a base name and all dot-delimited 'extensions'
1198 * on the end. Some web server configurations will fall back to
1199 * earlier pseudo-'extensions' to determine type and execute
1200 * scripts, so the blacklist needs to check them all.
1204 function splitExtensions( $filename ) {
1205 $bits = explode( '.', $filename );
1206 $basename = array_shift( $bits );
1207 return array( $basename, $bits );
1211 * Perform case-insensitive match against a list of file extensions.
1212 * Returns true if the extension is in the list.
1214 * @param string $ext
1215 * @param array $list
1218 function checkFileExtension( $ext, $list ) {
1219 return in_array( strtolower( $ext ), $list );
1223 * Perform case-insensitive match against a list of file extensions.
1224 * Returns true if any of the extensions are in the list.
1227 * @param array $list
1230 function checkFileExtensionList( $ext, $list ) {
1231 foreach( $ext as $e ) {
1232 if( in_array( strtolower( $e ), $list ) ) {
1240 * Verifies that it's ok to include the uploaded file
1242 * @param string $tmpfile the full path of the temporary file to verify
1243 * @param string $extension The filename extension that the file is to be served with
1244 * @return mixed true of the file is verified, a WikiError object otherwise.
1246 function verify( $tmpfile, $extension ) {
1247 #magically determine mime type
1248 $magic = MimeMagic
::singleton();
1249 $mime = $magic->guessMimeType($tmpfile,false);
1251 #check mime type, if desired
1252 global $wgVerifyMimeType;
1253 if ($wgVerifyMimeType) {
1255 wfDebug ( "\n\nmime: <$mime> extension: <$extension>\n\n");
1256 #check mime type against file extension
1257 if( !$this->verifyExtension( $mime, $extension ) ) {
1258 return new WikiErrorMsg( 'uploadcorrupt' );
1261 #check mime type blacklist
1262 global $wgMimeTypeBlacklist;
1263 if( isset($wgMimeTypeBlacklist) && !is_null($wgMimeTypeBlacklist)
1264 && $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
1265 return new WikiErrorMsg( 'filetype-badmime', htmlspecialchars( $mime ) );
1269 #check for htmlish code and javascript
1270 if( $this->detectScript ( $tmpfile, $mime, $extension ) ) {
1271 return new WikiErrorMsg( 'uploadscripted' );
1275 * Scan the uploaded file for viruses
1277 $virus= $this->detectVirus($tmpfile);
1279 return new WikiErrorMsg( 'uploadvirus', htmlspecialchars($virus) );
1282 wfDebug( __METHOD__
.": all clear; passing.\n" );
1287 * Checks if the mime type of the uploaded file matches the file extension.
1289 * @param string $mime the mime type of the uploaded file
1290 * @param string $extension The filename extension that the file is to be served with
1293 function verifyExtension( $mime, $extension ) {
1294 $magic = MimeMagic
::singleton();
1296 if ( ! $mime ||
$mime == 'unknown' ||
$mime == 'unknown/unknown' )
1297 if ( ! $magic->isRecognizableExtension( $extension ) ) {
1298 wfDebug( __METHOD__
.": passing file with unknown detected mime type; " .
1299 "unrecognized extension '$extension', can't verify\n" );
1302 wfDebug( __METHOD__
.": rejecting file with unknown detected mime type; ".
1303 "recognized extension '$extension', so probably invalid file\n" );
1307 $match= $magic->isMatchingExtension($extension,$mime);
1309 if ($match===NULL) {
1310 wfDebug( __METHOD__
.": no file extension known for mime type $mime, passing file\n" );
1312 } elseif ($match===true) {
1313 wfDebug( __METHOD__
.": mime type $mime matches extension $extension, passing file\n" );
1315 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
1319 wfDebug( __METHOD__
.": mime type $mime mismatches file extension $extension, rejecting file\n" );
1325 * Heuristic for detecting files that *could* contain JavaScript instructions or
1326 * things that may look like HTML to a browser and are thus
1327 * potentially harmful. The present implementation will produce false positives in some situations.
1329 * @param string $file Pathname to the temporary upload file
1330 * @param string $mime The mime type of the file
1331 * @param string $extension The extension of the file
1332 * @return bool true if the file contains something looking like embedded scripts
1334 function detectScript($file, $mime, $extension) {
1335 global $wgAllowTitlesInSVG;
1337 #ugly hack: for text files, always look at the entire file.
1338 #For binarie field, just check the first K.
1340 if (strpos($mime,'text/')===0) $chunk = file_get_contents( $file );
1342 $fp = fopen( $file, 'rb' );
1343 $chunk = fread( $fp, 1024 );
1347 $chunk= strtolower( $chunk );
1349 if (!$chunk) return false;
1351 #decode from UTF-16 if needed (could be used for obfuscation).
1352 if (substr($chunk,0,2)=="\xfe\xff") $enc= "UTF-16BE";
1353 elseif (substr($chunk,0,2)=="\xff\xfe") $enc= "UTF-16LE";
1356 if ($enc) $chunk= iconv($enc,"ASCII//IGNORE",$chunk);
1358 $chunk= trim($chunk);
1360 #FIXME: convert from UTF-16 if necessarry!
1362 wfDebug("SpecialUpload::detectScript: checking for embedded scripts and HTML stuff\n");
1364 #check for HTML doctype
1365 if (eregi("<!DOCTYPE *X?HTML",$chunk)) return true;
1368 * Internet Explorer for Windows performs some really stupid file type
1369 * autodetection which can cause it to interpret valid image files as HTML
1370 * and potentially execute JavaScript, creating a cross-site scripting
1373 * Apple's Safari browser also performs some unsafe file type autodetection
1374 * which can cause legitimate files to be interpreted as HTML if the
1375 * web server is not correctly configured to send the right content-type
1376 * (or if you're really uploading plain text and octet streams!)
1378 * Returns true if IE is likely to mistake the given file for HTML.
1379 * Also returns true if Safari would mistake the given file for HTML
1380 * when served with a generic content-type.
1386 '<html', #also in safari
1389 '<script', #also in safari
1392 if( ! $wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
1396 foreach( $tags as $tag ) {
1397 if( false !== strpos( $chunk, $tag ) ) {
1403 * look for javascript
1406 #resolve entity-refs to look at attributes. may be harsh on big files... cache result?
1407 $chunk = Sanitizer
::decodeCharReferences( $chunk );
1409 #look for script-types
1410 if (preg_match('!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim',$chunk)) return true;
1412 #look for html-style script-urls
1413 if (preg_match('!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim',$chunk)) return true;
1415 #look for css-style script-urls
1416 if (preg_match('!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim',$chunk)) return true;
1418 wfDebug("SpecialUpload::detectScript: no scripts found\n");
1423 * Generic wrapper function for a virus scanner program.
1424 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
1425 * $wgAntivirusRequired may be used to deny upload if the scan fails.
1427 * @param string $file Pathname to the temporary upload file
1428 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
1429 * or a string containing feedback from the virus scanner if a virus was found.
1430 * If textual feedback is missing but a virus was found, this function returns true.
1432 function detectVirus($file) {
1433 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
1435 if ( !$wgAntivirus ) {
1436 wfDebug( __METHOD__
.": virus scanner disabled\n");
1440 if ( !$wgAntivirusSetup[$wgAntivirus] ) {
1441 wfDebug( __METHOD__
.": unknown virus scanner: $wgAntivirus\n" );
1443 $wgOut->addHTML( "<div class='error'>Bad configuration: unknown virus scanner: <i>$wgAntivirus</i></div>\n" );
1444 return "unknown antivirus: $wgAntivirus";
1447 # look up scanner configuration
1448 $command = $wgAntivirusSetup[$wgAntivirus]["command"];
1449 $exitCodeMap = $wgAntivirusSetup[$wgAntivirus]["codemap"];
1450 $msgPattern = isset( $wgAntivirusSetup[$wgAntivirus]["messagepattern"] ) ?
1451 $wgAntivirusSetup[$wgAntivirus]["messagepattern"] : null;
1453 if ( strpos( $command,"%f" ) === false ) {
1454 # simple pattern: append file to scan
1455 $command .= " " . wfEscapeShellArg( $file );
1457 # complex pattern: replace "%f" with file to scan
1458 $command = str_replace( "%f", wfEscapeShellArg( $file ), $command );
1461 wfDebug( __METHOD__
.": running virus scan: $command \n" );
1463 # execute virus scanner
1466 #NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
1467 # that does not seem to be worth the pain.
1468 # Ask me (Duesentrieb) about it if it's ever needed.
1470 if ( wfIsWindows() ) {
1471 exec( "$command", $output, $exitCode );
1473 exec( "$command 2>&1", $output, $exitCode );
1476 # map exit code to AV_xxx constants.
1477 $mappedCode = $exitCode;
1478 if ( $exitCodeMap ) {
1479 if ( isset( $exitCodeMap[$exitCode] ) ) {
1480 $mappedCode = $exitCodeMap[$exitCode];
1481 } elseif ( isset( $exitCodeMap["*"] ) ) {
1482 $mappedCode = $exitCodeMap["*"];
1486 if ( $mappedCode === AV_SCAN_FAILED
) {
1487 # scan failed (code was mapped to false by $exitCodeMap)
1488 wfDebug( __METHOD__
.": failed to scan $file (code $exitCode).\n" );
1490 if ( $wgAntivirusRequired ) {
1491 return "scan failed (code $exitCode)";
1495 } else if ( $mappedCode === AV_SCAN_ABORTED
) {
1496 # scan failed because filetype is unknown (probably imune)
1497 wfDebug( __METHOD__
.": unsupported file type $file (code $exitCode).\n" );
1499 } else if ( $mappedCode === AV_NO_VIRUS
) {
1501 wfDebug( __METHOD__
.": file passed virus scan.\n" );
1504 $output = join( "\n", $output );
1505 $output = trim( $output );
1508 $output = true; #if there's no output, return true
1509 } elseif ( $msgPattern ) {
1511 if ( preg_match( $msgPattern, $output, $groups ) ) {
1513 $output = $groups[1];
1518 wfDebug( __METHOD__
.": FOUND VIRUS! scanner feedback: $output" );
1524 * Check if the temporary file is MacBinary-encoded, as some uploads
1525 * from Internet Explorer on Mac OS Classic and Mac OS X will be.
1526 * If so, the data fork will be extracted to a second temporary file,
1527 * which will then be checked for validity and either kept or discarded.
1531 function checkMacBinary() {
1532 $macbin = new MacBinary( $this->mTempPath
);
1533 if( $macbin->isValid() ) {
1534 $dataFile = tempnam( wfTempDir(), "WikiMacBinary" );
1535 $dataHandle = fopen( $dataFile, 'wb' );
1537 wfDebug( "SpecialUpload::checkMacBinary: Extracting MacBinary data fork to $dataFile\n" );
1538 $macbin->extractData( $dataHandle );
1540 $this->mTempPath
= $dataFile;
1541 $this->mFileSize
= $macbin->dataForkLength();
1543 // We'll have to manually remove the new file if it's not kept.
1544 $this->mRemoveTempFile
= true;
1550 * If we've modified the upload file we need to manually remove it
1551 * on exit to clean up.
1554 function cleanupTempFile() {
1555 if ( $this->mRemoveTempFile
&& file_exists( $this->mTempPath
) ) {
1556 wfDebug( "SpecialUpload::cleanupTempFile: Removing temporary file {$this->mTempPath}\n" );
1557 unlink( $this->mTempPath
);
1562 * Check if there's an overwrite conflict and, if so, if restrictions
1563 * forbid this user from performing the upload.
1565 * @return mixed true on success, WikiError on failure
1568 function checkOverwrite( $name ) {
1569 $img = wfFindFile( $name );
1573 global $wgUser, $wgOut;
1574 if( $img->isLocal() ) {
1575 if( !self
::userCanReUpload( $wgUser, $img->name
) ) {
1576 $error = 'fileexists-forbidden';
1579 if( !$wgUser->isAllowed( 'reupload' ) ||
1580 !$wgUser->isAllowed( 'reupload-shared' ) ) {
1581 $error = "fileexists-shared-forbidden";
1587 $errorText = wfMsg( $error, wfEscapeWikiText( $img->getName() ) );
1591 // Rockin', go ahead and upload
1596 * Check if a user is the last uploader
1599 * @param string $img, image name
1602 public static function userCanReUpload( User
$user, $img ) {
1603 if( $user->isAllowed( 'reupload' ) )
1604 return true; // non-conditional
1605 if( !$user->isAllowed( 'reupload-own' ) )
1608 $dbr = wfGetDB( DB_SLAVE
);
1609 $row = $dbr->selectRow('image',
1610 /* SELECT */ 'img_user',
1611 /* WHERE */ array( 'img_name' => $img )
1616 return $user->getID() == $row->img_user
;
1620 * Display an error with a wikitext description
1622 function showError( $description ) {
1624 $wgOut->setPageTitle( wfMsg( "internalerror" ) );
1625 $wgOut->setRobotpolicy( "noindex,nofollow" );
1626 $wgOut->setArticleRelated( false );
1627 $wgOut->enableClientCache( false );
1628 $wgOut->addWikiText( $description );
1632 * Get the initial image page text based on a comment and optional file status information
1634 static function getInitialPageText( $comment, $license, $copyStatus, $source ) {
1635 global $wgUseCopyrightUpload;
1636 if ( $wgUseCopyrightUpload ) {
1637 if ( $license != '' ) {
1638 $licensetxt = '== ' . wfMsgForContent( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1640 $pageText = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $comment . "\n" .
1641 '== ' . wfMsgForContent ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
1643 '== ' . wfMsgForContent ( 'filesource' ) . " ==\n" . $source ;
1645 if ( $license != '' ) {
1646 $filedesc = $comment == '' ?
'' : '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $comment . "\n";
1647 $pageText = $filedesc .
1648 '== ' . wfMsgForContent ( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1650 $pageText = $comment;
1657 * If there are rows in the deletion log for this file, show them,
1658 * along with a nice little note for the user
1660 * @param OutputPage $out
1661 * @param string filename
1663 private function showDeletionLog( $out, $filename ) {
1665 $loglist = new LogEventsList( $wgUser->getSkin(), $out );
1666 $pager = new LogPager( $loglist, 'delete', false, $filename );
1667 if( $pager->getNumRows() > 0 ) {
1668 $out->addHtml( '<div id="mw-upload-deleted-warn">' );
1669 $out->addWikiMsg( 'upload-wasdeleted' );
1671 $loglist->beginLogEventsList() .
1673 $loglist->endLogEventsList()
1675 $out->addHtml( '</div>' );