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;
39 var $mComment, $mLicense, $mIgnoreWarning, $mCurlError;
40 var $mDestName, $mTempPath, $mFileSize, $mFileProps;
41 var $mCopyrightStatus, $mCopyrightSource, $mReUpload, $mAction, $mUploadClicked;
42 var $mSrcName, $mSessionKey, $mStashed, $mDesiredDestName, $mRemoveTempFile, $mSourceType;
43 var $mDestWarningAck, $mCurlDestHandle;
46 # Placeholders for text injection by hooks (must be HTML)
47 # extensions should take care to _append_ to the present value
48 var $uploadFormTextTop;
49 var $uploadFormTextAfterSummary;
51 const SESSION_VERSION
= 1;
55 * Constructor : initialise object
56 * Get data POSTed through the form and assign them to the object
57 * @param $request Data posted.
59 function UploadForm( &$request ) {
60 global $wgAllowCopyUploads;
61 $this->mDesiredDestName
= $request->getText( 'wpDestFile' );
62 $this->mIgnoreWarning
= $request->getCheck( 'wpIgnoreWarning' );
63 $this->mComment
= $request->getText( 'wpUploadDescription' );
65 if( !$request->wasPosted() ) {
66 # GET requests just give the main form; no data except destination
67 # filename and description
71 # Placeholders for text injection by hooks (empty per default)
72 $this->uploadFormTextTop
= "";
73 $this->uploadFormTextAfterSummary
= "";
75 $this->mReUpload
= $request->getCheck( 'wpReUpload' );
76 $this->mUploadClicked
= $request->getCheck( 'wpUpload' );
78 $this->mLicense
= $request->getText( 'wpLicense' );
79 $this->mCopyrightStatus
= $request->getText( 'wpUploadCopyStatus' );
80 $this->mCopyrightSource
= $request->getText( 'wpUploadSource' );
81 $this->mWatchthis
= $request->getBool( 'wpWatchthis' );
82 $this->mSourceType
= $request->getText( 'wpSourceType' );
83 $this->mDestWarningAck
= $request->getText( 'wpDestFileWarningAck' );
85 $this->mAction
= $request->getVal( 'action' );
87 $this->mSessionKey
= $request->getInt( 'wpSessionKey' );
88 if( !empty( $this->mSessionKey
) &&
89 isset( $_SESSION['wsUploadData'][$this->mSessionKey
]['version'] ) &&
90 $_SESSION['wsUploadData'][$this->mSessionKey
]['version'] == self
::SESSION_VERSION
) {
92 * Confirming a temporarily stashed upload.
93 * We don't want path names to be forged, so we keep
94 * them in the session on the server and just give
95 * an opaque key to the user agent.
97 $data = $_SESSION['wsUploadData'][$this->mSessionKey
];
98 $this->mTempPath
= $data['mTempPath'];
99 $this->mFileSize
= $data['mFileSize'];
100 $this->mSrcName
= $data['mSrcName'];
101 $this->mFileProps
= $data['mFileProps'];
102 $this->mCurlError
= 0/*UPLOAD_ERR_OK*/;
103 $this->mStashed
= true;
104 $this->mRemoveTempFile
= false;
107 *Check for a newly uploaded file.
109 if( $wgAllowCopyUploads && $this->mSourceType
== 'web' ) {
110 $this->initializeFromUrl( $request );
112 $this->initializeFromUpload( $request );
118 * Initialize the uploaded file from PHP data
121 function initializeFromUpload( $request ) {
122 $this->mTempPath
= $request->getFileTempName( 'wpUploadFile' );
123 $this->mFileSize
= $request->getFileSize( 'wpUploadFile' );
124 $this->mSrcName
= $request->getFileName( 'wpUploadFile' );
125 $this->mCurlError
= $request->getUploadError( 'wpUploadFile' );
126 $this->mSessionKey
= false;
127 $this->mStashed
= false;
128 $this->mRemoveTempFile
= false; // PHP will handle this
132 * Copy a web file to a temporary file
135 function initializeFromUrl( $request ) {
136 global $wgTmpDirectory;
137 $url = $request->getText( 'wpUploadFileURL' );
138 $local_file = tempnam( $wgTmpDirectory, 'WEBUPLOAD' );
140 $this->mTempPath
= $local_file;
141 $this->mFileSize
= 0; # Will be set by curlCopy
142 $this->mCurlError
= $this->curlCopy( $url, $local_file );
143 $this->mSrcName
= array_pop( explode( '/', $url ) );
144 $this->mSessionKey
= false;
145 $this->mStashed
= false;
147 // PHP won't auto-cleanup the file
148 $this->mRemoveTempFile
= file_exists( $local_file );
153 * Returns true if there was an error, false otherwise
155 private function curlCopy( $url, $dest ) {
156 global $wgUser, $wgOut;
158 if( !$wgUser->isAllowed( 'upload_by_url' ) ) {
159 $wgOut->permissionRequired( 'upload_by_url' );
163 # Maybe remove some pasting blanks :-)
165 if( stripos($url, 'http://') !== 0 && stripos($url, 'ftp://') !== 0 ) {
166 # Only HTTP or FTP URLs
167 $wgOut->errorPage( 'upload-proto-error', 'upload-proto-error-text' );
171 # Open temporary file
172 $this->mCurlDestHandle
= @fopen
( $this->mTempPath
, "wb" );
173 if( $this->mCurlDestHandle
=== false ) {
174 # Could not open temporary file to write in
175 $wgOut->errorPage( 'upload-file-error', 'upload-file-error-text');
180 curl_setopt( $ch, CURLOPT_HTTP_VERSION
, 1.0); # Probably not needed, but apparently can work around some bug
181 curl_setopt( $ch, CURLOPT_TIMEOUT
, 10); # 10 seconds timeout
182 curl_setopt( $ch, CURLOPT_LOW_SPEED_LIMIT
, 512); # 0.5KB per second minimum transfer speed
183 curl_setopt( $ch, CURLOPT_URL
, $url);
184 curl_setopt( $ch, CURLOPT_WRITEFUNCTION
, array( $this, 'uploadCurlCallback' ) );
186 $error = curl_errno( $ch ) ?
true : false;
187 $errornum = curl_errno( $ch );
188 // if ( $error ) print curl_error ( $ch ) ; # Debugging output
191 fclose( $this->mCurlDestHandle
);
192 unset( $this->mCurlDestHandle
);
195 if( wfEmptyMsg( "upload-curl-error$errornum", wfMsg("upload-curl-error$errornum") ) )
196 $wgOut->errorPage( 'upload-misc-error', 'upload-misc-error-text' );
198 $wgOut->errorPage( "upload-curl-error$errornum", "upload-curl-error$errornum-text" );
205 * Callback function for CURL-based web transfer
206 * Write data to file unless we've passed the length limit;
207 * if so, abort immediately.
210 function uploadCurlCallback( $ch, $data ) {
211 global $wgMaxUploadSize;
212 $length = strlen( $data );
213 $this->mFileSize +
= $length;
214 if( $this->mFileSize
> $wgMaxUploadSize ) {
217 fwrite( $this->mCurlDestHandle
, $data );
226 global $wgUser, $wgOut;
227 global $wgEnableUploads;
229 # Check uploading enabled
230 if( !$wgEnableUploads ) {
231 $wgOut->showErrorPage( 'uploaddisabled', 'uploaddisabledtext', array( $this->mDesiredDestName
) );
236 if( !$wgUser->isAllowed( 'upload' ) ) {
237 if( !$wgUser->isLoggedIn() ) {
238 $wgOut->showErrorPage( 'uploadnologin', 'uploadnologintext' );
240 $wgOut->permissionRequired( 'upload' );
246 if( $wgUser->isBlocked() ) {
247 $wgOut->blockedPage();
252 $wgOut->readOnlyPage();
256 if( $this->mReUpload
) {
257 if( !$this->unsaveUploadedFile() ) {
260 $this->mainUploadForm();
261 } else if( 'submit' == $this->mAction ||
$this->mUploadClicked
) {
262 $this->processUpload();
264 $this->mainUploadForm();
267 $this->cleanupTempFile();
272 * Checks are made in SpecialUpload::execute()
276 function processUpload(){
277 global $wgUser, $wgOut, $wgFileExtensions;
280 $value = $this->internalProcessUpload( $details );
284 $wgOut->redirect( $this->mLocalFile
->getTitle()->getFullURL() );
287 case self
::BEFORE_PROCESSING
:
290 case self
::LARGE_FILE_SERVER
:
291 $this->mainUploadForm( wfMsgHtml( 'largefileserver' ) );
294 case self
::EMPTY_FILE
:
295 $this->mainUploadForm( wfMsgHtml( 'emptyfile' ) );
298 case self
::MIN_LENGHT_PARTNAME
:
299 $this->mainUploadForm( wfMsgHtml( 'minlength1' ) );
302 case self
::ILLEGAL_FILENAME
:
303 $filtered = $details['filtered'];
304 $this->uploadError( wfMsgWikiHtml( 'illegalfilename', htmlspecialchars( $filtered ) ) );
307 case self
::PROTECTED_PAGE
:
308 return $this->uploadError( wfMsgWikiHtml( 'protectedpage' ) );
310 case self
::OVERWRITE_EXISTING_FILE
:
311 $errorText = $details['overwrite'];
312 $overwrite = new WikiError( $wgOut->parse( $errorText ) );
313 return $this->uploadError( $overwrite->toString() );
315 case self
::FILETYPE_MISSING
:
316 return $this->uploadError( wfMsgExt( 'filetype-missing', array ( 'parseinline' ) ) );
318 case self
::FILETYPE_BADTYPE
:
319 $finalExt = $details['finalExt'];
320 return $this->uploadError( wfMsgExt( 'filetype-badtype', array ( 'parseinline' ), htmlspecialchars( $finalExt ), implode ( ', ', $wgFileExtensions ) ) );
322 case self
::VERIFICATION_ERROR
:
323 $veri = $details['veri'];
324 return $this->uploadError( $veri->toString() );
326 case self
::UPLOAD_VERIFICATION_ERROR
:
327 $error = $details['error'];
328 return $this->uploadError( $error );
330 case self
::UPLOAD_WARNING
:
331 $warning = $details['warning'];
332 return $this->uploadWarning( $warning );
335 /* TODO: Each case returns instead of breaking to maintain the highest level of compatibility during branch merging.
336 They should be reviewed and corrected separatelly.
338 new MWException( __METHOD__
. ": Unknown value `{$value}`" );
342 * Really do the upload
343 * Checks are made in SpecialUpload::execute()
345 * @param array $resultDetails contains result-specific dict of additional values
349 function internalProcessUpload( &$resultDetails ) {
352 if( !wfRunHooks( 'UploadForm:BeforeProcessing', array( &$this ) ) )
354 wfDebug( "Hook 'UploadForm:BeforeProcessing' broke processing the file." );
355 return self
::BEFORE_PROCESSING
;
358 /* Check for PHP error if any, requires php 4.2 or newer */
359 if( $this->mCurlError
== 1/*UPLOAD_ERR_INI_SIZE*/ ) {
360 return self
::LARGE_FILE_SERVER
;
364 * If there was no filename or a zero size given, give up quick.
366 if( trim( $this->mSrcName
) == '' ||
empty( $this->mFileSize
) ) {
367 return self
::EMPTY_FILE
;
370 # Chop off any directories in the given filename
371 if( $this->mDesiredDestName
) {
372 $basename = $this->mDesiredDestName
;
374 $basename = $this->mSrcName
;
376 $filtered = wfBaseName( $basename );
379 * We'll want to blacklist against *any* 'extension', and use
380 * only the final one for the whitelist.
382 list( $partname, $ext ) = $this->splitExtensions( $filtered );
384 if( count( $ext ) ) {
385 $finalExt = $ext[count( $ext ) - 1];
390 # If there was more than one "extension", reassemble the base
391 # filename to prevent bogus complaints about length
392 if( count( $ext ) > 1 ) {
393 for( $i = 0; $i < count( $ext ) - 1; $i++
)
394 $partname .= '.' . $ext[$i];
397 if( strlen( $partname ) < 1 ) {
398 return self
::MIN_LENGHT_PARTNAME
;
402 * Filter out illegal characters, and try to make a legible name
403 * out of it. We'll strip some silently that Title would die on.
405 $filtered = preg_replace ( "/[^".Title
::legalChars()."]|:/", '-', $filtered );
406 $nt = Title
::makeTitleSafe( NS_IMAGE
, $filtered );
407 if( is_null( $nt ) ) {
408 $resultDetails = array( 'filtered' => $filtered );
409 return self
::ILLEGAL_FILENAME
;
411 $this->mLocalFile
= wfLocalFile( $nt );
412 $this->mDestName
= $this->mLocalFile
->getName();
415 * If the image is protected, non-sysop users won't be able
416 * to modify it by uploading a new revision.
418 if( !$nt->userCan( 'edit' ) ) {
419 return self
::PROTECTED_PAGE
;
423 * In some cases we may forbid overwriting of existing files.
425 $overwrite = $this->checkOverwrite( $this->mDestName
);
426 if( $overwrite !== true ) {
427 $resultDetails = array( 'overwrite' => $overwrite );
428 return self
::OVERWRITE_EXISTING_FILE
;
431 /* Don't allow users to override the blacklist (check file extension) */
432 global $wgStrictFileExtensions;
433 global $wgFileExtensions, $wgFileBlacklist;
434 if ($finalExt == '') {
435 return self
::FILETYPE_MISSING
;
436 } elseif ( $this->checkFileExtensionList( $ext, $wgFileBlacklist ) ||
437 ($wgStrictFileExtensions && !$this->checkFileExtension( $finalExt, $wgFileExtensions ) ) ) {
438 $resultDetails = array( 'finalExt' => $finalExt );
439 return self
::FILETYPE_BADTYPE
;
443 * Look at the contents of the file; if we can recognize the
444 * type but it's corrupt or data of the wrong type, we should
445 * probably not accept it.
447 if( !$this->mStashed
) {
448 $this->mFileProps
= File
::getPropsFromPath( $this->mTempPath
, $finalExt );
449 $this->checkMacBinary();
450 $veri = $this->verify( $this->mTempPath
, $finalExt );
452 if( $veri !== true ) { //it's a wiki error...
453 $resultDetails = array( 'veri' => $veri );
454 return self
::VERIFICATION_ERROR
;
458 * Provide an opportunity for extensions to add further checks
461 if( !wfRunHooks( 'UploadVerification',
462 array( $this->mDestName
, $this->mTempPath
, &$error ) ) ) {
463 $resultDetails = array( 'error' => $error );
464 return self
::UPLOAD_VERIFICATION_ERROR
;
470 * Check for non-fatal conditions
472 if ( ! $this->mIgnoreWarning
) {
475 global $wgCapitalLinks;
476 if( $wgCapitalLinks ) {
477 $filtered = ucfirst( $filtered );
479 if( $basename != $filtered ) {
480 $warning .= '<li>'.wfMsgHtml( 'badfilename', htmlspecialchars( $this->mDestName
) ).'</li>';
483 global $wgCheckFileExtensions;
484 if ( $wgCheckFileExtensions ) {
485 if ( ! $this->checkFileExtension( $finalExt, $wgFileExtensions ) ) {
486 $warning .= '<li>'.wfMsgExt( 'filetype-badtype', array ( 'parseinline' ),
487 htmlspecialchars( $finalExt ), implode ( ', ', $wgFileExtensions ) ).'</li>';
491 global $wgUploadSizeWarning;
492 if ( $wgUploadSizeWarning && ( $this->mFileSize
> $wgUploadSizeWarning ) ) {
493 $skin = $wgUser->getSkin();
494 $wsize = $skin->formatSize( $wgUploadSizeWarning );
495 $asize = $skin->formatSize( $this->mFileSize
);
496 $warning .= '<li>' . wfMsgHtml( 'large-file', $wsize, $asize ) . '</li>';
498 if ( $this->mFileSize
== 0 ) {
499 $warning .= '<li>'.wfMsgHtml( 'emptyfile' ).'</li>';
502 if ( !$this->mDestWarningAck
) {
503 $warning .= self
::getExistsWarning( $this->mLocalFile
);
505 if( $warning != '' ) {
507 * Stash the file in a temporary location; the user can choose
508 * to let it through and we'll complete the upload then.
510 $resultDetails = array( 'warning' => $warning );
511 return self
::UPLOAD_WARNING
;
516 * Try actually saving the thing...
517 * It will show an error form on failure.
519 $pageText = self
::getInitialPageText( $this->mComment
, $this->mLicense
,
520 $this->mCopyrightStatus
, $this->mCopyrightSource
);
522 $status = $this->mLocalFile
->upload( $this->mTempPath
, $this->mComment
, $pageText,
523 File
::DELETE_SOURCE
, $this->mFileProps
);
524 if ( !$status->isGood() ) {
525 $this->showError( $status->getWikiText() );
527 if ( $this->mWatchthis
) {
529 $wgUser->addWatch( $this->mLocalFile
->getTitle() );
531 // Success, redirect to description page
532 $img = null; // @todo: added to avoid passing a ref to null - should this be defined somewhere?
533 wfRunHooks( 'UploadComplete', array( &$img ) );
534 return self
::SUCCESS
;
539 * Do existence checks on a file and produce a warning
540 * This check is static and can be done pre-upload via AJAX
541 * Returns an HTML fragment consisting of one or more LI elements if there is a warning
542 * Returns an empty string if there is no warning
544 static function getExistsWarning( $file ) {
546 // Check for uppercase extension. We allow these filenames but check if an image
547 // with lowercase extension exists already
550 if( strpos( $file->getName(), '.' ) == false ) {
551 $partname = $file->getName();
554 list( $partname, $rawExtension ) = explode( '.', $file->getName(), 2 );
556 $sk = $wgUser->getSkin();
558 if ( $rawExtension != $file->getExtension() ) {
559 // We're not using the normalized form of the extension.
560 // Normal form is lowercase, using most common of alternate
561 // extensions (eg 'jpg' rather than 'JPEG').
563 // Check for another file using the normalized form...
564 $nt_lc = Title
::newFromText( $partname . '.' . $file->getExtension() );
565 $file_lc = wfLocalFile( $nt_lc );
570 if( $file->exists() ) {
571 $dlink = $sk->makeKnownLinkObj( $file->getTitle() );
572 if ( $file->allowInlineDisplay() ) {
573 $dlink2 = $sk->makeImageLinkObj( $file->getTitle(), wfMsgExt( 'fileexists-thumb', 'parseinline', $dlink ),
574 $file->getName(), 'right', array(), false, true );
575 } elseif ( !$file->allowInlineDisplay() && $file->isSafeFile() ) {
576 $icon = $file->iconThumb();
577 $dlink2 = '<div style="float:right" id="mw-media-icon">' .
578 $icon->toHtml( array( 'desc-link' => true ) ) . '<br />' . $dlink . '</div>';
583 $warning .= '<li>' . wfMsgExt( 'fileexists', 'parseline', $dlink ) . '</li>' . $dlink2;
585 } elseif ( $file_lc && $file_lc->exists() ) {
586 # Check if image with lowercase extension exists.
587 # It's not forbidden but in 99% it makes no sense to upload the same filename with uppercase extension
588 $dlink = $sk->makeKnownLinkObj( $nt_lc );
589 if ( $file_lc->allowInlineDisplay() ) {
590 $dlink2 = $sk->makeImageLinkObj( $nt_lc, wfMsgExt( 'fileexists-thumb', 'parseinline', $dlink ),
591 $nt_lc->getText(), 'right', array(), false, true );
592 } elseif ( !$file_lc->allowInlineDisplay() && $file_lc->isSafeFile() ) {
593 $icon = $file_lc->iconThumb();
594 $dlink2 = '<div style="float:right" id="mw-media-icon">' .
595 $icon->toHtml( array( 'desc-link' => true ) ) . '<br />' . $dlink . '</div>';
600 $warning .= '<li>' . wfMsgExt( 'fileexists-extension', 'parsemag', $file->getName(), $dlink ) . '</li>' . $dlink2;
602 } elseif ( ( substr( $partname , 3, 3 ) == 'px-' ||
substr( $partname , 2, 3 ) == 'px-' )
603 && ereg( "[0-9]{2}" , substr( $partname , 0, 2) ) )
605 # Check for filenames like 50px- or 180px-, these are mostly thumbnails
606 $nt_thb = Title
::newFromText( substr( $partname , strpos( $partname , '-' ) +
1 ) . '.' . $rawExtension );
607 $file_thb = wfLocalFile( $nt_thb );
608 if ($file_thb->exists() ) {
609 # Check if an image without leading '180px-' (or similiar) exists
610 $dlink = $sk->makeKnownLinkObj( $nt_thb);
611 if ( $file_thb->allowInlineDisplay() ) {
612 $dlink2 = $sk->makeImageLinkObj( $nt_thb,
613 wfMsgExt( 'fileexists-thumb', 'parseinline', $dlink ),
614 $nt_thb->getText(), 'right', array(), false, true );
615 } elseif ( !$file_thb->allowInlineDisplay() && $file_thb->isSafeFile() ) {
616 $icon = $file_thb->iconThumb();
617 $dlink2 = '<div style="float:right" id="mw-media-icon">' .
618 $icon->toHtml( array( 'desc-link' => true ) ) . '<br />' .
624 $warning .= '<li>' . wfMsgExt( 'fileexists-thumbnail-yes', 'parsemag', $dlink ) .
627 # Image w/o '180px-' does not exists, but we do not like these filenames
628 $warning .= '<li>' . wfMsgExt( 'file-thumbnail-no', 'parseinline' ,
629 substr( $partname , 0, strpos( $partname , '-' ) +
1 ) ) . '</li>';
633 $filenamePrefixBlacklist = self
::getFilenamePrefixBlacklist();
635 foreach( $filenamePrefixBlacklist as $prefix ) {
636 if ( substr( $partname, 0, strlen( $prefix ) ) == $prefix ) {
637 $warning .= '<li>' . wfMsgExt( 'filename-bad-prefix', 'parseinline', $prefix ) . '</li>';
642 if ( $file->wasDeleted() && !$file->exists() ) {
643 # If the file existed before and was deleted, warn the user of this
644 # Don't bother doing so if the file exists now, however
645 $ltitle = SpecialPage
::getTitleFor( 'Log' );
646 $llink = $sk->makeKnownLinkObj( $ltitle, wfMsgHtml( 'deletionlog' ),
647 'type=delete&page=' . $file->getTitle()->getPrefixedUrl() );
648 $warning .= '<li>' . wfMsgWikiHtml( 'filewasdeleted', $llink ) . '</li>';
654 * Get a list of warnings
656 * @param string local filename, e.g. 'file exists', 'non-descriptive filename'
657 * @return array list of warning messages
659 static function ajaxGetExistsWarning( $filename ) {
660 $file = wfFindFile( $filename );
662 // Force local file so we have an object to do further checks against
663 // if there isn't an exact match...
664 $file = wfLocalFile( $filename );
668 $warning = self
::getExistsWarning( $file );
669 if ( $warning !== '' ) {
670 $s = "<ul>$warning</ul>";
677 * Render a preview of a given license for the AJAX preview on upload
679 * @param string $license
682 public static function ajaxGetLicensePreview( $license ) {
683 global $wgParser, $wgUser;
684 $text = '{{' . $license . '}}';
685 $title = Title
::makeTitle( NS_IMAGE
, 'Sample.jpg' );
686 $options = ParserOptions
::newFromUser( $wgUser );
688 // Expand subst: first, then live templates...
689 $text = $wgParser->preSaveTransform( $text, $title, $wgUser, $options );
690 $output = $wgParser->parse( $text, $title, $options );
692 return $output->getText();
696 * Get a list of blacklisted filename prefixes from [[MediaWiki:filename-prefix-blacklist]]
698 * @return array list of prefixes
700 public static function getFilenamePrefixBlacklist() {
701 $blacklist = array();
702 $message = wfMsgForContent( 'filename-prefix-blacklist' );
703 if( $message && !( wfEmptyMsg( 'filename-prefix-blacklist', $message ) ||
$message == '-' ) ) {
704 $lines = explode( "\n", $message );
705 foreach( $lines as $line ) {
706 // Remove comment lines
707 $comment = substr( trim( $line ), 0, 1 );
708 if ( $comment == '#' ||
$comment == '' ) {
711 // Remove additional comments after a prefix
712 $comment = strpos( $line, '#' );
713 if ( $comment > 0 ) {
714 $line = substr( $line, 0, $comment-1 );
716 $blacklist[] = trim( $line );
723 * Stash a file in a temporary directory for later processing
724 * after the user has confirmed it.
726 * If the user doesn't explicitly cancel or accept, these files
727 * can accumulate in the temp directory.
729 * @param string $saveName - the destination filename
730 * @param string $tempName - the source temporary file to save
731 * @return string - full path the stashed file, or false on failure
734 function saveTempUploadedFile( $saveName, $tempName ) {
736 $repo = RepoGroup
::singleton()->getLocalRepo();
737 $status = $repo->storeTemp( $saveName, $tempName );
738 if ( !$status->isGood() ) {
739 $this->showError( $status->getWikiText() );
742 return $status->value
;
747 * Stash a file in a temporary directory for later processing,
748 * and save the necessary descriptive info into the session.
749 * Returns a key value which will be passed through a form
750 * to pick up the path info on a later invocation.
755 function stashSession() {
756 $stash = $this->saveTempUploadedFile( $this->mDestName
, $this->mTempPath
);
759 # Couldn't save the file.
763 $key = mt_rand( 0, 0x7fffffff );
764 $_SESSION['wsUploadData'][$key] = array(
765 'mTempPath' => $stash,
766 'mFileSize' => $this->mFileSize
,
767 'mSrcName' => $this->mSrcName
,
768 'mFileProps' => $this->mFileProps
,
769 'version' => self
::SESSION_VERSION
,
775 * Remove a temporarily kept file stashed by saveTempUploadedFile().
779 function unsaveUploadedFile() {
781 $repo = RepoGroup
::singleton()->getLocalRepo();
782 $success = $repo->freeTemp( $this->mTempPath
);
784 $wgOut->showFileDeleteError( $this->mTempPath
);
791 /* -------------------------------------------------------------- */
794 * @param string $error as HTML
797 function uploadError( $error ) {
799 $wgOut->addHTML( "<h2>" . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
800 $wgOut->addHTML( "<span class='error'>{$error}</span>\n" );
804 * There's something wrong with this file, not enough to reject it
805 * totally but we require manual intervention to save it for real.
806 * Stash it away, then present a form asking to confirm or cancel.
808 * @param string $warning as HTML
811 function uploadWarning( $warning ) {
812 global $wgOut, $wgContLang;
813 global $wgUseCopyrightUpload;
815 $this->mSessionKey
= $this->stashSession();
816 if( !$this->mSessionKey
) {
817 # Couldn't save file; an error has been displayed so let's go.
821 $wgOut->addHTML( "<h2>" . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
822 $wgOut->addHTML( "<ul class='warning'>{$warning}</ul><br />\n" );
824 $save = wfMsgHtml( 'savefile' );
825 $reupload = wfMsgHtml( 'reupload' );
826 $iw = wfMsgWikiHtml( 'ignorewarning' );
827 $reup = wfMsgWikiHtml( 'reuploaddesc' );
828 $titleObj = SpecialPage
::getTitleFor( 'Upload' );
829 $action = $titleObj->escapeLocalURL( 'action=submit' );
830 $align1 = $wgContLang->isRTL() ?
'left' : 'right';
831 $align2 = $wgContLang->isRTL() ?
'right' : 'left';
833 if ( $wgUseCopyrightUpload )
836 <input type='hidden' name='wpUploadCopyStatus' value=\"" . htmlspecialchars( $this->mCopyrightStatus
) . "\" />
837 <input type='hidden' name='wpUploadSource' value=\"" . htmlspecialchars( $this->mCopyrightSource
) . "\" />
844 <form id='uploadwarning' method='post' enctype='multipart/form-data' action='$action'>
845 <input type='hidden' name='wpIgnoreWarning' value='1' />
846 <input type='hidden' name='wpSessionKey' value=\"" . htmlspecialchars( $this->mSessionKey
) . "\" />
847 <input type='hidden' name='wpUploadDescription' value=\"" . htmlspecialchars( $this->mComment
) . "\" />
848 <input type='hidden' name='wpLicense' value=\"" . htmlspecialchars( $this->mLicense
) . "\" />
849 <input type='hidden' name='wpDestFile' value=\"" . htmlspecialchars( $this->mDesiredDestName
) . "\" />
850 <input type='hidden' name='wpWatchthis' value=\"" . htmlspecialchars( intval( $this->mWatchthis
) ) . "\" />
856 <input tabindex='2' type='submit' name='wpUpload' value=\"$save\" />
858 <td align='$align2'>$iw</td>
862 <input tabindex='2' type='submit' name='wpReUpload' value=\"{$reupload}\" />
864 <td align='$align2'>$reup</td>
867 </table></form>\n" );
871 * Displays the main upload form, optionally with a highlighted
872 * error message up at the top.
874 * @param string $msg as HTML
877 function mainUploadForm( $msg='' ) {
878 global $wgOut, $wgUser, $wgContLang;
879 global $wgUseCopyrightUpload, $wgUseAjax, $wgAjaxUploadDestCheck, $wgAjaxLicensePreview;
880 global $wgRequest, $wgAllowCopyUploads;
881 global $wgStylePath, $wgStyleVersion;
883 $useAjaxDestCheck = $wgUseAjax && $wgAjaxUploadDestCheck;
884 $useAjaxLicensePreview = $wgUseAjax && $wgAjaxLicensePreview;
886 $adc = wfBoolToStr( $useAjaxDestCheck );
887 $alp = wfBoolToStr( $useAjaxLicensePreview );
889 $wgOut->addScript( "<script type=\"text/javascript\">
890 wgAjaxUploadDestCheck = {$adc};
891 wgAjaxLicensePreview = {$alp};
893 <script type=\"text/javascript\" src=\"{$wgStylePath}/common/upload.js?{$wgStyleVersion}\"></script>
896 if( !wfRunHooks( 'UploadForm:initial', array( &$this ) ) )
898 wfDebug( "Hook 'UploadForm:initial' broke output of the upload form" );
902 if( $this->mDesiredDestName
) {
903 $title = Title
::makeTitleSafe( NS_IMAGE
, $this->mDesiredDestName
);
904 // Show a subtitle link to deleted revisions (to sysops et al only)
905 if( $title instanceof Title
&& ( $count = $title->isDeleted() ) > 0 && $wgUser->isAllowed( 'deletedhistory' ) ) {
907 $wgUser->isAllowed( 'delete' ) ?
'thisisdeleted' : 'viewdeleted',
908 array( 'parse', 'replaceafter' ),
909 $wgUser->getSkin()->makeKnownLinkObj(
910 SpecialPage
::getTitleFor( 'Undelete', $title->getPrefixedText() ),
911 wfMsgExt( 'restorelink', array( 'parsemag', 'escape' ), $count )
914 $wgOut->addHtml( "<div id=\"contentSub2\">{$link}</div>" );
917 // Show the relevant lines from deletion log (for still deleted files only)
918 if( $title instanceof Title
&& $title->isDeleted() > 0 && !$title->exists() ) {
919 $this->showDeletionLog( $wgOut, $title->getPrefixedText() );
923 $cols = intval($wgUser->getOption( 'cols' ));
924 $ew = $wgUser->getOption( 'editwidth' );
925 if ( $ew ) $ew = " style=\"width:100%\"";
929 $sub = wfMsgHtml( 'uploaderror' );
930 $wgOut->addHTML( "<h2>{$sub}</h2>\n" .
931 "<span class='error'>{$msg}</span>\n" );
933 $wgOut->addHTML( '<div id="uploadtext">' );
934 $wgOut->addWikiText( wfMsgNoTrans( 'uploadtext', $this->mDesiredDestName
) );
935 $wgOut->addHTML( '</div>' );
937 $sourcefilename = wfMsgHtml( 'sourcefilename' );
938 $destfilename = wfMsgHtml( 'destfilename' );
939 $summary = wfMsgExt( 'fileuploadsummary', 'parseinline' );
941 $licenses = new Licenses();
942 $license = wfMsgExt( 'license', array( 'parseinline' ) );
943 $nolicense = wfMsgHtml( 'nolicense' );
944 $licenseshtml = $licenses->getHtml();
946 $ulb = wfMsgHtml( 'uploadbtn' );
949 $titleObj = SpecialPage
::getTitleFor( 'Upload' );
950 $action = $titleObj->escapeLocalURL();
952 $encDestName = htmlspecialchars( $this->mDesiredDestName
);
955 ( $wgUser->getOption( 'watchdefault' ) ||
956 ( $wgUser->getOption( 'watchcreations' ) && $this->mDesiredDestName
== '' ) )
957 ?
'checked="checked"'
959 $warningChecked = $this->mIgnoreWarning ?
'checked' : '';
961 // Prepare form for upload or upload/copy
962 if( $wgAllowCopyUploads && $wgUser->isAllowed( 'upload_by_url' ) ) {
964 "<input type='radio' id='wpSourceTypeFile' name='wpSourceType' value='file' " .
965 "onchange='toggle_element_activation(\"wpUploadFileURL\",\"wpUploadFile\")' checked />" .
966 "<input tabindex='1' type='file' name='wpUploadFile' id='wpUploadFile' " .
968 "toggle_element_activation(\"wpUploadFileURL\",\"wpUploadFile\");" .
969 "toggle_element_check(\"wpSourceTypeFile\",\"wpSourceTypeURL\")'" .
970 ($this->mDesiredDestName?
"":"onchange='fillDestFilename(\"wpUploadFile\")' ") . "size='40' />" .
971 wfMsgHTML( 'upload_source_file' ) . "<br/>" .
972 "<input type='radio' id='wpSourceTypeURL' name='wpSourceType' value='web' " .
973 "onchange='toggle_element_activation(\"wpUploadFile\",\"wpUploadFileURL\")' />" .
974 "<input tabindex='1' type='text' name='wpUploadFileURL' id='wpUploadFileURL' " .
976 "toggle_element_activation(\"wpUploadFile\",\"wpUploadFileURL\");" .
977 "toggle_element_check(\"wpSourceTypeURL\",\"wpSourceTypeFile\")'" .
978 ($this->mDesiredDestName?
"":"onchange='fillDestFilename(\"wpUploadFileURL\")' ") . "size='40' DISABLED />" .
979 wfMsgHtml( 'upload_source_url' ) ;
982 "<input tabindex='1' type='file' name='wpUploadFile' id='wpUploadFile' " .
983 ($this->mDesiredDestName?
"":"onchange='fillDestFilename(\"wpUploadFile\")' ") .
985 "<input type='hidden' name='wpSourceType' value='file' />" ;
987 if ( $useAjaxDestCheck ) {
988 $warningRow = "<tr><td colspan='2' id='wpDestFile-warning'> </td></tr>";
989 $destOnkeyup = 'onkeyup="wgUploadWarningObj.keypress();"';
995 $encComment = htmlspecialchars( $this->mComment
);
996 $align1 = $wgContLang->isRTL() ?
'left' : 'right';
997 $align2 = $wgContLang->isRTL() ?
'right' : 'left';
999 $wgOut->addHTML( <<<EOT
1000 <form id='upload' method='post' enctype='multipart/form-data' action="$action">
1003 {$this->uploadFormTextTop}
1004 <td align='$align1' valign='top'><label for='wpUploadFile'>{$sourcefilename}:</label></td>
1005 <td align='$align2'>
1010 <td align='$align1'><label for='wpDestFile'>{$destfilename}:</label></td>
1011 <td align='$align2'>
1012 <input tabindex='2' type='text' name='wpDestFile' id='wpDestFile' size='40'
1013 value="$encDestName" $destOnkeyup />
1017 <td align='$align1'><label for='wpUploadDescription'>{$summary}</label></td>
1018 <td align='$align2'>
1019 <textarea tabindex='3' name='wpUploadDescription' id='wpUploadDescription' rows='6'
1020 cols='{$cols}'{$ew}>$encComment</textarea>
1021 {$this->uploadFormTextAfterSummary}
1028 if ( $licenseshtml != '' ) {
1029 global $wgStylePath;
1031 <td align='$align1'><label for='wpLicense'>$license:</label></td>
1032 <td align='$align2'>
1033 <select name='wpLicense' id='wpLicense' tabindex='4'
1034 onchange='licenseSelectorCheck()'>
1035 <option value=''>$nolicense</option>
1041 if( $useAjaxLicensePreview ) {
1044 <td id=\"mw-license-preview\"></td>
1050 if ( $wgUseCopyrightUpload ) {
1051 $filestatus = wfMsgHtml ( 'filestatus' );
1052 $copystatus = htmlspecialchars( $this->mCopyrightStatus
);
1053 $filesource = wfMsgHtml ( 'filesource' );
1054 $uploadsource = htmlspecialchars( $this->mCopyrightSource
);
1057 <td align='$align1' nowrap='nowrap'><label for='wpUploadCopyStatus'>$filestatus:</label></td>
1058 <td><input tabindex='5' type='text' name='wpUploadCopyStatus' id='wpUploadCopyStatus'
1059 value=\"$copystatus\" size='40' /></td>
1062 <td align='$align1'><label for='wpUploadCopyStatus'>$filesource:</label></td>
1063 <td><input tabindex='6' type='text' name='wpUploadSource' id='wpUploadCopyStatus'
1064 value=\"$uploadsource\" size='40' /></td>
1073 <input tabindex='7' type='checkbox' name='wpWatchthis' id='wpWatchthis' $watchChecked value='true' />
1074 <label for='wpWatchthis'>" . wfMsgHtml( 'watchthisupload' ) . "</label>
1075 <input tabindex='8' type='checkbox' name='wpIgnoreWarning' id='wpIgnoreWarning' value='true' $warningChecked/>
1076 <label for='wpIgnoreWarning'>" . wfMsgHtml( 'ignorewarnings' ) . "</label>
1082 <td align='$align2'><input tabindex='9' type='submit' name='wpUpload' value=\"{$ulb}\"" . $wgUser->getSkin()->tooltipAndAccesskey( 'upload' ) . " /></td>
1086 <td align='$align2'>
1088 $wgOut->addWikiText( wfMsgForContent( 'edittools' ) );
1094 <input type='hidden' name='wpDestFileWarningAck' id='wpDestFileWarningAck' value=''/>
1098 /* -------------------------------------------------------------- */
1101 * Split a file into a base name and all dot-delimited 'extensions'
1102 * on the end. Some web server configurations will fall back to
1103 * earlier pseudo-'extensions' to determine type and execute
1104 * scripts, so the blacklist needs to check them all.
1108 function splitExtensions( $filename ) {
1109 $bits = explode( '.', $filename );
1110 $basename = array_shift( $bits );
1111 return array( $basename, $bits );
1115 * Perform case-insensitive match against a list of file extensions.
1116 * Returns true if the extension is in the list.
1118 * @param string $ext
1119 * @param array $list
1122 function checkFileExtension( $ext, $list ) {
1123 return in_array( strtolower( $ext ), $list );
1127 * Perform case-insensitive match against a list of file extensions.
1128 * Returns true if any of the extensions are in the list.
1131 * @param array $list
1134 function checkFileExtensionList( $ext, $list ) {
1135 foreach( $ext as $e ) {
1136 if( in_array( strtolower( $e ), $list ) ) {
1144 * Verifies that it's ok to include the uploaded file
1146 * @param string $tmpfile the full path of the temporary file to verify
1147 * @param string $extension The filename extension that the file is to be served with
1148 * @return mixed true of the file is verified, a WikiError object otherwise.
1150 function verify( $tmpfile, $extension ) {
1151 #magically determine mime type
1152 $magic=& MimeMagic
::singleton();
1153 $mime= $magic->guessMimeType($tmpfile,false);
1155 #check mime type, if desired
1156 global $wgVerifyMimeType;
1157 if ($wgVerifyMimeType) {
1159 wfDebug ( "\n\nmime: <$mime> extension: <$extension>\n\n");
1160 #check mime type against file extension
1161 if( !$this->verifyExtension( $mime, $extension ) ) {
1162 return new WikiErrorMsg( 'uploadcorrupt' );
1165 #check mime type blacklist
1166 global $wgMimeTypeBlacklist;
1167 if( isset($wgMimeTypeBlacklist) && !is_null($wgMimeTypeBlacklist)
1168 && $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
1169 return new WikiErrorMsg( 'filetype-badmime', htmlspecialchars( $mime ) );
1173 #check for htmlish code and javascript
1174 if( $this->detectScript ( $tmpfile, $mime, $extension ) ) {
1175 return new WikiErrorMsg( 'uploadscripted' );
1179 * Scan the uploaded file for viruses
1181 $virus= $this->detectVirus($tmpfile);
1183 return new WikiErrorMsg( 'uploadvirus', htmlspecialchars($virus) );
1186 wfDebug( __METHOD__
.": all clear; passing.\n" );
1191 * Checks if the mime type of the uploaded file matches the file extension.
1193 * @param string $mime the mime type of the uploaded file
1194 * @param string $extension The filename extension that the file is to be served with
1197 function verifyExtension( $mime, $extension ) {
1198 $magic =& MimeMagic
::singleton();
1200 if ( ! $mime ||
$mime == 'unknown' ||
$mime == 'unknown/unknown' )
1201 if ( ! $magic->isRecognizableExtension( $extension ) ) {
1202 wfDebug( __METHOD__
.": passing file with unknown detected mime type; " .
1203 "unrecognized extension '$extension', can't verify\n" );
1206 wfDebug( __METHOD__
.": rejecting file with unknown detected mime type; ".
1207 "recognized extension '$extension', so probably invalid file\n" );
1211 $match= $magic->isMatchingExtension($extension,$mime);
1213 if ($match===NULL) {
1214 wfDebug( __METHOD__
.": no file extension known for mime type $mime, passing file\n" );
1216 } elseif ($match===true) {
1217 wfDebug( __METHOD__
.": mime type $mime matches extension $extension, passing file\n" );
1219 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
1223 wfDebug( __METHOD__
.": mime type $mime mismatches file extension $extension, rejecting file\n" );
1229 * Heuristic for detecting files that *could* contain JavaScript instructions or
1230 * things that may look like HTML to a browser and are thus
1231 * potentially harmful. The present implementation will produce false positives in some situations.
1233 * @param string $file Pathname to the temporary upload file
1234 * @param string $mime The mime type of the file
1235 * @param string $extension The extension of the file
1236 * @return bool true if the file contains something looking like embedded scripts
1238 function detectScript($file, $mime, $extension) {
1239 global $wgAllowTitlesInSVG;
1241 #ugly hack: for text files, always look at the entire file.
1242 #For binarie field, just check the first K.
1244 if (strpos($mime,'text/')===0) $chunk = file_get_contents( $file );
1246 $fp = fopen( $file, 'rb' );
1247 $chunk = fread( $fp, 1024 );
1251 $chunk= strtolower( $chunk );
1253 if (!$chunk) return false;
1255 #decode from UTF-16 if needed (could be used for obfuscation).
1256 if (substr($chunk,0,2)=="\xfe\xff") $enc= "UTF-16BE";
1257 elseif (substr($chunk,0,2)=="\xff\xfe") $enc= "UTF-16LE";
1260 if ($enc) $chunk= iconv($enc,"ASCII//IGNORE",$chunk);
1262 $chunk= trim($chunk);
1264 #FIXME: convert from UTF-16 if necessarry!
1266 wfDebug("SpecialUpload::detectScript: checking for embedded scripts and HTML stuff\n");
1268 #check for HTML doctype
1269 if (eregi("<!DOCTYPE *X?HTML",$chunk)) return true;
1272 * Internet Explorer for Windows performs some really stupid file type
1273 * autodetection which can cause it to interpret valid image files as HTML
1274 * and potentially execute JavaScript, creating a cross-site scripting
1277 * Apple's Safari browser also performs some unsafe file type autodetection
1278 * which can cause legitimate files to be interpreted as HTML if the
1279 * web server is not correctly configured to send the right content-type
1280 * (or if you're really uploading plain text and octet streams!)
1282 * Returns true if IE is likely to mistake the given file for HTML.
1283 * Also returns true if Safari would mistake the given file for HTML
1284 * when served with a generic content-type.
1290 '<html', #also in safari
1293 '<script', #also in safari
1296 if( ! $wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
1300 foreach( $tags as $tag ) {
1301 if( false !== strpos( $chunk, $tag ) ) {
1307 * look for javascript
1310 #resolve entity-refs to look at attributes. may be harsh on big files... cache result?
1311 $chunk = Sanitizer
::decodeCharReferences( $chunk );
1313 #look for script-types
1314 if (preg_match('!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim',$chunk)) return true;
1316 #look for html-style script-urls
1317 if (preg_match('!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim',$chunk)) return true;
1319 #look for css-style script-urls
1320 if (preg_match('!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim',$chunk)) return true;
1322 wfDebug("SpecialUpload::detectScript: no scripts found\n");
1327 * Generic wrapper function for a virus scanner program.
1328 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
1329 * $wgAntivirusRequired may be used to deny upload if the scan fails.
1331 * @param string $file Pathname to the temporary upload file
1332 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
1333 * or a string containing feedback from the virus scanner if a virus was found.
1334 * If textual feedback is missing but a virus was found, this function returns true.
1336 function detectVirus($file) {
1337 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
1339 if ( !$wgAntivirus ) {
1340 wfDebug( __METHOD__
.": virus scanner disabled\n");
1344 if ( !$wgAntivirusSetup[$wgAntivirus] ) {
1345 wfDebug( __METHOD__
.": unknown virus scanner: $wgAntivirus\n" );
1347 $wgOut->addHTML( "<div class='error'>Bad configuration: unknown virus scanner: <i>$wgAntivirus</i></div>\n" );
1348 return "unknown antivirus: $wgAntivirus";
1351 # look up scanner configuration
1352 $command = $wgAntivirusSetup[$wgAntivirus]["command"];
1353 $exitCodeMap = $wgAntivirusSetup[$wgAntivirus]["codemap"];
1354 $msgPattern = isset( $wgAntivirusSetup[$wgAntivirus]["messagepattern"] ) ?
1355 $wgAntivirusSetup[$wgAntivirus]["messagepattern"] : null;
1357 if ( strpos( $command,"%f" ) === false ) {
1358 # simple pattern: append file to scan
1359 $command .= " " . wfEscapeShellArg( $file );
1361 # complex pattern: replace "%f" with file to scan
1362 $command = str_replace( "%f", wfEscapeShellArg( $file ), $command );
1365 wfDebug( __METHOD__
.": running virus scan: $command \n" );
1367 # execute virus scanner
1370 #NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
1371 # that does not seem to be worth the pain.
1372 # Ask me (Duesentrieb) about it if it's ever needed.
1374 if ( wfIsWindows() ) {
1375 exec( "$command", $output, $exitCode );
1377 exec( "$command 2>&1", $output, $exitCode );
1380 # map exit code to AV_xxx constants.
1381 $mappedCode = $exitCode;
1382 if ( $exitCodeMap ) {
1383 if ( isset( $exitCodeMap[$exitCode] ) ) {
1384 $mappedCode = $exitCodeMap[$exitCode];
1385 } elseif ( isset( $exitCodeMap["*"] ) ) {
1386 $mappedCode = $exitCodeMap["*"];
1390 if ( $mappedCode === AV_SCAN_FAILED
) {
1391 # scan failed (code was mapped to false by $exitCodeMap)
1392 wfDebug( __METHOD__
.": failed to scan $file (code $exitCode).\n" );
1394 if ( $wgAntivirusRequired ) {
1395 return "scan failed (code $exitCode)";
1399 } else if ( $mappedCode === AV_SCAN_ABORTED
) {
1400 # scan failed because filetype is unknown (probably imune)
1401 wfDebug( __METHOD__
.": unsupported file type $file (code $exitCode).\n" );
1403 } else if ( $mappedCode === AV_NO_VIRUS
) {
1405 wfDebug( __METHOD__
.": file passed virus scan.\n" );
1408 $output = join( "\n", $output );
1409 $output = trim( $output );
1412 $output = true; #if there's no output, return true
1413 } elseif ( $msgPattern ) {
1415 if ( preg_match( $msgPattern, $output, $groups ) ) {
1417 $output = $groups[1];
1422 wfDebug( __METHOD__
.": FOUND VIRUS! scanner feedback: $output" );
1428 * Check if the temporary file is MacBinary-encoded, as some uploads
1429 * from Internet Explorer on Mac OS Classic and Mac OS X will be.
1430 * If so, the data fork will be extracted to a second temporary file,
1431 * which will then be checked for validity and either kept or discarded.
1435 function checkMacBinary() {
1436 $macbin = new MacBinary( $this->mTempPath
);
1437 if( $macbin->isValid() ) {
1438 $dataFile = tempnam( wfTempDir(), "WikiMacBinary" );
1439 $dataHandle = fopen( $dataFile, 'wb' );
1441 wfDebug( "SpecialUpload::checkMacBinary: Extracting MacBinary data fork to $dataFile\n" );
1442 $macbin->extractData( $dataHandle );
1444 $this->mTempPath
= $dataFile;
1445 $this->mFileSize
= $macbin->dataForkLength();
1447 // We'll have to manually remove the new file if it's not kept.
1448 $this->mRemoveTempFile
= true;
1454 * If we've modified the upload file we need to manually remove it
1455 * on exit to clean up.
1458 function cleanupTempFile() {
1459 if ( $this->mRemoveTempFile
&& file_exists( $this->mTempPath
) ) {
1460 wfDebug( "SpecialUpload::cleanupTempFile: Removing temporary file {$this->mTempPath}\n" );
1461 unlink( $this->mTempPath
);
1466 * Check if there's an overwrite conflict and, if so, if restrictions
1467 * forbid this user from performing the upload.
1469 * @return mixed true on success, WikiError on failure
1472 function checkOverwrite( $name ) {
1473 $img = wfFindFile( $name );
1477 global $wgUser, $wgOut;
1478 if( $img->isLocal() ) {
1479 if( !self
::userCanReUpload( $wgUser, $img->name
) ) {
1480 $error = 'fileexists-forbidden';
1483 if( !$wgUser->isAllowed( 'reupload' ) ||
1484 !$wgUser->isAllowed( 'reupload-shared' ) ) {
1485 $error = "fileexists-shared-forbidden";
1491 $errorText = wfMsg( $error, wfEscapeWikiText( $img->getName() ) );
1495 // Rockin', go ahead and upload
1500 * Check if a user is the last uploader
1503 * @param string $img, image name
1506 public static function userCanReUpload( User
$user, $img ) {
1507 if( $user->isAllowed( 'reupload' ) )
1508 return true; // non-conditional
1509 if( !$user->isAllowed( 'reupload-own' ) )
1512 $dbr = wfGetDB( DB_SLAVE
);
1513 $row = $dbr->selectRow('image',
1514 /* SELECT */ 'img_user',
1515 /* WHERE */ array( 'img_name' => $img )
1520 return $user->getID() == $row->img_user
;
1524 * Display an error with a wikitext description
1526 function showError( $description ) {
1528 $wgOut->setPageTitle( wfMsg( "internalerror" ) );
1529 $wgOut->setRobotpolicy( "noindex,nofollow" );
1530 $wgOut->setArticleRelated( false );
1531 $wgOut->enableClientCache( false );
1532 $wgOut->addWikiText( $description );
1536 * Get the initial image page text based on a comment and optional file status information
1538 static function getInitialPageText( $comment, $license, $copyStatus, $source ) {
1539 global $wgUseCopyrightUpload;
1540 if ( $wgUseCopyrightUpload ) {
1541 if ( $license != '' ) {
1542 $licensetxt = '== ' . wfMsgForContent( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1544 $pageText = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $comment . "\n" .
1545 '== ' . wfMsgForContent ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
1547 '== ' . wfMsgForContent ( 'filesource' ) . " ==\n" . $source ;
1549 if ( $license != '' ) {
1550 $filedesc = $comment == '' ?
'' : '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $comment . "\n";
1551 $pageText = $filedesc .
1552 '== ' . wfMsgForContent ( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1554 $pageText = $comment;
1561 * If there are rows in the deletion log for this file, show them,
1562 * along with a nice little note for the user
1564 * @param OutputPage $out
1565 * @param string filename
1567 private function showDeletionLog( $out, $filename ) {
1568 $reader = new LogReader(
1571 'page' => $filename,
1576 if( $reader->hasRows() ) {
1577 $out->addHtml( '<div id="mw-upload-deleted-warn">' );
1578 $out->addWikiText( wfMsg( 'upload-wasdeleted' ) );
1579 $viewer = new LogViewer( $reader );
1580 $viewer->showList( $out );
1581 $out->addHtml( '</div>' );