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->mForReUpload
= $request->getBool( 'wpForReUpload' );
66 $this->mReUpload
= $request->getCheck( 'wpReUpload' );
68 if( !$request->wasPosted() ) {
69 # GET requests just give the main form; no data except destination
70 # filename and description
74 # Placeholders for text injection by hooks (empty per default)
75 $this->uploadFormTextTop
= "";
76 $this->uploadFormTextAfterSummary
= "";
77 $this->mUploadClicked
= $request->getCheck( 'wpUpload' );
79 $this->mLicense
= $request->getText( 'wpLicense' );
80 $this->mCopyrightStatus
= $request->getText( 'wpUploadCopyStatus' );
81 $this->mCopyrightSource
= $request->getText( 'wpUploadSource' );
82 $this->mWatchthis
= $request->getBool( 'wpWatchthis' );
83 $this->mSourceType
= $request->getText( 'wpSourceType' );
84 $this->mDestWarningAck
= $request->getText( 'wpDestFileWarningAck' );
86 $this->mAction
= $request->getVal( 'action' );
88 $this->mSessionKey
= $request->getInt( 'wpSessionKey' );
89 if( !empty( $this->mSessionKey
) &&
90 isset( $_SESSION['wsUploadData'][$this->mSessionKey
]['version'] ) &&
91 $_SESSION['wsUploadData'][$this->mSessionKey
]['version'] == self
::SESSION_VERSION
) {
93 * Confirming a temporarily stashed upload.
94 * We don't want path names to be forged, so we keep
95 * them in the session on the server and just give
96 * an opaque key to the user agent.
98 $data = $_SESSION['wsUploadData'][$this->mSessionKey
];
99 $this->mTempPath
= $data['mTempPath'];
100 $this->mFileSize
= $data['mFileSize'];
101 $this->mSrcName
= $data['mSrcName'];
102 $this->mFileProps
= $data['mFileProps'];
103 $this->mCurlError
= 0/*UPLOAD_ERR_OK*/;
104 $this->mStashed
= true;
105 $this->mRemoveTempFile
= false;
108 *Check for a newly uploaded file.
110 if( $wgAllowCopyUploads && $this->mSourceType
== 'web' ) {
111 $this->initializeFromUrl( $request );
113 $this->initializeFromUpload( $request );
119 * Initialize the uploaded file from PHP data
122 function initializeFromUpload( $request ) {
123 $this->mTempPath
= $request->getFileTempName( 'wpUploadFile' );
124 $this->mFileSize
= $request->getFileSize( 'wpUploadFile' );
125 $this->mSrcName
= $request->getFileName( 'wpUploadFile' );
126 $this->mCurlError
= $request->getUploadError( 'wpUploadFile' );
127 $this->mSessionKey
= false;
128 $this->mStashed
= false;
129 $this->mRemoveTempFile
= false; // PHP will handle this
133 * Copy a web file to a temporary file
136 function initializeFromUrl( $request ) {
137 global $wgTmpDirectory;
138 $url = $request->getText( 'wpUploadFileURL' );
139 $local_file = tempnam( $wgTmpDirectory, 'WEBUPLOAD' );
141 $this->mTempPath
= $local_file;
142 $this->mFileSize
= 0; # Will be set by curlCopy
143 $this->mCurlError
= $this->curlCopy( $url, $local_file );
144 $pathParts = explode( '/', $url );
145 $this->mSrcName
= array_pop( $pathParts );
146 $this->mSessionKey
= false;
147 $this->mStashed
= false;
149 // PHP won't auto-cleanup the file
150 $this->mRemoveTempFile
= file_exists( $local_file );
155 * Returns true if there was an error, false otherwise
157 private function curlCopy( $url, $dest ) {
158 global $wgUser, $wgOut, $wgHTTPProxy, $wgCopyUploadTimeout;
160 if( !$wgUser->isAllowed( 'upload_by_url' ) ) {
161 $wgOut->permissionRequired( 'upload_by_url' );
165 # Maybe remove some pasting blanks :-)
167 if( stripos($url, 'http://') !== 0 && stripos($url, 'ftp://') !== 0 ) {
168 # Only HTTP or FTP URLs
169 $wgOut->showErrorPage( 'upload-proto-error', 'upload-proto-error-text' );
173 # Open temporary file
174 $this->mCurlDestHandle
= @fopen
( $this->mTempPath
, "wb" );
175 if( $this->mCurlDestHandle
=== false ) {
176 # Could not open temporary file to write in
177 $wgOut->showErrorPage( 'upload-file-error', 'upload-file-error-text');
182 curl_setopt( $ch, CURLOPT_HTTP_VERSION
, 1.0); # Probably not needed, but apparently can work around some bug
183 curl_setopt( $ch, CURLOPT_TIMEOUT
, $wgCopyUploadTimeout); # Default 30 seconds timeout
184 curl_setopt( $ch, CURLOPT_LOW_SPEED_LIMIT
, 512); # 0.5KB per second minimum transfer speed
185 curl_setopt( $ch, CURLOPT_URL
, $url);
187 curl_setopt( $ch, CURLOPT_PROXY
, $wgHTTPProxy );
189 curl_setopt( $ch, CURLOPT_WRITEFUNCTION
, array( $this, 'uploadCurlCallback' ) );
191 $error = curl_errno( $ch ) ?
true : false;
192 $errornum = curl_errno( $ch );
193 // if ( $error ) print curl_error ( $ch ) ; # Debugging output
196 fclose( $this->mCurlDestHandle
);
197 unset( $this->mCurlDestHandle
);
200 if( wfEmptyMsg( "upload-curl-error$errornum", wfMsg("upload-curl-error$errornum") ) )
201 $wgOut->showErrorPage( 'upload-misc-error', 'upload-misc-error-text' );
203 $wgOut->showErrorPage( "upload-curl-error$errornum", "upload-curl-error$errornum-text" );
210 * Callback function for CURL-based web transfer
211 * Write data to file unless we've passed the length limit;
212 * if so, abort immediately.
215 function uploadCurlCallback( $ch, $data ) {
216 global $wgMaxUploadSize;
217 $length = strlen( $data );
218 $this->mFileSize +
= $length;
219 if( $this->mFileSize
> $wgMaxUploadSize ) {
222 fwrite( $this->mCurlDestHandle
, $data );
231 global $wgUser, $wgOut;
232 global $wgEnableUploads;
234 # Check php's file_uploads setting
235 if( !wfIniGetBool( 'file_uploads' ) ) {
236 $wgOut->showErrorPage( 'uploaddisabled', 'php-uploaddisabledtext', array( $this->mDesiredDestName
) );
240 # Check uploading enabled
241 if( !$wgEnableUploads ) {
242 $wgOut->showErrorPage( 'uploaddisabled', 'uploaddisabledtext', array( $this->mDesiredDestName
) );
247 global $wgGroupPermissions;
248 if( !$wgUser->isAllowed( 'upload' ) ) {
249 if( !$wgUser->isLoggedIn() && ( $wgGroupPermissions['user']['upload']
250 ||
$wgGroupPermissions['autoconfirmed']['upload'] ) ) {
251 // Custom message if logged-in users without any special rights can upload
252 $wgOut->showErrorPage( 'uploadnologin', 'uploadnologintext' );
254 $wgOut->permissionRequired( 'upload' );
260 if( $wgUser->isBlocked() ) {
261 $wgOut->blockedPage();
266 $wgOut->readOnlyPage();
270 if( $this->mReUpload
) {
271 if( !$this->unsaveUploadedFile() ) {
274 # Because it is probably checked and shouldn't be
275 $this->mIgnoreWarning
= false;
277 $this->mainUploadForm();
278 } else if( 'submit' == $this->mAction ||
$this->mUploadClicked
) {
279 $this->processUpload();
281 $this->mainUploadForm();
284 $this->cleanupTempFile();
289 * Checks are made in SpecialUpload::execute()
293 function processUpload(){
294 global $wgOut, $wgFileExtensions, $wgLang;
297 $value = $this->internalProcessUpload( $details );
301 $wgOut->redirect( $this->mLocalFile
->getTitle()->getFullURL() );
304 case self
::BEFORE_PROCESSING
:
307 case self
::LARGE_FILE_SERVER
:
308 $this->mainUploadForm( wfMsgHtml( 'largefileserver' ) );
311 case self
::EMPTY_FILE
:
312 $this->mainUploadForm( wfMsgHtml( 'emptyfile' ) );
315 case self
::MIN_LENGTH_PARTNAME
:
316 $this->mainUploadForm( wfMsgHtml( 'minlength1' ) );
319 case self
::ILLEGAL_FILENAME
:
320 $filtered = $details['filtered'];
321 $this->uploadError( wfMsgWikiHtml( 'illegalfilename', htmlspecialchars( $filtered ) ) );
324 case self
::PROTECTED_PAGE
:
325 $wgOut->showPermissionsErrorPage( $details['permissionserrors'] );
328 case self
::OVERWRITE_EXISTING_FILE
:
329 $errorText = $details['overwrite'];
330 $this->uploadError( $wgOut->parse( $errorText ) );
333 case self
::FILETYPE_MISSING
:
334 $this->uploadError( wfMsgExt( 'filetype-missing', array ( 'parseinline' ) ) );
337 case self
::FILETYPE_BADTYPE
:
338 $finalExt = $details['finalExt'];
340 wfMsgExt( 'filetype-banned-type',
341 array( 'parseinline' ),
342 htmlspecialchars( $finalExt ),
343 $wgLang->commaList( $wgFileExtensions ),
344 $wgLang->formatNum( count($wgFileExtensions) )
349 case self
::VERIFICATION_ERROR
:
350 $veri = $details['veri'];
351 $this->uploadError( $veri->toString() );
354 case self
::UPLOAD_VERIFICATION_ERROR
:
355 $error = $details['error'];
356 $this->uploadError( $error );
359 case self
::UPLOAD_WARNING
:
360 $warning = $details['warning'];
361 $this->uploadWarning( $warning );
364 case self
::INTERNAL_ERROR
:
365 $internal = $details['internal'];
366 $this->showError( $internal );
370 throw new MWException( __METHOD__
. ": Unknown value `{$value}`" );
375 * Really do the upload
376 * Checks are made in SpecialUpload::execute()
378 * @param array $resultDetails contains result-specific dict of additional values
382 function internalProcessUpload( &$resultDetails ) {
385 if( !wfRunHooks( 'UploadForm:BeforeProcessing', array( &$this ) ) )
387 wfDebug( "Hook 'UploadForm:BeforeProcessing' broke processing the file.\n" );
388 return self
::BEFORE_PROCESSING
;
392 * If there was no filename or a zero size given, give up quick.
394 if( trim( $this->mSrcName
) == '' ||
empty( $this->mFileSize
) ) {
395 return self
::EMPTY_FILE
;
398 /* Check for curl error */
399 if( $this->mCurlError
) {
400 return self
::BEFORE_PROCESSING
;
404 * Chop off any directories in the given filename. Then
405 * filter out illegal characters, and try to make a legible name
406 * out of it. We'll strip some silently that Title would die on.
408 if( $this->mDesiredDestName
) {
409 $basename = $this->mDesiredDestName
;
411 $basename = $this->mSrcName
;
413 $filtered = wfStripIllegalFilenameChars( $basename );
415 /* Normalize to title form before we do any further processing */
416 $nt = Title
::makeTitleSafe( NS_FILE
, $filtered );
417 if( is_null( $nt ) ) {
418 $resultDetails = array( 'filtered' => $filtered );
419 return self
::ILLEGAL_FILENAME
;
421 $filtered = $nt->getDBkey();
424 * We'll want to blacklist against *any* 'extension', and use
425 * only the final one for the whitelist.
427 list( $partname, $ext ) = $this->splitExtensions( $filtered );
429 if( count( $ext ) ) {
430 $finalExt = $ext[count( $ext ) - 1];
435 # If there was more than one "extension", reassemble the base
436 # filename to prevent bogus complaints about length
437 if( count( $ext ) > 1 ) {
438 for( $i = 0; $i < count( $ext ) - 1; $i++
)
439 $partname .= '.' . $ext[$i];
442 if( strlen( $partname ) < 1 ) {
443 return self
::MIN_LENGTH_PARTNAME
;
446 $this->mLocalFile
= wfLocalFile( $nt );
447 $this->mDestName
= $this->mLocalFile
->getName();
450 * If the image is protected, non-sysop users won't be able
451 * to modify it by uploading a new revision.
453 $permErrors = $nt->getUserPermissionsErrors( 'edit', $wgUser );
454 $permErrorsUpload = $nt->getUserPermissionsErrors( 'upload', $wgUser );
455 $permErrorsCreate = ( $nt->exists() ?
array() : $nt->getUserPermissionsErrors( 'create', $wgUser ) );
457 if( $permErrors ||
$permErrorsUpload ||
$permErrorsCreate ) {
458 // merge all the problems into one list, avoiding duplicates
459 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsUpload, $permErrors ) );
460 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsCreate, $permErrors ) );
461 $resultDetails = array( 'permissionserrors' => $permErrors );
462 return self
::PROTECTED_PAGE
;
466 * In some cases we may forbid overwriting of existing files.
468 $overwrite = $this->checkOverwrite( $this->mDestName
);
469 if( $overwrite !== true ) {
470 $resultDetails = array( 'overwrite' => $overwrite );
471 return self
::OVERWRITE_EXISTING_FILE
;
474 /* Don't allow users to override the blacklist (check file extension) */
475 global $wgCheckFileExtensions, $wgStrictFileExtensions;
476 global $wgFileExtensions, $wgFileBlacklist;
477 if ($finalExt == '') {
478 return self
::FILETYPE_MISSING
;
479 } elseif ( $this->checkFileExtensionList( $ext, $wgFileBlacklist ) ||
480 ($wgCheckFileExtensions && $wgStrictFileExtensions &&
481 !$this->checkFileExtension( $finalExt, $wgFileExtensions ) ) ) {
482 $resultDetails = array( 'finalExt' => $finalExt );
483 return self
::FILETYPE_BADTYPE
;
487 * Look at the contents of the file; if we can recognize the
488 * type but it's corrupt or data of the wrong type, we should
489 * probably not accept it.
491 if( !$this->mStashed
) {
492 $this->mFileProps
= File
::getPropsFromPath( $this->mTempPath
, $finalExt );
493 $this->checkMacBinary();
494 $veri = $this->verify( $this->mTempPath
, $finalExt );
496 if( $veri !== true ) { //it's a wiki error...
497 $resultDetails = array( 'veri' => $veri );
498 return self
::VERIFICATION_ERROR
;
502 * Provide an opportunity for extensions to add further checks
505 if( !wfRunHooks( 'UploadVerification',
506 array( $this->mDestName
, $this->mTempPath
, &$error ) ) ) {
507 $resultDetails = array( 'error' => $error );
508 return self
::UPLOAD_VERIFICATION_ERROR
;
514 * Check for non-fatal conditions
516 if ( ! $this->mIgnoreWarning
) {
519 $comparableName = str_replace( ' ', '_', $basename );
520 global $wgCapitalLinks, $wgContLang;
521 if ( $wgCapitalLinks ) {
522 $comparableName = $wgContLang->ucfirst( $comparableName );
525 if( $comparableName !== $filtered ) {
526 $warning .= '<li>'.wfMsgHtml( 'badfilename', htmlspecialchars( $this->mDestName
) ).'</li>';
529 global $wgCheckFileExtensions;
530 if ( $wgCheckFileExtensions ) {
531 if ( !$this->checkFileExtension( $finalExt, $wgFileExtensions ) ) {
534 wfMsgExt( 'filetype-unwanted-type',
535 array( 'parseinline' ),
536 htmlspecialchars( $finalExt ),
537 $wgLang->commaList( $wgFileExtensions ),
538 $wgLang->formatNum( count($wgFileExtensions) )
543 global $wgUploadSizeWarning;
544 if ( $wgUploadSizeWarning && ( $this->mFileSize
> $wgUploadSizeWarning ) ) {
545 $skin = $wgUser->getSkin();
546 $wsize = $skin->formatSize( $wgUploadSizeWarning );
547 $asize = $skin->formatSize( $this->mFileSize
);
548 $warning .= '<li>' . wfMsgHtml( 'large-file', $wsize, $asize ) . '</li>';
550 if ( $this->mFileSize
== 0 ) {
551 $warning .= '<li>'.wfMsgHtml( 'emptyfile' ).'</li>';
554 if ( !$this->mDestWarningAck
) {
555 $warning .= self
::getExistsWarning( $this->mLocalFile
);
558 $warning .= $this->getDupeWarning( $this->mTempPath
, $finalExt, $nt );
560 if( $warning != '' ) {
562 * Stash the file in a temporary location; the user can choose
563 * to let it through and we'll complete the upload then.
565 $resultDetails = array( 'warning' => $warning );
566 return self
::UPLOAD_WARNING
;
571 * Try actually saving the thing...
572 * It will show an error form on failure.
574 if( !$this->mForReUpload
) {
575 $pageText = self
::getInitialPageText( $this->mComment
, $this->mLicense
,
576 $this->mCopyrightStatus
, $this->mCopyrightSource
);
581 $status = $this->mLocalFile
->upload( $this->mTempPath
, $this->mComment
, $pageText,
582 File
::DELETE_SOURCE
, $this->mFileProps
);
583 if ( !$status->isGood() ) {
584 $resultDetails = array( 'internal' => $status->getWikiText() );
585 return self
::INTERNAL_ERROR
;
587 if ( $this->mWatchthis
) {
589 $wgUser->addWatch( $this->mLocalFile
->getTitle() );
591 // Success, redirect to description page
592 $img = null; // @todo: added to avoid passing a ref to null - should this be defined somewhere?
593 wfRunHooks( 'UploadComplete', array( &$this ) );
594 return self
::SUCCESS
;
599 * Do existence checks on a file and produce a warning
600 * This check is static and can be done pre-upload via AJAX
601 * Returns an HTML fragment consisting of one or more LI elements if there is a warning
602 * Returns an empty string if there is no warning
604 static function getExistsWarning( $file ) {
605 global $wgUser, $wgContLang;
606 // Check for uppercase extension. We allow these filenames but check if an image
607 // with lowercase extension exists already
609 $align = $wgContLang->isRtl() ?
'left' : 'right';
611 if( strpos( $file->getName(), '.' ) == false ) {
612 $partname = $file->getName();
615 $n = strrpos( $file->getName(), '.' );
616 $rawExtension = substr( $file->getName(), $n +
1 );
617 $partname = substr( $file->getName(), 0, $n );
620 $sk = $wgUser->getSkin();
622 if ( $rawExtension != $file->getExtension() ) {
623 // We're not using the normalized form of the extension.
624 // Normal form is lowercase, using most common of alternate
625 // extensions (eg 'jpg' rather than 'JPEG').
627 // Check for another file using the normalized form...
628 $nt_lc = Title
::makeTitle( NS_FILE
, $partname . '.' . $file->getExtension() );
629 $file_lc = wfLocalFile( $nt_lc );
634 if( $file->exists() ) {
635 $dlink = $sk->makeKnownLinkObj( $file->getTitle() );
636 if ( $file->allowInlineDisplay() ) {
637 $dlink2 = $sk->makeImageLinkObj( $file->getTitle(), wfMsgExt( 'fileexists-thumb', 'parseinline' ),
638 $file->getName(), $align, array(), false, true );
639 } elseif ( !$file->allowInlineDisplay() && $file->isSafeFile() ) {
640 $icon = $file->iconThumb();
641 $dlink2 = '<div style="float:' . $align . '" id="mw-media-icon">' .
642 $icon->toHtml( array( 'desc-link' => true ) ) . '<br />' . $dlink . '</div>';
647 $warning .= '<li>' . wfMsgExt( 'fileexists', array('parseinline','replaceafter'), $dlink ) . '</li>' . $dlink2;
649 } elseif( $file->getTitle()->getArticleID() ) {
650 $lnk = $sk->makeKnownLinkObj( $file->getTitle(), '', 'redirect=no' );
651 $warning .= '<li>' . wfMsgExt( 'filepageexists', array( 'parseinline', 'replaceafter' ), $lnk ) . '</li>';
652 } elseif ( $file_lc && $file_lc->exists() ) {
653 # Check if image with lowercase extension exists.
654 # It's not forbidden but in 99% it makes no sense to upload the same filename with uppercase extension
655 $dlink = $sk->makeKnownLinkObj( $nt_lc );
656 if ( $file_lc->allowInlineDisplay() ) {
657 $dlink2 = $sk->makeImageLinkObj( $nt_lc, wfMsgExt( 'fileexists-thumb', 'parseinline' ),
658 $nt_lc->getText(), $align, array(), false, true );
659 } elseif ( !$file_lc->allowInlineDisplay() && $file_lc->isSafeFile() ) {
660 $icon = $file_lc->iconThumb();
661 $dlink2 = '<div style="float:' . $align . '" id="mw-media-icon">' .
662 $icon->toHtml( array( 'desc-link' => true ) ) . '<br />' . $dlink . '</div>';
668 wfMsgExt( 'fileexists-extension', 'parsemag',
669 $file->getTitle()->getPrefixedText(), $dlink ) .
672 } elseif ( ( substr( $partname , 3, 3 ) == 'px-' ||
substr( $partname , 2, 3 ) == 'px-' )
673 && preg_match( "/[0-9]{2}/" , substr( $partname , 0, 2 ) ) )
675 # Check for filenames like 50px- or 180px-, these are mostly thumbnails
676 $nt_thb = Title
::newFromText( substr( $partname , strpos( $partname , '-' ) +
1 ) . '.' . $rawExtension );
677 $file_thb = wfLocalFile( $nt_thb );
678 if ($file_thb->exists() ) {
679 # Check if an image without leading '180px-' (or similiar) exists
680 $dlink = $sk->makeKnownLinkObj( $nt_thb);
681 if ( $file_thb->allowInlineDisplay() ) {
682 $dlink2 = $sk->makeImageLinkObj( $nt_thb,
683 wfMsgExt( 'fileexists-thumb', 'parseinline' ),
684 $nt_thb->getText(), $align, array(), false, true );
685 } elseif ( !$file_thb->allowInlineDisplay() && $file_thb->isSafeFile() ) {
686 $icon = $file_thb->iconThumb();
687 $dlink2 = '<div style="float:' . $align . '" id="mw-media-icon">' .
688 $icon->toHtml( array( 'desc-link' => true ) ) . '<br />' .
694 $warning .= '<li>' . wfMsgExt( 'fileexists-thumbnail-yes', 'parsemag', $dlink ) .
697 # Image w/o '180px-' does not exists, but we do not like these filenames
698 $warning .= '<li>' . wfMsgExt( 'file-thumbnail-no', 'parseinline' ,
699 substr( $partname , 0, strpos( $partname , '-' ) +
1 ) ) . '</li>';
703 $filenamePrefixBlacklist = self
::getFilenamePrefixBlacklist();
705 foreach( $filenamePrefixBlacklist as $prefix ) {
706 if ( substr( $partname, 0, strlen( $prefix ) ) == $prefix ) {
707 $warning .= '<li>' . wfMsgExt( 'filename-bad-prefix', 'parseinline', $prefix ) . '</li>';
712 if ( $file->wasDeleted() && !$file->exists() ) {
713 # If the file existed before and was deleted, warn the user of this
714 # Don't bother doing so if the file exists now, however
715 $ltitle = SpecialPage
::getTitleFor( 'Log' );
716 $llink = $sk->makeKnownLinkObj( $ltitle, wfMsgHtml( 'deletionlog' ),
717 'type=delete&page=' . $file->getTitle()->getPrefixedUrl() );
718 $warning .= '<li>' . wfMsgWikiHtml( 'filewasdeleted', $llink ) . '</li>';
724 * Get a list of warnings
726 * @param string local filename, e.g. 'file exists', 'non-descriptive filename'
727 * @return array list of warning messages
729 static function ajaxGetExistsWarning( $filename ) {
730 $file = wfFindFile( $filename );
732 // Force local file so we have an object to do further checks against
733 // if there isn't an exact match...
734 $file = wfLocalFile( $filename );
738 $warning = self
::getExistsWarning( $file );
739 if ( $warning !== '' ) {
740 $s = "<ul>$warning</ul>";
747 * Render a preview of a given license for the AJAX preview on upload
749 * @param string $license
752 public static function ajaxGetLicensePreview( $license ) {
753 global $wgParser, $wgUser;
754 $text = '{{' . $license . '}}';
755 $title = Title
::makeTitle( NS_FILE
, 'Sample.jpg' );
756 $options = ParserOptions
::newFromUser( $wgUser );
758 // Expand subst: first, then live templates...
759 $text = $wgParser->preSaveTransform( $text, $title, $wgUser, $options );
760 $output = $wgParser->parse( $text, $title, $options );
762 return $output->getText();
766 * Check for duplicate files and throw up a warning before the upload
769 function getDupeWarning( $tempfile, $extension, $destinationTitle ) {
770 $hash = File
::sha1Base36( $tempfile );
771 $dupes = RepoGroup
::singleton()->findBySha1( $hash );
772 $archivedImage = new ArchivedFile( null, 0, $hash.".$extension" );
776 foreach( $dupes as $file ) {
777 $title = $file->getTitle();
778 # Don't throw the warning when the titles are the same, it's a reupload
779 # and highly redundant.
780 if ( !$title->equals( $destinationTitle ) ||
!$this->mForReUpload
) {
781 $msg .= $title->getPrefixedText() .
782 "|" . $title->getText() . "\n";
785 $msg .= "</gallery>";
787 wfMsgExt( "file-exists-duplicate", array( "parse" ), count( $dupes ) ) .
788 $wgOut->parse( $msg ) .
790 } elseif ( $archivedImage->getID() > 0 ) {
792 $name = Title
::makeTitle( NS_FILE
, $archivedImage->getName() )->getPrefixedText();
793 return Xml
::tags( 'li', null, wfMsgExt( 'file-deleted-duplicate', array( 'parseinline' ), array( $name ) ) );
800 * Get a list of blacklisted filename prefixes from [[MediaWiki:filename-prefix-blacklist]]
802 * @return array list of prefixes
804 public static function getFilenamePrefixBlacklist() {
805 $blacklist = array();
806 $message = wfMsgForContent( 'filename-prefix-blacklist' );
807 if( $message && !( wfEmptyMsg( 'filename-prefix-blacklist', $message ) ||
$message == '-' ) ) {
808 $lines = explode( "\n", $message );
809 foreach( $lines as $line ) {
810 // Remove comment lines
811 $comment = substr( trim( $line ), 0, 1 );
812 if ( $comment == '#' ||
$comment == '' ) {
815 // Remove additional comments after a prefix
816 $comment = strpos( $line, '#' );
817 if ( $comment > 0 ) {
818 $line = substr( $line, 0, $comment-1 );
820 $blacklist[] = trim( $line );
827 * Stash a file in a temporary directory for later processing
828 * after the user has confirmed it.
830 * If the user doesn't explicitly cancel or accept, these files
831 * can accumulate in the temp directory.
833 * @param string $saveName - the destination filename
834 * @param string $tempName - the source temporary file to save
835 * @return string - full path the stashed file, or false on failure
838 function saveTempUploadedFile( $saveName, $tempName ) {
840 $repo = RepoGroup
::singleton()->getLocalRepo();
841 $status = $repo->storeTemp( $saveName, $tempName );
842 if ( !$status->isGood() ) {
843 $this->showError( $status->getWikiText() );
846 return $status->value
;
851 * Stash a file in a temporary directory for later processing,
852 * and save the necessary descriptive info into the session.
853 * Returns a key value which will be passed through a form
854 * to pick up the path info on a later invocation.
859 function stashSession() {
860 $stash = $this->saveTempUploadedFile( $this->mDestName
, $this->mTempPath
);
863 # Couldn't save the file.
867 $key = mt_rand( 0, 0x7fffffff );
868 $_SESSION['wsUploadData'][$key] = array(
869 'mTempPath' => $stash,
870 'mFileSize' => $this->mFileSize
,
871 'mSrcName' => $this->mSrcName
,
872 'mFileProps' => $this->mFileProps
,
873 'version' => self
::SESSION_VERSION
,
879 * Remove a temporarily kept file stashed by saveTempUploadedFile().
883 function unsaveUploadedFile() {
885 if( !$this->mTempPath
) return true; // nothing to delete
886 $repo = RepoGroup
::singleton()->getLocalRepo();
887 $success = $repo->freeTemp( $this->mTempPath
);
889 $wgOut->showFileDeleteError( $this->mTempPath
);
896 /* -------------------------------------------------------------- */
899 * @param string $error as HTML
902 function uploadError( $error ) {
904 $wgOut->addHTML( '<h2>' . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
905 $wgOut->addHTML( '<span class="error">' . $error . '</span>' );
909 * There's something wrong with this file, not enough to reject it
910 * totally but we require manual intervention to save it for real.
911 * Stash it away, then present a form asking to confirm or cancel.
913 * @param string $warning as HTML
916 function uploadWarning( $warning ) {
918 global $wgUseCopyrightUpload;
920 $this->mSessionKey
= $this->stashSession();
921 if( !$this->mSessionKey
) {
922 # Couldn't save file; an error has been displayed so let's go.
926 $wgOut->addHTML( '<h2>' . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
927 $wgOut->addHTML( '<ul class="warning">' . $warning . "</ul>\n" );
929 $titleObj = SpecialPage
::getTitleFor( 'Upload' );
931 if ( $wgUseCopyrightUpload ) {
932 $copyright = Xml
::hidden( 'wpUploadCopyStatus', $this->mCopyrightStatus
) . "\n" .
933 Xml
::hidden( 'wpUploadSource', $this->mCopyrightSource
) . "\n";
939 Xml
::openElement( 'form', array( 'method' => 'post', 'action' => $titleObj->getLocalURL( 'action=submit' ),
940 'enctype' => 'multipart/form-data', 'id' => 'uploadwarning' ) ) . "\n" .
941 Xml
::hidden( 'wpIgnoreWarning', '1' ) . "\n" .
942 Xml
::hidden( 'wpSessionKey', $this->mSessionKey
) . "\n" .
943 Xml
::hidden( 'wpUploadDescription', $this->mComment
) . "\n" .
944 Xml
::hidden( 'wpLicense', $this->mLicense
) . "\n" .
945 Xml
::hidden( 'wpDestFile', $this->mDesiredDestName
) . "\n" .
946 Xml
::hidden( 'wpWatchthis', $this->mWatchthis
) . "\n" .
947 "{$copyright}<br />" .
948 Xml
::submitButton( wfMsg( 'ignorewarning' ), array ( 'name' => 'wpUpload', 'id' => 'wpUpload', 'checked' => 'checked' ) ) . ' ' .
949 Xml
::submitButton( wfMsg( 'reuploaddesc' ), array ( 'name' => 'wpReUpload', 'id' => 'wpReUpload' ) ) .
950 Xml
::closeElement( 'form' ) . "\n"
955 * Displays the main upload form, optionally with a highlighted
956 * error message up at the top.
958 * @param string $msg as HTML
961 function mainUploadForm( $msg='' ) {
962 global $wgOut, $wgUser, $wgLang, $wgMaxUploadSize;
963 global $wgUseCopyrightUpload, $wgUseAjax, $wgAjaxUploadDestCheck, $wgAjaxLicensePreview;
964 global $wgRequest, $wgAllowCopyUploads;
965 global $wgStylePath, $wgStyleVersion;
967 $useAjaxDestCheck = $wgUseAjax && $wgAjaxUploadDestCheck;
968 $useAjaxLicensePreview = $wgUseAjax && $wgAjaxLicensePreview;
970 $adc = wfBoolToStr( $useAjaxDestCheck );
971 $alp = wfBoolToStr( $useAjaxLicensePreview );
972 $autofill = wfBoolToStr( $this->mDesiredDestName
== '' );
974 $wgOut->addScript( "<script type=\"text/javascript\">
975 wgAjaxUploadDestCheck = {$adc};
976 wgAjaxLicensePreview = {$alp};
977 wgUploadAutoFill = {$autofill};
979 $wgOut->addScriptFile( 'upload.js' );
980 $wgOut->addScriptFile( 'edit.js' ); // For <charinsert> support
982 if( !wfRunHooks( 'UploadForm:initial', array( &$this ) ) )
984 wfDebug( "Hook 'UploadForm:initial' broke output of the upload form\n" );
988 if( $this->mDesiredDestName
) {
989 $title = Title
::makeTitleSafe( NS_FILE
, $this->mDesiredDestName
);
990 // Show a subtitle link to deleted revisions (to sysops et al only)
991 if( $title instanceof Title
&& ( $count = $title->isDeleted() ) > 0 && $wgUser->isAllowed( 'deletedhistory' ) ) {
993 $wgUser->isAllowed( 'delete' ) ?
'thisisdeleted' : 'viewdeleted',
994 array( 'parse', 'replaceafter' ),
995 $wgUser->getSkin()->makeKnownLinkObj(
996 SpecialPage
::getTitleFor( 'Undelete', $title->getPrefixedText() ),
997 wfMsgExt( 'restorelink', array( 'parsemag', 'escape' ), $count )
1000 $wgOut->addHTML( "<div id=\"contentSub2\">{$link}</div>" );
1003 // Show the relevant lines from deletion log (for still deleted files only)
1004 if( $title instanceof Title
&& $title->isDeletedQuick() && !$title->exists() ) {
1005 $this->showDeletionLog( $wgOut, $title->getPrefixedText() );
1009 $cols = intval($wgUser->getOption( 'cols' ));
1011 if( $wgUser->getOption( 'editwidth' ) ) {
1012 $width = " style=\"width:100%\"";
1018 $sub = wfMsgHtml( 'uploaderror' );
1019 $wgOut->addHTML( "<h2>{$sub}</h2>\n" .
1020 "<span class='error'>{$msg}</span>\n" );
1022 $wgOut->addHTML( '<div id="uploadtext">' );
1023 $wgOut->addWikiMsg( 'uploadtext', $this->mDesiredDestName
);
1024 $wgOut->addHTML( "</div>\n" );
1026 # Print a list of allowed file extensions, if so configured. We ignore
1027 # MIME type here, it's incomprehensible to most people and too long.
1028 global $wgCheckFileExtensions, $wgStrictFileExtensions,
1029 $wgFileExtensions, $wgFileBlacklist;
1031 $allowedExtensions = '';
1032 if( $wgCheckFileExtensions ) {
1033 if( $wgStrictFileExtensions ) {
1034 # Everything not permitted is banned
1036 '<div id="mw-upload-permitted">' .
1037 wfMsgWikiHtml( 'upload-permitted', $wgLang->commaList( $wgFileExtensions ) ) .
1040 # We have to list both preferred and prohibited
1042 '<div id="mw-upload-preferred">' .
1043 wfMsgWikiHtml( 'upload-preferred', $wgLang->commaList( $wgFileExtensions ) ) .
1045 '<div id="mw-upload-prohibited">' .
1046 wfMsgWikiHtml( 'upload-prohibited', $wgLang->commaList( $wgFileBlacklist ) ) .
1050 # Everything is permitted.
1051 $extensionsList = '';
1054 # Get the maximum file size from php.ini as $wgMaxUploadSize works for uploads from URL via CURL only
1055 # See http://www.php.net/manual/en/faq.using.php#faq.using.shorthandbytes for possible values of upload_max_filesize and post_max_filesize
1056 $max_sizes = array();
1057 $max_sizes[] = trim( ini_get( 'upload_max_filesize' ) );
1058 $max_sizes[] = trim( ini_get( 'post_max_size' ) );
1059 foreach( $max_sizes as &$size) {
1060 $last = strtoupper( substr( $size, -1 ) );
1063 $size = substr( $size, 0, -1 ) * 1024 * 1024 * 1024;
1066 $size = substr( $size, 0, -1 ) * 1024 * 1024;
1069 $size = substr( $size, 0, -1 ) * 1024;
1073 $val = min( $max_sizes[0], $max_sizes[1] );
1074 $val = $wgAllowCopyUploads ?
min( $wgMaxUploadSize, $val ) : $val;
1075 $maxUploadSize = '<div id="mw-upload-maxfilesize">' .
1076 wfMsgExt( 'upload-maxfilesize', array( 'parseinline', 'escapenoentities' ),
1077 $wgLang->formatSize( $val ) ) .
1080 $sourcefilename = wfMsgExt( 'sourcefilename', array( 'parseinline', 'escapenoentities' ) );
1081 $destfilename = wfMsgExt( 'destfilename', array( 'parseinline', 'escapenoentities' ) );
1083 $msg = $this->mForReUpload ?
'filereuploadsummary' : 'fileuploadsummary';
1084 $summary = wfMsgExt( $msg, 'parseinline' );
1086 $licenses = new Licenses();
1087 $license = wfMsgExt( 'license', array( 'parseinline' ) );
1088 $nolicense = wfMsgHtml( 'nolicense' );
1089 $licenseshtml = $licenses->getHtml();
1091 $ulb = wfMsgHtml( 'uploadbtn' );
1094 $titleObj = SpecialPage
::getTitleFor( 'Upload' );
1096 $encDestName = htmlspecialchars( $this->mDesiredDestName
);
1098 $watchChecked = $this->watchCheck() ?
'checked="checked"' : '';
1099 # Re-uploads should not need "file exist already" warnings
1100 $warningChecked = ($this->mIgnoreWarning ||
$this->mForReUpload
) ?
'checked="checked"' : '';
1102 // Prepare form for upload or upload/copy
1103 if( $wgAllowCopyUploads && $wgUser->isAllowed( 'upload_by_url' ) ) {
1105 "<input type='radio' id='wpSourceTypeFile' name='wpSourceType' value='file' " .
1106 "onchange='toggle_element_activation(\"wpUploadFileURL\",\"wpUploadFile\")' checked='checked' />" .
1107 "<input tabindex='1' type='file' name='wpUploadFile' id='wpUploadFile' " .
1109 "toggle_element_activation(\"wpUploadFileURL\",\"wpUploadFile\");" .
1110 "toggle_element_check(\"wpSourceTypeFile\",\"wpSourceTypeURL\")' " .
1111 "onchange='fillDestFilename(\"wpUploadFile\")' size='60' />" .
1112 wfMsgHTML( 'upload_source_file' ) . "<br/>" .
1113 "<input type='radio' id='wpSourceTypeURL' name='wpSourceType' value='web' " .
1114 "onchange='toggle_element_activation(\"wpUploadFile\",\"wpUploadFileURL\")' />" .
1115 "<input tabindex='1' type='text' name='wpUploadFileURL' id='wpUploadFileURL' " .
1117 "toggle_element_activation(\"wpUploadFile\",\"wpUploadFileURL\");" .
1118 "toggle_element_check(\"wpSourceTypeURL\",\"wpSourceTypeFile\")' " .
1119 "onchange='fillDestFilename(\"wpUploadFileURL\")' size='60' disabled='disabled' />" .
1120 wfMsgHtml( 'upload_source_url' ) ;
1123 "<input tabindex='1' type='file' name='wpUploadFile' id='wpUploadFile' " .
1124 ($this->mDesiredDestName?
"":"onchange='fillDestFilename(\"wpUploadFile\")' ") .
1126 "<input type='hidden' name='wpSourceType' value='file' />" ;
1128 if ( $useAjaxDestCheck ) {
1129 $warningRow = "<tr><td colspan='2' id='wpDestFile-warning'> </td></tr>";
1130 $destOnkeyup = 'onkeyup="wgUploadWarningObj.keypress();"';
1135 $encComment = htmlspecialchars( $this->mComment
);
1139 Xml
::openElement( 'form', array( 'method' => 'post', 'action' => $titleObj->getLocalURL(),
1140 'enctype' => 'multipart/form-data', 'id' => 'mw-upload-form' ) ) .
1141 Xml
::openElement( 'fieldset' ) .
1142 Xml
::element( 'legend', null, wfMsg( 'upload' ) ) .
1143 Xml
::openElement( 'table', array( 'border' => '0', 'id' => 'mw-upload-table' ) ) .
1145 {$this->uploadFormTextTop}
1146 <td class='mw-label'>
1147 <label for='wpUploadFile'>{$sourcefilename}</label>
1149 <td class='mw-input'>
1161 <td class='mw-label'>
1162 <label for='wpDestFile'>{$destfilename}</label>
1164 <td class='mw-input'>"
1166 if( $this->mForReUpload
) {
1168 Xml
::hidden( 'wpDestFile', $this->mDesiredDestName
, array('id'=>'wpDestFile','tabindex'=>2) ) .
1176 "<input tabindex='2' type='text' name='wpDestFile' id='wpDestFile' size='60'
1177 value=\"{$encDestName}\" onchange='toggleFilenameFiller()' $destOnkeyup />"
1186 <td class='mw-label'>
1187 <label for='wpUploadDescription'>{$summary}</label>
1189 <td class='mw-input'>
1190 <textarea tabindex='3' name='wpUploadDescription' id='wpUploadDescription' rows='6'
1191 cols='{$cols}'{$width}>$encComment</textarea>
1192 {$this->uploadFormTextAfterSummary}
1197 # Re-uploads should not need license info
1198 if ( !$this->mForReUpload
&& $licenseshtml != '' ) {
1199 global $wgStylePath;
1201 <td class='mw-label'>
1202 <label for='wpLicense'>$license</label>
1204 <td class='mw-input'>
1205 <select name='wpLicense' id='wpLicense' tabindex='4'
1206 onchange='licenseSelectorCheck()'>
1207 <option value=''>$nolicense</option>
1214 if( $useAjaxLicensePreview ) {
1217 <td id=\"mw-license-preview\"></td>
1224 if ( !$this->mForReUpload
&& $wgUseCopyrightUpload ) {
1225 $filestatus = wfMsgExt( 'filestatus', 'escapenoentities' );
1226 $copystatus = htmlspecialchars( $this->mCopyrightStatus
);
1227 $filesource = wfMsgExt( 'filesource', 'escapenoentities' );
1228 $uploadsource = htmlspecialchars( $this->mCopyrightSource
);
1231 <td class='mw-label' style='white-space: nowrap;'>
1232 <label for='wpUploadCopyStatus'>$filestatus</label></td>
1233 <td class='mw-input'>
1234 <input tabindex='5' type='text' name='wpUploadCopyStatus' id='wpUploadCopyStatus'
1235 value=\"$copystatus\" size='60' />
1239 <td class='mw-label'>
1240 <label for='wpUploadCopyStatus'>$filesource</label>
1242 <td class='mw-input'>
1243 <input tabindex='6' type='text' name='wpUploadSource' id='wpUploadCopyStatus'
1244 value=\"$uploadsource\" size='60' />
1254 <input tabindex='7' type='checkbox' name='wpWatchthis' id='wpWatchthis' $watchChecked value='true' />
1255 <label for='wpWatchthis'>" . wfMsgHtml( 'watchthisupload' ) . "</label>
1256 <input tabindex='8' type='checkbox' name='wpIgnoreWarning' id='wpIgnoreWarning' value='true' $warningChecked />
1257 <label for='wpIgnoreWarning'>" . wfMsgHtml( 'ignorewarnings' ) . "</label>
1263 <td class='mw-input'>
1264 <input tabindex='9' type='submit' name='wpUpload' value=\"{$ulb}\"" .
1265 $wgUser->getSkin()->tooltipAndAccesskey( 'upload' ) . " />
1270 <td class='mw-input'>"
1272 $wgOut->addHTML( '<div class="mw-editTools">' );
1273 $wgOut->addWikiMsgArray( 'edittools', array(), array( 'content' ) );
1274 $wgOut->addHTML( '</div>' );
1278 Xml
::closeElement( 'table' ) .
1279 Xml
::hidden( 'wpDestFileWarningAck', '', array( 'id' => 'wpDestFileWarningAck' ) ) .
1280 Xml
::hidden( 'wpForReUpload', $this->mForReUpload
, array( 'id' => 'wpForReUpload' ) ) .
1281 Xml
::closeElement( 'fieldset' ) .
1282 Xml
::closeElement( 'form' )
1284 $uploadfooter = wfMsgNoTrans( 'uploadfooter' );
1285 if( $uploadfooter != '-' && !wfEmptyMsg( 'uploadfooter', $uploadfooter ) ){
1286 $wgOut->addWikiText( '<div id="mw-upload-footer-message">' . $uploadfooter . '</div>' );
1290 /* -------------------------------------------------------------- */
1293 * See if we should check the 'watch this page' checkbox on the form
1294 * based on the user's preferences and whether we're being asked
1295 * to create a new file or update an existing one.
1297 * In the case where 'watch edits' is off but 'watch creations' is on,
1298 * we'll leave the box unchecked.
1300 * Note that the page target can be changed *on the form*, so our check
1301 * state can get out of sync.
1303 function watchCheck() {
1305 if( $wgUser->getOption( 'watchdefault' ) ) {
1310 $local = wfLocalFile( $this->mDesiredDestName
);
1311 if( $local && $local->exists() ) {
1312 // We're uploading a new version of an existing file.
1313 // No creation, so don't watch it if we're not already.
1314 return $local->getTitle()->userIsWatching();
1316 // New page should get watched if that's our option.
1317 return $wgUser->getOption( 'watchcreations' );
1322 * Split a file into a base name and all dot-delimited 'extensions'
1323 * on the end. Some web server configurations will fall back to
1324 * earlier pseudo-'extensions' to determine type and execute
1325 * scripts, so the blacklist needs to check them all.
1329 public function splitExtensions( $filename ) {
1330 $bits = explode( '.', $filename );
1331 $basename = array_shift( $bits );
1332 return array( $basename, $bits );
1336 * Perform case-insensitive match against a list of file extensions.
1337 * Returns true if the extension is in the list.
1339 * @param string $ext
1340 * @param array $list
1343 function checkFileExtension( $ext, $list ) {
1344 return in_array( strtolower( $ext ), $list );
1348 * Perform case-insensitive match against a list of file extensions.
1349 * Returns true if any of the extensions are in the list.
1352 * @param array $list
1355 public function checkFileExtensionList( $ext, $list ) {
1356 foreach( $ext as $e ) {
1357 if( in_array( strtolower( $e ), $list ) ) {
1365 * Verifies that it's ok to include the uploaded file
1367 * @param string $tmpfile the full path of the temporary file to verify
1368 * @param string $extension The filename extension that the file is to be served with
1369 * @return mixed true of the file is verified, a WikiError object otherwise.
1371 function verify( $tmpfile, $extension ) {
1372 #magically determine mime type
1373 $magic = MimeMagic
::singleton();
1374 $mime = $magic->guessMimeType($tmpfile,false);
1377 #check mime type, if desired
1378 global $wgVerifyMimeType;
1379 if ($wgVerifyMimeType) {
1380 wfDebug ( "\n\nmime: <$mime> extension: <$extension>\n\n");
1381 #check mime type against file extension
1382 if( !self
::verifyExtension( $mime, $extension ) ) {
1383 return new WikiErrorMsg( 'uploadcorrupt' );
1386 #check mime type blacklist
1387 global $wgMimeTypeBlacklist;
1388 if( isset($wgMimeTypeBlacklist) && !is_null($wgMimeTypeBlacklist) ) {
1389 if ( $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
1390 return new WikiErrorMsg( 'filetype-badmime', htmlspecialchars( $mime ) );
1394 $fp = fopen( $tmpfile, 'rb' );
1395 $chunk = fread( $fp, 256 );
1397 $extMime = $magic->guessTypesForExtension( $extension );
1398 $ieTypes = $magic->getIEMimeTypes( $tmpfile, $chunk, $extMime );
1399 foreach ( $ieTypes as $ieType ) {
1400 if ( $this->checkFileExtension( $ieType, $wgMimeTypeBlacklist ) ) {
1401 return new WikiErrorMsg( 'filetype-bad-ie-mime', $ieType );
1407 #check for htmlish code and javascript
1408 if( $this->detectScript ( $tmpfile, $mime, $extension ) ) {
1409 return new WikiErrorMsg( 'uploadscripted' );
1411 if( $extension == 'svg' ||
$mime == 'image/svg+xml' ) {
1412 if( $this->detectScriptInSvg( $tmpfile ) ) {
1413 return new WikiErrorMsg( 'uploadscripted' );
1418 * Scan the uploaded file for viruses
1420 $virus= $this->detectVirus($tmpfile);
1422 return new WikiErrorMsg( 'uploadvirus', htmlspecialchars($virus) );
1425 wfDebug( __METHOD__
.": all clear; passing.\n" );
1430 * Checks if the mime type of the uploaded file matches the file extension.
1432 * @param string $mime the mime type of the uploaded file
1433 * @param string $extension The filename extension that the file is to be served with
1436 static function verifyExtension( $mime, $extension ) {
1437 $magic = MimeMagic
::singleton();
1439 if ( ! $mime ||
$mime == 'unknown' ||
$mime == 'unknown/unknown' )
1440 if ( ! $magic->isRecognizableExtension( $extension ) ) {
1441 wfDebug( __METHOD__
.": passing file with unknown detected mime type; " .
1442 "unrecognized extension '$extension', can't verify\n" );
1445 wfDebug( __METHOD__
.": rejecting file with unknown detected mime type; ".
1446 "recognized extension '$extension', so probably invalid file\n" );
1450 $match= $magic->isMatchingExtension($extension,$mime);
1452 if ($match===NULL) {
1453 wfDebug( __METHOD__
.": no file extension known for mime type $mime, passing file\n" );
1455 } elseif ($match===true) {
1456 wfDebug( __METHOD__
.": mime type $mime matches extension $extension, passing file\n" );
1458 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
1462 wfDebug( __METHOD__
.": mime type $mime mismatches file extension $extension, rejecting file\n" );
1469 * Heuristic for detecting files that *could* contain JavaScript instructions or
1470 * things that may look like HTML to a browser and are thus
1471 * potentially harmful. The present implementation will produce false positives in some situations.
1473 * @param string $file Pathname to the temporary upload file
1474 * @param string $mime The mime type of the file
1475 * @param string $extension The extension of the file
1476 * @return bool true if the file contains something looking like embedded scripts
1478 function detectScript($file, $mime, $extension) {
1479 global $wgAllowTitlesInSVG;
1481 #ugly hack: for text files, always look at the entire file.
1482 #For binarie field, just check the first K.
1484 if (strpos($mime,'text/')===0) $chunk = file_get_contents( $file );
1486 $fp = fopen( $file, 'rb' );
1487 $chunk = fread( $fp, 1024 );
1491 $chunk= strtolower( $chunk );
1493 if (!$chunk) return false;
1495 #decode from UTF-16 if needed (could be used for obfuscation).
1496 if (substr($chunk,0,2)=="\xfe\xff") $enc= "UTF-16BE";
1497 elseif (substr($chunk,0,2)=="\xff\xfe") $enc= "UTF-16LE";
1500 if ($enc) $chunk= iconv($enc,"ASCII//IGNORE",$chunk);
1502 $chunk= trim($chunk);
1504 #FIXME: convert from UTF-16 if necessarry!
1506 wfDebug("SpecialUpload::detectScript: checking for embedded scripts and HTML stuff\n");
1508 #check for HTML doctype
1509 if ( preg_match( "/<!DOCTYPE *X?HTML/i", $chunk ) ) return true;
1512 * Internet Explorer for Windows performs some really stupid file type
1513 * autodetection which can cause it to interpret valid image files as HTML
1514 * and potentially execute JavaScript, creating a cross-site scripting
1517 * Apple's Safari browser also performs some unsafe file type autodetection
1518 * which can cause legitimate files to be interpreted as HTML if the
1519 * web server is not correctly configured to send the right content-type
1520 * (or if you're really uploading plain text and octet streams!)
1522 * Returns true if IE is likely to mistake the given file for HTML.
1523 * Also returns true if Safari would mistake the given file for HTML
1524 * when served with a generic content-type.
1531 '<html', #also in safari
1534 '<script', #also in safari
1537 if( ! $wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
1541 foreach( $tags as $tag ) {
1542 if( false !== strpos( $chunk, $tag ) ) {
1548 * look for javascript
1551 #resolve entity-refs to look at attributes. may be harsh on big files... cache result?
1552 $chunk = Sanitizer
::decodeCharReferences( $chunk );
1554 #look for script-types
1555 if (preg_match('!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim',$chunk)) return true;
1557 #look for html-style script-urls
1558 if (preg_match('!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim',$chunk)) return true;
1560 #look for css-style script-urls
1561 if (preg_match('!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim',$chunk)) return true;
1563 wfDebug("SpecialUpload::detectScript: no scripts found\n");
1567 function detectScriptInSvg( $filename ) {
1568 $check = new XmlTypeCheck( $filename, array( $this, 'checkSvgScriptCallback' ) );
1569 return $check->filterMatch
;
1573 * @todo Replace this with a whitelist filter!
1575 function checkSvgScriptCallback( $element, $attribs ) {
1576 $stripped = $this->stripXmlNamespace( $element );
1578 if( $stripped == 'script' ) {
1579 wfDebug( __METHOD__
. ": Found script element '$element' in uploaded file.\n" );
1583 foreach( $attribs as $attrib => $value ) {
1584 $stripped = $this->stripXmlNamespace( $attrib );
1585 if( substr( $stripped, 0, 2 ) == 'on' ) {
1586 wfDebug( __METHOD__
. ": Found script attribute '$attrib'='value' in uploaded file.\n" );
1589 if( $stripped == 'href' && strpos( strtolower( $value ), 'javascript:' ) !== false ) {
1590 wfDebug( __METHOD__
. ": Found script href attribute '$attrib'='$value' in uploaded file.\n" );
1596 private function stripXmlNamespace( $name ) {
1597 // 'http://www.w3.org/2000/svg:script' -> 'script'
1598 $parts = explode( ':', strtolower( $name ) );
1599 return array_pop( $parts );
1603 * Generic wrapper function for a virus scanner program.
1604 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
1605 * $wgAntivirusRequired may be used to deny upload if the scan fails.
1607 * @param string $file Pathname to the temporary upload file
1608 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
1609 * or a string containing feedback from the virus scanner if a virus was found.
1610 * If textual feedback is missing but a virus was found, this function returns true.
1612 function detectVirus($file) {
1613 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
1615 if ( !$wgAntivirus ) {
1616 wfDebug( __METHOD__
.": virus scanner disabled\n");
1620 if ( !$wgAntivirusSetup[$wgAntivirus] ) {
1621 wfDebug( __METHOD__
.": unknown virus scanner: $wgAntivirus\n" );
1622 $wgOut->wrapWikiMsg( '<div class="error">$1</div>', array( 'virus-badscanner', $wgAntivirus ) );
1623 return wfMsg('virus-unknownscanner') . " $wgAntivirus";
1626 # look up scanner configuration
1627 $command = $wgAntivirusSetup[$wgAntivirus]["command"];
1628 $exitCodeMap = $wgAntivirusSetup[$wgAntivirus]["codemap"];
1629 $msgPattern = isset( $wgAntivirusSetup[$wgAntivirus]["messagepattern"] ) ?
1630 $wgAntivirusSetup[$wgAntivirus]["messagepattern"] : null;
1632 if ( strpos( $command,"%f" ) === false ) {
1633 # simple pattern: append file to scan
1634 $command .= " " . wfEscapeShellArg( $file );
1636 # complex pattern: replace "%f" with file to scan
1637 $command = str_replace( "%f", wfEscapeShellArg( $file ), $command );
1640 wfDebug( __METHOD__
.": running virus scan: $command \n" );
1642 # execute virus scanner
1645 #NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
1646 # that does not seem to be worth the pain.
1647 # Ask me (Duesentrieb) about it if it's ever needed.
1649 if ( wfIsWindows() ) {
1650 exec( "$command", $output, $exitCode );
1652 exec( "$command 2>&1", $output, $exitCode );
1655 # map exit code to AV_xxx constants.
1656 $mappedCode = $exitCode;
1657 if ( $exitCodeMap ) {
1658 if ( isset( $exitCodeMap[$exitCode] ) ) {
1659 $mappedCode = $exitCodeMap[$exitCode];
1660 } elseif ( isset( $exitCodeMap["*"] ) ) {
1661 $mappedCode = $exitCodeMap["*"];
1665 if ( $mappedCode === AV_SCAN_FAILED
) {
1666 # scan failed (code was mapped to false by $exitCodeMap)
1667 wfDebug( __METHOD__
.": failed to scan $file (code $exitCode).\n" );
1669 if ( $wgAntivirusRequired ) {
1670 return wfMsg('virus-scanfailed', array( $exitCode ) );
1674 } else if ( $mappedCode === AV_SCAN_ABORTED
) {
1675 # scan failed because filetype is unknown (probably imune)
1676 wfDebug( __METHOD__
.": unsupported file type $file (code $exitCode).\n" );
1678 } else if ( $mappedCode === AV_NO_VIRUS
) {
1680 wfDebug( __METHOD__
.": file passed virus scan.\n" );
1683 $output = join( "\n", $output );
1684 $output = trim( $output );
1687 $output = true; #if there's no output, return true
1688 } elseif ( $msgPattern ) {
1690 if ( preg_match( $msgPattern, $output, $groups ) ) {
1692 $output = $groups[1];
1697 wfDebug( __METHOD__
.": FOUND VIRUS! scanner feedback: $output \n" );
1703 * Check if the temporary file is MacBinary-encoded, as some uploads
1704 * from Internet Explorer on Mac OS Classic and Mac OS X will be.
1705 * If so, the data fork will be extracted to a second temporary file,
1706 * which will then be checked for validity and either kept or discarded.
1710 function checkMacBinary() {
1711 $macbin = new MacBinary( $this->mTempPath
);
1712 if( $macbin->isValid() ) {
1713 $dataFile = tempnam( wfTempDir(), "WikiMacBinary" );
1714 $dataHandle = fopen( $dataFile, 'wb' );
1716 wfDebug( "SpecialUpload::checkMacBinary: Extracting MacBinary data fork to $dataFile\n" );
1717 $macbin->extractData( $dataHandle );
1719 $this->mTempPath
= $dataFile;
1720 $this->mFileSize
= $macbin->dataForkLength();
1722 // We'll have to manually remove the new file if it's not kept.
1723 $this->mRemoveTempFile
= true;
1729 * If we've modified the upload file we need to manually remove it
1730 * on exit to clean up.
1733 function cleanupTempFile() {
1734 if ( $this->mRemoveTempFile
&& $this->mTempPath
&& file_exists( $this->mTempPath
) ) {
1735 wfDebug( "SpecialUpload::cleanupTempFile: Removing temporary file {$this->mTempPath}\n" );
1736 unlink( $this->mTempPath
);
1741 * Check if there's an overwrite conflict and, if so, if restrictions
1742 * forbid this user from performing the upload.
1744 * @return mixed true on success, WikiError on failure
1747 function checkOverwrite( $name ) {
1748 $img = wfFindFile( $name );
1752 global $wgUser, $wgOut;
1753 if( $img->isLocal() ) {
1754 if( !self
::userCanReUpload( $wgUser, $img->name
) ) {
1755 $error = 'fileexists-forbidden';
1758 if( !$wgUser->isAllowed( 'reupload' ) ||
1759 !$wgUser->isAllowed( 'reupload-shared' ) ) {
1760 $error = "fileexists-shared-forbidden";
1766 $errorText = wfMsg( $error, wfEscapeWikiText( $img->getName() ) );
1770 // Rockin', go ahead and upload
1775 * Check if a user is the last uploader
1778 * @param string $img, image name
1781 public static function userCanReUpload( User
$user, $img ) {
1782 if( $user->isAllowed( 'reupload' ) )
1783 return true; // non-conditional
1784 if( !$user->isAllowed( 'reupload-own' ) )
1787 $dbr = wfGetDB( DB_SLAVE
);
1788 $row = $dbr->selectRow('image',
1789 /* SELECT */ 'img_user',
1790 /* WHERE */ array( 'img_name' => $img )
1795 return $user->getId() == $row->img_user
;
1799 * Display an error with a wikitext description
1801 function showError( $description ) {
1803 $wgOut->setPageTitle( wfMsg( "internalerror" ) );
1804 $wgOut->setRobotPolicy( "noindex,nofollow" );
1805 $wgOut->setArticleRelated( false );
1806 $wgOut->enableClientCache( false );
1807 $wgOut->addWikiText( $description );
1811 * Get the initial image page text based on a comment and optional file status information
1813 static function getInitialPageText( $comment, $license, $copyStatus, $source ) {
1814 global $wgUseCopyrightUpload;
1815 if ( $wgUseCopyrightUpload ) {
1816 if ( $license != '' ) {
1817 $licensetxt = '== ' . wfMsgForContent( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1819 $pageText = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $comment . "\n" .
1820 '== ' . wfMsgForContent ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
1822 '== ' . wfMsgForContent ( 'filesource' ) . " ==\n" . $source ;
1824 if ( $license != '' ) {
1825 $filedesc = $comment == '' ?
'' : '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $comment . "\n";
1826 $pageText = $filedesc .
1827 '== ' . wfMsgForContent ( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1829 $pageText = $comment;
1836 * If there are rows in the deletion log for this file, show them,
1837 * along with a nice little note for the user
1839 * @param OutputPage $out
1840 * @param string filename
1842 private function showDeletionLog( $out, $filename ) {
1844 $loglist = new LogEventsList( $wgUser->getSkin(), $out );
1845 $pager = new LogPager( $loglist, 'delete', false, $filename );
1846 if( $pager->getNumRows() > 0 ) {
1847 $out->addHTML( '<div class="mw-warning-with-logexcerpt">' );
1848 $out->addWikiMsg( 'upload-wasdeleted' );
1850 $loglist->beginLogEventsList() .
1852 $loglist->endLogEventsList()
1854 $out->addHTML( '</div>' );