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_LENGHT_PARTNAME
= 4;
27 const ILLEGAL_FILENAME
= 5;
28 const PROTECTED_PAGE
= 6;
29 const OVERWRITE_EXISTING_FILE
= 7;
30 const FILETYPE_MISSING
= 8;
31 const FILETYPE_BADTYPE
= 9;
32 const VERIFICATION_ERROR
= 10;
33 const UPLOAD_VERIFICATION_ERROR
= 11;
34 const UPLOAD_WARNING
= 12;
35 const INTERNAL_ERROR
= 13;
40 var $mComment, $mLicense, $mIgnoreWarning, $mCurlError;
41 var $mDestName, $mTempPath, $mFileSize, $mFileProps;
42 var $mCopyrightStatus, $mCopyrightSource, $mReUpload, $mAction, $mUploadClicked;
43 var $mSrcName, $mSessionKey, $mStashed, $mDesiredDestName, $mRemoveTempFile, $mSourceType;
44 var $mDestWarningAck, $mCurlDestHandle;
47 # Placeholders for text injection by hooks (must be HTML)
48 # extensions should take care to _append_ to the present value
49 var $uploadFormTextTop;
50 var $uploadFormTextAfterSummary;
52 const SESSION_VERSION
= 1;
56 * Constructor : initialise object
57 * Get data POSTed through the form and assign them to the object
58 * @param $request Data posted.
60 function UploadForm( &$request ) {
61 global $wgAllowCopyUploads;
62 $this->mDesiredDestName
= $request->getText( 'wpDestFile' );
63 $this->mIgnoreWarning
= $request->getCheck( 'wpIgnoreWarning' );
64 $this->mComment
= $request->getText( 'wpUploadDescription' );
66 if( !$request->wasPosted() ) {
67 # GET requests just give the main form; no data except destination
68 # filename and description
72 # Placeholders for text injection by hooks (empty per default)
73 $this->uploadFormTextTop
= "";
74 $this->uploadFormTextAfterSummary
= "";
76 $this->mReUpload
= $request->getCheck( 'wpReUpload' );
77 $this->mUploadClicked
= $request->getCheck( 'wpUpload' );
79 $this->mLicense
= $request->getText( 'wpLicense' );
80 $this->mCopyrightStatus
= $request->getText( 'wpUploadCopyStatus' );
81 $this->mCopyrightSource
= $request->getText( 'wpUploadSource' );
82 $this->mWatchthis
= $request->getBool( 'wpWatchthis' );
83 $this->mSourceType
= $request->getText( 'wpSourceType' );
84 $this->mDestWarningAck
= $request->getText( 'wpDestFileWarningAck' );
86 $this->mAction
= $request->getVal( 'action' );
88 $this->mSessionKey
= $request->getInt( 'wpSessionKey' );
89 if( !empty( $this->mSessionKey
) &&
90 isset( $_SESSION['wsUploadData'][$this->mSessionKey
]['version'] ) &&
91 $_SESSION['wsUploadData'][$this->mSessionKey
]['version'] == self
::SESSION_VERSION
) {
93 * Confirming a temporarily stashed upload.
94 * We don't want path names to be forged, so we keep
95 * them in the session on the server and just give
96 * an opaque key to the user agent.
98 $data = $_SESSION['wsUploadData'][$this->mSessionKey
];
99 $this->mTempPath
= $data['mTempPath'];
100 $this->mFileSize
= $data['mFileSize'];
101 $this->mSrcName
= $data['mSrcName'];
102 $this->mFileProps
= $data['mFileProps'];
103 $this->mCurlError
= 0/*UPLOAD_ERR_OK*/;
104 $this->mStashed
= true;
105 $this->mRemoveTempFile
= false;
108 *Check for a newly uploaded file.
110 if( $wgAllowCopyUploads && $this->mSourceType
== 'web' ) {
111 $this->initializeFromUrl( $request );
113 $this->initializeFromUpload( $request );
119 * Initialize the uploaded file from PHP data
122 function initializeFromUpload( $request ) {
123 $this->mTempPath
= $request->getFileTempName( 'wpUploadFile' );
124 $this->mFileSize
= $request->getFileSize( 'wpUploadFile' );
125 $this->mSrcName
= $request->getFileName( 'wpUploadFile' );
126 $this->mCurlError
= $request->getUploadError( 'wpUploadFile' );
127 $this->mSessionKey
= false;
128 $this->mStashed
= false;
129 $this->mRemoveTempFile
= false; // PHP will handle this
133 * Copy a web file to a temporary file
136 function initializeFromUrl( $request ) {
137 global $wgTmpDirectory;
138 $url = $request->getText( 'wpUploadFileURL' );
139 $local_file = tempnam( $wgTmpDirectory, 'WEBUPLOAD' );
141 $this->mTempPath
= $local_file;
142 $this->mFileSize
= 0; # Will be set by curlCopy
143 $this->mCurlError
= $this->curlCopy( $url, $local_file );
144 $pathParts = explode( '/', $url );
145 $this->mSrcName
= array_pop( $pathParts );
146 $this->mSessionKey
= false;
147 $this->mStashed
= false;
149 // PHP won't auto-cleanup the file
150 $this->mRemoveTempFile
= file_exists( $local_file );
155 * Returns true if there was an error, false otherwise
157 private function curlCopy( $url, $dest ) {
158 global $wgUser, $wgOut;
160 if( !$wgUser->isAllowed( 'upload_by_url' ) ) {
161 $wgOut->permissionRequired( 'upload_by_url' );
165 # Maybe remove some pasting blanks :-)
167 if( stripos($url, 'http://') !== 0 && stripos($url, 'ftp://') !== 0 ) {
168 # Only HTTP or FTP URLs
169 $wgOut->showErrorPage( 'upload-proto-error', 'upload-proto-error-text' );
173 # Open temporary file
174 $this->mCurlDestHandle
= @fopen
( $this->mTempPath
, "wb" );
175 if( $this->mCurlDestHandle
=== false ) {
176 # Could not open temporary file to write in
177 $wgOut->showErrorPage( 'upload-file-error', 'upload-file-error-text');
182 curl_setopt( $ch, CURLOPT_HTTP_VERSION
, 1.0); # Probably not needed, but apparently can work around some bug
183 curl_setopt( $ch, CURLOPT_TIMEOUT
, 10); # 10 seconds timeout
184 curl_setopt( $ch, CURLOPT_LOW_SPEED_LIMIT
, 512); # 0.5KB per second minimum transfer speed
185 curl_setopt( $ch, CURLOPT_URL
, $url);
186 curl_setopt( $ch, CURLOPT_WRITEFUNCTION
, array( $this, 'uploadCurlCallback' ) );
188 $error = curl_errno( $ch ) ?
true : false;
189 $errornum = curl_errno( $ch );
190 // if ( $error ) print curl_error ( $ch ) ; # Debugging output
193 fclose( $this->mCurlDestHandle
);
194 unset( $this->mCurlDestHandle
);
197 if( wfEmptyMsg( "upload-curl-error$errornum", wfMsg("upload-curl-error$errornum") ) )
198 $wgOut->showErrorPage( 'upload-misc-error', 'upload-misc-error-text' );
200 $wgOut->showErrorPage( "upload-curl-error$errornum", "upload-curl-error$errornum-text" );
207 * Callback function for CURL-based web transfer
208 * Write data to file unless we've passed the length limit;
209 * if so, abort immediately.
212 function uploadCurlCallback( $ch, $data ) {
213 global $wgMaxUploadSize;
214 $length = strlen( $data );
215 $this->mFileSize +
= $length;
216 if( $this->mFileSize
> $wgMaxUploadSize ) {
219 fwrite( $this->mCurlDestHandle
, $data );
228 global $wgUser, $wgOut;
229 global $wgEnableUploads;
231 # Check uploading enabled
232 if( !$wgEnableUploads ) {
233 $wgOut->showErrorPage( 'uploaddisabled', 'uploaddisabledtext', array( $this->mDesiredDestName
) );
238 if( !$wgUser->isAllowed( 'upload' ) ) {
239 if( !$wgUser->isLoggedIn() ) {
240 $wgOut->showErrorPage( 'uploadnologin', 'uploadnologintext' );
242 $wgOut->permissionRequired( 'upload' );
248 if( $wgUser->isBlocked() ) {
249 $wgOut->blockedPage();
254 $wgOut->readOnlyPage();
258 if( $this->mReUpload
) {
259 if( !$this->unsaveUploadedFile() ) {
262 # Because it is probably checked and shouldn't be
263 $this->mIgnoreWarning
= false;
265 $this->mainUploadForm();
266 } else if( 'submit' == $this->mAction ||
$this->mUploadClicked
) {
267 $this->processUpload();
269 $this->mainUploadForm();
272 $this->cleanupTempFile();
277 * Checks are made in SpecialUpload::execute()
281 function processUpload(){
282 global $wgUser, $wgOut, $wgFileExtensions, $wgLang;
285 $value = $this->internalProcessUpload( $details );
289 $wgOut->redirect( $this->mLocalFile
->getTitle()->getFullURL() );
292 case self
::BEFORE_PROCESSING
:
295 case self
::LARGE_FILE_SERVER
:
296 $this->mainUploadForm( wfMsgHtml( 'largefileserver' ) );
299 case self
::EMPTY_FILE
:
300 $this->mainUploadForm( wfMsgHtml( 'emptyfile' ) );
303 case self
::MIN_LENGHT_PARTNAME
:
304 $this->mainUploadForm( wfMsgHtml( 'minlength1' ) );
307 case self
::ILLEGAL_FILENAME
:
308 $filtered = $details['filtered'];
309 $this->uploadError( wfMsgWikiHtml( 'illegalfilename', htmlspecialchars( $filtered ) ) );
312 case self
::PROTECTED_PAGE
:
313 $wgOut->showPermissionsErrorPage( $details['permissionserrors'] );
316 case self
::OVERWRITE_EXISTING_FILE
:
317 $errorText = $details['overwrite'];
318 $this->uploadError( $wgOut->parse( $errorText ) );
321 case self
::FILETYPE_MISSING
:
322 $this->uploadError( wfMsgExt( 'filetype-missing', array ( 'parseinline' ) ) );
325 case self
::FILETYPE_BADTYPE
:
326 $finalExt = $details['finalExt'];
328 wfMsgExt( 'filetype-banned-type',
329 array( 'parseinline' ),
330 htmlspecialchars( $finalExt ),
331 $wgLang->commaList( $wgFileExtensions ),
332 $wgLang->formatNum( count($wgFileExtensions) )
337 case self
::VERIFICATION_ERROR
:
338 $veri = $details['veri'];
339 $this->uploadError( $veri->toString() );
342 case self
::UPLOAD_VERIFICATION_ERROR
:
343 $error = $details['error'];
344 $this->uploadError( $error );
347 case self
::UPLOAD_WARNING
:
348 $warning = $details['warning'];
349 $this->uploadWarning( $warning );
352 case self
::INTERNAL_ERROR
:
353 $internal = $details['internal'];
354 $this->showError( $internal );
358 throw new MWException( __METHOD__
. ": Unknown value `{$value}`" );
363 * Really do the upload
364 * Checks are made in SpecialUpload::execute()
366 * @param array $resultDetails contains result-specific dict of additional values
370 function internalProcessUpload( &$resultDetails ) {
373 if( !wfRunHooks( 'UploadForm:BeforeProcessing', array( &$this ) ) )
375 wfDebug( "Hook 'UploadForm:BeforeProcessing' broke processing the file." );
376 return self
::BEFORE_PROCESSING
;
380 * If there was no filename or a zero size given, give up quick.
382 if( trim( $this->mSrcName
) == '' ||
empty( $this->mFileSize
) ) {
383 return self
::EMPTY_FILE
;
386 /* Check for curl error */
387 if( $this->mCurlError
) {
388 return self
::BEFORE_PROCESSING
;
392 * Chop off any directories in the given filename. Then
393 * filter out illegal characters, and try to make a legible name
394 * out of it. We'll strip some silently that Title would die on.
396 if( $this->mDesiredDestName
) {
397 $basename = $this->mDesiredDestName
;
399 $basename = $this->mSrcName
;
401 $filtered = wfStripIllegalFilenameChars( $basename );
404 * We'll want to blacklist against *any* 'extension', and use
405 * only the final one for the whitelist.
407 list( $partname, $ext ) = $this->splitExtensions( $filtered );
409 if( count( $ext ) ) {
410 $finalExt = trim( $ext[count( $ext ) - 1] );
415 # If there was more than one "extension", reassemble the base
416 # filename to prevent bogus complaints about length
417 if( count( $ext ) > 1 ) {
418 for( $i = 0; $i < count( $ext ) - 1; $i++
)
419 $partname .= '.' . $ext[$i];
422 if( strlen( $partname ) < 1 ) {
423 return self
::MIN_LENGHT_PARTNAME
;
426 $nt = Title
::makeTitleSafe( NS_IMAGE
, $filtered );
427 if( is_null( $nt ) ) {
428 $resultDetails = array( 'filtered' => $filtered );
429 return self
::ILLEGAL_FILENAME
;
431 $this->mLocalFile
= wfLocalFile( $nt );
432 $this->mDestName
= $this->mLocalFile
->getName();
435 * If the image is protected, non-sysop users won't be able
436 * to modify it by uploading a new revision.
438 $permErrors = $nt->getUserPermissionsErrors( 'edit', $wgUser );
439 $permErrorsUpload = $nt->getUserPermissionsErrors( 'upload', $wgUser );
440 $permErrorsCreate = ( $nt->exists() ?
array() : $nt->getUserPermissionsErrors( 'create', $wgUser ) );
442 if( $permErrors ||
$permErrorsUpload ||
$permErrorsCreate ) {
443 // merge all the problems into one list, avoiding duplicates
444 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsUpload, $permErrors ) );
445 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsCreate, $permErrors ) );
446 $resultDetails = array( 'permissionserrors' => $permErrors );
447 return self
::PROTECTED_PAGE
;
451 * In some cases we may forbid overwriting of existing files.
453 $overwrite = $this->checkOverwrite( $this->mDestName
);
454 if( $overwrite !== true ) {
455 $resultDetails = array( 'overwrite' => $overwrite );
456 return self
::OVERWRITE_EXISTING_FILE
;
459 /* Don't allow users to override the blacklist (check file extension) */
460 global $wgCheckFileExtensions, $wgStrictFileExtensions;
461 global $wgFileExtensions, $wgFileBlacklist;
462 if ($finalExt == '') {
463 return self
::FILETYPE_MISSING
;
464 } elseif ( $this->checkFileExtensionList( $ext, $wgFileBlacklist ) ||
465 ($wgCheckFileExtensions && $wgStrictFileExtensions &&
466 !$this->checkFileExtension( $finalExt, $wgFileExtensions ) ) ) {
467 $resultDetails = array( 'finalExt' => $finalExt );
468 return self
::FILETYPE_BADTYPE
;
472 * Look at the contents of the file; if we can recognize the
473 * type but it's corrupt or data of the wrong type, we should
474 * probably not accept it.
476 if( !$this->mStashed
) {
477 $this->mFileProps
= File
::getPropsFromPath( $this->mTempPath
, $finalExt );
478 $this->checkMacBinary();
479 $veri = $this->verify( $this->mTempPath
, $finalExt );
481 if( $veri !== true ) { //it's a wiki error...
482 $resultDetails = array( 'veri' => $veri );
483 return self
::VERIFICATION_ERROR
;
487 * Provide an opportunity for extensions to add further checks
490 if( !wfRunHooks( 'UploadVerification',
491 array( $this->mDestName
, $this->mTempPath
, &$error ) ) ) {
492 $resultDetails = array( 'error' => $error );
493 return self
::UPLOAD_VERIFICATION_ERROR
;
499 * Check for non-fatal conditions
501 if ( ! $this->mIgnoreWarning
) {
504 global $wgCapitalLinks;
505 if( $wgCapitalLinks ) {
506 $filtered = ucfirst( $filtered );
508 if( $basename != $filtered ) {
509 $warning .= '<li>'.wfMsgHtml( 'badfilename', htmlspecialchars( $this->mDestName
) ).'</li>';
512 global $wgCheckFileExtensions;
513 if ( $wgCheckFileExtensions ) {
514 if ( !$this->checkFileExtension( $finalExt, $wgFileExtensions ) ) {
517 wfMsgExt( 'filetype-unwanted-type',
518 array( 'parseinline' ),
519 htmlspecialchars( $finalExt ),
520 $wgLang->commaList( $wgFileExtensions ),
521 $wgLang->formatNum( count($wgFileExtensions) )
526 global $wgUploadSizeWarning;
527 if ( $wgUploadSizeWarning && ( $this->mFileSize
> $wgUploadSizeWarning ) ) {
528 $skin = $wgUser->getSkin();
529 $wsize = $skin->formatSize( $wgUploadSizeWarning );
530 $asize = $skin->formatSize( $this->mFileSize
);
531 $warning .= '<li>' . wfMsgHtml( 'large-file', $wsize, $asize ) . '</li>';
533 if ( $this->mFileSize
== 0 ) {
534 $warning .= '<li>'.wfMsgHtml( 'emptyfile' ).'</li>';
537 if ( !$this->mDestWarningAck
) {
538 $warning .= self
::getExistsWarning( $this->mLocalFile
);
541 $warning .= $this->getDupeWarning( $this->mTempPath
, $finalExt );
543 if( $warning != '' ) {
545 * Stash the file in a temporary location; the user can choose
546 * to let it through and we'll complete the upload then.
548 $resultDetails = array( 'warning' => $warning );
549 return self
::UPLOAD_WARNING
;
554 * Try actually saving the thing...
555 * It will show an error form on failure.
557 $pageText = self
::getInitialPageText( $this->mComment
, $this->mLicense
,
558 $this->mCopyrightStatus
, $this->mCopyrightSource
);
560 $status = $this->mLocalFile
->upload( $this->mTempPath
, $this->mComment
, $pageText,
561 File
::DELETE_SOURCE
, $this->mFileProps
);
562 if ( !$status->isGood() ) {
563 $resultDetails = array( 'internal' => $status->getWikiText() );
564 return self
::INTERNAL_ERROR
;
566 if ( $this->mWatchthis
) {
568 $wgUser->addWatch( $this->mLocalFile
->getTitle() );
570 // Success, redirect to description page
571 $img = null; // @todo: added to avoid passing a ref to null - should this be defined somewhere?
572 wfRunHooks( 'UploadComplete', array( &$this ) );
573 return self
::SUCCESS
;
578 * Do existence checks on a file and produce a warning
579 * This check is static and can be done pre-upload via AJAX
580 * Returns an HTML fragment consisting of one or more LI elements if there is a warning
581 * Returns an empty string if there is no warning
583 static function getExistsWarning( $file ) {
584 global $wgUser, $wgContLang;
585 // Check for uppercase extension. We allow these filenames but check if an image
586 // with lowercase extension exists already
588 $align = $wgContLang->isRtl() ?
'left' : 'right';
590 if( strpos( $file->getName(), '.' ) == false ) {
591 $partname = $file->getName();
594 $n = strrpos( $file->getName(), '.' );
595 $rawExtension = substr( $file->getName(), $n +
1 );
596 $partname = substr( $file->getName(), 0, $n );
599 $sk = $wgUser->getSkin();
601 if ( $rawExtension != $file->getExtension() ) {
602 // We're not using the normalized form of the extension.
603 // Normal form is lowercase, using most common of alternate
604 // extensions (eg 'jpg' rather than 'JPEG').
606 // Check for another file using the normalized form...
607 $nt_lc = Title
::makeTitle( NS_IMAGE
, $partname . '.' . $file->getExtension() );
608 $file_lc = wfLocalFile( $nt_lc );
613 if( $file->exists() ) {
614 $dlink = $sk->makeKnownLinkObj( $file->getTitle() );
615 if ( $file->allowInlineDisplay() ) {
616 $dlink2 = $sk->makeImageLinkObj( $file->getTitle(), wfMsgExt( 'fileexists-thumb', 'parseinline' ),
617 $file->getName(), $align, array(), false, true );
618 } elseif ( !$file->allowInlineDisplay() && $file->isSafeFile() ) {
619 $icon = $file->iconThumb();
620 $dlink2 = '<div style="float:' . $align . '" id="mw-media-icon">' .
621 $icon->toHtml( array( 'desc-link' => true ) ) . '<br />' . $dlink . '</div>';
626 $warning .= '<li>' . wfMsgExt( 'fileexists', array('parseinline','replaceafter'), $dlink ) . '</li>' . $dlink2;
628 } elseif( $file->getTitle()->getArticleID() ) {
629 $lnk = $sk->makeKnownLinkObj( $file->getTitle(), '', 'redirect=no' );
630 $warning .= '<li>' . wfMsgExt( 'filepageexists', array( 'parseinline', 'replaceafter' ), $lnk ) . '</li>';
631 } elseif ( $file_lc && $file_lc->exists() ) {
632 # Check if image with lowercase extension exists.
633 # It's not forbidden but in 99% it makes no sense to upload the same filename with uppercase extension
634 $dlink = $sk->makeKnownLinkObj( $nt_lc );
635 if ( $file_lc->allowInlineDisplay() ) {
636 $dlink2 = $sk->makeImageLinkObj( $nt_lc, wfMsgExt( 'fileexists-thumb', 'parseinline' ),
637 $nt_lc->getText(), $align, array(), false, true );
638 } elseif ( !$file_lc->allowInlineDisplay() && $file_lc->isSafeFile() ) {
639 $icon = $file_lc->iconThumb();
640 $dlink2 = '<div style="float:' . $align . '" id="mw-media-icon">' .
641 $icon->toHtml( array( 'desc-link' => true ) ) . '<br />' . $dlink . '</div>';
647 wfMsgExt( 'fileexists-extension', 'parsemag',
648 $file->getTitle()->getPrefixedText(), $dlink ) .
651 } elseif ( ( substr( $partname , 3, 3 ) == 'px-' ||
substr( $partname , 2, 3 ) == 'px-' )
652 && ereg( "[0-9]{2}" , substr( $partname , 0, 2) ) )
654 # Check for filenames like 50px- or 180px-, these are mostly thumbnails
655 $nt_thb = Title
::newFromText( substr( $partname , strpos( $partname , '-' ) +
1 ) . '.' . $rawExtension );
656 $file_thb = wfLocalFile( $nt_thb );
657 if ($file_thb->exists() ) {
658 # Check if an image without leading '180px-' (or similiar) exists
659 $dlink = $sk->makeKnownLinkObj( $nt_thb);
660 if ( $file_thb->allowInlineDisplay() ) {
661 $dlink2 = $sk->makeImageLinkObj( $nt_thb,
662 wfMsgExt( 'fileexists-thumb', 'parseinline' ),
663 $nt_thb->getText(), $align, array(), false, true );
664 } elseif ( !$file_thb->allowInlineDisplay() && $file_thb->isSafeFile() ) {
665 $icon = $file_thb->iconThumb();
666 $dlink2 = '<div style="float:' . $align . '" id="mw-media-icon">' .
667 $icon->toHtml( array( 'desc-link' => true ) ) . '<br />' .
673 $warning .= '<li>' . wfMsgExt( 'fileexists-thumbnail-yes', 'parsemag', $dlink ) .
676 # Image w/o '180px-' does not exists, but we do not like these filenames
677 $warning .= '<li>' . wfMsgExt( 'file-thumbnail-no', 'parseinline' ,
678 substr( $partname , 0, strpos( $partname , '-' ) +
1 ) ) . '</li>';
682 $filenamePrefixBlacklist = self
::getFilenamePrefixBlacklist();
684 foreach( $filenamePrefixBlacklist as $prefix ) {
685 if ( substr( $partname, 0, strlen( $prefix ) ) == $prefix ) {
686 $warning .= '<li>' . wfMsgExt( 'filename-bad-prefix', 'parseinline', $prefix ) . '</li>';
691 if ( $file->wasDeleted() && !$file->exists() ) {
692 # If the file existed before and was deleted, warn the user of this
693 # Don't bother doing so if the file exists now, however
694 $ltitle = SpecialPage
::getTitleFor( 'Log' );
695 $llink = $sk->makeKnownLinkObj( $ltitle, wfMsgHtml( 'deletionlog' ),
696 'type=delete&page=' . $file->getTitle()->getPrefixedUrl() );
697 $warning .= '<li>' . wfMsgWikiHtml( 'filewasdeleted', $llink ) . '</li>';
703 * Get a list of warnings
705 * @param string local filename, e.g. 'file exists', 'non-descriptive filename'
706 * @return array list of warning messages
708 static function ajaxGetExistsWarning( $filename ) {
709 $file = wfFindFile( $filename );
711 // Force local file so we have an object to do further checks against
712 // if there isn't an exact match...
713 $file = wfLocalFile( $filename );
717 $warning = self
::getExistsWarning( $file );
718 if ( $warning !== '' ) {
719 $s = "<ul>$warning</ul>";
726 * Render a preview of a given license for the AJAX preview on upload
728 * @param string $license
731 public static function ajaxGetLicensePreview( $license ) {
732 global $wgParser, $wgUser;
733 $text = '{{' . $license . '}}';
734 $title = Title
::makeTitle( NS_IMAGE
, 'Sample.jpg' );
735 $options = ParserOptions
::newFromUser( $wgUser );
737 // Expand subst: first, then live templates...
738 $text = $wgParser->preSaveTransform( $text, $title, $wgUser, $options );
739 $output = $wgParser->parse( $text, $title, $options );
741 return $output->getText();
745 * Check for duplicate files and throw up a warning before the upload
748 function getDupeWarning( $tempfile, $extension ) {
749 $hash = File
::sha1Base36( $tempfile );
750 $dupes = RepoGroup
::singleton()->findBySha1( $hash );
751 $archivedImage = new ArchivedFile( null, 0, $hash.".$extension" );
755 foreach( $dupes as $file ) {
756 $title = $file->getTitle();
757 $msg .= $title->getPrefixedText() .
758 "|" . $title->getText() . "\n";
760 $msg .= "</gallery>";
762 wfMsgExt( "file-exists-duplicate", array( "parse" ), count( $dupes ) ) .
763 $wgOut->parse( $msg ) .
765 } elseif ( $archivedImage->getID() > 0 ) {
767 $name = Title
::makeTitle( NS_IMAGE
, $archivedImage->getName() )->getPrefixedText();
768 return Xml
::tags( 'li', null, wfMsgExt( 'file-deleted-duplicate', array( 'parseinline' ), array( $name ) ) );
775 * Get a list of blacklisted filename prefixes from [[MediaWiki:filename-prefix-blacklist]]
777 * @return array list of prefixes
779 public static function getFilenamePrefixBlacklist() {
780 $blacklist = array();
781 $message = wfMsgForContent( 'filename-prefix-blacklist' );
782 if( $message && !( wfEmptyMsg( 'filename-prefix-blacklist', $message ) ||
$message == '-' ) ) {
783 $lines = explode( "\n", $message );
784 foreach( $lines as $line ) {
785 // Remove comment lines
786 $comment = substr( trim( $line ), 0, 1 );
787 if ( $comment == '#' ||
$comment == '' ) {
790 // Remove additional comments after a prefix
791 $comment = strpos( $line, '#' );
792 if ( $comment > 0 ) {
793 $line = substr( $line, 0, $comment-1 );
795 $blacklist[] = trim( $line );
802 * Stash a file in a temporary directory for later processing
803 * after the user has confirmed it.
805 * If the user doesn't explicitly cancel or accept, these files
806 * can accumulate in the temp directory.
808 * @param string $saveName - the destination filename
809 * @param string $tempName - the source temporary file to save
810 * @return string - full path the stashed file, or false on failure
813 function saveTempUploadedFile( $saveName, $tempName ) {
815 $repo = RepoGroup
::singleton()->getLocalRepo();
816 $status = $repo->storeTemp( $saveName, $tempName );
817 if ( !$status->isGood() ) {
818 $this->showError( $status->getWikiText() );
821 return $status->value
;
826 * Stash a file in a temporary directory for later processing,
827 * and save the necessary descriptive info into the session.
828 * Returns a key value which will be passed through a form
829 * to pick up the path info on a later invocation.
834 function stashSession() {
835 $stash = $this->saveTempUploadedFile( $this->mDestName
, $this->mTempPath
);
838 # Couldn't save the file.
842 $key = mt_rand( 0, 0x7fffffff );
843 $_SESSION['wsUploadData'][$key] = array(
844 'mTempPath' => $stash,
845 'mFileSize' => $this->mFileSize
,
846 'mSrcName' => $this->mSrcName
,
847 'mFileProps' => $this->mFileProps
,
848 'version' => self
::SESSION_VERSION
,
854 * Remove a temporarily kept file stashed by saveTempUploadedFile().
858 function unsaveUploadedFile() {
860 $repo = RepoGroup
::singleton()->getLocalRepo();
861 $success = $repo->freeTemp( $this->mTempPath
);
863 $wgOut->showFileDeleteError( $this->mTempPath
);
870 /* -------------------------------------------------------------- */
873 * @param string $error as HTML
876 function uploadError( $error ) {
878 $wgOut->addHTML( '<h2>' . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
879 $wgOut->addHTML( '<span class="error">' . $error . '</span>' );
883 * There's something wrong with this file, not enough to reject it
884 * totally but we require manual intervention to save it for real.
885 * Stash it away, then present a form asking to confirm or cancel.
887 * @param string $warning as HTML
890 function uploadWarning( $warning ) {
892 global $wgUseCopyrightUpload;
894 $this->mSessionKey
= $this->stashSession();
895 if( !$this->mSessionKey
) {
896 # Couldn't save file; an error has been displayed so let's go.
900 $wgOut->addHTML( '<h2>' . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
901 $wgOut->addHTML( '<ul class="warning">' . $warning . "</ul>\n" );
903 $titleObj = SpecialPage
::getTitleFor( 'Upload' );
905 if ( $wgUseCopyrightUpload ) {
906 $copyright = Xml
::hidden( 'wpUploadCopyStatus', $this->mCopyrightStatus
) . "\n" .
907 Xml
::hidden( 'wpUploadSource', $this->mCopyrightSource
) . "\n";
913 Xml
::openElement( 'form', array( 'method' => 'post', 'action' => $titleObj->getLocalURL( 'action=submit' ),
914 'enctype' => 'multipart/form-data', 'id' => 'uploadwarning' ) ) . "\n" .
915 Xml
::hidden( 'wpIgnoreWarning', '1' ) . "\n" .
916 Xml
::hidden( 'wpSessionKey', $this->mSessionKey
) . "\n" .
917 Xml
::hidden( 'wpUploadDescription', $this->mComment
) . "\n" .
918 Xml
::hidden( 'wpLicense', $this->mLicense
) . "\n" .
919 Xml
::hidden( 'wpDestFile', $this->mDesiredDestName
) . "\n" .
920 Xml
::hidden( 'wpWatchthis', $this->mWatchthis
) . "\n" .
921 "{$copyright}<br />" .
922 Xml
::submitButton( wfMsg( 'ignorewarning' ), array ( 'name' => 'wpUpload', 'id' => 'wpUpload', 'checked' => 'checked' ) ) . ' ' .
923 Xml
::submitButton( wfMsg( 'reuploaddesc' ), array ( 'name' => 'wpReUpload', 'id' => 'wpReUpload' ) ) .
924 Xml
::closeElement( 'form' ) . "\n"
929 * Displays the main upload form, optionally with a highlighted
930 * error message up at the top.
932 * @param string $msg as HTML
935 function mainUploadForm( $msg='' ) {
936 global $wgOut, $wgUser, $wgLang, $wgMaxUploadSize;
937 global $wgUseCopyrightUpload, $wgUseAjax, $wgAjaxUploadDestCheck, $wgAjaxLicensePreview;
938 global $wgRequest, $wgAllowCopyUploads;
939 global $wgStylePath, $wgStyleVersion;
941 $useAjaxDestCheck = $wgUseAjax && $wgAjaxUploadDestCheck;
942 $useAjaxLicensePreview = $wgUseAjax && $wgAjaxLicensePreview;
944 $adc = wfBoolToStr( $useAjaxDestCheck );
945 $alp = wfBoolToStr( $useAjaxLicensePreview );
946 $autofill = wfBoolToStr( $this->mDesiredDestName
== '' );
948 $wgOut->addScript( "<script type=\"text/javascript\">
949 wgAjaxUploadDestCheck = {$adc};
950 wgAjaxLicensePreview = {$alp};
951 wgUploadAutoFill = {$autofill};
953 $wgOut->addScriptFile( 'upload.js' );
954 $wgOut->addScriptFile( 'edit.js' ); // For <charinsert> support
956 if( !wfRunHooks( 'UploadForm:initial', array( &$this ) ) )
958 wfDebug( "Hook 'UploadForm:initial' broke output of the upload form" );
962 if( $this->mDesiredDestName
) {
963 $title = Title
::makeTitleSafe( NS_IMAGE
, $this->mDesiredDestName
);
964 // Show a subtitle link to deleted revisions (to sysops et al only)
965 if( $title instanceof Title
&& ( $count = $title->isDeleted() ) > 0 && $wgUser->isAllowed( 'deletedhistory' ) ) {
967 $wgUser->isAllowed( 'delete' ) ?
'thisisdeleted' : 'viewdeleted',
968 array( 'parse', 'replaceafter' ),
969 $wgUser->getSkin()->makeKnownLinkObj(
970 SpecialPage
::getTitleFor( 'Undelete', $title->getPrefixedText() ),
971 wfMsgExt( 'restorelink', array( 'parsemag', 'escape' ), $count )
974 $wgOut->addHTML( "<div id=\"contentSub2\">{$link}</div>" );
977 // Show the relevant lines from deletion log (for still deleted files only)
978 if( $title instanceof Title
&& $title->isDeleted() > 0 && !$title->exists() ) {
979 $this->showDeletionLog( $wgOut, $title->getPrefixedText() );
983 $cols = intval($wgUser->getOption( 'cols' ));
985 if( $wgUser->getOption( 'editwidth' ) ) {
986 $width = " style=\"width:100%\"";
992 $sub = wfMsgHtml( 'uploaderror' );
993 $wgOut->addHTML( "<h2>{$sub}</h2>\n" .
994 "<span class='error'>{$msg}</span>\n" );
996 $wgOut->addHTML( '<div id="uploadtext">' );
997 $wgOut->addWikiMsg( 'uploadtext', $this->mDesiredDestName
);
998 $wgOut->addHTML( "</div>\n" );
1000 # Print a list of allowed file extensions, if so configured. We ignore
1001 # MIME type here, it's incomprehensible to most people and too long.
1002 global $wgCheckFileExtensions, $wgStrictFileExtensions,
1003 $wgFileExtensions, $wgFileBlacklist;
1005 $allowedExtensions = '';
1006 if( $wgCheckFileExtensions ) {
1007 if( $wgStrictFileExtensions ) {
1008 # Everything not permitted is banned
1010 '<div id="mw-upload-permitted">' .
1011 wfMsgWikiHtml( 'upload-permitted', $wgLang->commaList( $wgFileExtensions ) ) .
1014 # We have to list both preferred and prohibited
1016 '<div id="mw-upload-preferred">' .
1017 wfMsgWikiHtml( 'upload-preferred', $wgLang->commaList( $wgFileExtensions ) ) .
1019 '<div id="mw-upload-prohibited">' .
1020 wfMsgWikiHtml( 'upload-prohibited', $wgLang->commaList( $wgFileBlacklist ) ) .
1024 # Everything is permitted.
1025 $extensionsList = '';
1028 # Get the maximum file size from php.ini as $wgMaxUploadSize works for uploads from URL via CURL only
1029 # See http://www.php.net/manual/en/ini.core.php#ini.upload-max-filesize for possible values of upload_max_filesize
1030 $val = trim( ini_get( 'upload_max_filesize' ) );
1031 $last = strtoupper( ( substr( $val, -1 ) ) );
1034 $val2 = substr( $val, 0, -1 ) * 1024 * 1024 * 1024;
1037 $val2 = substr( $val, 0, -1 ) * 1024 * 1024;
1040 $val2 = substr( $val, 0, -1 ) * 1024;
1045 $val2 = $wgAllowCopyUploads ?
min( $wgMaxUploadSize, $val2 ) : $val2;
1046 $maxUploadSize = '<div id="mw-upload-maxfilesize">' .
1047 wfMsgExt( 'upload-maxfilesize', array( 'parseinline', 'escapenoentities' ),
1048 $wgLang->formatSize( $val2 ) ) .
1051 $sourcefilename = wfMsgExt( 'sourcefilename', array( 'parseinline', 'escapenoentities' ) );
1052 $destfilename = wfMsgExt( 'destfilename', array( 'parseinline', 'escapenoentities' ) );
1054 $summary = wfMsgExt( 'fileuploadsummary', 'parseinline' );
1056 $licenses = new Licenses();
1057 $license = wfMsgExt( 'license', array( 'parseinline' ) );
1058 $nolicense = wfMsgHtml( 'nolicense' );
1059 $licenseshtml = $licenses->getHtml();
1061 $ulb = wfMsgHtml( 'uploadbtn' );
1064 $titleObj = SpecialPage
::getTitleFor( 'Upload' );
1066 $encDestName = htmlspecialchars( $this->mDesiredDestName
);
1068 $watchChecked = $this->watchCheck()
1069 ?
'checked="checked"'
1071 $warningChecked = $this->mIgnoreWarning ?
'checked' : '';
1073 // Prepare form for upload or upload/copy
1074 if( $wgAllowCopyUploads && $wgUser->isAllowed( 'upload_by_url' ) ) {
1076 "<input type='radio' id='wpSourceTypeFile' name='wpSourceType' value='file' " .
1077 "onchange='toggle_element_activation(\"wpUploadFileURL\",\"wpUploadFile\")' checked='checked' />" .
1078 "<input tabindex='1' type='file' name='wpUploadFile' id='wpUploadFile' " .
1080 "toggle_element_activation(\"wpUploadFileURL\",\"wpUploadFile\");" .
1081 "toggle_element_check(\"wpSourceTypeFile\",\"wpSourceTypeURL\")' " .
1082 "onchange='fillDestFilename(\"wpUploadFile\")' size='60' />" .
1083 wfMsgHTML( 'upload_source_file' ) . "<br/>" .
1084 "<input type='radio' id='wpSourceTypeURL' name='wpSourceType' value='web' " .
1085 "onchange='toggle_element_activation(\"wpUploadFile\",\"wpUploadFileURL\")' />" .
1086 "<input tabindex='1' type='text' name='wpUploadFileURL' id='wpUploadFileURL' " .
1088 "toggle_element_activation(\"wpUploadFile\",\"wpUploadFileURL\");" .
1089 "toggle_element_check(\"wpSourceTypeURL\",\"wpSourceTypeFile\")' " .
1090 "onchange='fillDestFilename(\"wpUploadFileURL\")' size='60' disabled='disabled' />" .
1091 wfMsgHtml( 'upload_source_url' ) ;
1094 "<input tabindex='1' type='file' name='wpUploadFile' id='wpUploadFile' " .
1095 ($this->mDesiredDestName?
"":"onchange='fillDestFilename(\"wpUploadFile\")' ") .
1097 "<input type='hidden' name='wpSourceType' value='file' />" ;
1099 if ( $useAjaxDestCheck ) {
1100 $warningRow = "<tr><td colspan='2' id='wpDestFile-warning'> </td></tr>";
1101 $destOnkeyup = 'onkeyup="wgUploadWarningObj.keypress();"';
1107 $encComment = htmlspecialchars( $this->mComment
);
1110 Xml
::openElement( 'form', array( 'method' => 'post', 'action' => $titleObj->getLocalURL(),
1111 'enctype' => 'multipart/form-data', 'id' => 'mw-upload-form' ) ) .
1112 Xml
::openElement( 'fieldset' ) .
1113 Xml
::element( 'legend', null, wfMsg( 'upload' ) ) .
1114 Xml
::openElement( 'table', array( 'border' => '0', 'id' => 'mw-upload-table' ) ) .
1116 {$this->uploadFormTextTop}
1117 <td class='mw-label'>
1118 <label for='wpUploadFile'>{$sourcefilename}</label>
1120 <td class='mw-input'>
1132 <td class='mw-label'>
1133 <label for='wpDestFile'>{$destfilename}</label>
1135 <td class='mw-input'>
1136 <input tabindex='2' type='text' name='wpDestFile' id='wpDestFile' size='60'
1137 value=\"{$encDestName}\" onchange='toggleFilenameFiller()' $destOnkeyup />
1141 <td class='mw-label'>
1142 <label for='wpUploadDescription'>{$summary}</label>
1144 <td class='mw-input'>
1145 <textarea tabindex='3' name='wpUploadDescription' id='wpUploadDescription' rows='6'
1146 cols='{$cols}'{$width}>$encComment</textarea>
1147 {$this->uploadFormTextAfterSummary}
1153 if ( $licenseshtml != '' ) {
1154 global $wgStylePath;
1156 <td class='mw-label'>
1157 <label for='wpLicense'>$license</label>
1159 <td class='mw-input'>
1160 <select name='wpLicense' id='wpLicense' tabindex='4'
1161 onchange='licenseSelectorCheck()'>
1162 <option value=''>$nolicense</option>
1169 if( $useAjaxLicensePreview ) {
1172 <td id=\"mw-license-preview\"></td>
1179 if ( $wgUseCopyrightUpload ) {
1180 $filestatus = wfMsgExt( 'filestatus', 'escapenoentities' );
1181 $copystatus = htmlspecialchars( $this->mCopyrightStatus
);
1182 $filesource = wfMsgExt( 'filesource', 'escapenoentities' );
1183 $uploadsource = htmlspecialchars( $this->mCopyrightSource
);
1186 <td class='mw-label' style='white-space: nowrap;'>
1187 <label for='wpUploadCopyStatus'>$filestatus</label></td>
1188 <td class='mw-input'>
1189 <input tabindex='5' type='text' name='wpUploadCopyStatus' id='wpUploadCopyStatus'
1190 value=\"$copystatus\" size='60' />
1194 <td class='mw-label'>
1195 <label for='wpUploadCopyStatus'>$filesource</label>
1197 <td class='mw-input'>
1198 <input tabindex='6' type='text' name='wpUploadSource' id='wpUploadCopyStatus'
1199 value=\"$uploadsource\" size='60' />
1209 <input tabindex='7' type='checkbox' name='wpWatchthis' id='wpWatchthis' $watchChecked value='true' />
1210 <label for='wpWatchthis'>" . wfMsgHtml( 'watchthisupload' ) . "</label>
1211 <input tabindex='8' type='checkbox' name='wpIgnoreWarning' id='wpIgnoreWarning' value='true' $warningChecked/>
1212 <label for='wpIgnoreWarning'>" . wfMsgHtml( 'ignorewarnings' ) . "</label>
1218 <td class='mw-input'>
1219 <input tabindex='9' type='submit' name='wpUpload' value=\"{$ulb}\"" . $wgUser->getSkin()->tooltipAndAccesskey( 'upload' ) . " />
1224 <td class='mw-input'>"
1226 $wgOut->addWikiText( wfMsgForContent( 'edittools' ) );
1230 Xml
::closeElement( 'table' ) .
1231 Xml
::hidden( 'wpDestFileWarningAck', '', array( 'id' => 'wpDestFileWarningAck' ) ) .
1232 Xml
::closeElement( 'fieldset' ) .
1233 Xml
::closeElement( 'form' )
1235 $uploadfooter = wfMsgNoTrans( 'uploadfooter' );
1236 if( $uploadfooter != '-' && !wfEmptyMsg( 'uploadfooter', $uploadfooter ) ){
1237 $wgOut->addWikiText( '<div id="mw-upload-footer-message">' . $uploadfooter . '</div>' );
1241 /* -------------------------------------------------------------- */
1244 * See if we should check the 'watch this page' checkbox on the form
1245 * based on the user's preferences and whether we're being asked
1246 * to create a new file or update an existing one.
1248 * In the case where 'watch edits' is off but 'watch creations' is on,
1249 * we'll leave the box unchecked.
1251 * Note that the page target can be changed *on the form*, so our check
1252 * state can get out of sync.
1254 function watchCheck() {
1256 if( $wgUser->getOption( 'watchdefault' ) ) {
1261 $local = wfLocalFile( $this->mDesiredDestName
);
1262 if( $local && $local->exists() ) {
1263 // We're uploading a new version of an existing file.
1264 // No creation, so don't watch it if we're not already.
1265 return $local->getTitle()->userIsWatching();
1267 // New page should get watched if that's our option.
1268 return $wgUser->getOption( 'watchcreations' );
1273 * Split a file into a base name and all dot-delimited 'extensions'
1274 * on the end. Some web server configurations will fall back to
1275 * earlier pseudo-'extensions' to determine type and execute
1276 * scripts, so the blacklist needs to check them all.
1280 public function splitExtensions( $filename ) {
1281 $bits = explode( '.', $filename );
1282 $basename = array_shift( $bits );
1283 return array( $basename, $bits );
1287 * Perform case-insensitive match against a list of file extensions.
1288 * Returns true if the extension is in the list.
1290 * @param string $ext
1291 * @param array $list
1294 function checkFileExtension( $ext, $list ) {
1295 return in_array( strtolower( $ext ), $list );
1299 * Perform case-insensitive match against a list of file extensions.
1300 * Returns true if any of the extensions are in the list.
1303 * @param array $list
1306 public function checkFileExtensionList( $ext, $list ) {
1307 foreach( $ext as $e ) {
1308 if( in_array( strtolower( $e ), $list ) ) {
1316 * Verifies that it's ok to include the uploaded file
1318 * @param string $tmpfile the full path of the temporary file to verify
1319 * @param string $extension The filename extension that the file is to be served with
1320 * @return mixed true of the file is verified, a WikiError object otherwise.
1322 function verify( $tmpfile, $extension ) {
1323 #magically determine mime type
1324 $magic = MimeMagic
::singleton();
1325 $mime = $magic->guessMimeType($tmpfile,false);
1327 #check mime type, if desired
1328 global $wgVerifyMimeType;
1329 if ($wgVerifyMimeType) {
1331 wfDebug ( "\n\nmime: <$mime> extension: <$extension>\n\n");
1332 #check mime type against file extension
1333 if( !self
::verifyExtension( $mime, $extension ) ) {
1334 return new WikiErrorMsg( 'uploadcorrupt' );
1337 #check mime type blacklist
1338 global $wgMimeTypeBlacklist;
1339 if( isset($wgMimeTypeBlacklist) && !is_null($wgMimeTypeBlacklist)
1340 && $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
1341 return new WikiErrorMsg( 'filetype-badmime', htmlspecialchars( $mime ) );
1345 #check for htmlish code and javascript
1346 if( $this->detectScript ( $tmpfile, $mime, $extension ) ) {
1347 return new WikiErrorMsg( 'uploadscripted' );
1349 if( $extension == 'svg' ||
$mime == 'image/svg+xml' ) {
1350 if( $this->detectScriptInSvg( $tmpfile ) ) {
1351 return new WikiErrorMsg( 'uploadscripted' );
1356 * Scan the uploaded file for viruses
1358 $virus= $this->detectVirus($tmpfile);
1360 return new WikiErrorMsg( 'uploadvirus', htmlspecialchars($virus) );
1363 wfDebug( __METHOD__
.": all clear; passing.\n" );
1368 * Checks if the mime type of the uploaded file matches the file extension.
1370 * @param string $mime the mime type of the uploaded file
1371 * @param string $extension The filename extension that the file is to be served with
1374 static function verifyExtension( $mime, $extension ) {
1375 $magic = MimeMagic
::singleton();
1377 if ( ! $mime ||
$mime == 'unknown' ||
$mime == 'unknown/unknown' )
1378 if ( ! $magic->isRecognizableExtension( $extension ) ) {
1379 wfDebug( __METHOD__
.": passing file with unknown detected mime type; " .
1380 "unrecognized extension '$extension', can't verify\n" );
1383 wfDebug( __METHOD__
.": rejecting file with unknown detected mime type; ".
1384 "recognized extension '$extension', so probably invalid file\n" );
1388 $match= $magic->isMatchingExtension($extension,$mime);
1390 if ($match===NULL) {
1391 wfDebug( __METHOD__
.": no file extension known for mime type $mime, passing file\n" );
1393 } elseif ($match===true) {
1394 wfDebug( __METHOD__
.": mime type $mime matches extension $extension, passing file\n" );
1396 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
1400 wfDebug( __METHOD__
.": mime type $mime mismatches file extension $extension, rejecting file\n" );
1406 * Heuristic for detecting files that *could* contain JavaScript instructions or
1407 * things that may look like HTML to a browser and are thus
1408 * potentially harmful. The present implementation will produce false positives in some situations.
1410 * @param string $file Pathname to the temporary upload file
1411 * @param string $mime The mime type of the file
1412 * @param string $extension The extension of the file
1413 * @return bool true if the file contains something looking like embedded scripts
1415 function detectScript($file, $mime, $extension) {
1416 global $wgAllowTitlesInSVG;
1418 #ugly hack: for text files, always look at the entire file.
1419 #For binarie field, just check the first K.
1421 if (strpos($mime,'text/')===0) $chunk = file_get_contents( $file );
1423 $fp = fopen( $file, 'rb' );
1424 $chunk = fread( $fp, 1024 );
1428 $chunk= strtolower( $chunk );
1430 if (!$chunk) return false;
1432 #decode from UTF-16 if needed (could be used for obfuscation).
1433 if (substr($chunk,0,2)=="\xfe\xff") $enc= "UTF-16BE";
1434 elseif (substr($chunk,0,2)=="\xff\xfe") $enc= "UTF-16LE";
1437 if ($enc) $chunk= iconv($enc,"ASCII//IGNORE",$chunk);
1439 $chunk= trim($chunk);
1441 #FIXME: convert from UTF-16 if necessarry!
1443 wfDebug("SpecialUpload::detectScript: checking for embedded scripts and HTML stuff\n");
1445 #check for HTML doctype
1446 if (eregi("<!DOCTYPE *X?HTML",$chunk)) return true;
1449 * Internet Explorer for Windows performs some really stupid file type
1450 * autodetection which can cause it to interpret valid image files as HTML
1451 * and potentially execute JavaScript, creating a cross-site scripting
1454 * Apple's Safari browser also performs some unsafe file type autodetection
1455 * which can cause legitimate files to be interpreted as HTML if the
1456 * web server is not correctly configured to send the right content-type
1457 * (or if you're really uploading plain text and octet streams!)
1459 * Returns true if IE is likely to mistake the given file for HTML.
1460 * Also returns true if Safari would mistake the given file for HTML
1461 * when served with a generic content-type.
1468 '<html', #also in safari
1471 '<script', #also in safari
1474 if( ! $wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
1478 foreach( $tags as $tag ) {
1479 if( false !== strpos( $chunk, $tag ) ) {
1485 * look for javascript
1488 #resolve entity-refs to look at attributes. may be harsh on big files... cache result?
1489 $chunk = Sanitizer
::decodeCharReferences( $chunk );
1491 #look for script-types
1492 if (preg_match('!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim',$chunk)) return true;
1494 #look for html-style script-urls
1495 if (preg_match('!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim',$chunk)) return true;
1497 #look for css-style script-urls
1498 if (preg_match('!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim',$chunk)) return true;
1500 wfDebug("SpecialUpload::detectScript: no scripts found\n");
1504 function detectScriptInSvg( $filename ) {
1505 $check = new XmlTypeCheck( $filename, array( $this, 'checkSvgScriptCallback' ) );
1506 return $check->filterMatch
;
1510 * @todo Replace this with a whitelist filter!
1512 function checkSvgScriptCallback( $element, $attribs ) {
1513 $stripped = $this->stripXmlNamespace( $element );
1515 if( $stripped == 'script' ) {
1516 wfDebug( __METHOD__
. ": Found script element '$element' in uploaded file.\n" );
1520 foreach( $attribs as $attrib => $value ) {
1521 $stripped = $this->stripXmlNamespace( $attrib );
1522 if( substr( $stripped, 0, 2 ) == 'on' ) {
1523 wfDebug( __METHOD__
. ": Found script attribute '$attrib'='value' in uploaded file.\n" );
1526 if( $stripped == 'href' && strpos( strtolower( $value ), 'javascript:' ) !== false ) {
1527 wfDebug( __METHOD__
. ": Found script href attribute '$attrib'='$value' in uploaded file.\n" );
1533 private function stripXmlNamespace( $name ) {
1534 // 'http://www.w3.org/2000/svg:script' -> 'script'
1535 $parts = explode( ':', strtolower( $name ) );
1536 return array_pop( $parts );
1540 * Generic wrapper function for a virus scanner program.
1541 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
1542 * $wgAntivirusRequired may be used to deny upload if the scan fails.
1544 * @param string $file Pathname to the temporary upload file
1545 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
1546 * or a string containing feedback from the virus scanner if a virus was found.
1547 * If textual feedback is missing but a virus was found, this function returns true.
1549 function detectVirus($file) {
1550 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
1552 if ( !$wgAntivirus ) {
1553 wfDebug( __METHOD__
.": virus scanner disabled\n");
1557 if ( !$wgAntivirusSetup[$wgAntivirus] ) {
1558 wfDebug( __METHOD__
.": unknown virus scanner: $wgAntivirus\n" );
1559 $wgOut->wrapWikiMsg( '<div class="error">$1</div>', array( 'virus-badscanner', $wgAntivirus ) );
1560 return wfMsg('virus-unknownscanner') . " $wgAntivirus";
1563 # look up scanner configuration
1564 $command = $wgAntivirusSetup[$wgAntivirus]["command"];
1565 $exitCodeMap = $wgAntivirusSetup[$wgAntivirus]["codemap"];
1566 $msgPattern = isset( $wgAntivirusSetup[$wgAntivirus]["messagepattern"] ) ?
1567 $wgAntivirusSetup[$wgAntivirus]["messagepattern"] : null;
1569 if ( strpos( $command,"%f" ) === false ) {
1570 # simple pattern: append file to scan
1571 $command .= " " . wfEscapeShellArg( $file );
1573 # complex pattern: replace "%f" with file to scan
1574 $command = str_replace( "%f", wfEscapeShellArg( $file ), $command );
1577 wfDebug( __METHOD__
.": running virus scan: $command \n" );
1579 # execute virus scanner
1582 #NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
1583 # that does not seem to be worth the pain.
1584 # Ask me (Duesentrieb) about it if it's ever needed.
1586 if ( wfIsWindows() ) {
1587 exec( "$command", $output, $exitCode );
1589 exec( "$command 2>&1", $output, $exitCode );
1592 # map exit code to AV_xxx constants.
1593 $mappedCode = $exitCode;
1594 if ( $exitCodeMap ) {
1595 if ( isset( $exitCodeMap[$exitCode] ) ) {
1596 $mappedCode = $exitCodeMap[$exitCode];
1597 } elseif ( isset( $exitCodeMap["*"] ) ) {
1598 $mappedCode = $exitCodeMap["*"];
1602 if ( $mappedCode === AV_SCAN_FAILED
) {
1603 # scan failed (code was mapped to false by $exitCodeMap)
1604 wfDebug( __METHOD__
.": failed to scan $file (code $exitCode).\n" );
1606 if ( $wgAntivirusRequired ) {
1607 return wfMsg('virus-scanfailed', array( $exitCode ) );
1611 } else if ( $mappedCode === AV_SCAN_ABORTED
) {
1612 # scan failed because filetype is unknown (probably imune)
1613 wfDebug( __METHOD__
.": unsupported file type $file (code $exitCode).\n" );
1615 } else if ( $mappedCode === AV_NO_VIRUS
) {
1617 wfDebug( __METHOD__
.": file passed virus scan.\n" );
1620 $output = join( "\n", $output );
1621 $output = trim( $output );
1624 $output = true; #if there's no output, return true
1625 } elseif ( $msgPattern ) {
1627 if ( preg_match( $msgPattern, $output, $groups ) ) {
1629 $output = $groups[1];
1634 wfDebug( __METHOD__
.": FOUND VIRUS! scanner feedback: $output" );
1640 * Check if the temporary file is MacBinary-encoded, as some uploads
1641 * from Internet Explorer on Mac OS Classic and Mac OS X will be.
1642 * If so, the data fork will be extracted to a second temporary file,
1643 * which will then be checked for validity and either kept or discarded.
1647 function checkMacBinary() {
1648 $macbin = new MacBinary( $this->mTempPath
);
1649 if( $macbin->isValid() ) {
1650 $dataFile = tempnam( wfTempDir(), "WikiMacBinary" );
1651 $dataHandle = fopen( $dataFile, 'wb' );
1653 wfDebug( "SpecialUpload::checkMacBinary: Extracting MacBinary data fork to $dataFile\n" );
1654 $macbin->extractData( $dataHandle );
1656 $this->mTempPath
= $dataFile;
1657 $this->mFileSize
= $macbin->dataForkLength();
1659 // We'll have to manually remove the new file if it's not kept.
1660 $this->mRemoveTempFile
= true;
1666 * If we've modified the upload file we need to manually remove it
1667 * on exit to clean up.
1670 function cleanupTempFile() {
1671 if ( $this->mRemoveTempFile
&& file_exists( $this->mTempPath
) ) {
1672 wfDebug( "SpecialUpload::cleanupTempFile: Removing temporary file {$this->mTempPath}\n" );
1673 unlink( $this->mTempPath
);
1678 * Check if there's an overwrite conflict and, if so, if restrictions
1679 * forbid this user from performing the upload.
1681 * @return mixed true on success, WikiError on failure
1684 function checkOverwrite( $name ) {
1685 $img = wfFindFile( $name );
1689 global $wgUser, $wgOut;
1690 if( $img->isLocal() ) {
1691 if( !self
::userCanReUpload( $wgUser, $img->name
) ) {
1692 $error = 'fileexists-forbidden';
1695 if( !$wgUser->isAllowed( 'reupload' ) ||
1696 !$wgUser->isAllowed( 'reupload-shared' ) ) {
1697 $error = "fileexists-shared-forbidden";
1703 $errorText = wfMsg( $error, wfEscapeWikiText( $img->getName() ) );
1707 // Rockin', go ahead and upload
1712 * Check if a user is the last uploader
1715 * @param string $img, image name
1718 public static function userCanReUpload( User
$user, $img ) {
1719 if( $user->isAllowed( 'reupload' ) )
1720 return true; // non-conditional
1721 if( !$user->isAllowed( 'reupload-own' ) )
1724 $dbr = wfGetDB( DB_SLAVE
);
1725 $row = $dbr->selectRow('image',
1726 /* SELECT */ 'img_user',
1727 /* WHERE */ array( 'img_name' => $img )
1732 return $user->getId() == $row->img_user
;
1736 * Display an error with a wikitext description
1738 function showError( $description ) {
1740 $wgOut->setPageTitle( wfMsg( "internalerror" ) );
1741 $wgOut->setRobotPolicy( "noindex,nofollow" );
1742 $wgOut->setArticleRelated( false );
1743 $wgOut->enableClientCache( false );
1744 $wgOut->addWikiText( $description );
1748 * Get the initial image page text based on a comment and optional file status information
1750 static function getInitialPageText( $comment, $license, $copyStatus, $source ) {
1751 global $wgUseCopyrightUpload;
1752 if ( $wgUseCopyrightUpload ) {
1753 if ( $license != '' ) {
1754 $licensetxt = '== ' . wfMsgForContent( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1756 $pageText = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $comment . "\n" .
1757 '== ' . wfMsgForContent ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
1759 '== ' . wfMsgForContent ( 'filesource' ) . " ==\n" . $source ;
1761 if ( $license != '' ) {
1762 $filedesc = $comment == '' ?
'' : '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $comment . "\n";
1763 $pageText = $filedesc .
1764 '== ' . wfMsgForContent ( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1766 $pageText = $comment;
1773 * If there are rows in the deletion log for this file, show them,
1774 * along with a nice little note for the user
1776 * @param OutputPage $out
1777 * @param string filename
1779 private function showDeletionLog( $out, $filename ) {
1781 $loglist = new LogEventsList( $wgUser->getSkin(), $out );
1782 $pager = new LogPager( $loglist, 'delete', false, $filename );
1783 if( $pager->getNumRows() > 0 ) {
1784 $out->addHTML( '<div class="mw-warning-with-logexcerpt">' );
1785 $out->addWikiMsg( 'upload-wasdeleted' );
1787 $loglist->beginLogEventsList() .
1789 $loglist->endLogEventsList()
1791 $out->addHTML( '</div>' );