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 ),
332 wfMsgExt( 'comma-separator', array( 'escapenoentities' ) ),
335 $wgLang->formatNum( count($wgFileExtensions) )
340 case self
::VERIFICATION_ERROR
:
341 $veri = $details['veri'];
342 $this->uploadError( $veri->toString() );
345 case self
::UPLOAD_VERIFICATION_ERROR
:
346 $error = $details['error'];
347 $this->uploadError( $error );
350 case self
::UPLOAD_WARNING
:
351 $warning = $details['warning'];
352 $this->uploadWarning( $warning );
355 case self
::INTERNAL_ERROR
:
356 $internal = $details['internal'];
357 $this->showError( $internal );
361 throw new MWException( __METHOD__
. ": Unknown value `{$value}`" );
366 * Really do the upload
367 * Checks are made in SpecialUpload::execute()
369 * @param array $resultDetails contains result-specific dict of additional values
373 function internalProcessUpload( &$resultDetails ) {
376 if( !wfRunHooks( 'UploadForm:BeforeProcessing', array( &$this ) ) )
378 wfDebug( "Hook 'UploadForm:BeforeProcessing' broke processing the file." );
379 return self
::BEFORE_PROCESSING
;
383 * If there was no filename or a zero size given, give up quick.
385 if( trim( $this->mSrcName
) == '' ||
empty( $this->mFileSize
) ) {
386 return self
::EMPTY_FILE
;
389 /* Check for curl error */
390 if( $this->mCurlError
) {
391 return self
::BEFORE_PROCESSING
;
394 # Chop off any directories in the given filename
395 if( $this->mDesiredDestName
) {
396 $basename = $this->mDesiredDestName
;
398 $basename = $this->mSrcName
;
400 $filtered = wfBaseName( $basename );
403 * We'll want to blacklist against *any* 'extension', and use
404 * only the final one for the whitelist.
406 list( $partname, $ext ) = $this->splitExtensions( $filtered );
408 if( count( $ext ) ) {
409 $finalExt = $ext[count( $ext ) - 1];
414 # If there was more than one "extension", reassemble the base
415 # filename to prevent bogus complaints about length
416 if( count( $ext ) > 1 ) {
417 for( $i = 0; $i < count( $ext ) - 1; $i++
)
418 $partname .= '.' . $ext[$i];
421 if( strlen( $partname ) < 1 ) {
422 return self
::MIN_LENGHT_PARTNAME
;
426 * Filter out illegal characters, and try to make a legible name
427 * out of it. We'll strip some silently that Title would die on.
429 $filtered = preg_replace ( "/[^".Title
::legalChars()."]|:/", '-', $filtered );
431 $filtered = preg_replace ( "/[*?]/", '-', $filtered );
432 $nt = Title
::makeTitleSafe( NS_IMAGE
, $filtered );
433 if( is_null( $nt ) ) {
434 $resultDetails = array( 'filtered' => $filtered );
435 return self
::ILLEGAL_FILENAME
;
437 $this->mLocalFile
= wfLocalFile( $nt );
438 $this->mDestName
= $this->mLocalFile
->getName();
441 * If the image is protected, non-sysop users won't be able
442 * to modify it by uploading a new revision.
444 $permErrors = $nt->getUserPermissionsErrors( 'edit', $wgUser );
445 $permErrorsUpload = $nt->getUserPermissionsErrors( 'upload', $wgUser );
446 $permErrorsCreate = ( $nt->exists() ?
array() : $nt->getUserPermissionsErrors( 'create', $wgUser ) );
448 if( $permErrors ||
$permErrorsUpload ||
$permErrorsCreate ) {
449 // merge all the problems into one list, avoiding duplicates
450 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsUpload, $permErrors ) );
451 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsCreate, $permErrors ) );
452 $resultDetails = array( 'permissionserrors' => $permErrors );
453 return self
::PROTECTED_PAGE
;
457 * In some cases we may forbid overwriting of existing files.
459 $overwrite = $this->checkOverwrite( $this->mDestName
);
460 if( $overwrite !== true ) {
461 $resultDetails = array( 'overwrite' => $overwrite );
462 return self
::OVERWRITE_EXISTING_FILE
;
465 /* Don't allow users to override the blacklist (check file extension) */
466 global $wgCheckFileExtensions, $wgStrictFileExtensions;
467 global $wgFileExtensions, $wgFileBlacklist;
468 if ($finalExt == '') {
469 return self
::FILETYPE_MISSING
;
470 } elseif ( $this->checkFileExtensionList( $ext, $wgFileBlacklist ) ||
471 ($wgCheckFileExtensions && $wgStrictFileExtensions &&
472 !$this->checkFileExtension( $finalExt, $wgFileExtensions ) ) ) {
473 $resultDetails = array( 'finalExt' => $finalExt );
474 return self
::FILETYPE_BADTYPE
;
478 * Look at the contents of the file; if we can recognize the
479 * type but it's corrupt or data of the wrong type, we should
480 * probably not accept it.
482 if( !$this->mStashed
) {
483 $this->mFileProps
= File
::getPropsFromPath( $this->mTempPath
, $finalExt );
484 $this->checkMacBinary();
485 $veri = $this->verify( $this->mTempPath
, $finalExt );
487 if( $veri !== true ) { //it's a wiki error...
488 $resultDetails = array( 'veri' => $veri );
489 return self
::VERIFICATION_ERROR
;
493 * Provide an opportunity for extensions to add further checks
496 if( !wfRunHooks( 'UploadVerification',
497 array( $this->mDestName
, $this->mTempPath
, &$error ) ) ) {
498 $resultDetails = array( 'error' => $error );
499 return self
::UPLOAD_VERIFICATION_ERROR
;
505 * Check for non-fatal conditions
507 if ( ! $this->mIgnoreWarning
) {
510 global $wgCapitalLinks;
511 if( $wgCapitalLinks ) {
512 $filtered = ucfirst( $filtered );
514 if( $basename != $filtered ) {
515 $warning .= '<li>'.wfMsgHtml( 'badfilename', htmlspecialchars( $this->mDestName
) ).'</li>';
518 global $wgCheckFileExtensions;
519 if ( $wgCheckFileExtensions ) {
520 if ( !$this->checkFileExtension( $finalExt, $wgFileExtensions ) ) {
523 wfMsgExt( 'filetype-unwanted-type',
524 array( 'parseinline' ),
525 htmlspecialchars( $finalExt ),
527 wfMsgExt( 'comma-separator', array( 'escapenoentities' ) ),
530 $wgLang->formatNum( count($wgFileExtensions) )
535 global $wgUploadSizeWarning;
536 if ( $wgUploadSizeWarning && ( $this->mFileSize
> $wgUploadSizeWarning ) ) {
537 $skin = $wgUser->getSkin();
538 $wsize = $skin->formatSize( $wgUploadSizeWarning );
539 $asize = $skin->formatSize( $this->mFileSize
);
540 $warning .= '<li>' . wfMsgHtml( 'large-file', $wsize, $asize ) . '</li>';
542 if ( $this->mFileSize
== 0 ) {
543 $warning .= '<li>'.wfMsgHtml( 'emptyfile' ).'</li>';
546 if ( !$this->mDestWarningAck
) {
547 $warning .= self
::getExistsWarning( $this->mLocalFile
);
550 $warning .= $this->getDupeWarning( $this->mTempPath
);
552 if( $warning != '' ) {
554 * Stash the file in a temporary location; the user can choose
555 * to let it through and we'll complete the upload then.
557 $resultDetails = array( 'warning' => $warning );
558 return self
::UPLOAD_WARNING
;
563 * Try actually saving the thing...
564 * It will show an error form on failure.
566 $pageText = self
::getInitialPageText( $this->mComment
, $this->mLicense
,
567 $this->mCopyrightStatus
, $this->mCopyrightSource
);
569 $status = $this->mLocalFile
->upload( $this->mTempPath
, $this->mComment
, $pageText,
570 File
::DELETE_SOURCE
, $this->mFileProps
);
571 if ( !$status->isGood() ) {
572 $resultDetails = array( 'internal' => $status->getWikiText() );
573 return self
::INTERNAL_ERROR
;
575 if ( $this->mWatchthis
) {
577 $wgUser->addWatch( $this->mLocalFile
->getTitle() );
579 // Success, redirect to description page
580 $img = null; // @todo: added to avoid passing a ref to null - should this be defined somewhere?
581 wfRunHooks( 'UploadComplete', array( &$this ) );
582 return self
::SUCCESS
;
587 * Do existence checks on a file and produce a warning
588 * This check is static and can be done pre-upload via AJAX
589 * Returns an HTML fragment consisting of one or more LI elements if there is a warning
590 * Returns an empty string if there is no warning
592 static function getExistsWarning( $file ) {
593 global $wgUser, $wgContLang;
594 // Check for uppercase extension. We allow these filenames but check if an image
595 // with lowercase extension exists already
597 $align = $wgContLang->isRtl() ?
'left' : 'right';
599 if( strpos( $file->getName(), '.' ) == false ) {
600 $partname = $file->getName();
603 $n = strrpos( $file->getName(), '.' );
604 $rawExtension = substr( $file->getName(), $n +
1 );
605 $partname = substr( $file->getName(), 0, $n );
608 $sk = $wgUser->getSkin();
610 if ( $rawExtension != $file->getExtension() ) {
611 // We're not using the normalized form of the extension.
612 // Normal form is lowercase, using most common of alternate
613 // extensions (eg 'jpg' rather than 'JPEG').
615 // Check for another file using the normalized form...
616 $nt_lc = Title
::makeTitle( NS_IMAGE
, $partname . '.' . $file->getExtension() );
617 $file_lc = wfLocalFile( $nt_lc );
622 if( $file->exists() ) {
623 $dlink = $sk->makeKnownLinkObj( $file->getTitle() );
624 if ( $file->allowInlineDisplay() ) {
625 $dlink2 = $sk->makeImageLinkObj( $file->getTitle(), wfMsgExt( 'fileexists-thumb', 'parseinline' ),
626 $file->getName(), $align, array(), false, true );
627 } elseif ( !$file->allowInlineDisplay() && $file->isSafeFile() ) {
628 $icon = $file->iconThumb();
629 $dlink2 = '<div style="float:' . $align . '" id="mw-media-icon">' .
630 $icon->toHtml( array( 'desc-link' => true ) ) . '<br />' . $dlink . '</div>';
635 $warning .= '<li>' . wfMsgExt( 'fileexists', array('parseinline','replaceafter'), $dlink ) . '</li>' . $dlink2;
637 } elseif( $file->getTitle()->getArticleID() ) {
638 $lnk = $sk->makeKnownLinkObj( $file->getTitle(), '', 'redirect=no' );
639 $warning .= '<li>' . wfMsgExt( 'filepageexists', array( 'parseinline', 'replaceafter' ), $lnk ) . '</li>';
640 } elseif ( $file_lc && $file_lc->exists() ) {
641 # Check if image with lowercase extension exists.
642 # It's not forbidden but in 99% it makes no sense to upload the same filename with uppercase extension
643 $dlink = $sk->makeKnownLinkObj( $nt_lc );
644 if ( $file_lc->allowInlineDisplay() ) {
645 $dlink2 = $sk->makeImageLinkObj( $nt_lc, wfMsgExt( 'fileexists-thumb', 'parseinline' ),
646 $nt_lc->getText(), $align, array(), false, true );
647 } elseif ( !$file_lc->allowInlineDisplay() && $file_lc->isSafeFile() ) {
648 $icon = $file_lc->iconThumb();
649 $dlink2 = '<div style="float:' . $align . '" id="mw-media-icon">' .
650 $icon->toHtml( array( 'desc-link' => true ) ) . '<br />' . $dlink . '</div>';
656 wfMsgExt( 'fileexists-extension', 'parsemag',
657 $file->getTitle()->getPrefixedText(), $dlink ) .
660 } elseif ( ( substr( $partname , 3, 3 ) == 'px-' ||
substr( $partname , 2, 3 ) == 'px-' )
661 && ereg( "[0-9]{2}" , substr( $partname , 0, 2) ) )
663 # Check for filenames like 50px- or 180px-, these are mostly thumbnails
664 $nt_thb = Title
::newFromText( substr( $partname , strpos( $partname , '-' ) +
1 ) . '.' . $rawExtension );
665 $file_thb = wfLocalFile( $nt_thb );
666 if ($file_thb->exists() ) {
667 # Check if an image without leading '180px-' (or similiar) exists
668 $dlink = $sk->makeKnownLinkObj( $nt_thb);
669 if ( $file_thb->allowInlineDisplay() ) {
670 $dlink2 = $sk->makeImageLinkObj( $nt_thb,
671 wfMsgExt( 'fileexists-thumb', 'parseinline' ),
672 $nt_thb->getText(), $align, array(), false, true );
673 } elseif ( !$file_thb->allowInlineDisplay() && $file_thb->isSafeFile() ) {
674 $icon = $file_thb->iconThumb();
675 $dlink2 = '<div style="float:' . $align . '" id="mw-media-icon">' .
676 $icon->toHtml( array( 'desc-link' => true ) ) . '<br />' .
682 $warning .= '<li>' . wfMsgExt( 'fileexists-thumbnail-yes', 'parsemag', $dlink ) .
685 # Image w/o '180px-' does not exists, but we do not like these filenames
686 $warning .= '<li>' . wfMsgExt( 'file-thumbnail-no', 'parseinline' ,
687 substr( $partname , 0, strpos( $partname , '-' ) +
1 ) ) . '</li>';
691 $filenamePrefixBlacklist = self
::getFilenamePrefixBlacklist();
693 foreach( $filenamePrefixBlacklist as $prefix ) {
694 if ( substr( $partname, 0, strlen( $prefix ) ) == $prefix ) {
695 $warning .= '<li>' . wfMsgExt( 'filename-bad-prefix', 'parseinline', $prefix ) . '</li>';
700 if ( $file->wasDeleted() && !$file->exists() ) {
701 # If the file existed before and was deleted, warn the user of this
702 # Don't bother doing so if the file exists now, however
703 $ltitle = SpecialPage
::getTitleFor( 'Log' );
704 $llink = $sk->makeKnownLinkObj( $ltitle, wfMsgHtml( 'deletionlog' ),
705 'type=delete&page=' . $file->getTitle()->getPrefixedUrl() );
706 $warning .= '<li>' . wfMsgWikiHtml( 'filewasdeleted', $llink ) . '</li>';
712 * Get a list of warnings
714 * @param string local filename, e.g. 'file exists', 'non-descriptive filename'
715 * @return array list of warning messages
717 static function ajaxGetExistsWarning( $filename ) {
718 $file = wfFindFile( $filename );
720 // Force local file so we have an object to do further checks against
721 // if there isn't an exact match...
722 $file = wfLocalFile( $filename );
726 $warning = self
::getExistsWarning( $file );
727 if ( $warning !== '' ) {
728 $s = "<ul>$warning</ul>";
735 * Render a preview of a given license for the AJAX preview on upload
737 * @param string $license
740 public static function ajaxGetLicensePreview( $license ) {
741 global $wgParser, $wgUser;
742 $text = '{{' . $license . '}}';
743 $title = Title
::makeTitle( NS_IMAGE
, 'Sample.jpg' );
744 $options = ParserOptions
::newFromUser( $wgUser );
746 // Expand subst: first, then live templates...
747 $text = $wgParser->preSaveTransform( $text, $title, $wgUser, $options );
748 $output = $wgParser->parse( $text, $title, $options );
750 return $output->getText();
754 * Check for duplicate files and throw up a warning before the upload
757 function getDupeWarning( $tempfile ) {
758 $hash = File
::sha1Base36( $tempfile );
759 $dupes = RepoGroup
::singleton()->findBySha1( $hash );
763 foreach( $dupes as $file ) {
764 $title = $file->getTitle();
765 $msg .= $title->getPrefixedText() .
766 "|" . $title->getText() . "\n";
768 $msg .= "</gallery>";
770 wfMsgExt( "file-exists-duplicate", array( "parse" ), count( $dupes ) ) .
771 $wgOut->parse( $msg ) .
779 * Get a list of blacklisted filename prefixes from [[MediaWiki:filename-prefix-blacklist]]
781 * @return array list of prefixes
783 public static function getFilenamePrefixBlacklist() {
784 $blacklist = array();
785 $message = wfMsgForContent( 'filename-prefix-blacklist' );
786 if( $message && !( wfEmptyMsg( 'filename-prefix-blacklist', $message ) ||
$message == '-' ) ) {
787 $lines = explode( "\n", $message );
788 foreach( $lines as $line ) {
789 // Remove comment lines
790 $comment = substr( trim( $line ), 0, 1 );
791 if ( $comment == '#' ||
$comment == '' ) {
794 // Remove additional comments after a prefix
795 $comment = strpos( $line, '#' );
796 if ( $comment > 0 ) {
797 $line = substr( $line, 0, $comment-1 );
799 $blacklist[] = trim( $line );
806 * Stash a file in a temporary directory for later processing
807 * after the user has confirmed it.
809 * If the user doesn't explicitly cancel or accept, these files
810 * can accumulate in the temp directory.
812 * @param string $saveName - the destination filename
813 * @param string $tempName - the source temporary file to save
814 * @return string - full path the stashed file, or false on failure
817 function saveTempUploadedFile( $saveName, $tempName ) {
819 $repo = RepoGroup
::singleton()->getLocalRepo();
820 $status = $repo->storeTemp( $saveName, $tempName );
821 if ( !$status->isGood() ) {
822 $this->showError( $status->getWikiText() );
825 return $status->value
;
830 * Stash a file in a temporary directory for later processing,
831 * and save the necessary descriptive info into the session.
832 * Returns a key value which will be passed through a form
833 * to pick up the path info on a later invocation.
838 function stashSession() {
839 $stash = $this->saveTempUploadedFile( $this->mDestName
, $this->mTempPath
);
842 # Couldn't save the file.
846 $key = mt_rand( 0, 0x7fffffff );
847 $_SESSION['wsUploadData'][$key] = array(
848 'mTempPath' => $stash,
849 'mFileSize' => $this->mFileSize
,
850 'mSrcName' => $this->mSrcName
,
851 'mFileProps' => $this->mFileProps
,
852 'version' => self
::SESSION_VERSION
,
858 * Remove a temporarily kept file stashed by saveTempUploadedFile().
862 function unsaveUploadedFile() {
864 $repo = RepoGroup
::singleton()->getLocalRepo();
865 $success = $repo->freeTemp( $this->mTempPath
);
867 $wgOut->showFileDeleteError( $this->mTempPath
);
874 /* -------------------------------------------------------------- */
877 * @param string $error as HTML
880 function uploadError( $error ) {
882 $wgOut->addHTML( '<h2>' . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
883 $wgOut->addHTML( '<span class="error">' . $error . '</span>' );
887 * There's something wrong with this file, not enough to reject it
888 * totally but we require manual intervention to save it for real.
889 * Stash it away, then present a form asking to confirm or cancel.
891 * @param string $warning as HTML
894 function uploadWarning( $warning ) {
896 global $wgUseCopyrightUpload;
898 $this->mSessionKey
= $this->stashSession();
899 if( !$this->mSessionKey
) {
900 # Couldn't save file; an error has been displayed so let's go.
904 $wgOut->addHTML( '<h2>' . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
905 $wgOut->addHTML( '<ul class="warning">' . $warning . "</ul>\n" );
907 $titleObj = SpecialPage
::getTitleFor( 'Upload' );
909 if ( $wgUseCopyrightUpload ) {
910 $copyright = Xml
::hidden( 'wpUploadCopyStatus', $this->mCopyrightStatus
) . "\n" .
911 Xml
::hidden( 'wpUploadSource', $this->mCopyrightSource
) . "\n";
917 Xml
::openElement( 'form', array( 'method' => 'post', 'action' => $titleObj->getLocalURL( 'action=submit' ),
918 'enctype' => 'multipart/form-data', 'id' => 'uploadwarning' ) ) . "\n" .
919 Xml
::hidden( 'wpIgnoreWarning', '1' ) . "\n" .
920 Xml
::hidden( 'wpSessionKey', $this->mSessionKey
) . "\n" .
921 Xml
::hidden( 'wpUploadDescription', $this->mComment
) . "\n" .
922 Xml
::hidden( 'wpLicense', $this->mLicense
) . "\n" .
923 Xml
::hidden( 'wpDestFile', $this->mDesiredDestName
) . "\n" .
924 Xml
::hidden( 'wpWatchthis', $this->mWatchthis
) . "\n" .
925 "{$copyright}<br />" .
926 Xml
::submitButton( wfMsg( 'ignorewarning' ), array ( 'name' => 'wpUpload', 'id' => 'wpUpload', 'checked' => 'checked' ) ) . ' ' .
927 Xml
::submitButton( wfMsg( 'reuploaddesc' ), array ( 'name' => 'wpReUpload', 'id' => 'wpReUpload' ) ) .
928 Xml
::closeElement( 'form' ) . "\n"
933 * Displays the main upload form, optionally with a highlighted
934 * error message up at the top.
936 * @param string $msg as HTML
939 function mainUploadForm( $msg='' ) {
940 global $wgOut, $wgUser, $wgLang, $wgMaxUploadSize;
941 global $wgUseCopyrightUpload, $wgUseAjax, $wgAjaxUploadDestCheck, $wgAjaxLicensePreview;
942 global $wgRequest, $wgAllowCopyUploads;
943 global $wgStylePath, $wgStyleVersion;
945 $useAjaxDestCheck = $wgUseAjax && $wgAjaxUploadDestCheck;
946 $useAjaxLicensePreview = $wgUseAjax && $wgAjaxLicensePreview;
948 $adc = wfBoolToStr( $useAjaxDestCheck );
949 $alp = wfBoolToStr( $useAjaxLicensePreview );
950 $autofill = wfBoolToStr( $this->mDesiredDestName
== '' );
952 $wgOut->addScript( "<script type=\"text/javascript\">
953 wgAjaxUploadDestCheck = {$adc};
954 wgAjaxLicensePreview = {$alp};
955 wgUploadAutoFill = {$autofill};
957 $wgOut->addScriptFile( 'upload.js' );
958 $wgOut->addScriptFile( 'edit.js' ); // For <charinsert> support
960 if( !wfRunHooks( 'UploadForm:initial', array( &$this ) ) )
962 wfDebug( "Hook 'UploadForm:initial' broke output of the upload form" );
966 if( $this->mDesiredDestName
) {
967 $title = Title
::makeTitleSafe( NS_IMAGE
, $this->mDesiredDestName
);
968 // Show a subtitle link to deleted revisions (to sysops et al only)
969 if( $title instanceof Title
&& ( $count = $title->isDeleted() ) > 0 && $wgUser->isAllowed( 'deletedhistory' ) ) {
971 $wgUser->isAllowed( 'delete' ) ?
'thisisdeleted' : 'viewdeleted',
972 array( 'parse', 'replaceafter' ),
973 $wgUser->getSkin()->makeKnownLinkObj(
974 SpecialPage
::getTitleFor( 'Undelete', $title->getPrefixedText() ),
975 wfMsgExt( 'restorelink', array( 'parsemag', 'escape' ), $count )
978 $wgOut->addHtml( "<div id=\"contentSub2\">{$link}</div>" );
981 // Show the relevant lines from deletion log (for still deleted files only)
982 if( $title instanceof Title
&& $title->isDeleted() > 0 && !$title->exists() ) {
983 $this->showDeletionLog( $wgOut, $title->getPrefixedText() );
987 $cols = intval($wgUser->getOption( 'cols' ));
989 if( $wgUser->getOption( 'editwidth' ) ) {
990 $width = " style=\"width:100%\"";
996 $sub = wfMsgHtml( 'uploaderror' );
997 $wgOut->addHTML( "<h2>{$sub}</h2>\n" .
998 "<span class='error'>{$msg}</span>\n" );
1000 $wgOut->addHTML( '<div id="uploadtext">' );
1001 $wgOut->addWikiMsg( 'uploadtext', $this->mDesiredDestName
);
1002 $wgOut->addHTML( "</div>\n" );
1004 # Print a list of allowed file extensions, if so configured. We ignore
1005 # MIME type here, it's incomprehensible to most people and too long.
1006 global $wgCheckFileExtensions, $wgStrictFileExtensions,
1007 $wgFileExtensions, $wgFileBlacklist;
1009 $allowedExtensions = '';
1010 if( $wgCheckFileExtensions ) {
1011 $delim = wfMsgExt( 'comma-separator', array( 'escapenoentities' ) );
1012 if( $wgStrictFileExtensions ) {
1013 # Everything not permitted is banned
1015 '<div id="mw-upload-permitted">' .
1016 wfMsgWikiHtml( 'upload-permitted', implode( $wgFileExtensions, $delim ) ) .
1019 # We have to list both preferred and prohibited
1021 '<div id="mw-upload-preferred">' .
1022 wfMsgWikiHtml( 'upload-preferred', implode( $wgFileExtensions, $delim ) ) .
1024 '<div id="mw-upload-prohibited">' .
1025 wfMsgWikiHtml( 'upload-prohibited', implode( $wgFileBlacklist, $delim ) ) .
1029 # Everything is permitted.
1030 $extensionsList = '';
1033 # Get the maximum file size from php.ini as $wgMaxUploadSize works for uploads from URL via CURL only
1034 # See http://www.php.net/manual/en/ini.core.php#ini.upload-max-filesize for possible values of upload_max_filesize
1035 $val = trim( ini_get( 'upload_max_filesize' ) );
1036 $last = strtoupper( ( substr( $val, -1 ) ) );
1039 $val2 = substr( $val, 0, -1 ) * 1024 * 1024 * 1024;
1042 $val2 = substr( $val, 0, -1 ) * 1024 * 1024;
1045 $val2 = substr( $val, 0, -1 ) * 1024;
1050 $val2 = $wgAllowCopyUploads ?
min( $wgMaxUploadSize, $val2 ) : $val2;
1051 $maxUploadSize = '<div id="mw-upload-maxfilesize">' .
1052 wfMsgExt( 'upload-maxfilesize', array( 'parseinline', 'escapenoentities' ),
1053 $wgLang->formatSize( $val2 ) ) .
1056 $sourcefilename = wfMsgExt( 'sourcefilename', array( 'parseinline', 'escapenoentities' ) );
1057 $destfilename = wfMsgExt( 'destfilename', array( 'parseinline', 'escapenoentities' ) );
1059 $summary = wfMsgExt( 'fileuploadsummary', 'parseinline' );
1061 $licenses = new Licenses();
1062 $license = wfMsgExt( 'license', array( 'parseinline' ) );
1063 $nolicense = wfMsgHtml( 'nolicense' );
1064 $licenseshtml = $licenses->getHtml();
1066 $ulb = wfMsgHtml( 'uploadbtn' );
1069 $titleObj = SpecialPage
::getTitleFor( 'Upload' );
1071 $encDestName = htmlspecialchars( $this->mDesiredDestName
);
1073 $watchChecked = $this->watchCheck()
1074 ?
'checked="checked"'
1076 $warningChecked = $this->mIgnoreWarning ?
'checked' : '';
1078 // Prepare form for upload or upload/copy
1079 if( $wgAllowCopyUploads && $wgUser->isAllowed( 'upload_by_url' ) ) {
1081 "<input type='radio' id='wpSourceTypeFile' name='wpSourceType' value='file' " .
1082 "onchange='toggle_element_activation(\"wpUploadFileURL\",\"wpUploadFile\")' checked='checked' />" .
1083 "<input tabindex='1' type='file' name='wpUploadFile' id='wpUploadFile' " .
1085 "toggle_element_activation(\"wpUploadFileURL\",\"wpUploadFile\");" .
1086 "toggle_element_check(\"wpSourceTypeFile\",\"wpSourceTypeURL\")' " .
1087 "onchange='fillDestFilename(\"wpUploadFile\")' size='60' />" .
1088 wfMsgHTML( 'upload_source_file' ) . "<br/>" .
1089 "<input type='radio' id='wpSourceTypeURL' name='wpSourceType' value='web' " .
1090 "onchange='toggle_element_activation(\"wpUploadFile\",\"wpUploadFileURL\")' />" .
1091 "<input tabindex='1' type='text' name='wpUploadFileURL' id='wpUploadFileURL' " .
1093 "toggle_element_activation(\"wpUploadFile\",\"wpUploadFileURL\");" .
1094 "toggle_element_check(\"wpSourceTypeURL\",\"wpSourceTypeFile\")' " .
1095 "onchange='fillDestFilename(\"wpUploadFileURL\")' size='60' disabled='disabled' />" .
1096 wfMsgHtml( 'upload_source_url' ) ;
1099 "<input tabindex='1' type='file' name='wpUploadFile' id='wpUploadFile' " .
1100 ($this->mDesiredDestName?
"":"onchange='fillDestFilename(\"wpUploadFile\")' ") .
1102 "<input type='hidden' name='wpSourceType' value='file' />" ;
1104 if ( $useAjaxDestCheck ) {
1105 $warningRow = "<tr><td colspan='2' id='wpDestFile-warning'> </td></tr>";
1106 $destOnkeyup = 'onkeyup="wgUploadWarningObj.keypress();"';
1112 $encComment = htmlspecialchars( $this->mComment
);
1115 Xml
::openElement( 'form', array( 'method' => 'post', 'action' => $titleObj->getLocalURL(),
1116 'enctype' => 'multipart/form-data', 'id' => 'mw-upload-form' ) ) .
1117 Xml
::openElement( 'fieldset' ) .
1118 Xml
::element( 'legend', null, wfMsg( 'upload' ) ) .
1119 Xml
::openElement( 'table', array( 'border' => '0', 'id' => 'mw-upload-table' ) ) .
1121 {$this->uploadFormTextTop}
1122 <td class='mw-label'>
1123 <label for='wpUploadFile'>{$sourcefilename}</label>
1125 <td class='mw-input'>
1137 <td class='mw-label'>
1138 <label for='wpDestFile'>{$destfilename}</label>
1140 <td class='mw-input'>
1141 <input tabindex='2' type='text' name='wpDestFile' id='wpDestFile' size='60'
1142 value=\"{$encDestName}\" onchange='toggleFilenameFiller()' $destOnkeyup />
1146 <td class='mw-label'>
1147 <label for='wpUploadDescription'>{$summary}</label>
1149 <td class='mw-input'>
1150 <textarea tabindex='3' name='wpUploadDescription' id='wpUploadDescription' rows='6'
1151 cols='{$cols}'{$width}>$encComment</textarea>
1152 {$this->uploadFormTextAfterSummary}
1158 if ( $licenseshtml != '' ) {
1159 global $wgStylePath;
1161 <td class='mw-label'>
1162 <label for='wpLicense'>$license</label>
1164 <td class='mw-input'>
1165 <select name='wpLicense' id='wpLicense' tabindex='4'
1166 onchange='licenseSelectorCheck()'>
1167 <option value=''>$nolicense</option>
1174 if( $useAjaxLicensePreview ) {
1177 <td id=\"mw-license-preview\"></td>
1184 if ( $wgUseCopyrightUpload ) {
1185 $filestatus = wfMsgExt( 'filestatus', 'escapenoentities' );
1186 $copystatus = htmlspecialchars( $this->mCopyrightStatus
);
1187 $filesource = wfMsgExt( 'filesource', 'escapenoentities' );
1188 $uploadsource = htmlspecialchars( $this->mCopyrightSource
);
1191 <td class='mw-label' style='white-space: nowrap;'>
1192 <label for='wpUploadCopyStatus'>$filestatus</label></td>
1193 <td class='mw-input'>
1194 <input tabindex='5' type='text' name='wpUploadCopyStatus' id='wpUploadCopyStatus'
1195 value=\"$copystatus\" size='60' />
1199 <td class='mw-label'>
1200 <label for='wpUploadCopyStatus'>$filesource</label>
1202 <td class='mw-input'>
1203 <input tabindex='6' type='text' name='wpUploadSource' id='wpUploadCopyStatus'
1204 value=\"$uploadsource\" size='60' />
1214 <input tabindex='7' type='checkbox' name='wpWatchthis' id='wpWatchthis' $watchChecked value='true' />
1215 <label for='wpWatchthis'>" . wfMsgHtml( 'watchthisupload' ) . "</label>
1216 <input tabindex='8' type='checkbox' name='wpIgnoreWarning' id='wpIgnoreWarning' value='true' $warningChecked/>
1217 <label for='wpIgnoreWarning'>" . wfMsgHtml( 'ignorewarnings' ) . "</label>
1223 <td class='mw-input'>
1224 <input tabindex='9' type='submit' name='wpUpload' value=\"{$ulb}\"" . $wgUser->getSkin()->tooltipAndAccesskey( 'upload' ) . " />
1229 <td class='mw-input'>"
1231 $wgOut->addWikiText( wfMsgForContent( 'edittools' ) );
1235 Xml
::closeElement( 'table' ) .
1236 Xml
::hidden( 'wpDestFileWarningAck', '', array( 'id' => 'wpDestFileWarningAck' ) ) .
1237 Xml
::closeElement( 'fieldset' ) .
1238 Xml
::closeElement( 'form' )
1240 $uploadfooter = wfMsgNoTrans( 'uploadfooter' );
1241 if( $uploadfooter != '-' && !wfEmptyMsg( 'uploadfooter', $uploadfooter ) ){
1242 $wgOut->addWikiText( '<div id="mw-upload-footer-message">' . $uploadfooter . '</div>' );
1246 /* -------------------------------------------------------------- */
1249 * See if we should check the 'watch this page' checkbox on the form
1250 * based on the user's preferences and whether we're being asked
1251 * to create a new file or update an existing one.
1253 * In the case where 'watch edits' is off but 'watch creations' is on,
1254 * we'll leave the box unchecked.
1256 * Note that the page target can be changed *on the form*, so our check
1257 * state can get out of sync.
1259 function watchCheck() {
1261 if( $wgUser->getOption( 'watchdefault' ) ) {
1266 $local = wfLocalFile( $this->mDesiredDestName
);
1267 if( $local && $local->exists() ) {
1268 // We're uploading a new version of an existing file.
1269 // No creation, so don't watch it if we're not already.
1270 return $local->getTitle()->userIsWatching();
1272 // New page should get watched if that's our option.
1273 return $wgUser->getOption( 'watchcreations' );
1278 * Split a file into a base name and all dot-delimited 'extensions'
1279 * on the end. Some web server configurations will fall back to
1280 * earlier pseudo-'extensions' to determine type and execute
1281 * scripts, so the blacklist needs to check them all.
1285 function splitExtensions( $filename ) {
1286 $bits = explode( '.', $filename );
1287 $basename = array_shift( $bits );
1288 return array( $basename, $bits );
1292 * Perform case-insensitive match against a list of file extensions.
1293 * Returns true if the extension is in the list.
1295 * @param string $ext
1296 * @param array $list
1299 function checkFileExtension( $ext, $list ) {
1300 return in_array( strtolower( $ext ), $list );
1304 * Perform case-insensitive match against a list of file extensions.
1305 * Returns true if any of the extensions are in the list.
1308 * @param array $list
1311 function checkFileExtensionList( $ext, $list ) {
1312 foreach( $ext as $e ) {
1313 if( in_array( strtolower( $e ), $list ) ) {
1321 * Verifies that it's ok to include the uploaded file
1323 * @param string $tmpfile the full path of the temporary file to verify
1324 * @param string $extension The filename extension that the file is to be served with
1325 * @return mixed true of the file is verified, a WikiError object otherwise.
1327 function verify( $tmpfile, $extension ) {
1328 #magically determine mime type
1329 $magic = MimeMagic
::singleton();
1330 $mime = $magic->guessMimeType($tmpfile,false);
1332 #check mime type, if desired
1333 global $wgVerifyMimeType;
1334 if ($wgVerifyMimeType) {
1336 wfDebug ( "\n\nmime: <$mime> extension: <$extension>\n\n");
1337 #check mime type against file extension
1338 if( !self
::verifyExtension( $mime, $extension ) ) {
1339 return new WikiErrorMsg( 'uploadcorrupt' );
1342 #check mime type blacklist
1343 global $wgMimeTypeBlacklist;
1344 if( isset($wgMimeTypeBlacklist) && !is_null($wgMimeTypeBlacklist)
1345 && $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
1346 return new WikiErrorMsg( 'filetype-badmime', htmlspecialchars( $mime ) );
1350 #check for htmlish code and javascript
1351 if( $this->detectScript ( $tmpfile, $mime, $extension ) ) {
1352 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.
1467 '<html', #also in safari
1470 '<script', #also in safari
1473 if( ! $wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
1477 foreach( $tags as $tag ) {
1478 if( false !== strpos( $chunk, $tag ) ) {
1484 * look for javascript
1487 #resolve entity-refs to look at attributes. may be harsh on big files... cache result?
1488 $chunk = Sanitizer
::decodeCharReferences( $chunk );
1490 #look for script-types
1491 if (preg_match('!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim',$chunk)) return true;
1493 #look for html-style script-urls
1494 if (preg_match('!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim',$chunk)) return true;
1496 #look for css-style script-urls
1497 if (preg_match('!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim',$chunk)) return true;
1499 wfDebug("SpecialUpload::detectScript: no scripts found\n");
1504 * Generic wrapper function for a virus scanner program.
1505 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
1506 * $wgAntivirusRequired may be used to deny upload if the scan fails.
1508 * @param string $file Pathname to the temporary upload file
1509 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
1510 * or a string containing feedback from the virus scanner if a virus was found.
1511 * If textual feedback is missing but a virus was found, this function returns true.
1513 function detectVirus($file) {
1514 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
1516 if ( !$wgAntivirus ) {
1517 wfDebug( __METHOD__
.": virus scanner disabled\n");
1521 if ( !$wgAntivirusSetup[$wgAntivirus] ) {
1522 wfDebug( __METHOD__
.": unknown virus scanner: $wgAntivirus\n" );
1523 $wgOut->wrapWikiMsg( '<div class="error">$1</div>', array( 'virus-badscanner', $wgAntivirus ) );
1524 return wfMsg('virus-unknownscanner') . " $wgAntivirus";
1527 # look up scanner configuration
1528 $command = $wgAntivirusSetup[$wgAntivirus]["command"];
1529 $exitCodeMap = $wgAntivirusSetup[$wgAntivirus]["codemap"];
1530 $msgPattern = isset( $wgAntivirusSetup[$wgAntivirus]["messagepattern"] ) ?
1531 $wgAntivirusSetup[$wgAntivirus]["messagepattern"] : null;
1533 if ( strpos( $command,"%f" ) === false ) {
1534 # simple pattern: append file to scan
1535 $command .= " " . wfEscapeShellArg( $file );
1537 # complex pattern: replace "%f" with file to scan
1538 $command = str_replace( "%f", wfEscapeShellArg( $file ), $command );
1541 wfDebug( __METHOD__
.": running virus scan: $command \n" );
1543 # execute virus scanner
1546 #NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
1547 # that does not seem to be worth the pain.
1548 # Ask me (Duesentrieb) about it if it's ever needed.
1550 if ( wfIsWindows() ) {
1551 exec( "$command", $output, $exitCode );
1553 exec( "$command 2>&1", $output, $exitCode );
1556 # map exit code to AV_xxx constants.
1557 $mappedCode = $exitCode;
1558 if ( $exitCodeMap ) {
1559 if ( isset( $exitCodeMap[$exitCode] ) ) {
1560 $mappedCode = $exitCodeMap[$exitCode];
1561 } elseif ( isset( $exitCodeMap["*"] ) ) {
1562 $mappedCode = $exitCodeMap["*"];
1566 if ( $mappedCode === AV_SCAN_FAILED
) {
1567 # scan failed (code was mapped to false by $exitCodeMap)
1568 wfDebug( __METHOD__
.": failed to scan $file (code $exitCode).\n" );
1570 if ( $wgAntivirusRequired ) {
1571 return wfMsg('virus-scanfailed', array( $exitCode ) );
1575 } else if ( $mappedCode === AV_SCAN_ABORTED
) {
1576 # scan failed because filetype is unknown (probably imune)
1577 wfDebug( __METHOD__
.": unsupported file type $file (code $exitCode).\n" );
1579 } else if ( $mappedCode === AV_NO_VIRUS
) {
1581 wfDebug( __METHOD__
.": file passed virus scan.\n" );
1584 $output = join( "\n", $output );
1585 $output = trim( $output );
1588 $output = true; #if there's no output, return true
1589 } elseif ( $msgPattern ) {
1591 if ( preg_match( $msgPattern, $output, $groups ) ) {
1593 $output = $groups[1];
1598 wfDebug( __METHOD__
.": FOUND VIRUS! scanner feedback: $output" );
1604 * Check if the temporary file is MacBinary-encoded, as some uploads
1605 * from Internet Explorer on Mac OS Classic and Mac OS X will be.
1606 * If so, the data fork will be extracted to a second temporary file,
1607 * which will then be checked for validity and either kept or discarded.
1611 function checkMacBinary() {
1612 $macbin = new MacBinary( $this->mTempPath
);
1613 if( $macbin->isValid() ) {
1614 $dataFile = tempnam( wfTempDir(), "WikiMacBinary" );
1615 $dataHandle = fopen( $dataFile, 'wb' );
1617 wfDebug( "SpecialUpload::checkMacBinary: Extracting MacBinary data fork to $dataFile\n" );
1618 $macbin->extractData( $dataHandle );
1620 $this->mTempPath
= $dataFile;
1621 $this->mFileSize
= $macbin->dataForkLength();
1623 // We'll have to manually remove the new file if it's not kept.
1624 $this->mRemoveTempFile
= true;
1630 * If we've modified the upload file we need to manually remove it
1631 * on exit to clean up.
1634 function cleanupTempFile() {
1635 if ( $this->mRemoveTempFile
&& file_exists( $this->mTempPath
) ) {
1636 wfDebug( "SpecialUpload::cleanupTempFile: Removing temporary file {$this->mTempPath}\n" );
1637 unlink( $this->mTempPath
);
1642 * Check if there's an overwrite conflict and, if so, if restrictions
1643 * forbid this user from performing the upload.
1645 * @return mixed true on success, WikiError on failure
1648 function checkOverwrite( $name ) {
1649 $img = wfFindFile( $name );
1653 global $wgUser, $wgOut;
1654 if( $img->isLocal() ) {
1655 if( !self
::userCanReUpload( $wgUser, $img->name
) ) {
1656 $error = 'fileexists-forbidden';
1659 if( !$wgUser->isAllowed( 'reupload' ) ||
1660 !$wgUser->isAllowed( 'reupload-shared' ) ) {
1661 $error = "fileexists-shared-forbidden";
1667 $errorText = wfMsg( $error, wfEscapeWikiText( $img->getName() ) );
1671 // Rockin', go ahead and upload
1676 * Check if a user is the last uploader
1679 * @param string $img, image name
1682 public static function userCanReUpload( User
$user, $img ) {
1683 if( $user->isAllowed( 'reupload' ) )
1684 return true; // non-conditional
1685 if( !$user->isAllowed( 'reupload-own' ) )
1688 $dbr = wfGetDB( DB_SLAVE
);
1689 $row = $dbr->selectRow('image',
1690 /* SELECT */ 'img_user',
1691 /* WHERE */ array( 'img_name' => $img )
1696 return $user->getId() == $row->img_user
;
1700 * Display an error with a wikitext description
1702 function showError( $description ) {
1704 $wgOut->setPageTitle( wfMsg( "internalerror" ) );
1705 $wgOut->setRobotpolicy( "noindex,nofollow" );
1706 $wgOut->setArticleRelated( false );
1707 $wgOut->enableClientCache( false );
1708 $wgOut->addWikiText( $description );
1712 * Get the initial image page text based on a comment and optional file status information
1714 static function getInitialPageText( $comment, $license, $copyStatus, $source ) {
1715 global $wgUseCopyrightUpload;
1716 if ( $wgUseCopyrightUpload ) {
1717 if ( $license != '' ) {
1718 $licensetxt = '== ' . wfMsgForContent( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1720 $pageText = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $comment . "\n" .
1721 '== ' . wfMsgForContent ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
1723 '== ' . wfMsgForContent ( 'filesource' ) . " ==\n" . $source ;
1725 if ( $license != '' ) {
1726 $filedesc = $comment == '' ?
'' : '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $comment . "\n";
1727 $pageText = $filedesc .
1728 '== ' . wfMsgForContent ( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1730 $pageText = $comment;
1737 * If there are rows in the deletion log for this file, show them,
1738 * along with a nice little note for the user
1740 * @param OutputPage $out
1741 * @param string filename
1743 private function showDeletionLog( $out, $filename ) {
1745 $loglist = new LogEventsList( $wgUser->getSkin(), $out );
1746 $pager = new LogPager( $loglist, 'delete', false, $filename );
1747 if( $pager->getNumRows() > 0 ) {
1748 $out->addHtml( '<div id="mw-upload-deleted-warn">' );
1749 $out->addWikiMsg( 'upload-wasdeleted' );
1751 $loglist->beginLogEventsList() .
1753 $loglist->endLogEventsList()
1755 $out->addHtml( '</div>' );