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;
160 if( !$wgUser->isAllowed( 'upload_by_url' ) ) {
161 $wgOut->permissionRequired( 'upload_by_url' );
165 # Maybe remove some pasting blanks :-)
167 if( stripos($url, 'http://') !== 0 && stripos($url, 'ftp://') !== 0 ) {
168 # Only HTTP or FTP URLs
169 $wgOut->showErrorPage( 'upload-proto-error', 'upload-proto-error-text' );
173 # Open temporary file
174 $this->mCurlDestHandle
= @fopen
( $this->mTempPath
, "wb" );
175 if( $this->mCurlDestHandle
=== false ) {
176 # Could not open temporary file to write in
177 $wgOut->showErrorPage( 'upload-file-error', 'upload-file-error-text');
182 curl_setopt( $ch, CURLOPT_HTTP_VERSION
, 1.0); # Probably not needed, but apparently can work around some bug
183 curl_setopt( $ch, CURLOPT_TIMEOUT
, 10); # 10 seconds timeout
184 curl_setopt( $ch, CURLOPT_LOW_SPEED_LIMIT
, 512); # 0.5KB per second minimum transfer speed
185 curl_setopt( $ch, CURLOPT_URL
, $url);
186 curl_setopt( $ch, CURLOPT_WRITEFUNCTION
, array( $this, 'uploadCurlCallback' ) );
188 $error = curl_errno( $ch ) ?
true : false;
189 $errornum = curl_errno( $ch );
190 // if ( $error ) print curl_error ( $ch ) ; # Debugging output
193 fclose( $this->mCurlDestHandle
);
194 unset( $this->mCurlDestHandle
);
197 if( wfEmptyMsg( "upload-curl-error$errornum", wfMsg("upload-curl-error$errornum") ) )
198 $wgOut->showErrorPage( 'upload-misc-error', 'upload-misc-error-text' );
200 $wgOut->showErrorPage( "upload-curl-error$errornum", "upload-curl-error$errornum-text" );
207 * Callback function for CURL-based web transfer
208 * Write data to file unless we've passed the length limit;
209 * if so, abort immediately.
212 function uploadCurlCallback( $ch, $data ) {
213 global $wgMaxUploadSize;
214 $length = strlen( $data );
215 $this->mFileSize +
= $length;
216 if( $this->mFileSize
> $wgMaxUploadSize ) {
219 fwrite( $this->mCurlDestHandle
, $data );
228 global $wgUser, $wgOut;
229 global $wgEnableUploads;
231 # Check php's file_uploads setting
232 if( !wfIniGetBool( 'file_uploads' ) ) {
233 $wgOut->showErrorPage( 'uploaddisabled', 'php-uploaddisabledtext', array( $this->mDesiredDestName
) );
237 # Check uploading enabled
238 if( !$wgEnableUploads ) {
239 $wgOut->showErrorPage( 'uploaddisabled', 'uploaddisabledtext', array( $this->mDesiredDestName
) );
244 if( !$wgUser->isAllowed( 'upload' ) ) {
245 if( !$wgUser->isLoggedIn() ) {
246 $wgOut->showErrorPage( 'uploadnologin', 'uploadnologintext' );
248 $wgOut->permissionRequired( 'upload' );
254 if( $wgUser->isBlocked() ) {
255 $wgOut->blockedPage();
260 $wgOut->readOnlyPage();
264 if( $this->mReUpload
) {
265 if( !$this->unsaveUploadedFile() ) {
268 # Because it is probably checked and shouldn't be
269 $this->mIgnoreWarning
= false;
271 $this->mainUploadForm();
272 } else if( 'submit' == $this->mAction ||
$this->mUploadClicked
) {
273 $this->processUpload();
275 $this->mainUploadForm();
278 $this->cleanupTempFile();
283 * Checks are made in SpecialUpload::execute()
287 function processUpload(){
288 global $wgUser, $wgOut, $wgFileExtensions, $wgLang;
291 $value = $this->internalProcessUpload( $details );
295 $wgOut->redirect( $this->mLocalFile
->getTitle()->getFullURL() );
298 case self
::BEFORE_PROCESSING
:
301 case self
::LARGE_FILE_SERVER
:
302 $this->mainUploadForm( wfMsgHtml( 'largefileserver' ) );
305 case self
::EMPTY_FILE
:
306 $this->mainUploadForm( wfMsgHtml( 'emptyfile' ) );
309 case self
::MIN_LENGTH_PARTNAME
:
310 $this->mainUploadForm( wfMsgHtml( 'minlength1' ) );
313 case self
::ILLEGAL_FILENAME
:
314 $filtered = $details['filtered'];
315 $this->uploadError( wfMsgWikiHtml( 'illegalfilename', htmlspecialchars( $filtered ) ) );
318 case self
::PROTECTED_PAGE
:
319 $wgOut->showPermissionsErrorPage( $details['permissionserrors'] );
322 case self
::OVERWRITE_EXISTING_FILE
:
323 $errorText = $details['overwrite'];
324 $this->uploadError( $wgOut->parse( $errorText ) );
327 case self
::FILETYPE_MISSING
:
328 $this->uploadError( wfMsgExt( 'filetype-missing', array ( 'parseinline' ) ) );
331 case self
::FILETYPE_BADTYPE
:
332 $finalExt = $details['finalExt'];
334 wfMsgExt( 'filetype-banned-type',
335 array( 'parseinline' ),
336 htmlspecialchars( $finalExt ),
337 $wgLang->commaList( $wgFileExtensions ),
338 $wgLang->formatNum( count($wgFileExtensions) )
343 case self
::VERIFICATION_ERROR
:
344 $veri = $details['veri'];
345 $this->uploadError( $veri->toString() );
348 case self
::UPLOAD_VERIFICATION_ERROR
:
349 $error = $details['error'];
350 $this->uploadError( $error );
353 case self
::UPLOAD_WARNING
:
354 $warning = $details['warning'];
355 $this->uploadWarning( $warning );
358 case self
::INTERNAL_ERROR
:
359 $internal = $details['internal'];
360 $this->showError( $internal );
364 throw new MWException( __METHOD__
. ": Unknown value `{$value}`" );
369 * Really do the upload
370 * Checks are made in SpecialUpload::execute()
372 * @param array $resultDetails contains result-specific dict of additional values
376 function internalProcessUpload( &$resultDetails ) {
379 if( !wfRunHooks( 'UploadForm:BeforeProcessing', array( &$this ) ) )
381 wfDebug( "Hook 'UploadForm:BeforeProcessing' broke processing the file.\n" );
382 return self
::BEFORE_PROCESSING
;
386 * If there was no filename or a zero size given, give up quick.
388 if( trim( $this->mSrcName
) == '' ||
empty( $this->mFileSize
) ) {
389 return self
::EMPTY_FILE
;
392 /* Check for curl error */
393 if( $this->mCurlError
) {
394 return self
::BEFORE_PROCESSING
;
398 * Chop off any directories in the given filename. Then
399 * filter out illegal characters, and try to make a legible name
400 * out of it. We'll strip some silently that Title would die on.
402 if( $this->mDesiredDestName
) {
403 $basename = $this->mDesiredDestName
;
405 $basename = $this->mSrcName
;
407 $filtered = wfStripIllegalFilenameChars( $basename );
409 /* Normalize to title form before we do any further processing */
410 $nt = Title
::makeTitleSafe( NS_FILE
, $filtered );
411 if( is_null( $nt ) ) {
412 $resultDetails = array( 'filtered' => $filtered );
413 return self
::ILLEGAL_FILENAME
;
415 $filtered = $nt->getDBkey();
418 * We'll want to blacklist against *any* 'extension', and use
419 * only the final one for the whitelist.
421 list( $partname, $ext ) = $this->splitExtensions( $filtered );
423 if( count( $ext ) ) {
424 $finalExt = $ext[count( $ext ) - 1];
429 # If there was more than one "extension", reassemble the base
430 # filename to prevent bogus complaints about length
431 if( count( $ext ) > 1 ) {
432 for( $i = 0; $i < count( $ext ) - 1; $i++
)
433 $partname .= '.' . $ext[$i];
436 if( strlen( $partname ) < 1 ) {
437 return self
::MIN_LENGTH_PARTNAME
;
440 $this->mLocalFile
= wfLocalFile( $nt );
441 $this->mDestName
= $this->mLocalFile
->getName();
444 * If the image is protected, non-sysop users won't be able
445 * to modify it by uploading a new revision.
447 $permErrors = $nt->getUserPermissionsErrors( 'edit', $wgUser );
448 $permErrorsUpload = $nt->getUserPermissionsErrors( 'upload', $wgUser );
449 $permErrorsCreate = ( $nt->exists() ?
array() : $nt->getUserPermissionsErrors( 'create', $wgUser ) );
451 if( $permErrors ||
$permErrorsUpload ||
$permErrorsCreate ) {
452 // merge all the problems into one list, avoiding duplicates
453 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsUpload, $permErrors ) );
454 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsCreate, $permErrors ) );
455 $resultDetails = array( 'permissionserrors' => $permErrors );
456 return self
::PROTECTED_PAGE
;
460 * In some cases we may forbid overwriting of existing files.
462 $overwrite = $this->checkOverwrite( $this->mDestName
);
463 if( $overwrite !== true ) {
464 $resultDetails = array( 'overwrite' => $overwrite );
465 return self
::OVERWRITE_EXISTING_FILE
;
468 /* Don't allow users to override the blacklist (check file extension) */
469 global $wgCheckFileExtensions, $wgStrictFileExtensions;
470 global $wgFileExtensions, $wgFileBlacklist;
471 if ($finalExt == '') {
472 return self
::FILETYPE_MISSING
;
473 } elseif ( $this->checkFileExtensionList( $ext, $wgFileBlacklist ) ||
474 ($wgCheckFileExtensions && $wgStrictFileExtensions &&
475 !$this->checkFileExtension( $finalExt, $wgFileExtensions ) ) ) {
476 $resultDetails = array( 'finalExt' => $finalExt );
477 return self
::FILETYPE_BADTYPE
;
481 * Look at the contents of the file; if we can recognize the
482 * type but it's corrupt or data of the wrong type, we should
483 * probably not accept it.
485 if( !$this->mStashed
) {
486 $this->mFileProps
= File
::getPropsFromPath( $this->mTempPath
, $finalExt );
487 $this->checkMacBinary();
488 $veri = $this->verify( $this->mTempPath
, $finalExt );
490 if( $veri !== true ) { //it's a wiki error...
491 $resultDetails = array( 'veri' => $veri );
492 return self
::VERIFICATION_ERROR
;
496 * Provide an opportunity for extensions to add further checks
499 if( !wfRunHooks( 'UploadVerification',
500 array( $this->mDestName
, $this->mTempPath
, &$error ) ) ) {
501 $resultDetails = array( 'error' => $error );
502 return self
::UPLOAD_VERIFICATION_ERROR
;
508 * Check for non-fatal conditions
510 if ( ! $this->mIgnoreWarning
) {
513 $comparableName = str_replace( ' ', '_', $basename );
514 global $wgCapitalLinks, $wgContLang;
515 if ( $wgCapitalLinks ) {
516 $comparableName = $wgContLang->ucfirst( $comparableName );
519 if( $comparableName !== $filtered ) {
520 $warning .= '<li>'.wfMsgHtml( 'badfilename', htmlspecialchars( $this->mDestName
) ).'</li>';
523 global $wgCheckFileExtensions;
524 if ( $wgCheckFileExtensions ) {
525 if ( !$this->checkFileExtension( $finalExt, $wgFileExtensions ) ) {
528 wfMsgExt( 'filetype-unwanted-type',
529 array( 'parseinline' ),
530 htmlspecialchars( $finalExt ),
531 $wgLang->commaList( $wgFileExtensions ),
532 $wgLang->formatNum( count($wgFileExtensions) )
537 global $wgUploadSizeWarning;
538 if ( $wgUploadSizeWarning && ( $this->mFileSize
> $wgUploadSizeWarning ) ) {
539 $skin = $wgUser->getSkin();
540 $wsize = $skin->formatSize( $wgUploadSizeWarning );
541 $asize = $skin->formatSize( $this->mFileSize
);
542 $warning .= '<li>' . wfMsgHtml( 'large-file', $wsize, $asize ) . '</li>';
544 if ( $this->mFileSize
== 0 ) {
545 $warning .= '<li>'.wfMsgHtml( 'emptyfile' ).'</li>';
548 if ( !$this->mDestWarningAck
) {
549 $warning .= self
::getExistsWarning( $this->mLocalFile
);
552 $warning .= $this->getDupeWarning( $this->mTempPath
, $finalExt, $nt );
554 if( $warning != '' ) {
556 * Stash the file in a temporary location; the user can choose
557 * to let it through and we'll complete the upload then.
559 $resultDetails = array( 'warning' => $warning );
560 return self
::UPLOAD_WARNING
;
565 * Try actually saving the thing...
566 * It will show an error form on failure.
568 if( !$this->mForReUpload
) {
569 $pageText = self
::getInitialPageText( $this->mComment
, $this->mLicense
,
570 $this->mCopyrightStatus
, $this->mCopyrightSource
);
573 $status = $this->mLocalFile
->upload( $this->mTempPath
, $this->mComment
, $pageText,
574 File
::DELETE_SOURCE
, $this->mFileProps
);
575 if ( !$status->isGood() ) {
576 $resultDetails = array( 'internal' => $status->getWikiText() );
577 return self
::INTERNAL_ERROR
;
579 if ( $this->mWatchthis
) {
581 $wgUser->addWatch( $this->mLocalFile
->getTitle() );
583 // Success, redirect to description page
584 $img = null; // @todo: added to avoid passing a ref to null - should this be defined somewhere?
585 wfRunHooks( 'UploadComplete', array( &$this ) );
586 return self
::SUCCESS
;
591 * Do existence checks on a file and produce a warning
592 * This check is static and can be done pre-upload via AJAX
593 * Returns an HTML fragment consisting of one or more LI elements if there is a warning
594 * Returns an empty string if there is no warning
596 static function getExistsWarning( $file ) {
597 global $wgUser, $wgContLang;
598 // Check for uppercase extension. We allow these filenames but check if an image
599 // with lowercase extension exists already
601 $align = $wgContLang->isRtl() ?
'left' : 'right';
603 if( strpos( $file->getName(), '.' ) == false ) {
604 $partname = $file->getName();
607 $n = strrpos( $file->getName(), '.' );
608 $rawExtension = substr( $file->getName(), $n +
1 );
609 $partname = substr( $file->getName(), 0, $n );
612 $sk = $wgUser->getSkin();
614 if ( $rawExtension != $file->getExtension() ) {
615 // We're not using the normalized form of the extension.
616 // Normal form is lowercase, using most common of alternate
617 // extensions (eg 'jpg' rather than 'JPEG').
619 // Check for another file using the normalized form...
620 $nt_lc = Title
::makeTitle( NS_FILE
, $partname . '.' . $file->getExtension() );
621 $file_lc = wfLocalFile( $nt_lc );
626 if( $file->exists() ) {
627 $dlink = $sk->makeKnownLinkObj( $file->getTitle() );
628 if ( $file->allowInlineDisplay() ) {
629 $dlink2 = $sk->makeImageLinkObj( $file->getTitle(), wfMsgExt( 'fileexists-thumb', 'parseinline' ),
630 $file->getName(), $align, array(), false, true );
631 } elseif ( !$file->allowInlineDisplay() && $file->isSafeFile() ) {
632 $icon = $file->iconThumb();
633 $dlink2 = '<div style="float:' . $align . '" id="mw-media-icon">' .
634 $icon->toHtml( array( 'desc-link' => true ) ) . '<br />' . $dlink . '</div>';
639 $warning .= '<li>' . wfMsgExt( 'fileexists', array('parseinline','replaceafter'), $dlink ) . '</li>' . $dlink2;
641 } elseif( $file->getTitle()->getArticleID() ) {
642 $lnk = $sk->makeKnownLinkObj( $file->getTitle(), '', 'redirect=no' );
643 $warning .= '<li>' . wfMsgExt( 'filepageexists', array( 'parseinline', 'replaceafter' ), $lnk ) . '</li>';
644 } elseif ( $file_lc && $file_lc->exists() ) {
645 # Check if image with lowercase extension exists.
646 # It's not forbidden but in 99% it makes no sense to upload the same filename with uppercase extension
647 $dlink = $sk->makeKnownLinkObj( $nt_lc );
648 if ( $file_lc->allowInlineDisplay() ) {
649 $dlink2 = $sk->makeImageLinkObj( $nt_lc, wfMsgExt( 'fileexists-thumb', 'parseinline' ),
650 $nt_lc->getText(), $align, array(), false, true );
651 } elseif ( !$file_lc->allowInlineDisplay() && $file_lc->isSafeFile() ) {
652 $icon = $file_lc->iconThumb();
653 $dlink2 = '<div style="float:' . $align . '" id="mw-media-icon">' .
654 $icon->toHtml( array( 'desc-link' => true ) ) . '<br />' . $dlink . '</div>';
660 wfMsgExt( 'fileexists-extension', 'parsemag',
661 $file->getTitle()->getPrefixedText(), $dlink ) .
664 } elseif ( ( substr( $partname , 3, 3 ) == 'px-' ||
substr( $partname , 2, 3 ) == 'px-' )
665 && ereg( "[0-9]{2}" , substr( $partname , 0, 2) ) )
667 # Check for filenames like 50px- or 180px-, these are mostly thumbnails
668 $nt_thb = Title
::newFromText( substr( $partname , strpos( $partname , '-' ) +
1 ) . '.' . $rawExtension );
669 $file_thb = wfLocalFile( $nt_thb );
670 if ($file_thb->exists() ) {
671 # Check if an image without leading '180px-' (or similiar) exists
672 $dlink = $sk->makeKnownLinkObj( $nt_thb);
673 if ( $file_thb->allowInlineDisplay() ) {
674 $dlink2 = $sk->makeImageLinkObj( $nt_thb,
675 wfMsgExt( 'fileexists-thumb', 'parseinline' ),
676 $nt_thb->getText(), $align, array(), false, true );
677 } elseif ( !$file_thb->allowInlineDisplay() && $file_thb->isSafeFile() ) {
678 $icon = $file_thb->iconThumb();
679 $dlink2 = '<div style="float:' . $align . '" id="mw-media-icon">' .
680 $icon->toHtml( array( 'desc-link' => true ) ) . '<br />' .
686 $warning .= '<li>' . wfMsgExt( 'fileexists-thumbnail-yes', 'parsemag', $dlink ) .
689 # Image w/o '180px-' does not exists, but we do not like these filenames
690 $warning .= '<li>' . wfMsgExt( 'file-thumbnail-no', 'parseinline' ,
691 substr( $partname , 0, strpos( $partname , '-' ) +
1 ) ) . '</li>';
695 $filenamePrefixBlacklist = self
::getFilenamePrefixBlacklist();
697 foreach( $filenamePrefixBlacklist as $prefix ) {
698 if ( substr( $partname, 0, strlen( $prefix ) ) == $prefix ) {
699 $warning .= '<li>' . wfMsgExt( 'filename-bad-prefix', 'parseinline', $prefix ) . '</li>';
704 if ( $file->wasDeleted() && !$file->exists() ) {
705 # If the file existed before and was deleted, warn the user of this
706 # Don't bother doing so if the file exists now, however
707 $ltitle = SpecialPage
::getTitleFor( 'Log' );
708 $llink = $sk->makeKnownLinkObj( $ltitle, wfMsgHtml( 'deletionlog' ),
709 'type=delete&page=' . $file->getTitle()->getPrefixedUrl() );
710 $warning .= '<li>' . wfMsgWikiHtml( 'filewasdeleted', $llink ) . '</li>';
716 * Get a list of warnings
718 * @param string local filename, e.g. 'file exists', 'non-descriptive filename'
719 * @return array list of warning messages
721 static function ajaxGetExistsWarning( $filename ) {
722 $file = wfFindFile( $filename );
724 // Force local file so we have an object to do further checks against
725 // if there isn't an exact match...
726 $file = wfLocalFile( $filename );
730 $warning = self
::getExistsWarning( $file );
731 if ( $warning !== '' ) {
732 $s = "<ul>$warning</ul>";
739 * Render a preview of a given license for the AJAX preview on upload
741 * @param string $license
744 public static function ajaxGetLicensePreview( $license ) {
745 global $wgParser, $wgUser;
746 $text = '{{' . $license . '}}';
747 $title = Title
::makeTitle( NS_FILE
, 'Sample.jpg' );
748 $options = ParserOptions
::newFromUser( $wgUser );
750 // Expand subst: first, then live templates...
751 $text = $wgParser->preSaveTransform( $text, $title, $wgUser, $options );
752 $output = $wgParser->parse( $text, $title, $options );
754 return $output->getText();
758 * Check for duplicate files and throw up a warning before the upload
761 function getDupeWarning( $tempfile, $extension, $destinationTitle ) {
762 $hash = File
::sha1Base36( $tempfile );
763 $dupes = RepoGroup
::singleton()->findBySha1( $hash );
764 $archivedImage = new ArchivedFile( null, 0, $hash.".$extension" );
768 foreach( $dupes as $file ) {
769 $title = $file->getTitle();
770 # Don't throw the warning when the titles are the same, it's a reupload
771 # and highly redundant.
772 if ( !$title->equals( $destinationTitle ) ||
!$this->mForReUpload
) {
773 $msg .= $title->getPrefixedText() .
774 "|" . $title->getText() . "\n";
777 $msg .= "</gallery>";
779 wfMsgExt( "file-exists-duplicate", array( "parse" ), count( $dupes ) ) .
780 $wgOut->parse( $msg ) .
782 } elseif ( $archivedImage->getID() > 0 ) {
784 $name = Title
::makeTitle( NS_FILE
, $archivedImage->getName() )->getPrefixedText();
785 return Xml
::tags( 'li', null, wfMsgExt( 'file-deleted-duplicate', array( 'parseinline' ), array( $name ) ) );
792 * Get a list of blacklisted filename prefixes from [[MediaWiki:filename-prefix-blacklist]]
794 * @return array list of prefixes
796 public static function getFilenamePrefixBlacklist() {
797 $blacklist = array();
798 $message = wfMsgForContent( 'filename-prefix-blacklist' );
799 if( $message && !( wfEmptyMsg( 'filename-prefix-blacklist', $message ) ||
$message == '-' ) ) {
800 $lines = explode( "\n", $message );
801 foreach( $lines as $line ) {
802 // Remove comment lines
803 $comment = substr( trim( $line ), 0, 1 );
804 if ( $comment == '#' ||
$comment == '' ) {
807 // Remove additional comments after a prefix
808 $comment = strpos( $line, '#' );
809 if ( $comment > 0 ) {
810 $line = substr( $line, 0, $comment-1 );
812 $blacklist[] = trim( $line );
819 * Stash a file in a temporary directory for later processing
820 * after the user has confirmed it.
822 * If the user doesn't explicitly cancel or accept, these files
823 * can accumulate in the temp directory.
825 * @param string $saveName - the destination filename
826 * @param string $tempName - the source temporary file to save
827 * @return string - full path the stashed file, or false on failure
830 function saveTempUploadedFile( $saveName, $tempName ) {
832 $repo = RepoGroup
::singleton()->getLocalRepo();
833 $status = $repo->storeTemp( $saveName, $tempName );
834 if ( !$status->isGood() ) {
835 $this->showError( $status->getWikiText() );
838 return $status->value
;
843 * Stash a file in a temporary directory for later processing,
844 * and save the necessary descriptive info into the session.
845 * Returns a key value which will be passed through a form
846 * to pick up the path info on a later invocation.
851 function stashSession() {
852 $stash = $this->saveTempUploadedFile( $this->mDestName
, $this->mTempPath
);
855 # Couldn't save the file.
859 $key = mt_rand( 0, 0x7fffffff );
860 $_SESSION['wsUploadData'][$key] = array(
861 'mTempPath' => $stash,
862 'mFileSize' => $this->mFileSize
,
863 'mSrcName' => $this->mSrcName
,
864 'mFileProps' => $this->mFileProps
,
865 'version' => self
::SESSION_VERSION
,
871 * Remove a temporarily kept file stashed by saveTempUploadedFile().
875 function unsaveUploadedFile() {
877 if( !$this->mTempPath
) return true; // nothing to delete
878 $repo = RepoGroup
::singleton()->getLocalRepo();
879 $success = $repo->freeTemp( $this->mTempPath
);
881 $wgOut->showFileDeleteError( $this->mTempPath
);
888 /* -------------------------------------------------------------- */
891 * @param string $error as HTML
894 function uploadError( $error ) {
896 $wgOut->addHTML( '<h2>' . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
897 $wgOut->addHTML( '<span class="error">' . $error . '</span>' );
901 * There's something wrong with this file, not enough to reject it
902 * totally but we require manual intervention to save it for real.
903 * Stash it away, then present a form asking to confirm or cancel.
905 * @param string $warning as HTML
908 function uploadWarning( $warning ) {
910 global $wgUseCopyrightUpload;
912 $this->mSessionKey
= $this->stashSession();
913 if( !$this->mSessionKey
) {
914 # Couldn't save file; an error has been displayed so let's go.
918 $wgOut->addHTML( '<h2>' . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
919 $wgOut->addHTML( '<ul class="warning">' . $warning . "</ul>\n" );
921 $titleObj = SpecialPage
::getTitleFor( 'Upload' );
923 if ( $wgUseCopyrightUpload ) {
924 $copyright = Xml
::hidden( 'wpUploadCopyStatus', $this->mCopyrightStatus
) . "\n" .
925 Xml
::hidden( 'wpUploadSource', $this->mCopyrightSource
) . "\n";
931 Xml
::openElement( 'form', array( 'method' => 'post', 'action' => $titleObj->getLocalURL( 'action=submit' ),
932 'enctype' => 'multipart/form-data', 'id' => 'uploadwarning' ) ) . "\n" .
933 Xml
::hidden( 'wpIgnoreWarning', '1' ) . "\n" .
934 Xml
::hidden( 'wpSessionKey', $this->mSessionKey
) . "\n" .
935 Xml
::hidden( 'wpUploadDescription', $this->mComment
) . "\n" .
936 Xml
::hidden( 'wpLicense', $this->mLicense
) . "\n" .
937 Xml
::hidden( 'wpDestFile', $this->mDesiredDestName
) . "\n" .
938 Xml
::hidden( 'wpWatchthis', $this->mWatchthis
) . "\n" .
939 "{$copyright}<br />" .
940 Xml
::submitButton( wfMsg( 'ignorewarning' ), array ( 'name' => 'wpUpload', 'id' => 'wpUpload', 'checked' => 'checked' ) ) . ' ' .
941 Xml
::submitButton( wfMsg( 'reuploaddesc' ), array ( 'name' => 'wpReUpload', 'id' => 'wpReUpload' ) ) .
942 Xml
::closeElement( 'form' ) . "\n"
947 * Displays the main upload form, optionally with a highlighted
948 * error message up at the top.
950 * @param string $msg as HTML
953 function mainUploadForm( $msg='' ) {
954 global $wgOut, $wgUser, $wgLang, $wgMaxUploadSize;
955 global $wgUseCopyrightUpload, $wgUseAjax, $wgAjaxUploadDestCheck, $wgAjaxLicensePreview;
956 global $wgRequest, $wgAllowCopyUploads;
957 global $wgStylePath, $wgStyleVersion;
959 $useAjaxDestCheck = $wgUseAjax && $wgAjaxUploadDestCheck;
960 $useAjaxLicensePreview = $wgUseAjax && $wgAjaxLicensePreview;
962 $adc = wfBoolToStr( $useAjaxDestCheck );
963 $alp = wfBoolToStr( $useAjaxLicensePreview );
964 $autofill = wfBoolToStr( $this->mDesiredDestName
== '' );
966 $wgOut->addScript( "<script type=\"text/javascript\">
967 wgAjaxUploadDestCheck = {$adc};
968 wgAjaxLicensePreview = {$alp};
969 wgUploadAutoFill = {$autofill};
971 $wgOut->addScriptFile( 'upload.js' );
972 $wgOut->addScriptFile( 'edit.js' ); // For <charinsert> support
974 if( !wfRunHooks( 'UploadForm:initial', array( &$this ) ) )
976 wfDebug( "Hook 'UploadForm:initial' broke output of the upload form\n" );
980 if( $this->mDesiredDestName
) {
981 $title = Title
::makeTitleSafe( NS_FILE
, $this->mDesiredDestName
);
982 // Show a subtitle link to deleted revisions (to sysops et al only)
983 if( $title instanceof Title
&& ( $count = $title->isDeleted() ) > 0 && $wgUser->isAllowed( 'deletedhistory' ) ) {
985 $wgUser->isAllowed( 'delete' ) ?
'thisisdeleted' : 'viewdeleted',
986 array( 'parse', 'replaceafter' ),
987 $wgUser->getSkin()->makeKnownLinkObj(
988 SpecialPage
::getTitleFor( 'Undelete', $title->getPrefixedText() ),
989 wfMsgExt( 'restorelink', array( 'parsemag', 'escape' ), $count )
992 $wgOut->addHTML( "<div id=\"contentSub2\">{$link}</div>" );
995 // Show the relevant lines from deletion log (for still deleted files only)
996 if( $title instanceof Title
&& $title->isDeleted() > 0 && !$title->exists() ) {
997 $this->showDeletionLog( $wgOut, $title->getPrefixedText() );
1001 $cols = intval($wgUser->getOption( 'cols' ));
1003 if( $wgUser->getOption( 'editwidth' ) ) {
1004 $width = " style=\"width:100%\"";
1010 $sub = wfMsgHtml( 'uploaderror' );
1011 $wgOut->addHTML( "<h2>{$sub}</h2>\n" .
1012 "<span class='error'>{$msg}</span>\n" );
1014 $wgOut->addHTML( '<div id="uploadtext">' );
1015 $wgOut->addWikiMsg( 'uploadtext', $this->mDesiredDestName
);
1016 $wgOut->addHTML( "</div>\n" );
1018 # Print a list of allowed file extensions, if so configured. We ignore
1019 # MIME type here, it's incomprehensible to most people and too long.
1020 global $wgCheckFileExtensions, $wgStrictFileExtensions,
1021 $wgFileExtensions, $wgFileBlacklist;
1023 $allowedExtensions = '';
1024 if( $wgCheckFileExtensions ) {
1025 if( $wgStrictFileExtensions ) {
1026 # Everything not permitted is banned
1028 '<div id="mw-upload-permitted">' .
1029 wfMsgWikiHtml( 'upload-permitted', $wgLang->commaList( $wgFileExtensions ) ) .
1032 # We have to list both preferred and prohibited
1034 '<div id="mw-upload-preferred">' .
1035 wfMsgWikiHtml( 'upload-preferred', $wgLang->commaList( $wgFileExtensions ) ) .
1037 '<div id="mw-upload-prohibited">' .
1038 wfMsgWikiHtml( 'upload-prohibited', $wgLang->commaList( $wgFileBlacklist ) ) .
1042 # Everything is permitted.
1043 $extensionsList = '';
1046 # Get the maximum file size from php.ini as $wgMaxUploadSize works for uploads from URL via CURL only
1047 # See http://www.php.net/manual/en/ini.core.php#ini.upload-max-filesize for possible values of upload_max_filesize
1048 $val = trim( ini_get( 'upload_max_filesize' ) );
1049 $last = strtoupper( ( substr( $val, -1 ) ) );
1052 $val2 = substr( $val, 0, -1 ) * 1024 * 1024 * 1024;
1055 $val2 = substr( $val, 0, -1 ) * 1024 * 1024;
1058 $val2 = substr( $val, 0, -1 ) * 1024;
1063 $val2 = $wgAllowCopyUploads ?
min( $wgMaxUploadSize, $val2 ) : $val2;
1064 $maxUploadSize = '<div id="mw-upload-maxfilesize">' .
1065 wfMsgExt( 'upload-maxfilesize', array( 'parseinline', 'escapenoentities' ),
1066 $wgLang->formatSize( $val2 ) ) .
1069 $sourcefilename = wfMsgExt( 'sourcefilename', array( 'parseinline', 'escapenoentities' ) );
1070 $destfilename = wfMsgExt( 'destfilename', array( 'parseinline', 'escapenoentities' ) );
1072 $msg = $this->mForReUpload ?
'filereuploadsummary' : 'fileuploadsummary';
1073 $summary = wfMsgExt( $msg, 'parseinline' );
1075 $licenses = new Licenses();
1076 $license = wfMsgExt( 'license', array( 'parseinline' ) );
1077 $nolicense = wfMsgHtml( 'nolicense' );
1078 $licenseshtml = $licenses->getHtml();
1080 $ulb = wfMsgHtml( 'uploadbtn' );
1083 $titleObj = SpecialPage
::getTitleFor( 'Upload' );
1085 $encDestName = htmlspecialchars( $this->mDesiredDestName
);
1087 $watchChecked = $this->watchCheck() ?
'checked="checked"' : '';
1088 # Re-uploads should not need "file exist already" warnings
1089 $warningChecked = ($this->mIgnoreWarning ||
$this->mForReUpload
) ?
'checked="checked"' : '';
1091 // Prepare form for upload or upload/copy
1092 if( $wgAllowCopyUploads && $wgUser->isAllowed( 'upload_by_url' ) ) {
1094 "<input type='radio' id='wpSourceTypeFile' name='wpSourceType' value='file' " .
1095 "onchange='toggle_element_activation(\"wpUploadFileURL\",\"wpUploadFile\")' checked='checked' />" .
1096 "<input tabindex='1' type='file' name='wpUploadFile' id='wpUploadFile' " .
1098 "toggle_element_activation(\"wpUploadFileURL\",\"wpUploadFile\");" .
1099 "toggle_element_check(\"wpSourceTypeFile\",\"wpSourceTypeURL\")' " .
1100 "onchange='fillDestFilename(\"wpUploadFile\")' size='60' />" .
1101 wfMsgHTML( 'upload_source_file' ) . "<br/>" .
1102 "<input type='radio' id='wpSourceTypeURL' name='wpSourceType' value='web' " .
1103 "onchange='toggle_element_activation(\"wpUploadFile\",\"wpUploadFileURL\")' />" .
1104 "<input tabindex='1' type='text' name='wpUploadFileURL' id='wpUploadFileURL' " .
1106 "toggle_element_activation(\"wpUploadFile\",\"wpUploadFileURL\");" .
1107 "toggle_element_check(\"wpSourceTypeURL\",\"wpSourceTypeFile\")' " .
1108 "onchange='fillDestFilename(\"wpUploadFileURL\")' size='60' disabled='disabled' />" .
1109 wfMsgHtml( 'upload_source_url' ) ;
1112 "<input tabindex='1' type='file' name='wpUploadFile' id='wpUploadFile' " .
1113 ($this->mDesiredDestName?
"":"onchange='fillDestFilename(\"wpUploadFile\")' ") .
1115 "<input type='hidden' name='wpSourceType' value='file' />" ;
1117 if ( $useAjaxDestCheck ) {
1118 $warningRow = "<tr><td colspan='2' id='wpDestFile-warning'> </td></tr>";
1119 $destOnkeyup = 'onkeyup="wgUploadWarningObj.keypress();"';
1124 # Uploading a new version? If so, the name is fixed.
1125 $on = $this->mForReUpload ?
"readonly='readonly'" : "";
1127 $encComment = htmlspecialchars( $this->mComment
);
1130 Xml
::openElement( 'form', array( 'method' => 'post', 'action' => $titleObj->getLocalURL(),
1131 'enctype' => 'multipart/form-data', 'id' => 'mw-upload-form' ) ) .
1132 Xml
::openElement( 'fieldset' ) .
1133 Xml
::element( 'legend', null, wfMsg( 'upload' ) ) .
1134 Xml
::openElement( 'table', array( 'border' => '0', 'id' => 'mw-upload-table' ) ) .
1136 {$this->uploadFormTextTop}
1137 <td class='mw-label'>
1138 <label for='wpUploadFile'>{$sourcefilename}</label>
1140 <td class='mw-input'>
1152 <td class='mw-label'>
1153 <label for='wpDestFile'>{$destfilename}</label>
1155 <td class='mw-input'>
1156 <input tabindex='2' type='text' name='wpDestFile' id='wpDestFile' size='60'
1157 value=\"{$encDestName}\" onchange='toggleFilenameFiller()' $on $destOnkeyup />
1161 <td class='mw-label'>
1162 <label for='wpUploadDescription'>{$summary}</label>
1164 <td class='mw-input'>
1165 <textarea tabindex='3' name='wpUploadDescription' id='wpUploadDescription' rows='6'
1166 cols='{$cols}'{$width}>$encComment</textarea>
1167 {$this->uploadFormTextAfterSummary}
1172 # Re-uploads should not need license info
1173 if ( !$this->mForReUpload
&& $licenseshtml != '' ) {
1174 global $wgStylePath;
1176 <td class='mw-label'>
1177 <label for='wpLicense'>$license</label>
1179 <td class='mw-input'>
1180 <select name='wpLicense' id='wpLicense' tabindex='4'
1181 onchange='licenseSelectorCheck()'>
1182 <option value=''>$nolicense</option>
1189 if( $useAjaxLicensePreview ) {
1192 <td id=\"mw-license-preview\"></td>
1199 if ( !$this->mForReUpload
&& $wgUseCopyrightUpload ) {
1200 $filestatus = wfMsgExt( 'filestatus', 'escapenoentities' );
1201 $copystatus = htmlspecialchars( $this->mCopyrightStatus
);
1202 $filesource = wfMsgExt( 'filesource', 'escapenoentities' );
1203 $uploadsource = htmlspecialchars( $this->mCopyrightSource
);
1206 <td class='mw-label' style='white-space: nowrap;'>
1207 <label for='wpUploadCopyStatus'>$filestatus</label></td>
1208 <td class='mw-input'>
1209 <input tabindex='5' type='text' name='wpUploadCopyStatus' id='wpUploadCopyStatus'
1210 value=\"$copystatus\" size='60' />
1214 <td class='mw-label'>
1215 <label for='wpUploadCopyStatus'>$filesource</label>
1217 <td class='mw-input'>
1218 <input tabindex='6' type='text' name='wpUploadSource' id='wpUploadCopyStatus'
1219 value=\"$uploadsource\" size='60' />
1229 <input tabindex='7' type='checkbox' name='wpWatchthis' id='wpWatchthis' $watchChecked value='true' />
1230 <label for='wpWatchthis'>" . wfMsgHtml( 'watchthisupload' ) . "</label>
1231 <input tabindex='8' type='checkbox' name='wpIgnoreWarning' id='wpIgnoreWarning' value='true' $warningChecked />
1232 <label for='wpIgnoreWarning'>" . wfMsgHtml( 'ignorewarnings' ) . "</label>
1238 <td class='mw-input'>
1239 <input tabindex='9' type='submit' name='wpUpload' value=\"{$ulb}\"" . $wgUser->getSkin()->tooltipAndAccesskey( 'upload' ) . " />
1244 <td class='mw-input'>"
1246 $wgOut->addWikiText( wfMsgForContent( 'edittools' ) );
1250 Xml
::closeElement( 'table' ) .
1251 Xml
::hidden( 'wpDestFileWarningAck', '', array( 'id' => 'wpDestFileWarningAck' ) ) .
1252 Xml
::hidden( 'wpForReUpload', $this->mForReUpload
, array( 'id' => 'wpForReUpload' ) ) .
1253 Xml
::closeElement( 'fieldset' ) .
1254 Xml
::closeElement( 'form' )
1256 $uploadfooter = wfMsgNoTrans( 'uploadfooter' );
1257 if( $uploadfooter != '-' && !wfEmptyMsg( 'uploadfooter', $uploadfooter ) ){
1258 $wgOut->addWikiText( '<div id="mw-upload-footer-message">' . $uploadfooter . '</div>' );
1262 /* -------------------------------------------------------------- */
1265 * See if we should check the 'watch this page' checkbox on the form
1266 * based on the user's preferences and whether we're being asked
1267 * to create a new file or update an existing one.
1269 * In the case where 'watch edits' is off but 'watch creations' is on,
1270 * we'll leave the box unchecked.
1272 * Note that the page target can be changed *on the form*, so our check
1273 * state can get out of sync.
1275 function watchCheck() {
1277 if( $wgUser->getOption( 'watchdefault' ) ) {
1282 $local = wfLocalFile( $this->mDesiredDestName
);
1283 if( $local && $local->exists() ) {
1284 // We're uploading a new version of an existing file.
1285 // No creation, so don't watch it if we're not already.
1286 return $local->getTitle()->userIsWatching();
1288 // New page should get watched if that's our option.
1289 return $wgUser->getOption( 'watchcreations' );
1294 * Split a file into a base name and all dot-delimited 'extensions'
1295 * on the end. Some web server configurations will fall back to
1296 * earlier pseudo-'extensions' to determine type and execute
1297 * scripts, so the blacklist needs to check them all.
1301 public function splitExtensions( $filename ) {
1302 $bits = explode( '.', $filename );
1303 $basename = array_shift( $bits );
1304 return array( $basename, $bits );
1308 * Perform case-insensitive match against a list of file extensions.
1309 * Returns true if the extension is in the list.
1311 * @param string $ext
1312 * @param array $list
1315 function checkFileExtension( $ext, $list ) {
1316 return in_array( strtolower( $ext ), $list );
1320 * Perform case-insensitive match against a list of file extensions.
1321 * Returns true if any of the extensions are in the list.
1324 * @param array $list
1327 public function checkFileExtensionList( $ext, $list ) {
1328 foreach( $ext as $e ) {
1329 if( in_array( strtolower( $e ), $list ) ) {
1337 * Verifies that it's ok to include the uploaded file
1339 * @param string $tmpfile the full path of the temporary file to verify
1340 * @param string $extension The filename extension that the file is to be served with
1341 * @return mixed true of the file is verified, a WikiError object otherwise.
1343 function verify( $tmpfile, $extension ) {
1344 #magically determine mime type
1345 $magic = MimeMagic
::singleton();
1346 $mime = $magic->guessMimeType($tmpfile,false);
1349 #check mime type, if desired
1350 global $wgVerifyMimeType;
1351 if ($wgVerifyMimeType) {
1352 wfDebug ( "\n\nmime: <$mime> extension: <$extension>\n\n");
1353 #check mime type against file extension
1354 if( !self
::verifyExtension( $mime, $extension ) ) {
1355 return new WikiErrorMsg( 'uploadcorrupt' );
1358 #check mime type blacklist
1359 global $wgMimeTypeBlacklist;
1360 if( isset($wgMimeTypeBlacklist) && !is_null($wgMimeTypeBlacklist) ) {
1361 if ( $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
1362 return new WikiErrorMsg( 'filetype-badmime', htmlspecialchars( $mime ) );
1366 $fp = fopen( $tmpfile, 'rb' );
1367 $chunk = fread( $fp, 256 );
1369 $extMime = $magic->guessTypesForExtension( $extension );
1370 $ieTypes = $magic->getIEMimeTypes( $tmpfile, $chunk, $extMime );
1371 foreach ( $ieTypes as $ieType ) {
1372 if ( $this->checkFileExtension( $ieType, $wgMimeTypeBlacklist ) ) {
1373 return new WikiErrorMsg( 'filetype-bad-ie-mime', $ieType );
1379 #check for htmlish code and javascript
1380 if( $this->detectScript ( $tmpfile, $mime, $extension ) ) {
1381 return new WikiErrorMsg( 'uploadscripted' );
1383 if( $extension == 'svg' ||
$mime == 'image/svg+xml' ) {
1384 if( $this->detectScriptInSvg( $tmpfile ) ) {
1385 return new WikiErrorMsg( 'uploadscripted' );
1390 * Scan the uploaded file for viruses
1392 $virus= $this->detectVirus($tmpfile);
1394 return new WikiErrorMsg( 'uploadvirus', htmlspecialchars($virus) );
1397 wfDebug( __METHOD__
.": all clear; passing.\n" );
1402 * Checks if the mime type of the uploaded file matches the file extension.
1404 * @param string $mime the mime type of the uploaded file
1405 * @param string $extension The filename extension that the file is to be served with
1408 static function verifyExtension( $mime, $extension ) {
1409 $magic = MimeMagic
::singleton();
1411 if ( ! $mime ||
$mime == 'unknown' ||
$mime == 'unknown/unknown' )
1412 if ( ! $magic->isRecognizableExtension( $extension ) ) {
1413 wfDebug( __METHOD__
.": passing file with unknown detected mime type; " .
1414 "unrecognized extension '$extension', can't verify\n" );
1417 wfDebug( __METHOD__
.": rejecting file with unknown detected mime type; ".
1418 "recognized extension '$extension', so probably invalid file\n" );
1422 $match= $magic->isMatchingExtension($extension,$mime);
1424 if ($match===NULL) {
1425 wfDebug( __METHOD__
.": no file extension known for mime type $mime, passing file\n" );
1427 } elseif ($match===true) {
1428 wfDebug( __METHOD__
.": mime type $mime matches extension $extension, passing file\n" );
1430 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
1434 wfDebug( __METHOD__
.": mime type $mime mismatches file extension $extension, rejecting file\n" );
1441 * Heuristic for detecting files that *could* contain JavaScript instructions or
1442 * things that may look like HTML to a browser and are thus
1443 * potentially harmful. The present implementation will produce false positives in some situations.
1445 * @param string $file Pathname to the temporary upload file
1446 * @param string $mime The mime type of the file
1447 * @param string $extension The extension of the file
1448 * @return bool true if the file contains something looking like embedded scripts
1450 function detectScript($file, $mime, $extension) {
1451 global $wgAllowTitlesInSVG;
1453 #ugly hack: for text files, always look at the entire file.
1454 #For binarie field, just check the first K.
1456 if (strpos($mime,'text/')===0) $chunk = file_get_contents( $file );
1458 $fp = fopen( $file, 'rb' );
1459 $chunk = fread( $fp, 1024 );
1463 $chunk= strtolower( $chunk );
1465 if (!$chunk) return false;
1467 #decode from UTF-16 if needed (could be used for obfuscation).
1468 if (substr($chunk,0,2)=="\xfe\xff") $enc= "UTF-16BE";
1469 elseif (substr($chunk,0,2)=="\xff\xfe") $enc= "UTF-16LE";
1472 if ($enc) $chunk= iconv($enc,"ASCII//IGNORE",$chunk);
1474 $chunk= trim($chunk);
1476 #FIXME: convert from UTF-16 if necessarry!
1478 wfDebug("SpecialUpload::detectScript: checking for embedded scripts and HTML stuff\n");
1480 #check for HTML doctype
1481 if (eregi("<!DOCTYPE *X?HTML",$chunk)) return true;
1484 * Internet Explorer for Windows performs some really stupid file type
1485 * autodetection which can cause it to interpret valid image files as HTML
1486 * and potentially execute JavaScript, creating a cross-site scripting
1489 * Apple's Safari browser also performs some unsafe file type autodetection
1490 * which can cause legitimate files to be interpreted as HTML if the
1491 * web server is not correctly configured to send the right content-type
1492 * (or if you're really uploading plain text and octet streams!)
1494 * Returns true if IE is likely to mistake the given file for HTML.
1495 * Also returns true if Safari would mistake the given file for HTML
1496 * when served with a generic content-type.
1503 '<html', #also in safari
1506 '<script', #also in safari
1509 if( ! $wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
1513 foreach( $tags as $tag ) {
1514 if( false !== strpos( $chunk, $tag ) ) {
1520 * look for javascript
1523 #resolve entity-refs to look at attributes. may be harsh on big files... cache result?
1524 $chunk = Sanitizer
::decodeCharReferences( $chunk );
1526 #look for script-types
1527 if (preg_match('!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim',$chunk)) return true;
1529 #look for html-style script-urls
1530 if (preg_match('!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim',$chunk)) return true;
1532 #look for css-style script-urls
1533 if (preg_match('!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim',$chunk)) return true;
1535 wfDebug("SpecialUpload::detectScript: no scripts found\n");
1539 function detectScriptInSvg( $filename ) {
1540 $check = new XmlTypeCheck( $filename, array( $this, 'checkSvgScriptCallback' ) );
1541 return $check->filterMatch
;
1545 * @todo Replace this with a whitelist filter!
1547 function checkSvgScriptCallback( $element, $attribs ) {
1548 $stripped = $this->stripXmlNamespace( $element );
1550 if( $stripped == 'script' ) {
1551 wfDebug( __METHOD__
. ": Found script element '$element' in uploaded file.\n" );
1555 foreach( $attribs as $attrib => $value ) {
1556 $stripped = $this->stripXmlNamespace( $attrib );
1557 if( substr( $stripped, 0, 2 ) == 'on' ) {
1558 wfDebug( __METHOD__
. ": Found script attribute '$attrib'='value' in uploaded file.\n" );
1561 if( $stripped == 'href' && strpos( strtolower( $value ), 'javascript:' ) !== false ) {
1562 wfDebug( __METHOD__
. ": Found script href attribute '$attrib'='$value' in uploaded file.\n" );
1568 private function stripXmlNamespace( $name ) {
1569 // 'http://www.w3.org/2000/svg:script' -> 'script'
1570 $parts = explode( ':', strtolower( $name ) );
1571 return array_pop( $parts );
1575 * Generic wrapper function for a virus scanner program.
1576 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
1577 * $wgAntivirusRequired may be used to deny upload if the scan fails.
1579 * @param string $file Pathname to the temporary upload file
1580 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
1581 * or a string containing feedback from the virus scanner if a virus was found.
1582 * If textual feedback is missing but a virus was found, this function returns true.
1584 function detectVirus($file) {
1585 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
1587 if ( !$wgAntivirus ) {
1588 wfDebug( __METHOD__
.": virus scanner disabled\n");
1592 if ( !$wgAntivirusSetup[$wgAntivirus] ) {
1593 wfDebug( __METHOD__
.": unknown virus scanner: $wgAntivirus\n" );
1594 $wgOut->wrapWikiMsg( '<div class="error">$1</div>', array( 'virus-badscanner', $wgAntivirus ) );
1595 return wfMsg('virus-unknownscanner') . " $wgAntivirus";
1598 # look up scanner configuration
1599 $command = $wgAntivirusSetup[$wgAntivirus]["command"];
1600 $exitCodeMap = $wgAntivirusSetup[$wgAntivirus]["codemap"];
1601 $msgPattern = isset( $wgAntivirusSetup[$wgAntivirus]["messagepattern"] ) ?
1602 $wgAntivirusSetup[$wgAntivirus]["messagepattern"] : null;
1604 if ( strpos( $command,"%f" ) === false ) {
1605 # simple pattern: append file to scan
1606 $command .= " " . wfEscapeShellArg( $file );
1608 # complex pattern: replace "%f" with file to scan
1609 $command = str_replace( "%f", wfEscapeShellArg( $file ), $command );
1612 wfDebug( __METHOD__
.": running virus scan: $command \n" );
1614 # execute virus scanner
1617 #NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
1618 # that does not seem to be worth the pain.
1619 # Ask me (Duesentrieb) about it if it's ever needed.
1621 if ( wfIsWindows() ) {
1622 exec( "$command", $output, $exitCode );
1624 exec( "$command 2>&1", $output, $exitCode );
1627 # map exit code to AV_xxx constants.
1628 $mappedCode = $exitCode;
1629 if ( $exitCodeMap ) {
1630 if ( isset( $exitCodeMap[$exitCode] ) ) {
1631 $mappedCode = $exitCodeMap[$exitCode];
1632 } elseif ( isset( $exitCodeMap["*"] ) ) {
1633 $mappedCode = $exitCodeMap["*"];
1637 if ( $mappedCode === AV_SCAN_FAILED
) {
1638 # scan failed (code was mapped to false by $exitCodeMap)
1639 wfDebug( __METHOD__
.": failed to scan $file (code $exitCode).\n" );
1641 if ( $wgAntivirusRequired ) {
1642 return wfMsg('virus-scanfailed', array( $exitCode ) );
1646 } else if ( $mappedCode === AV_SCAN_ABORTED
) {
1647 # scan failed because filetype is unknown (probably imune)
1648 wfDebug( __METHOD__
.": unsupported file type $file (code $exitCode).\n" );
1650 } else if ( $mappedCode === AV_NO_VIRUS
) {
1652 wfDebug( __METHOD__
.": file passed virus scan.\n" );
1655 $output = join( "\n", $output );
1656 $output = trim( $output );
1659 $output = true; #if there's no output, return true
1660 } elseif ( $msgPattern ) {
1662 if ( preg_match( $msgPattern, $output, $groups ) ) {
1664 $output = $groups[1];
1669 wfDebug( __METHOD__
.": FOUND VIRUS! scanner feedback: $output \n" );
1675 * Check if the temporary file is MacBinary-encoded, as some uploads
1676 * from Internet Explorer on Mac OS Classic and Mac OS X will be.
1677 * If so, the data fork will be extracted to a second temporary file,
1678 * which will then be checked for validity and either kept or discarded.
1682 function checkMacBinary() {
1683 $macbin = new MacBinary( $this->mTempPath
);
1684 if( $macbin->isValid() ) {
1685 $dataFile = tempnam( wfTempDir(), "WikiMacBinary" );
1686 $dataHandle = fopen( $dataFile, 'wb' );
1688 wfDebug( "SpecialUpload::checkMacBinary: Extracting MacBinary data fork to $dataFile\n" );
1689 $macbin->extractData( $dataHandle );
1691 $this->mTempPath
= $dataFile;
1692 $this->mFileSize
= $macbin->dataForkLength();
1694 // We'll have to manually remove the new file if it's not kept.
1695 $this->mRemoveTempFile
= true;
1701 * If we've modified the upload file we need to manually remove it
1702 * on exit to clean up.
1705 function cleanupTempFile() {
1706 if ( $this->mRemoveTempFile
&& $this->mTempPath
&& file_exists( $this->mTempPath
) ) {
1707 wfDebug( "SpecialUpload::cleanupTempFile: Removing temporary file {$this->mTempPath}\n" );
1708 unlink( $this->mTempPath
);
1713 * Check if there's an overwrite conflict and, if so, if restrictions
1714 * forbid this user from performing the upload.
1716 * @return mixed true on success, WikiError on failure
1719 function checkOverwrite( $name ) {
1720 $img = wfFindFile( $name );
1724 global $wgUser, $wgOut;
1725 if( $img->isLocal() ) {
1726 if( !self
::userCanReUpload( $wgUser, $img->name
) ) {
1727 $error = 'fileexists-forbidden';
1730 if( !$wgUser->isAllowed( 'reupload' ) ||
1731 !$wgUser->isAllowed( 'reupload-shared' ) ) {
1732 $error = "fileexists-shared-forbidden";
1738 $errorText = wfMsg( $error, wfEscapeWikiText( $img->getName() ) );
1742 // Rockin', go ahead and upload
1747 * Check if a user is the last uploader
1750 * @param string $img, image name
1753 public static function userCanReUpload( User
$user, $img ) {
1754 if( $user->isAllowed( 'reupload' ) )
1755 return true; // non-conditional
1756 if( !$user->isAllowed( 'reupload-own' ) )
1759 $dbr = wfGetDB( DB_SLAVE
);
1760 $row = $dbr->selectRow('image',
1761 /* SELECT */ 'img_user',
1762 /* WHERE */ array( 'img_name' => $img )
1767 return $user->getId() == $row->img_user
;
1771 * Display an error with a wikitext description
1773 function showError( $description ) {
1775 $wgOut->setPageTitle( wfMsg( "internalerror" ) );
1776 $wgOut->setRobotPolicy( "noindex,nofollow" );
1777 $wgOut->setArticleRelated( false );
1778 $wgOut->enableClientCache( false );
1779 $wgOut->addWikiText( $description );
1783 * Get the initial image page text based on a comment and optional file status information
1785 static function getInitialPageText( $comment, $license, $copyStatus, $source ) {
1786 global $wgUseCopyrightUpload;
1787 if ( $wgUseCopyrightUpload ) {
1788 if ( $license != '' ) {
1789 $licensetxt = '== ' . wfMsgForContent( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1791 $pageText = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $comment . "\n" .
1792 '== ' . wfMsgForContent ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
1794 '== ' . wfMsgForContent ( 'filesource' ) . " ==\n" . $source ;
1796 if ( $license != '' ) {
1797 $filedesc = $comment == '' ?
'' : '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $comment . "\n";
1798 $pageText = $filedesc .
1799 '== ' . wfMsgForContent ( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1801 $pageText = $comment;
1808 * If there are rows in the deletion log for this file, show them,
1809 * along with a nice little note for the user
1811 * @param OutputPage $out
1812 * @param string filename
1814 private function showDeletionLog( $out, $filename ) {
1816 $loglist = new LogEventsList( $wgUser->getSkin(), $out );
1817 $pager = new LogPager( $loglist, 'delete', false, $filename );
1818 if( $pager->getNumRows() > 0 ) {
1819 $out->addHTML( '<div class="mw-warning-with-logexcerpt">' );
1820 $out->addWikiMsg( 'upload-wasdeleted' );
1822 $loglist->beginLogEventsList() .
1824 $loglist->endLogEventsList()
1826 $out->addHTML( '</div>' );