11 function wfSpecialUpload() {
13 $form = new UploadForm( $wgRequest );
18 * implements Special:Upload
19 * @ingroup SpecialPage
23 const BEFORE_PROCESSING
= 1;
24 const LARGE_FILE_SERVER
= 2;
26 const MIN_LENGTH_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' );
65 $this->mReUpload
= $request->getCheck( 'wpReUpload' );
67 if( !$request->wasPosted() ) {
68 # GET requests just give the main form; no data except destination
69 # filename and description
73 # Placeholders for text injection by hooks (empty per default)
74 $this->uploadFormTextTop
= "";
75 $this->uploadFormTextAfterSummary
= "";
77 $this->mReUpload
= $request->getCheck( 'wpReUpload' );
78 $this->mUploadClicked
= $request->getCheck( 'wpUpload' );
80 $this->mLicense
= $request->getText( 'wpLicense' );
81 $this->mCopyrightStatus
= $request->getText( 'wpUploadCopyStatus' );
82 $this->mCopyrightSource
= $request->getText( 'wpUploadSource' );
83 $this->mWatchthis
= $request->getBool( 'wpWatchthis' );
84 $this->mSourceType
= $request->getText( 'wpSourceType' );
85 $this->mDestWarningAck
= $request->getText( 'wpDestFileWarningAck' );
87 $this->mAction
= $request->getVal( 'action' );
89 $this->mSessionKey
= $request->getInt( 'wpSessionKey' );
90 if( !empty( $this->mSessionKey
) &&
91 isset( $_SESSION['wsUploadData'][$this->mSessionKey
]['version'] ) &&
92 $_SESSION['wsUploadData'][$this->mSessionKey
]['version'] == self
::SESSION_VERSION
) {
94 * Confirming a temporarily stashed upload.
95 * We don't want path names to be forged, so we keep
96 * them in the session on the server and just give
97 * an opaque key to the user agent.
99 $data = $_SESSION['wsUploadData'][$this->mSessionKey
];
100 $this->mTempPath
= $data['mTempPath'];
101 $this->mFileSize
= $data['mFileSize'];
102 $this->mSrcName
= $data['mSrcName'];
103 $this->mFileProps
= $data['mFileProps'];
104 $this->mCurlError
= 0/*UPLOAD_ERR_OK*/;
105 $this->mStashed
= true;
106 $this->mRemoveTempFile
= false;
109 *Check for a newly uploaded file.
111 if( $wgAllowCopyUploads && $this->mSourceType
== 'web' ) {
112 $this->initializeFromUrl( $request );
114 $this->initializeFromUpload( $request );
120 * Initialize the uploaded file from PHP data
123 function initializeFromUpload( $request ) {
124 $this->mTempPath
= $request->getFileTempName( 'wpUploadFile' );
125 $this->mFileSize
= $request->getFileSize( 'wpUploadFile' );
126 $this->mSrcName
= $request->getFileName( 'wpUploadFile' );
127 $this->mCurlError
= $request->getUploadError( 'wpUploadFile' );
128 $this->mSessionKey
= false;
129 $this->mStashed
= false;
130 $this->mRemoveTempFile
= false; // PHP will handle this
134 * Copy a web file to a temporary file
137 function initializeFromUrl( $request ) {
138 global $wgTmpDirectory;
139 $url = $request->getText( 'wpUploadFileURL' );
140 $local_file = tempnam( $wgTmpDirectory, 'WEBUPLOAD' );
142 $this->mTempPath
= $local_file;
143 $this->mFileSize
= 0; # Will be set by curlCopy
144 $this->mCurlError
= $this->curlCopy( $url, $local_file );
145 $pathParts = explode( '/', $url );
146 $this->mSrcName
= array_pop( $pathParts );
147 $this->mSessionKey
= false;
148 $this->mStashed
= false;
150 // PHP won't auto-cleanup the file
151 $this->mRemoveTempFile
= file_exists( $local_file );
156 * Returns true if there was an error, false otherwise
158 private function curlCopy( $url, $dest ) {
159 global $wgUser, $wgOut;
161 if( !$wgUser->isAllowed( 'upload_by_url' ) ) {
162 $wgOut->permissionRequired( 'upload_by_url' );
166 # Maybe remove some pasting blanks :-)
168 if( stripos($url, 'http://') !== 0 && stripos($url, 'ftp://') !== 0 ) {
169 # Only HTTP or FTP URLs
170 $wgOut->showErrorPage( 'upload-proto-error', 'upload-proto-error-text' );
174 # Open temporary file
175 $this->mCurlDestHandle
= @fopen
( $this->mTempPath
, "wb" );
176 if( $this->mCurlDestHandle
=== false ) {
177 # Could not open temporary file to write in
178 $wgOut->showErrorPage( 'upload-file-error', 'upload-file-error-text');
183 curl_setopt( $ch, CURLOPT_HTTP_VERSION
, 1.0); # Probably not needed, but apparently can work around some bug
184 curl_setopt( $ch, CURLOPT_TIMEOUT
, 10); # 10 seconds timeout
185 curl_setopt( $ch, CURLOPT_LOW_SPEED_LIMIT
, 512); # 0.5KB per second minimum transfer speed
186 curl_setopt( $ch, CURLOPT_URL
, $url);
187 curl_setopt( $ch, CURLOPT_WRITEFUNCTION
, array( $this, 'uploadCurlCallback' ) );
189 $error = curl_errno( $ch ) ?
true : false;
190 $errornum = curl_errno( $ch );
191 // if ( $error ) print curl_error ( $ch ) ; # Debugging output
194 fclose( $this->mCurlDestHandle
);
195 unset( $this->mCurlDestHandle
);
198 if( wfEmptyMsg( "upload-curl-error$errornum", wfMsg("upload-curl-error$errornum") ) )
199 $wgOut->showErrorPage( 'upload-misc-error', 'upload-misc-error-text' );
201 $wgOut->showErrorPage( "upload-curl-error$errornum", "upload-curl-error$errornum-text" );
208 * Callback function for CURL-based web transfer
209 * Write data to file unless we've passed the length limit;
210 * if so, abort immediately.
213 function uploadCurlCallback( $ch, $data ) {
214 global $wgMaxUploadSize;
215 $length = strlen( $data );
216 $this->mFileSize +
= $length;
217 if( $this->mFileSize
> $wgMaxUploadSize ) {
220 fwrite( $this->mCurlDestHandle
, $data );
229 global $wgUser, $wgOut;
230 global $wgEnableUploads;
232 # Check php's file_uploads setting
233 if( !wfIniGetBool( 'file_uploads' ) ) {
234 $wgOut->showErrorPage( 'uploaddisabled', 'php-uploaddisabledtext', array( $this->mDesiredDestName
) );
238 # Check uploading enabled
239 if( !$wgEnableUploads ) {
240 $wgOut->showErrorPage( 'uploaddisabled', 'uploaddisabledtext', array( $this->mDesiredDestName
) );
245 if( !$wgUser->isAllowed( 'upload' ) ) {
246 if( !$wgUser->isLoggedIn() ) {
247 $wgOut->showErrorPage( 'uploadnologin', 'uploadnologintext' );
249 $wgOut->permissionRequired( 'upload' );
255 if( $wgUser->isBlocked() ) {
256 $wgOut->blockedPage();
261 $wgOut->readOnlyPage();
265 if( $this->mReUpload
) {
266 if( !$this->unsaveUploadedFile() ) {
269 # Because it is probably checked and shouldn't be
270 $this->mIgnoreWarning
= false;
272 $this->mainUploadForm();
273 } else if( 'submit' == $this->mAction ||
$this->mUploadClicked
) {
274 $this->processUpload();
276 $this->mainUploadForm();
279 $this->cleanupTempFile();
284 * Checks are made in SpecialUpload::execute()
288 function processUpload(){
289 global $wgUser, $wgOut, $wgFileExtensions, $wgLang;
292 $value = $this->internalProcessUpload( $details );
296 $wgOut->redirect( $this->mLocalFile
->getTitle()->getFullURL() );
299 case self
::BEFORE_PROCESSING
:
302 case self
::LARGE_FILE_SERVER
:
303 $this->mainUploadForm( wfMsgHtml( 'largefileserver' ) );
306 case self
::EMPTY_FILE
:
307 $this->mainUploadForm( wfMsgHtml( 'emptyfile' ) );
310 case self
::MIN_LENGTH_PARTNAME
:
311 $this->mainUploadForm( wfMsgHtml( 'minlength1' ) );
314 case self
::ILLEGAL_FILENAME
:
315 $filtered = $details['filtered'];
316 $this->uploadError( wfMsgWikiHtml( 'illegalfilename', htmlspecialchars( $filtered ) ) );
319 case self
::PROTECTED_PAGE
:
320 $wgOut->showPermissionsErrorPage( $details['permissionserrors'] );
323 case self
::OVERWRITE_EXISTING_FILE
:
324 $errorText = $details['overwrite'];
325 $this->uploadError( $wgOut->parse( $errorText ) );
328 case self
::FILETYPE_MISSING
:
329 $this->uploadError( wfMsgExt( 'filetype-missing', array ( 'parseinline' ) ) );
332 case self
::FILETYPE_BADTYPE
:
333 $finalExt = $details['finalExt'];
335 wfMsgExt( 'filetype-banned-type',
336 array( 'parseinline' ),
337 htmlspecialchars( $finalExt ),
338 $wgLang->commaList( $wgFileExtensions ),
339 $wgLang->formatNum( count($wgFileExtensions) )
344 case self
::VERIFICATION_ERROR
:
345 $veri = $details['veri'];
346 $this->uploadError( $veri->toString() );
349 case self
::UPLOAD_VERIFICATION_ERROR
:
350 $error = $details['error'];
351 $this->uploadError( $error );
354 case self
::UPLOAD_WARNING
:
355 $warning = $details['warning'];
356 $this->uploadWarning( $warning );
359 case self
::INTERNAL_ERROR
:
360 $internal = $details['internal'];
361 $this->showError( $internal );
365 throw new MWException( __METHOD__
. ": Unknown value `{$value}`" );
370 * Really do the upload
371 * Checks are made in SpecialUpload::execute()
373 * @param array $resultDetails contains result-specific dict of additional values
377 function internalProcessUpload( &$resultDetails ) {
380 if( !wfRunHooks( 'UploadForm:BeforeProcessing', array( &$this ) ) )
382 wfDebug( "Hook 'UploadForm:BeforeProcessing' broke processing the file.\n" );
383 return self
::BEFORE_PROCESSING
;
387 * If there was no filename or a zero size given, give up quick.
389 if( trim( $this->mSrcName
) == '' ||
empty( $this->mFileSize
) ) {
390 return self
::EMPTY_FILE
;
393 /* Check for curl error */
394 if( $this->mCurlError
) {
395 return self
::BEFORE_PROCESSING
;
399 * Chop off any directories in the given filename. Then
400 * filter out illegal characters, and try to make a legible name
401 * out of it. We'll strip some silently that Title would die on.
403 if( $this->mDesiredDestName
) {
404 $basename = $this->mDesiredDestName
;
406 $basename = $this->mSrcName
;
408 $filtered = wfStripIllegalFilenameChars( $basename );
410 /* Normalize to title form before we do any further processing */
411 $nt = Title
::makeTitleSafe( NS_FILE
, $filtered );
412 if( is_null( $nt ) ) {
413 $resultDetails = array( 'filtered' => $filtered );
414 return self
::ILLEGAL_FILENAME
;
416 $filtered = $nt->getDBkey();
419 * We'll want to blacklist against *any* 'extension', and use
420 * only the final one for the whitelist.
422 list( $partname, $ext ) = $this->splitExtensions( $filtered );
424 if( count( $ext ) ) {
425 $finalExt = $ext[count( $ext ) - 1];
430 # If there was more than one "extension", reassemble the base
431 # filename to prevent bogus complaints about length
432 if( count( $ext ) > 1 ) {
433 for( $i = 0; $i < count( $ext ) - 1; $i++
)
434 $partname .= '.' . $ext[$i];
437 if( strlen( $partname ) < 1 ) {
438 return self
::MIN_LENGTH_PARTNAME
;
441 $this->mLocalFile
= wfLocalFile( $nt );
442 $this->mDestName
= $this->mLocalFile
->getName();
445 * If the image is protected, non-sysop users won't be able
446 * to modify it by uploading a new revision.
448 $permErrors = $nt->getUserPermissionsErrors( 'edit', $wgUser );
449 $permErrorsUpload = $nt->getUserPermissionsErrors( 'upload', $wgUser );
450 $permErrorsCreate = ( $nt->exists() ?
array() : $nt->getUserPermissionsErrors( 'create', $wgUser ) );
452 if( $permErrors ||
$permErrorsUpload ||
$permErrorsCreate ) {
453 // merge all the problems into one list, avoiding duplicates
454 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsUpload, $permErrors ) );
455 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsCreate, $permErrors ) );
456 $resultDetails = array( 'permissionserrors' => $permErrors );
457 return self
::PROTECTED_PAGE
;
461 * In some cases we may forbid overwriting of existing files.
463 $overwrite = $this->checkOverwrite( $this->mDestName
);
464 if( $overwrite !== true ) {
465 $resultDetails = array( 'overwrite' => $overwrite );
466 return self
::OVERWRITE_EXISTING_FILE
;
469 /* Don't allow users to override the blacklist (check file extension) */
470 global $wgCheckFileExtensions, $wgStrictFileExtensions;
471 global $wgFileExtensions, $wgFileBlacklist;
472 if ($finalExt == '') {
473 return self
::FILETYPE_MISSING
;
474 } elseif ( $this->checkFileExtensionList( $ext, $wgFileBlacklist ) ||
475 ($wgCheckFileExtensions && $wgStrictFileExtensions &&
476 !$this->checkFileExtension( $finalExt, $wgFileExtensions ) ) ) {
477 $resultDetails = array( 'finalExt' => $finalExt );
478 return self
::FILETYPE_BADTYPE
;
482 * Look at the contents of the file; if we can recognize the
483 * type but it's corrupt or data of the wrong type, we should
484 * probably not accept it.
486 if( !$this->mStashed
) {
487 $this->mFileProps
= File
::getPropsFromPath( $this->mTempPath
, $finalExt );
488 $this->checkMacBinary();
489 $veri = $this->verify( $this->mTempPath
, $finalExt );
491 if( $veri !== true ) { //it's a wiki error...
492 $resultDetails = array( 'veri' => $veri );
493 return self
::VERIFICATION_ERROR
;
497 * Provide an opportunity for extensions to add further checks
500 if( !wfRunHooks( 'UploadVerification',
501 array( $this->mDestName
, $this->mTempPath
, &$error ) ) ) {
502 $resultDetails = array( 'error' => $error );
503 return self
::UPLOAD_VERIFICATION_ERROR
;
509 * Check for non-fatal conditions
511 if ( ! $this->mIgnoreWarning
) {
514 $comparableName = str_replace( ' ', '_', $basename );
515 global $wgCapitalLinks, $wgContLang;
516 if ( $wgCapitalLinks ) {
517 $comparableName = $wgContLang->ucfirst( $comparableName );
520 if( $comparableName !== $filtered ) {
521 $warning .= '<li>'.wfMsgHtml( 'badfilename', htmlspecialchars( $this->mDestName
) ).'</li>';
524 global $wgCheckFileExtensions;
525 if ( $wgCheckFileExtensions ) {
526 if ( !$this->checkFileExtension( $finalExt, $wgFileExtensions ) ) {
529 wfMsgExt( 'filetype-unwanted-type',
530 array( 'parseinline' ),
531 htmlspecialchars( $finalExt ),
532 $wgLang->commaList( $wgFileExtensions ),
533 $wgLang->formatNum( count($wgFileExtensions) )
538 global $wgUploadSizeWarning;
539 if ( $wgUploadSizeWarning && ( $this->mFileSize
> $wgUploadSizeWarning ) ) {
540 $skin = $wgUser->getSkin();
541 $wsize = $skin->formatSize( $wgUploadSizeWarning );
542 $asize = $skin->formatSize( $this->mFileSize
);
543 $warning .= '<li>' . wfMsgHtml( 'large-file', $wsize, $asize ) . '</li>';
545 if ( $this->mFileSize
== 0 ) {
546 $warning .= '<li>'.wfMsgHtml( 'emptyfile' ).'</li>';
549 if ( !$this->mDestWarningAck
) {
550 $warning .= self
::getExistsWarning( $this->mLocalFile
);
553 $warning .= $this->getDupeWarning( $this->mTempPath
, $finalExt );
555 if( $warning != '' ) {
557 * Stash the file in a temporary location; the user can choose
558 * to let it through and we'll complete the upload then.
560 $resultDetails = array( 'warning' => $warning );
561 return self
::UPLOAD_WARNING
;
566 * Try actually saving the thing...
567 * It will show an error form on failure.
569 $pageText = self
::getInitialPageText( $this->mComment
, $this->mLicense
,
570 $this->mCopyrightStatus
, $this->mCopyrightSource
);
572 $status = $this->mLocalFile
->upload( $this->mTempPath
, $this->mComment
, $pageText,
573 File
::DELETE_SOURCE
, $this->mFileProps
);
574 if ( !$status->isGood() ) {
575 $resultDetails = array( 'internal' => $status->getWikiText() );
576 return self
::INTERNAL_ERROR
;
578 if ( $this->mWatchthis
) {
580 $wgUser->addWatch( $this->mLocalFile
->getTitle() );
582 // Success, redirect to description page
583 $img = null; // @todo: added to avoid passing a ref to null - should this be defined somewhere?
584 wfRunHooks( 'UploadComplete', array( &$this ) );
585 return self
::SUCCESS
;
590 * Do existence checks on a file and produce a warning
591 * This check is static and can be done pre-upload via AJAX
592 * Returns an HTML fragment consisting of one or more LI elements if there is a warning
593 * Returns an empty string if there is no warning
595 static function getExistsWarning( $file ) {
596 global $wgUser, $wgContLang;
597 // Check for uppercase extension. We allow these filenames but check if an image
598 // with lowercase extension exists already
600 $align = $wgContLang->isRtl() ?
'left' : 'right';
602 if( strpos( $file->getName(), '.' ) == false ) {
603 $partname = $file->getName();
606 $n = strrpos( $file->getName(), '.' );
607 $rawExtension = substr( $file->getName(), $n +
1 );
608 $partname = substr( $file->getName(), 0, $n );
611 $sk = $wgUser->getSkin();
613 if ( $rawExtension != $file->getExtension() ) {
614 // We're not using the normalized form of the extension.
615 // Normal form is lowercase, using most common of alternate
616 // extensions (eg 'jpg' rather than 'JPEG').
618 // Check for another file using the normalized form...
619 $nt_lc = Title
::makeTitle( NS_FILE
, $partname . '.' . $file->getExtension() );
620 $file_lc = wfLocalFile( $nt_lc );
625 if( $file->exists() ) {
626 $dlink = $sk->makeKnownLinkObj( $file->getTitle() );
627 if ( $file->allowInlineDisplay() ) {
628 $dlink2 = $sk->makeImageLinkObj( $file->getTitle(), wfMsgExt( 'fileexists-thumb', 'parseinline' ),
629 $file->getName(), $align, array(), false, true );
630 } elseif ( !$file->allowInlineDisplay() && $file->isSafeFile() ) {
631 $icon = $file->iconThumb();
632 $dlink2 = '<div style="float:' . $align . '" id="mw-media-icon">' .
633 $icon->toHtml( array( 'desc-link' => true ) ) . '<br />' . $dlink . '</div>';
638 $warning .= '<li>' . wfMsgExt( 'fileexists', array('parseinline','replaceafter'), $dlink ) . '</li>' . $dlink2;
640 } elseif( $file->getTitle()->getArticleID() ) {
641 $lnk = $sk->makeKnownLinkObj( $file->getTitle(), '', 'redirect=no' );
642 $warning .= '<li>' . wfMsgExt( 'filepageexists', array( 'parseinline', 'replaceafter' ), $lnk ) . '</li>';
643 } elseif ( $file_lc && $file_lc->exists() ) {
644 # Check if image with lowercase extension exists.
645 # It's not forbidden but in 99% it makes no sense to upload the same filename with uppercase extension
646 $dlink = $sk->makeKnownLinkObj( $nt_lc );
647 if ( $file_lc->allowInlineDisplay() ) {
648 $dlink2 = $sk->makeImageLinkObj( $nt_lc, wfMsgExt( 'fileexists-thumb', 'parseinline' ),
649 $nt_lc->getText(), $align, array(), false, true );
650 } elseif ( !$file_lc->allowInlineDisplay() && $file_lc->isSafeFile() ) {
651 $icon = $file_lc->iconThumb();
652 $dlink2 = '<div style="float:' . $align . '" id="mw-media-icon">' .
653 $icon->toHtml( array( 'desc-link' => true ) ) . '<br />' . $dlink . '</div>';
659 wfMsgExt( 'fileexists-extension', 'parsemag',
660 $file->getTitle()->getPrefixedText(), $dlink ) .
663 } elseif ( ( substr( $partname , 3, 3 ) == 'px-' ||
substr( $partname , 2, 3 ) == 'px-' )
664 && ereg( "[0-9]{2}" , substr( $partname , 0, 2) ) )
666 # Check for filenames like 50px- or 180px-, these are mostly thumbnails
667 $nt_thb = Title
::newFromText( substr( $partname , strpos( $partname , '-' ) +
1 ) . '.' . $rawExtension );
668 $file_thb = wfLocalFile( $nt_thb );
669 if ($file_thb->exists() ) {
670 # Check if an image without leading '180px-' (or similiar) exists
671 $dlink = $sk->makeKnownLinkObj( $nt_thb);
672 if ( $file_thb->allowInlineDisplay() ) {
673 $dlink2 = $sk->makeImageLinkObj( $nt_thb,
674 wfMsgExt( 'fileexists-thumb', 'parseinline' ),
675 $nt_thb->getText(), $align, array(), false, true );
676 } elseif ( !$file_thb->allowInlineDisplay() && $file_thb->isSafeFile() ) {
677 $icon = $file_thb->iconThumb();
678 $dlink2 = '<div style="float:' . $align . '" id="mw-media-icon">' .
679 $icon->toHtml( array( 'desc-link' => true ) ) . '<br />' .
685 $warning .= '<li>' . wfMsgExt( 'fileexists-thumbnail-yes', 'parsemag', $dlink ) .
688 # Image w/o '180px-' does not exists, but we do not like these filenames
689 $warning .= '<li>' . wfMsgExt( 'file-thumbnail-no', 'parseinline' ,
690 substr( $partname , 0, strpos( $partname , '-' ) +
1 ) ) . '</li>';
694 $filenamePrefixBlacklist = self
::getFilenamePrefixBlacklist();
696 foreach( $filenamePrefixBlacklist as $prefix ) {
697 if ( substr( $partname, 0, strlen( $prefix ) ) == $prefix ) {
698 $warning .= '<li>' . wfMsgExt( 'filename-bad-prefix', 'parseinline', $prefix ) . '</li>';
703 if ( $file->wasDeleted() && !$file->exists() ) {
704 # If the file existed before and was deleted, warn the user of this
705 # Don't bother doing so if the file exists now, however
706 $ltitle = SpecialPage
::getTitleFor( 'Log' );
707 $llink = $sk->makeKnownLinkObj( $ltitle, wfMsgHtml( 'deletionlog' ),
708 'type=delete&page=' . $file->getTitle()->getPrefixedUrl() );
709 $warning .= '<li>' . wfMsgWikiHtml( 'filewasdeleted', $llink ) . '</li>';
715 * Get a list of warnings
717 * @param string local filename, e.g. 'file exists', 'non-descriptive filename'
718 * @return array list of warning messages
720 static function ajaxGetExistsWarning( $filename ) {
721 $file = wfFindFile( $filename );
723 // Force local file so we have an object to do further checks against
724 // if there isn't an exact match...
725 $file = wfLocalFile( $filename );
729 $warning = self
::getExistsWarning( $file );
730 if ( $warning !== '' ) {
731 $s = "<ul>$warning</ul>";
738 * Render a preview of a given license for the AJAX preview on upload
740 * @param string $license
743 public static function ajaxGetLicensePreview( $license ) {
744 global $wgParser, $wgUser;
745 $text = '{{' . $license . '}}';
746 $title = Title
::makeTitle( NS_FILE
, 'Sample.jpg' );
747 $options = ParserOptions
::newFromUser( $wgUser );
749 // Expand subst: first, then live templates...
750 $text = $wgParser->preSaveTransform( $text, $title, $wgUser, $options );
751 $output = $wgParser->parse( $text, $title, $options );
753 return $output->getText();
757 * Check for duplicate files and throw up a warning before the upload
760 function getDupeWarning( $tempfile, $extension ) {
761 $hash = File
::sha1Base36( $tempfile );
762 $dupes = RepoGroup
::singleton()->findBySha1( $hash );
763 $archivedImage = new ArchivedFile( null, 0, $hash.".$extension" );
767 foreach( $dupes as $file ) {
768 $title = $file->getTitle();
769 $msg .= $title->getPrefixedText() .
770 "|" . $title->getText() . "\n";
772 $msg .= "</gallery>";
774 wfMsgExt( "file-exists-duplicate", array( "parse" ), count( $dupes ) ) .
775 $wgOut->parse( $msg ) .
777 } elseif ( $archivedImage->getID() > 0 ) {
779 $name = Title
::makeTitle( NS_FILE
, $archivedImage->getName() )->getPrefixedText();
780 return Xml
::tags( 'li', null, wfMsgExt( 'file-deleted-duplicate', array( 'parseinline' ), array( $name ) ) );
787 * Get a list of blacklisted filename prefixes from [[MediaWiki:filename-prefix-blacklist]]
789 * @return array list of prefixes
791 public static function getFilenamePrefixBlacklist() {
792 $blacklist = array();
793 $message = wfMsgForContent( 'filename-prefix-blacklist' );
794 if( $message && !( wfEmptyMsg( 'filename-prefix-blacklist', $message ) ||
$message == '-' ) ) {
795 $lines = explode( "\n", $message );
796 foreach( $lines as $line ) {
797 // Remove comment lines
798 $comment = substr( trim( $line ), 0, 1 );
799 if ( $comment == '#' ||
$comment == '' ) {
802 // Remove additional comments after a prefix
803 $comment = strpos( $line, '#' );
804 if ( $comment > 0 ) {
805 $line = substr( $line, 0, $comment-1 );
807 $blacklist[] = trim( $line );
814 * Stash a file in a temporary directory for later processing
815 * after the user has confirmed it.
817 * If the user doesn't explicitly cancel or accept, these files
818 * can accumulate in the temp directory.
820 * @param string $saveName - the destination filename
821 * @param string $tempName - the source temporary file to save
822 * @return string - full path the stashed file, or false on failure
825 function saveTempUploadedFile( $saveName, $tempName ) {
827 $repo = RepoGroup
::singleton()->getLocalRepo();
828 $status = $repo->storeTemp( $saveName, $tempName );
829 if ( !$status->isGood() ) {
830 $this->showError( $status->getWikiText() );
833 return $status->value
;
838 * Stash a file in a temporary directory for later processing,
839 * and save the necessary descriptive info into the session.
840 * Returns a key value which will be passed through a form
841 * to pick up the path info on a later invocation.
846 function stashSession() {
847 $stash = $this->saveTempUploadedFile( $this->mDestName
, $this->mTempPath
);
850 # Couldn't save the file.
854 $key = mt_rand( 0, 0x7fffffff );
855 $_SESSION['wsUploadData'][$key] = array(
856 'mTempPath' => $stash,
857 'mFileSize' => $this->mFileSize
,
858 'mSrcName' => $this->mSrcName
,
859 'mFileProps' => $this->mFileProps
,
860 'version' => self
::SESSION_VERSION
,
866 * Remove a temporarily kept file stashed by saveTempUploadedFile().
870 function unsaveUploadedFile() {
872 if( !$this->mTempPath
) return true; // nothing to delete
873 $repo = RepoGroup
::singleton()->getLocalRepo();
874 $success = $repo->freeTemp( $this->mTempPath
);
876 $wgOut->showFileDeleteError( $this->mTempPath
);
883 /* -------------------------------------------------------------- */
886 * @param string $error as HTML
889 function uploadError( $error ) {
891 $wgOut->addHTML( '<h2>' . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
892 $wgOut->addHTML( '<span class="error">' . $error . '</span>' );
896 * There's something wrong with this file, not enough to reject it
897 * totally but we require manual intervention to save it for real.
898 * Stash it away, then present a form asking to confirm or cancel.
900 * @param string $warning as HTML
903 function uploadWarning( $warning ) {
905 global $wgUseCopyrightUpload;
907 $this->mSessionKey
= $this->stashSession();
908 if( !$this->mSessionKey
) {
909 # Couldn't save file; an error has been displayed so let's go.
913 $wgOut->addHTML( '<h2>' . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
914 $wgOut->addHTML( '<ul class="warning">' . $warning . "</ul>\n" );
916 $titleObj = SpecialPage
::getTitleFor( 'Upload' );
918 if ( $wgUseCopyrightUpload ) {
919 $copyright = Xml
::hidden( 'wpUploadCopyStatus', $this->mCopyrightStatus
) . "\n" .
920 Xml
::hidden( 'wpUploadSource', $this->mCopyrightSource
) . "\n";
926 Xml
::openElement( 'form', array( 'method' => 'post', 'action' => $titleObj->getLocalURL( 'action=submit' ),
927 'enctype' => 'multipart/form-data', 'id' => 'uploadwarning' ) ) . "\n" .
928 Xml
::hidden( 'wpIgnoreWarning', '1' ) . "\n" .
929 Xml
::hidden( 'wpSessionKey', $this->mSessionKey
) . "\n" .
930 Xml
::hidden( 'wpUploadDescription', $this->mComment
) . "\n" .
931 Xml
::hidden( 'wpLicense', $this->mLicense
) . "\n" .
932 Xml
::hidden( 'wpDestFile', $this->mDesiredDestName
) . "\n" .
933 Xml
::hidden( 'wpWatchthis', $this->mWatchthis
) . "\n" .
934 "{$copyright}<br />" .
935 Xml
::submitButton( wfMsg( 'ignorewarning' ), array ( 'name' => 'wpUpload', 'id' => 'wpUpload', 'checked' => 'checked' ) ) . ' ' .
936 Xml
::submitButton( wfMsg( 'reuploaddesc' ), array ( 'name' => 'wpReUpload', 'id' => 'wpReUpload' ) ) .
937 Xml
::closeElement( 'form' ) . "\n"
942 * Displays the main upload form, optionally with a highlighted
943 * error message up at the top.
945 * @param string $msg as HTML
948 function mainUploadForm( $msg='' ) {
949 global $wgOut, $wgUser, $wgLang, $wgMaxUploadSize;
950 global $wgUseCopyrightUpload, $wgUseAjax, $wgAjaxUploadDestCheck, $wgAjaxLicensePreview;
951 global $wgRequest, $wgAllowCopyUploads;
952 global $wgStylePath, $wgStyleVersion;
954 $useAjaxDestCheck = $wgUseAjax && $wgAjaxUploadDestCheck;
955 $useAjaxLicensePreview = $wgUseAjax && $wgAjaxLicensePreview;
957 $adc = wfBoolToStr( $useAjaxDestCheck );
958 $alp = wfBoolToStr( $useAjaxLicensePreview );
959 $autofill = wfBoolToStr( $this->mDesiredDestName
== '' );
961 $wgOut->addScript( "<script type=\"text/javascript\">
962 wgAjaxUploadDestCheck = {$adc};
963 wgAjaxLicensePreview = {$alp};
964 wgUploadAutoFill = {$autofill};
966 $wgOut->addScriptFile( 'upload.js' );
967 $wgOut->addScriptFile( 'edit.js' ); // For <charinsert> support
969 if( !wfRunHooks( 'UploadForm:initial', array( &$this ) ) )
971 wfDebug( "Hook 'UploadForm:initial' broke output of the upload form\n" );
975 if( $this->mDesiredDestName
) {
976 $title = Title
::makeTitleSafe( NS_FILE
, $this->mDesiredDestName
);
977 // Show a subtitle link to deleted revisions (to sysops et al only)
978 if( $title instanceof Title
&& ( $count = $title->isDeleted() ) > 0 && $wgUser->isAllowed( 'deletedhistory' ) ) {
980 $wgUser->isAllowed( 'delete' ) ?
'thisisdeleted' : 'viewdeleted',
981 array( 'parse', 'replaceafter' ),
982 $wgUser->getSkin()->makeKnownLinkObj(
983 SpecialPage
::getTitleFor( 'Undelete', $title->getPrefixedText() ),
984 wfMsgExt( 'restorelink', array( 'parsemag', 'escape' ), $count )
987 $wgOut->addHTML( "<div id=\"contentSub2\">{$link}</div>" );
990 // Show the relevant lines from deletion log (for still deleted files only)
991 if( $title instanceof Title
&& $title->isDeleted() > 0 && !$title->exists() ) {
992 $this->showDeletionLog( $wgOut, $title->getPrefixedText() );
996 $cols = intval($wgUser->getOption( 'cols' ));
998 if( $wgUser->getOption( 'editwidth' ) ) {
999 $width = " style=\"width:100%\"";
1005 $sub = wfMsgHtml( 'uploaderror' );
1006 $wgOut->addHTML( "<h2>{$sub}</h2>\n" .
1007 "<span class='error'>{$msg}</span>\n" );
1010 $uploadMsg = $wgRequest->getVal( 'uploadmsg' );
1012 $uploadMsgName = 'uploadtext-' . $uploadMsg;
1013 // Fall back to normal message if the custom messages is empty
1014 if( wfEmptyMsg( $uploadMsgName, wfMsg( $uploadMsgName ) ) )
1015 $uploadMsgName = 'uploadtext';
1017 $uploadMsgName = 'uploadtext';
1020 $wgOut->addHTML( '<div id="uploadtext">' );
1021 $wgOut->addWikiMsg( $uploadMsgName, $this->mDesiredDestName
);
1022 $wgOut->addHTML( "</div>\n" );
1024 # Print a list of allowed file extensions, if so configured. We ignore
1025 # MIME type here, it's incomprehensible to most people and too long.
1026 global $wgCheckFileExtensions, $wgStrictFileExtensions,
1027 $wgFileExtensions, $wgFileBlacklist;
1029 $allowedExtensions = '';
1030 if( $wgCheckFileExtensions ) {
1031 if( $wgStrictFileExtensions ) {
1032 # Everything not permitted is banned
1034 '<div id="mw-upload-permitted">' .
1035 wfMsgWikiHtml( 'upload-permitted', $wgLang->commaList( $wgFileExtensions ) ) .
1038 # We have to list both preferred and prohibited
1040 '<div id="mw-upload-preferred">' .
1041 wfMsgWikiHtml( 'upload-preferred', $wgLang->commaList( $wgFileExtensions ) ) .
1043 '<div id="mw-upload-prohibited">' .
1044 wfMsgWikiHtml( 'upload-prohibited', $wgLang->commaList( $wgFileBlacklist ) ) .
1048 # Everything is permitted.
1049 $extensionsList = '';
1052 # Get the maximum file size from php.ini as $wgMaxUploadSize works for uploads from URL via CURL only
1053 # See http://www.php.net/manual/en/ini.core.php#ini.upload-max-filesize for possible values of upload_max_filesize
1054 $val = trim( ini_get( 'upload_max_filesize' ) );
1055 $last = strtoupper( ( substr( $val, -1 ) ) );
1058 $val2 = substr( $val, 0, -1 ) * 1024 * 1024 * 1024;
1061 $val2 = substr( $val, 0, -1 ) * 1024 * 1024;
1064 $val2 = substr( $val, 0, -1 ) * 1024;
1069 $val2 = $wgAllowCopyUploads ?
min( $wgMaxUploadSize, $val2 ) : $val2;
1070 $maxUploadSize = '<div id="mw-upload-maxfilesize">' .
1071 wfMsgExt( 'upload-maxfilesize', array( 'parseinline', 'escapenoentities' ),
1072 $wgLang->formatSize( $val2 ) ) .
1075 $sourcefilename = wfMsgExt( 'sourcefilename', array( 'parseinline', 'escapenoentities' ) );
1076 $destfilename = wfMsgExt( 'destfilename', array( 'parseinline', 'escapenoentities' ) );
1078 $msg = $this->mReUpload ?
'filereuploadsummary' : 'fileuploadsummary';
1079 $summary = wfMsgExt( $msg, 'parseinline' );
1081 $licenses = new Licenses();
1082 $license = wfMsgExt( 'license', array( 'parseinline' ) );
1083 $nolicense = wfMsgHtml( 'nolicense' );
1084 $licenseshtml = $licenses->getHtml();
1086 $ulb = wfMsgHtml( 'uploadbtn' );
1089 $titleObj = SpecialPage
::getTitleFor( 'Upload' );
1091 $encDestName = htmlspecialchars( $this->mDesiredDestName
);
1093 $watchChecked = $this->watchCheck() ?
'checked="checked"' : '';
1094 # Re-uploads should not need "file exist already" warnings
1095 $warningChecked = ($this->mIgnoreWarning ||
$this->mReUpload
) ?
'checked="checked"' : '';
1097 // Prepare form for upload or upload/copy
1098 if( $wgAllowCopyUploads && $wgUser->isAllowed( 'upload_by_url' ) ) {
1100 "<input type='radio' id='wpSourceTypeFile' name='wpSourceType' value='file' " .
1101 "onchange='toggle_element_activation(\"wpUploadFileURL\",\"wpUploadFile\")' checked='checked' />" .
1102 "<input tabindex='1' type='file' name='wpUploadFile' id='wpUploadFile' " .
1104 "toggle_element_activation(\"wpUploadFileURL\",\"wpUploadFile\");" .
1105 "toggle_element_check(\"wpSourceTypeFile\",\"wpSourceTypeURL\")' " .
1106 "onchange='fillDestFilename(\"wpUploadFile\")' size='60' />" .
1107 wfMsgHTML( 'upload_source_file' ) . "<br/>" .
1108 "<input type='radio' id='wpSourceTypeURL' name='wpSourceType' value='web' " .
1109 "onchange='toggle_element_activation(\"wpUploadFile\",\"wpUploadFileURL\")' />" .
1110 "<input tabindex='1' type='text' name='wpUploadFileURL' id='wpUploadFileURL' " .
1112 "toggle_element_activation(\"wpUploadFile\",\"wpUploadFileURL\");" .
1113 "toggle_element_check(\"wpSourceTypeURL\",\"wpSourceTypeFile\")' " .
1114 "onchange='fillDestFilename(\"wpUploadFileURL\")' size='60' disabled='disabled' />" .
1115 wfMsgHtml( 'upload_source_url' ) ;
1118 "<input tabindex='1' type='file' name='wpUploadFile' id='wpUploadFile' " .
1119 ($this->mDesiredDestName?
"":"onchange='fillDestFilename(\"wpUploadFile\")' ") .
1121 "<input type='hidden' name='wpSourceType' value='file' />" ;
1123 if ( $useAjaxDestCheck ) {
1124 $warningRow = "<tr><td colspan='2' id='wpDestFile-warning'> </td></tr>";
1125 $destOnkeyup = 'onkeyup="wgUploadWarningObj.keypress();"';
1130 # Uploading a new version? If so, the name is fixed.
1131 $on = $this->mReUpload ?
"disabled='disabled'" : "";
1133 $encComment = htmlspecialchars( $this->mComment
);
1136 Xml
::openElement( 'form', array( 'method' => 'post', 'action' => $titleObj->getLocalURL(),
1137 'enctype' => 'multipart/form-data', 'id' => 'mw-upload-form' ) ) .
1138 Xml
::openElement( 'fieldset' ) .
1139 Xml
::element( 'legend', null, wfMsg( 'upload' ) ) .
1140 Xml
::openElement( 'table', array( 'border' => '0', 'id' => 'mw-upload-table' ) ) .
1142 {$this->uploadFormTextTop}
1143 <td class='mw-label'>
1144 <label for='wpUploadFile'>{$sourcefilename}</label>
1146 <td class='mw-input'>
1158 <td class='mw-label'>
1159 <label for='wpDestFile'>{$destfilename}</label>
1161 <td class='mw-input'>
1162 <input tabindex='2' type='text' name='wpDestFile' id='wpDestFile' size='60'
1163 value=\"{$encDestName}\" onchange='toggleFilenameFiller()' $on $destOnkeyup />
1167 <td class='mw-label'>
1168 <label for='wpUploadDescription'>{$summary}</label>
1170 <td class='mw-input'>
1171 <textarea tabindex='3' name='wpUploadDescription' id='wpUploadDescription' rows='6'
1172 cols='{$cols}'{$width}>$encComment</textarea>
1173 {$this->uploadFormTextAfterSummary}
1178 # Re-uploads should not need license info
1179 if ( !$this->mReUpload
&& $licenseshtml != '' ) {
1180 global $wgStylePath;
1182 <td class='mw-label'>
1183 <label for='wpLicense'>$license</label>
1185 <td class='mw-input'>
1186 <select name='wpLicense' id='wpLicense' tabindex='4'
1187 onchange='licenseSelectorCheck()'>
1188 <option value=''>$nolicense</option>
1195 if( $useAjaxLicensePreview ) {
1198 <td id=\"mw-license-preview\"></td>
1205 if ( $wgUseCopyrightUpload ) {
1206 $filestatus = wfMsgExt( 'filestatus', 'escapenoentities' );
1207 $copystatus = htmlspecialchars( $this->mCopyrightStatus
);
1208 $filesource = wfMsgExt( 'filesource', 'escapenoentities' );
1209 $uploadsource = htmlspecialchars( $this->mCopyrightSource
);
1212 <td class='mw-label' style='white-space: nowrap;'>
1213 <label for='wpUploadCopyStatus'>$filestatus</label></td>
1214 <td class='mw-input'>
1215 <input tabindex='5' type='text' name='wpUploadCopyStatus' id='wpUploadCopyStatus'
1216 value=\"$copystatus\" size='60' />
1220 <td class='mw-label'>
1221 <label for='wpUploadCopyStatus'>$filesource</label>
1223 <td class='mw-input'>
1224 <input tabindex='6' type='text' name='wpUploadSource' id='wpUploadCopyStatus'
1225 value=\"$uploadsource\" size='60' />
1235 <input tabindex='7' type='checkbox' name='wpWatchthis' id='wpWatchthis' $watchChecked value='true' />
1236 <label for='wpWatchthis'>" . wfMsgHtml( 'watchthisupload' ) . "</label>
1237 <input tabindex='8' type='checkbox' name='wpIgnoreWarning' id='wpIgnoreWarning' value='true' $warningChecked />
1238 <label for='wpIgnoreWarning'>" . wfMsgHtml( 'ignorewarnings' ) . "</label>
1244 <td class='mw-input'>
1245 <input tabindex='9' type='submit' name='wpUpload' value=\"{$ulb}\"" . $wgUser->getSkin()->tooltipAndAccesskey( 'upload' ) . " />
1250 <td class='mw-input'>"
1252 $wgOut->addWikiText( wfMsgForContent( 'edittools' ) );
1256 Xml
::closeElement( 'table' ) .
1257 Xml
::hidden( 'wpDestFileWarningAck', '', array( 'id' => 'wpDestFileWarningAck' ) ) .
1258 Xml
::closeElement( 'fieldset' ) .
1259 Xml
::closeElement( 'form' )
1261 $uploadfooter = wfMsgNoTrans( 'uploadfooter' );
1262 if( $uploadfooter != '-' && !wfEmptyMsg( 'uploadfooter', $uploadfooter ) ){
1263 $wgOut->addWikiText( '<div id="mw-upload-footer-message">' . $uploadfooter . '</div>' );
1267 /* -------------------------------------------------------------- */
1270 * See if we should check the 'watch this page' checkbox on the form
1271 * based on the user's preferences and whether we're being asked
1272 * to create a new file or update an existing one.
1274 * In the case where 'watch edits' is off but 'watch creations' is on,
1275 * we'll leave the box unchecked.
1277 * Note that the page target can be changed *on the form*, so our check
1278 * state can get out of sync.
1280 function watchCheck() {
1282 if( $wgUser->getOption( 'watchdefault' ) ) {
1287 $local = wfLocalFile( $this->mDesiredDestName
);
1288 if( $local && $local->exists() ) {
1289 // We're uploading a new version of an existing file.
1290 // No creation, so don't watch it if we're not already.
1291 return $local->getTitle()->userIsWatching();
1293 // New page should get watched if that's our option.
1294 return $wgUser->getOption( 'watchcreations' );
1299 * Split a file into a base name and all dot-delimited 'extensions'
1300 * on the end. Some web server configurations will fall back to
1301 * earlier pseudo-'extensions' to determine type and execute
1302 * scripts, so the blacklist needs to check them all.
1306 public function splitExtensions( $filename ) {
1307 $bits = explode( '.', $filename );
1308 $basename = array_shift( $bits );
1309 return array( $basename, $bits );
1313 * Perform case-insensitive match against a list of file extensions.
1314 * Returns true if the extension is in the list.
1316 * @param string $ext
1317 * @param array $list
1320 function checkFileExtension( $ext, $list ) {
1321 return in_array( strtolower( $ext ), $list );
1325 * Perform case-insensitive match against a list of file extensions.
1326 * Returns true if any of the extensions are in the list.
1329 * @param array $list
1332 public function checkFileExtensionList( $ext, $list ) {
1333 foreach( $ext as $e ) {
1334 if( in_array( strtolower( $e ), $list ) ) {
1342 * Verifies that it's ok to include the uploaded file
1344 * @param string $tmpfile the full path of the temporary file to verify
1345 * @param string $extension The filename extension that the file is to be served with
1346 * @return mixed true of the file is verified, a WikiError object otherwise.
1348 function verify( $tmpfile, $extension ) {
1349 #magically determine mime type
1350 $magic = MimeMagic
::singleton();
1351 $mime = $magic->guessMimeType($tmpfile,false);
1354 #check mime type, if desired
1355 global $wgVerifyMimeType;
1356 if ($wgVerifyMimeType) {
1357 wfDebug ( "\n\nmime: <$mime> extension: <$extension>\n\n");
1358 #check mime type against file extension
1359 if( !self
::verifyExtension( $mime, $extension ) ) {
1360 return new WikiErrorMsg( 'uploadcorrupt' );
1363 #check mime type blacklist
1364 global $wgMimeTypeBlacklist;
1365 if( isset($wgMimeTypeBlacklist) && !is_null($wgMimeTypeBlacklist) ) {
1366 if ( $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
1367 return new WikiErrorMsg( 'filetype-badmime', htmlspecialchars( $mime ) );
1371 $fp = fopen( $tmpfile, 'rb' );
1372 $chunk = fread( $fp, 256 );
1374 $extMime = $magic->guessTypesForExtension( $extension );
1375 $ieTypes = $magic->getIEMimeTypes( $tmpfile, $chunk, $extMime );
1376 foreach ( $ieTypes as $ieType ) {
1377 if ( $this->checkFileExtension( $ieType, $wgMimeTypeBlacklist ) ) {
1378 return new WikiErrorMsg( 'filetype-bad-ie-mime', $ieType );
1384 #check for htmlish code and javascript
1385 if( $this->detectScript ( $tmpfile, $mime, $extension ) ) {
1386 return new WikiErrorMsg( 'uploadscripted' );
1388 if( $extension == 'svg' ||
$mime == 'image/svg+xml' ) {
1389 if( $this->detectScriptInSvg( $tmpfile ) ) {
1390 return new WikiErrorMsg( 'uploadscripted' );
1395 * Scan the uploaded file for viruses
1397 $virus= $this->detectVirus($tmpfile);
1399 return new WikiErrorMsg( 'uploadvirus', htmlspecialchars($virus) );
1402 wfDebug( __METHOD__
.": all clear; passing.\n" );
1407 * Checks if the mime type of the uploaded file matches the file extension.
1409 * @param string $mime the mime type of the uploaded file
1410 * @param string $extension The filename extension that the file is to be served with
1413 static function verifyExtension( $mime, $extension ) {
1414 $magic = MimeMagic
::singleton();
1416 if ( ! $mime ||
$mime == 'unknown' ||
$mime == 'unknown/unknown' )
1417 if ( ! $magic->isRecognizableExtension( $extension ) ) {
1418 wfDebug( __METHOD__
.": passing file with unknown detected mime type; " .
1419 "unrecognized extension '$extension', can't verify\n" );
1422 wfDebug( __METHOD__
.": rejecting file with unknown detected mime type; ".
1423 "recognized extension '$extension', so probably invalid file\n" );
1427 $match= $magic->isMatchingExtension($extension,$mime);
1429 if ($match===NULL) {
1430 wfDebug( __METHOD__
.": no file extension known for mime type $mime, passing file\n" );
1432 } elseif ($match===true) {
1433 wfDebug( __METHOD__
.": mime type $mime matches extension $extension, passing file\n" );
1435 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
1439 wfDebug( __METHOD__
.": mime type $mime mismatches file extension $extension, rejecting file\n" );
1446 * Heuristic for detecting files that *could* contain JavaScript instructions or
1447 * things that may look like HTML to a browser and are thus
1448 * potentially harmful. The present implementation will produce false positives in some situations.
1450 * @param string $file Pathname to the temporary upload file
1451 * @param string $mime The mime type of the file
1452 * @param string $extension The extension of the file
1453 * @return bool true if the file contains something looking like embedded scripts
1455 function detectScript($file, $mime, $extension) {
1456 global $wgAllowTitlesInSVG;
1458 #ugly hack: for text files, always look at the entire file.
1459 #For binarie field, just check the first K.
1461 if (strpos($mime,'text/')===0) $chunk = file_get_contents( $file );
1463 $fp = fopen( $file, 'rb' );
1464 $chunk = fread( $fp, 1024 );
1468 $chunk= strtolower( $chunk );
1470 if (!$chunk) return false;
1472 #decode from UTF-16 if needed (could be used for obfuscation).
1473 if (substr($chunk,0,2)=="\xfe\xff") $enc= "UTF-16BE";
1474 elseif (substr($chunk,0,2)=="\xff\xfe") $enc= "UTF-16LE";
1477 if ($enc) $chunk= iconv($enc,"ASCII//IGNORE",$chunk);
1479 $chunk= trim($chunk);
1481 #FIXME: convert from UTF-16 if necessarry!
1483 wfDebug("SpecialUpload::detectScript: checking for embedded scripts and HTML stuff\n");
1485 #check for HTML doctype
1486 if (eregi("<!DOCTYPE *X?HTML",$chunk)) return true;
1489 * Internet Explorer for Windows performs some really stupid file type
1490 * autodetection which can cause it to interpret valid image files as HTML
1491 * and potentially execute JavaScript, creating a cross-site scripting
1494 * Apple's Safari browser also performs some unsafe file type autodetection
1495 * which can cause legitimate files to be interpreted as HTML if the
1496 * web server is not correctly configured to send the right content-type
1497 * (or if you're really uploading plain text and octet streams!)
1499 * Returns true if IE is likely to mistake the given file for HTML.
1500 * Also returns true if Safari would mistake the given file for HTML
1501 * when served with a generic content-type.
1508 '<html', #also in safari
1511 '<script', #also in safari
1514 if( ! $wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
1518 foreach( $tags as $tag ) {
1519 if( false !== strpos( $chunk, $tag ) ) {
1525 * look for javascript
1528 #resolve entity-refs to look at attributes. may be harsh on big files... cache result?
1529 $chunk = Sanitizer
::decodeCharReferences( $chunk );
1531 #look for script-types
1532 if (preg_match('!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim',$chunk)) return true;
1534 #look for html-style script-urls
1535 if (preg_match('!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim',$chunk)) return true;
1537 #look for css-style script-urls
1538 if (preg_match('!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim',$chunk)) return true;
1540 wfDebug("SpecialUpload::detectScript: no scripts found\n");
1544 function detectScriptInSvg( $filename ) {
1545 $check = new XmlTypeCheck( $filename, array( $this, 'checkSvgScriptCallback' ) );
1546 return $check->filterMatch
;
1550 * @todo Replace this with a whitelist filter!
1552 function checkSvgScriptCallback( $element, $attribs ) {
1553 $stripped = $this->stripXmlNamespace( $element );
1555 if( $stripped == 'script' ) {
1556 wfDebug( __METHOD__
. ": Found script element '$element' in uploaded file.\n" );
1560 foreach( $attribs as $attrib => $value ) {
1561 $stripped = $this->stripXmlNamespace( $attrib );
1562 if( substr( $stripped, 0, 2 ) == 'on' ) {
1563 wfDebug( __METHOD__
. ": Found script attribute '$attrib'='value' in uploaded file.\n" );
1566 if( $stripped == 'href' && strpos( strtolower( $value ), 'javascript:' ) !== false ) {
1567 wfDebug( __METHOD__
. ": Found script href attribute '$attrib'='$value' in uploaded file.\n" );
1573 private function stripXmlNamespace( $name ) {
1574 // 'http://www.w3.org/2000/svg:script' -> 'script'
1575 $parts = explode( ':', strtolower( $name ) );
1576 return array_pop( $parts );
1580 * Generic wrapper function for a virus scanner program.
1581 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
1582 * $wgAntivirusRequired may be used to deny upload if the scan fails.
1584 * @param string $file Pathname to the temporary upload file
1585 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
1586 * or a string containing feedback from the virus scanner if a virus was found.
1587 * If textual feedback is missing but a virus was found, this function returns true.
1589 function detectVirus($file) {
1590 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
1592 if ( !$wgAntivirus ) {
1593 wfDebug( __METHOD__
.": virus scanner disabled\n");
1597 if ( !$wgAntivirusSetup[$wgAntivirus] ) {
1598 wfDebug( __METHOD__
.": unknown virus scanner: $wgAntivirus\n" );
1599 $wgOut->wrapWikiMsg( '<div class="error">$1</div>', array( 'virus-badscanner', $wgAntivirus ) );
1600 return wfMsg('virus-unknownscanner') . " $wgAntivirus";
1603 # look up scanner configuration
1604 $command = $wgAntivirusSetup[$wgAntivirus]["command"];
1605 $exitCodeMap = $wgAntivirusSetup[$wgAntivirus]["codemap"];
1606 $msgPattern = isset( $wgAntivirusSetup[$wgAntivirus]["messagepattern"] ) ?
1607 $wgAntivirusSetup[$wgAntivirus]["messagepattern"] : null;
1609 if ( strpos( $command,"%f" ) === false ) {
1610 # simple pattern: append file to scan
1611 $command .= " " . wfEscapeShellArg( $file );
1613 # complex pattern: replace "%f" with file to scan
1614 $command = str_replace( "%f", wfEscapeShellArg( $file ), $command );
1617 wfDebug( __METHOD__
.": running virus scan: $command \n" );
1619 # execute virus scanner
1622 #NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
1623 # that does not seem to be worth the pain.
1624 # Ask me (Duesentrieb) about it if it's ever needed.
1626 if ( wfIsWindows() ) {
1627 exec( "$command", $output, $exitCode );
1629 exec( "$command 2>&1", $output, $exitCode );
1632 # map exit code to AV_xxx constants.
1633 $mappedCode = $exitCode;
1634 if ( $exitCodeMap ) {
1635 if ( isset( $exitCodeMap[$exitCode] ) ) {
1636 $mappedCode = $exitCodeMap[$exitCode];
1637 } elseif ( isset( $exitCodeMap["*"] ) ) {
1638 $mappedCode = $exitCodeMap["*"];
1642 if ( $mappedCode === AV_SCAN_FAILED
) {
1643 # scan failed (code was mapped to false by $exitCodeMap)
1644 wfDebug( __METHOD__
.": failed to scan $file (code $exitCode).\n" );
1646 if ( $wgAntivirusRequired ) {
1647 return wfMsg('virus-scanfailed', array( $exitCode ) );
1651 } else if ( $mappedCode === AV_SCAN_ABORTED
) {
1652 # scan failed because filetype is unknown (probably imune)
1653 wfDebug( __METHOD__
.": unsupported file type $file (code $exitCode).\n" );
1655 } else if ( $mappedCode === AV_NO_VIRUS
) {
1657 wfDebug( __METHOD__
.": file passed virus scan.\n" );
1660 $output = join( "\n", $output );
1661 $output = trim( $output );
1664 $output = true; #if there's no output, return true
1665 } elseif ( $msgPattern ) {
1667 if ( preg_match( $msgPattern, $output, $groups ) ) {
1669 $output = $groups[1];
1674 wfDebug( __METHOD__
.": FOUND VIRUS! scanner feedback: $output \n" );
1680 * Check if the temporary file is MacBinary-encoded, as some uploads
1681 * from Internet Explorer on Mac OS Classic and Mac OS X will be.
1682 * If so, the data fork will be extracted to a second temporary file,
1683 * which will then be checked for validity and either kept or discarded.
1687 function checkMacBinary() {
1688 $macbin = new MacBinary( $this->mTempPath
);
1689 if( $macbin->isValid() ) {
1690 $dataFile = tempnam( wfTempDir(), "WikiMacBinary" );
1691 $dataHandle = fopen( $dataFile, 'wb' );
1693 wfDebug( "SpecialUpload::checkMacBinary: Extracting MacBinary data fork to $dataFile\n" );
1694 $macbin->extractData( $dataHandle );
1696 $this->mTempPath
= $dataFile;
1697 $this->mFileSize
= $macbin->dataForkLength();
1699 // We'll have to manually remove the new file if it's not kept.
1700 $this->mRemoveTempFile
= true;
1706 * If we've modified the upload file we need to manually remove it
1707 * on exit to clean up.
1710 function cleanupTempFile() {
1711 if ( $this->mRemoveTempFile
&& $this->mTempPath
&& file_exists( $this->mTempPath
) ) {
1712 wfDebug( "SpecialUpload::cleanupTempFile: Removing temporary file {$this->mTempPath}\n" );
1713 unlink( $this->mTempPath
);
1718 * Check if there's an overwrite conflict and, if so, if restrictions
1719 * forbid this user from performing the upload.
1721 * @return mixed true on success, WikiError on failure
1724 function checkOverwrite( $name ) {
1725 $img = wfFindFile( $name );
1729 global $wgUser, $wgOut;
1730 if( $img->isLocal() ) {
1731 if( !self
::userCanReUpload( $wgUser, $img->name
) ) {
1732 $error = 'fileexists-forbidden';
1735 if( !$wgUser->isAllowed( 'reupload' ) ||
1736 !$wgUser->isAllowed( 'reupload-shared' ) ) {
1737 $error = "fileexists-shared-forbidden";
1743 $errorText = wfMsg( $error, wfEscapeWikiText( $img->getName() ) );
1747 // Rockin', go ahead and upload
1752 * Check if a user is the last uploader
1755 * @param string $img, image name
1758 public static function userCanReUpload( User
$user, $img ) {
1759 if( $user->isAllowed( 'reupload' ) )
1760 return true; // non-conditional
1761 if( !$user->isAllowed( 'reupload-own' ) )
1764 $dbr = wfGetDB( DB_SLAVE
);
1765 $row = $dbr->selectRow('image',
1766 /* SELECT */ 'img_user',
1767 /* WHERE */ array( 'img_name' => $img )
1772 return $user->getId() == $row->img_user
;
1776 * Display an error with a wikitext description
1778 function showError( $description ) {
1780 $wgOut->setPageTitle( wfMsg( "internalerror" ) );
1781 $wgOut->setRobotPolicy( "noindex,nofollow" );
1782 $wgOut->setArticleRelated( false );
1783 $wgOut->enableClientCache( false );
1784 $wgOut->addWikiText( $description );
1788 * Get the initial image page text based on a comment and optional file status information
1790 static function getInitialPageText( $comment, $license, $copyStatus, $source ) {
1791 global $wgUseCopyrightUpload;
1792 if ( $wgUseCopyrightUpload ) {
1793 if ( $license != '' ) {
1794 $licensetxt = '== ' . wfMsgForContent( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1796 $pageText = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $comment . "\n" .
1797 '== ' . wfMsgForContent ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
1799 '== ' . wfMsgForContent ( 'filesource' ) . " ==\n" . $source ;
1801 if ( $license != '' ) {
1802 $filedesc = $comment == '' ?
'' : '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $comment . "\n";
1803 $pageText = $filedesc .
1804 '== ' . wfMsgForContent ( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1806 $pageText = $comment;
1813 * If there are rows in the deletion log for this file, show them,
1814 * along with a nice little note for the user
1816 * @param OutputPage $out
1817 * @param string filename
1819 private function showDeletionLog( $out, $filename ) {
1821 $loglist = new LogEventsList( $wgUser->getSkin(), $out );
1822 $pager = new LogPager( $loglist, 'delete', false, $filename );
1823 if( $pager->getNumRows() > 0 ) {
1824 $out->addHTML( '<div class="mw-warning-with-logexcerpt">' );
1825 $out->addWikiMsg( 'upload-wasdeleted' );
1827 $loglist->beginLogEventsList() .
1829 $loglist->endLogEventsList()
1831 $out->addHTML( '</div>' );