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
;
395 * Chop off any directories in the given filename. Then
396 * filter out illegal characters, and try to make a legible name
397 * out of it. We'll strip some silently that Title would die on.
399 if( $this->mDesiredDestName
) {
400 $basename = $this->mDesiredDestName
;
402 $basename = $this->mSrcName
;
404 $filtered = wfStripIllegalFilenameChars( $basename );
407 * We'll want to blacklist against *any* 'extension', and use
408 * only the final one for the whitelist.
410 list( $partname, $ext ) = $this->splitExtensions( $filtered );
412 if( count( $ext ) ) {
413 $finalExt = $ext[count( $ext ) - 1];
418 # If there was more than one "extension", reassemble the base
419 # filename to prevent bogus complaints about length
420 if( count( $ext ) > 1 ) {
421 for( $i = 0; $i < count( $ext ) - 1; $i++
)
422 $partname .= '.' . $ext[$i];
425 if( strlen( $partname ) < 1 ) {
426 return self
::MIN_LENGHT_PARTNAME
;
429 $nt = Title
::makeTitleSafe( NS_IMAGE
, $filtered );
430 if( is_null( $nt ) ) {
431 $resultDetails = array( 'filtered' => $filtered );
432 return self
::ILLEGAL_FILENAME
;
434 $this->mLocalFile
= wfLocalFile( $nt );
435 $this->mDestName
= $this->mLocalFile
->getName();
438 * If the image is protected, non-sysop users won't be able
439 * to modify it by uploading a new revision.
441 $permErrors = $nt->getUserPermissionsErrors( 'edit', $wgUser );
442 $permErrorsUpload = $nt->getUserPermissionsErrors( 'upload', $wgUser );
443 $permErrorsCreate = ( $nt->exists() ?
array() : $nt->getUserPermissionsErrors( 'create', $wgUser ) );
445 if( $permErrors ||
$permErrorsUpload ||
$permErrorsCreate ) {
446 // merge all the problems into one list, avoiding duplicates
447 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsUpload, $permErrors ) );
448 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsCreate, $permErrors ) );
449 $resultDetails = array( 'permissionserrors' => $permErrors );
450 return self
::PROTECTED_PAGE
;
454 * In some cases we may forbid overwriting of existing files.
456 $overwrite = $this->checkOverwrite( $this->mDestName
);
457 if( $overwrite !== true ) {
458 $resultDetails = array( 'overwrite' => $overwrite );
459 return self
::OVERWRITE_EXISTING_FILE
;
462 /* Don't allow users to override the blacklist (check file extension) */
463 global $wgCheckFileExtensions, $wgStrictFileExtensions;
464 global $wgFileExtensions, $wgFileBlacklist;
465 if ($finalExt == '') {
466 return self
::FILETYPE_MISSING
;
467 } elseif ( $this->checkFileExtensionList( $ext, $wgFileBlacklist ) ||
468 ($wgCheckFileExtensions && $wgStrictFileExtensions &&
469 !$this->checkFileExtension( $finalExt, $wgFileExtensions ) ) ) {
470 $resultDetails = array( 'finalExt' => $finalExt );
471 return self
::FILETYPE_BADTYPE
;
475 * Look at the contents of the file; if we can recognize the
476 * type but it's corrupt or data of the wrong type, we should
477 * probably not accept it.
479 if( !$this->mStashed
) {
480 $this->mFileProps
= File
::getPropsFromPath( $this->mTempPath
, $finalExt );
481 $this->checkMacBinary();
482 $veri = $this->verify( $this->mTempPath
, $finalExt );
484 if( $veri !== true ) { //it's a wiki error...
485 $resultDetails = array( 'veri' => $veri );
486 return self
::VERIFICATION_ERROR
;
490 * Provide an opportunity for extensions to add further checks
493 if( !wfRunHooks( 'UploadVerification',
494 array( $this->mDestName
, $this->mTempPath
, &$error ) ) ) {
495 $resultDetails = array( 'error' => $error );
496 return self
::UPLOAD_VERIFICATION_ERROR
;
502 * Check for non-fatal conditions
504 if ( ! $this->mIgnoreWarning
) {
507 global $wgCapitalLinks;
508 if( $wgCapitalLinks ) {
509 $filtered = ucfirst( $filtered );
511 if( $basename != $filtered ) {
512 $warning .= '<li>'.wfMsgHtml( 'badfilename', htmlspecialchars( $this->mDestName
) ).'</li>';
515 global $wgCheckFileExtensions;
516 if ( $wgCheckFileExtensions ) {
517 if ( !$this->checkFileExtension( $finalExt, $wgFileExtensions ) ) {
520 wfMsgExt( 'filetype-unwanted-type',
521 array( 'parseinline' ),
522 htmlspecialchars( $finalExt ),
524 wfMsgExt( 'comma-separator', array( 'escapenoentities' ) ),
527 $wgLang->formatNum( count($wgFileExtensions) )
532 global $wgUploadSizeWarning;
533 if ( $wgUploadSizeWarning && ( $this->mFileSize
> $wgUploadSizeWarning ) ) {
534 $skin = $wgUser->getSkin();
535 $wsize = $skin->formatSize( $wgUploadSizeWarning );
536 $asize = $skin->formatSize( $this->mFileSize
);
537 $warning .= '<li>' . wfMsgHtml( 'large-file', $wsize, $asize ) . '</li>';
539 if ( $this->mFileSize
== 0 ) {
540 $warning .= '<li>'.wfMsgHtml( 'emptyfile' ).'</li>';
543 if ( !$this->mDestWarningAck
) {
544 $warning .= self
::getExistsWarning( $this->mLocalFile
);
547 $warning .= $this->getDupeWarning( $this->mTempPath
);
549 if( $warning != '' ) {
551 * Stash the file in a temporary location; the user can choose
552 * to let it through and we'll complete the upload then.
554 $resultDetails = array( 'warning' => $warning );
555 return self
::UPLOAD_WARNING
;
560 * Try actually saving the thing...
561 * It will show an error form on failure.
563 $pageText = self
::getInitialPageText( $this->mComment
, $this->mLicense
,
564 $this->mCopyrightStatus
, $this->mCopyrightSource
);
566 $status = $this->mLocalFile
->upload( $this->mTempPath
, $this->mComment
, $pageText,
567 File
::DELETE_SOURCE
, $this->mFileProps
);
568 if ( !$status->isGood() ) {
569 $resultDetails = array( 'internal' => $status->getWikiText() );
570 return self
::INTERNAL_ERROR
;
572 if ( $this->mWatchthis
) {
574 $wgUser->addWatch( $this->mLocalFile
->getTitle() );
576 // Success, redirect to description page
577 $img = null; // @todo: added to avoid passing a ref to null - should this be defined somewhere?
578 wfRunHooks( 'UploadComplete', array( &$this ) );
579 return self
::SUCCESS
;
584 * Do existence checks on a file and produce a warning
585 * This check is static and can be done pre-upload via AJAX
586 * Returns an HTML fragment consisting of one or more LI elements if there is a warning
587 * Returns an empty string if there is no warning
589 static function getExistsWarning( $file ) {
590 global $wgUser, $wgContLang;
591 // Check for uppercase extension. We allow these filenames but check if an image
592 // with lowercase extension exists already
594 $align = $wgContLang->isRtl() ?
'left' : 'right';
596 if( strpos( $file->getName(), '.' ) == false ) {
597 $partname = $file->getName();
600 $n = strrpos( $file->getName(), '.' );
601 $rawExtension = substr( $file->getName(), $n +
1 );
602 $partname = substr( $file->getName(), 0, $n );
605 $sk = $wgUser->getSkin();
607 if ( $rawExtension != $file->getExtension() ) {
608 // We're not using the normalized form of the extension.
609 // Normal form is lowercase, using most common of alternate
610 // extensions (eg 'jpg' rather than 'JPEG').
612 // Check for another file using the normalized form...
613 $nt_lc = Title
::makeTitle( NS_IMAGE
, $partname . '.' . $file->getExtension() );
614 $file_lc = wfLocalFile( $nt_lc );
619 if( $file->exists() ) {
620 $dlink = $sk->makeKnownLinkObj( $file->getTitle() );
621 if ( $file->allowInlineDisplay() ) {
622 $dlink2 = $sk->makeImageLinkObj( $file->getTitle(), wfMsgExt( 'fileexists-thumb', 'parseinline' ),
623 $file->getName(), $align, array(), false, true );
624 } elseif ( !$file->allowInlineDisplay() && $file->isSafeFile() ) {
625 $icon = $file->iconThumb();
626 $dlink2 = '<div style="float:' . $align . '" id="mw-media-icon">' .
627 $icon->toHtml( array( 'desc-link' => true ) ) . '<br />' . $dlink . '</div>';
632 $warning .= '<li>' . wfMsgExt( 'fileexists', array('parseinline','replaceafter'), $dlink ) . '</li>' . $dlink2;
634 } elseif( $file->getTitle()->getArticleID() ) {
635 $lnk = $sk->makeKnownLinkObj( $file->getTitle(), '', 'redirect=no' );
636 $warning .= '<li>' . wfMsgExt( 'filepageexists', array( 'parseinline', 'replaceafter' ), $lnk ) . '</li>';
637 } elseif ( $file_lc && $file_lc->exists() ) {
638 # Check if image with lowercase extension exists.
639 # It's not forbidden but in 99% it makes no sense to upload the same filename with uppercase extension
640 $dlink = $sk->makeKnownLinkObj( $nt_lc );
641 if ( $file_lc->allowInlineDisplay() ) {
642 $dlink2 = $sk->makeImageLinkObj( $nt_lc, wfMsgExt( 'fileexists-thumb', 'parseinline' ),
643 $nt_lc->getText(), $align, array(), false, true );
644 } elseif ( !$file_lc->allowInlineDisplay() && $file_lc->isSafeFile() ) {
645 $icon = $file_lc->iconThumb();
646 $dlink2 = '<div style="float:' . $align . '" id="mw-media-icon">' .
647 $icon->toHtml( array( 'desc-link' => true ) ) . '<br />' . $dlink . '</div>';
653 wfMsgExt( 'fileexists-extension', 'parsemag',
654 $file->getTitle()->getPrefixedText(), $dlink ) .
657 } elseif ( ( substr( $partname , 3, 3 ) == 'px-' ||
substr( $partname , 2, 3 ) == 'px-' )
658 && ereg( "[0-9]{2}" , substr( $partname , 0, 2) ) )
660 # Check for filenames like 50px- or 180px-, these are mostly thumbnails
661 $nt_thb = Title
::newFromText( substr( $partname , strpos( $partname , '-' ) +
1 ) . '.' . $rawExtension );
662 $file_thb = wfLocalFile( $nt_thb );
663 if ($file_thb->exists() ) {
664 # Check if an image without leading '180px-' (or similiar) exists
665 $dlink = $sk->makeKnownLinkObj( $nt_thb);
666 if ( $file_thb->allowInlineDisplay() ) {
667 $dlink2 = $sk->makeImageLinkObj( $nt_thb,
668 wfMsgExt( 'fileexists-thumb', 'parseinline' ),
669 $nt_thb->getText(), $align, array(), false, true );
670 } elseif ( !$file_thb->allowInlineDisplay() && $file_thb->isSafeFile() ) {
671 $icon = $file_thb->iconThumb();
672 $dlink2 = '<div style="float:' . $align . '" id="mw-media-icon">' .
673 $icon->toHtml( array( 'desc-link' => true ) ) . '<br />' .
679 $warning .= '<li>' . wfMsgExt( 'fileexists-thumbnail-yes', 'parsemag', $dlink ) .
682 # Image w/o '180px-' does not exists, but we do not like these filenames
683 $warning .= '<li>' . wfMsgExt( 'file-thumbnail-no', 'parseinline' ,
684 substr( $partname , 0, strpos( $partname , '-' ) +
1 ) ) . '</li>';
688 $filenamePrefixBlacklist = self
::getFilenamePrefixBlacklist();
690 foreach( $filenamePrefixBlacklist as $prefix ) {
691 if ( substr( $partname, 0, strlen( $prefix ) ) == $prefix ) {
692 $warning .= '<li>' . wfMsgExt( 'filename-bad-prefix', 'parseinline', $prefix ) . '</li>';
697 if ( $file->wasDeleted() && !$file->exists() ) {
698 # If the file existed before and was deleted, warn the user of this
699 # Don't bother doing so if the file exists now, however
700 $ltitle = SpecialPage
::getTitleFor( 'Log' );
701 $llink = $sk->makeKnownLinkObj( $ltitle, wfMsgHtml( 'deletionlog' ),
702 'type=delete&page=' . $file->getTitle()->getPrefixedUrl() );
703 $warning .= '<li>' . wfMsgWikiHtml( 'filewasdeleted', $llink ) . '</li>';
709 * Get a list of warnings
711 * @param string local filename, e.g. 'file exists', 'non-descriptive filename'
712 * @return array list of warning messages
714 static function ajaxGetExistsWarning( $filename ) {
715 $file = wfFindFile( $filename );
717 // Force local file so we have an object to do further checks against
718 // if there isn't an exact match...
719 $file = wfLocalFile( $filename );
723 $warning = self
::getExistsWarning( $file );
724 if ( $warning !== '' ) {
725 $s = "<ul>$warning</ul>";
732 * Render a preview of a given license for the AJAX preview on upload
734 * @param string $license
737 public static function ajaxGetLicensePreview( $license ) {
738 global $wgParser, $wgUser;
739 $text = '{{' . $license . '}}';
740 $title = Title
::makeTitle( NS_IMAGE
, 'Sample.jpg' );
741 $options = ParserOptions
::newFromUser( $wgUser );
743 // Expand subst: first, then live templates...
744 $text = $wgParser->preSaveTransform( $text, $title, $wgUser, $options );
745 $output = $wgParser->parse( $text, $title, $options );
747 return $output->getText();
751 * Check for duplicate files and throw up a warning before the upload
754 function getDupeWarning( $tempfile ) {
755 $hash = File
::sha1Base36( $tempfile );
756 $dupes = RepoGroup
::singleton()->findBySha1( $hash );
760 foreach( $dupes as $file ) {
761 $title = $file->getTitle();
762 $msg .= $title->getPrefixedText() .
763 "|" . $title->getText() . "\n";
765 $msg .= "</gallery>";
767 wfMsgExt( "file-exists-duplicate", array( "parse" ), count( $dupes ) ) .
768 $wgOut->parse( $msg ) .
776 * Get a list of blacklisted filename prefixes from [[MediaWiki:filename-prefix-blacklist]]
778 * @return array list of prefixes
780 public static function getFilenamePrefixBlacklist() {
781 $blacklist = array();
782 $message = wfMsgForContent( 'filename-prefix-blacklist' );
783 if( $message && !( wfEmptyMsg( 'filename-prefix-blacklist', $message ) ||
$message == '-' ) ) {
784 $lines = explode( "\n", $message );
785 foreach( $lines as $line ) {
786 // Remove comment lines
787 $comment = substr( trim( $line ), 0, 1 );
788 if ( $comment == '#' ||
$comment == '' ) {
791 // Remove additional comments after a prefix
792 $comment = strpos( $line, '#' );
793 if ( $comment > 0 ) {
794 $line = substr( $line, 0, $comment-1 );
796 $blacklist[] = trim( $line );
803 * Stash a file in a temporary directory for later processing
804 * after the user has confirmed it.
806 * If the user doesn't explicitly cancel or accept, these files
807 * can accumulate in the temp directory.
809 * @param string $saveName - the destination filename
810 * @param string $tempName - the source temporary file to save
811 * @return string - full path the stashed file, or false on failure
814 function saveTempUploadedFile( $saveName, $tempName ) {
816 $repo = RepoGroup
::singleton()->getLocalRepo();
817 $status = $repo->storeTemp( $saveName, $tempName );
818 if ( !$status->isGood() ) {
819 $this->showError( $status->getWikiText() );
822 return $status->value
;
827 * Stash a file in a temporary directory for later processing,
828 * and save the necessary descriptive info into the session.
829 * Returns a key value which will be passed through a form
830 * to pick up the path info on a later invocation.
835 function stashSession() {
836 $stash = $this->saveTempUploadedFile( $this->mDestName
, $this->mTempPath
);
839 # Couldn't save the file.
843 $key = mt_rand( 0, 0x7fffffff );
844 $_SESSION['wsUploadData'][$key] = array(
845 'mTempPath' => $stash,
846 'mFileSize' => $this->mFileSize
,
847 'mSrcName' => $this->mSrcName
,
848 'mFileProps' => $this->mFileProps
,
849 'version' => self
::SESSION_VERSION
,
855 * Remove a temporarily kept file stashed by saveTempUploadedFile().
859 function unsaveUploadedFile() {
861 $repo = RepoGroup
::singleton()->getLocalRepo();
862 $success = $repo->freeTemp( $this->mTempPath
);
864 $wgOut->showFileDeleteError( $this->mTempPath
);
871 /* -------------------------------------------------------------- */
874 * @param string $error as HTML
877 function uploadError( $error ) {
879 $wgOut->addHTML( '<h2>' . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
880 $wgOut->addHTML( '<span class="error">' . $error . '</span>' );
884 * There's something wrong with this file, not enough to reject it
885 * totally but we require manual intervention to save it for real.
886 * Stash it away, then present a form asking to confirm or cancel.
888 * @param string $warning as HTML
891 function uploadWarning( $warning ) {
893 global $wgUseCopyrightUpload;
895 $this->mSessionKey
= $this->stashSession();
896 if( !$this->mSessionKey
) {
897 # Couldn't save file; an error has been displayed so let's go.
901 $wgOut->addHTML( '<h2>' . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
902 $wgOut->addHTML( '<ul class="warning">' . $warning . "</ul>\n" );
904 $titleObj = SpecialPage
::getTitleFor( 'Upload' );
906 if ( $wgUseCopyrightUpload ) {
907 $copyright = Xml
::hidden( 'wpUploadCopyStatus', $this->mCopyrightStatus
) . "\n" .
908 Xml
::hidden( 'wpUploadSource', $this->mCopyrightSource
) . "\n";
914 Xml
::openElement( 'form', array( 'method' => 'post', 'action' => $titleObj->getLocalURL( 'action=submit' ),
915 'enctype' => 'multipart/form-data', 'id' => 'uploadwarning' ) ) . "\n" .
916 Xml
::hidden( 'wpIgnoreWarning', '1' ) . "\n" .
917 Xml
::hidden( 'wpSessionKey', $this->mSessionKey
) . "\n" .
918 Xml
::hidden( 'wpUploadDescription', $this->mComment
) . "\n" .
919 Xml
::hidden( 'wpLicense', $this->mLicense
) . "\n" .
920 Xml
::hidden( 'wpDestFile', $this->mDesiredDestName
) . "\n" .
921 Xml
::hidden( 'wpWatchthis', $this->mWatchthis
) . "\n" .
922 "{$copyright}<br />" .
923 Xml
::submitButton( wfMsg( 'ignorewarning' ), array ( 'name' => 'wpUpload', 'id' => 'wpUpload', 'checked' => 'checked' ) ) . ' ' .
924 Xml
::submitButton( wfMsg( 'reuploaddesc' ), array ( 'name' => 'wpReUpload', 'id' => 'wpReUpload' ) ) .
925 Xml
::closeElement( 'form' ) . "\n"
930 * Displays the main upload form, optionally with a highlighted
931 * error message up at the top.
933 * @param string $msg as HTML
936 function mainUploadForm( $msg='' ) {
937 global $wgOut, $wgUser, $wgLang, $wgMaxUploadSize;
938 global $wgUseCopyrightUpload, $wgUseAjax, $wgAjaxUploadDestCheck, $wgAjaxLicensePreview;
939 global $wgRequest, $wgAllowCopyUploads;
940 global $wgStylePath, $wgStyleVersion;
942 $useAjaxDestCheck = $wgUseAjax && $wgAjaxUploadDestCheck;
943 $useAjaxLicensePreview = $wgUseAjax && $wgAjaxLicensePreview;
945 $adc = wfBoolToStr( $useAjaxDestCheck );
946 $alp = wfBoolToStr( $useAjaxLicensePreview );
947 $autofill = wfBoolToStr( $this->mDesiredDestName
== '' );
949 $wgOut->addScript( "<script type=\"text/javascript\">
950 wgAjaxUploadDestCheck = {$adc};
951 wgAjaxLicensePreview = {$alp};
952 wgUploadAutoFill = {$autofill};
954 $wgOut->addScriptFile( 'upload.js' );
955 $wgOut->addScriptFile( 'edit.js' ); // For <charinsert> support
957 if( !wfRunHooks( 'UploadForm:initial', array( &$this ) ) )
959 wfDebug( "Hook 'UploadForm:initial' broke output of the upload form" );
963 if( $this->mDesiredDestName
) {
964 $title = Title
::makeTitleSafe( NS_IMAGE
, $this->mDesiredDestName
);
965 // Show a subtitle link to deleted revisions (to sysops et al only)
966 if( $title instanceof Title
&& ( $count = $title->isDeleted() ) > 0 && $wgUser->isAllowed( 'deletedhistory' ) ) {
968 $wgUser->isAllowed( 'delete' ) ?
'thisisdeleted' : 'viewdeleted',
969 array( 'parse', 'replaceafter' ),
970 $wgUser->getSkin()->makeKnownLinkObj(
971 SpecialPage
::getTitleFor( 'Undelete', $title->getPrefixedText() ),
972 wfMsgExt( 'restorelink', array( 'parsemag', 'escape' ), $count )
975 $wgOut->addHtml( "<div id=\"contentSub2\">{$link}</div>" );
978 // Show the relevant lines from deletion log (for still deleted files only)
979 if( $title instanceof Title
&& $title->isDeleted() > 0 && !$title->exists() ) {
980 $this->showDeletionLog( $wgOut, $title->getPrefixedText() );
984 $cols = intval($wgUser->getOption( 'cols' ));
986 if( $wgUser->getOption( 'editwidth' ) ) {
987 $width = " style=\"width:100%\"";
993 $sub = wfMsgHtml( 'uploaderror' );
994 $wgOut->addHTML( "<h2>{$sub}</h2>\n" .
995 "<span class='error'>{$msg}</span>\n" );
997 $wgOut->addHTML( '<div id="uploadtext">' );
998 $wgOut->addWikiMsg( 'uploadtext', $this->mDesiredDestName
);
999 $wgOut->addHTML( "</div>\n" );
1001 # Print a list of allowed file extensions, if so configured. We ignore
1002 # MIME type here, it's incomprehensible to most people and too long.
1003 global $wgCheckFileExtensions, $wgStrictFileExtensions,
1004 $wgFileExtensions, $wgFileBlacklist;
1006 $allowedExtensions = '';
1007 if( $wgCheckFileExtensions ) {
1008 $delim = wfMsgExt( 'comma-separator', array( 'escapenoentities' ) );
1009 if( $wgStrictFileExtensions ) {
1010 # Everything not permitted is banned
1012 '<div id="mw-upload-permitted">' .
1013 wfMsgWikiHtml( 'upload-permitted', implode( $wgFileExtensions, $delim ) ) .
1016 # We have to list both preferred and prohibited
1018 '<div id="mw-upload-preferred">' .
1019 wfMsgWikiHtml( 'upload-preferred', implode( $wgFileExtensions, $delim ) ) .
1021 '<div id="mw-upload-prohibited">' .
1022 wfMsgWikiHtml( 'upload-prohibited', implode( $wgFileBlacklist, $delim ) ) .
1026 # Everything is permitted.
1027 $extensionsList = '';
1030 # Get the maximum file size from php.ini as $wgMaxUploadSize works for uploads from URL via CURL only
1031 # See http://www.php.net/manual/en/ini.core.php#ini.upload-max-filesize for possible values of upload_max_filesize
1032 $val = trim( ini_get( 'upload_max_filesize' ) );
1033 $last = strtoupper( ( substr( $val, -1 ) ) );
1036 $val2 = substr( $val, 0, -1 ) * 1024 * 1024 * 1024;
1039 $val2 = substr( $val, 0, -1 ) * 1024 * 1024;
1042 $val2 = substr( $val, 0, -1 ) * 1024;
1047 $val2 = $wgAllowCopyUploads ?
min( $wgMaxUploadSize, $val2 ) : $val2;
1048 $maxUploadSize = '<div id="mw-upload-maxfilesize">' .
1049 wfMsgExt( 'upload-maxfilesize', array( 'parseinline', 'escapenoentities' ),
1050 $wgLang->formatSize( $val2 ) ) .
1053 $sourcefilename = wfMsgExt( 'sourcefilename', array( 'parseinline', 'escapenoentities' ) );
1054 $destfilename = wfMsgExt( 'destfilename', array( 'parseinline', 'escapenoentities' ) );
1056 $summary = wfMsgExt( 'fileuploadsummary', 'parseinline' );
1058 $licenses = new Licenses();
1059 $license = wfMsgExt( 'license', array( 'parseinline' ) );
1060 $nolicense = wfMsgHtml( 'nolicense' );
1061 $licenseshtml = $licenses->getHtml();
1063 $ulb = wfMsgHtml( 'uploadbtn' );
1066 $titleObj = SpecialPage
::getTitleFor( 'Upload' );
1068 $encDestName = htmlspecialchars( $this->mDesiredDestName
);
1070 $watchChecked = $this->watchCheck()
1071 ?
'checked="checked"'
1073 $warningChecked = $this->mIgnoreWarning ?
'checked' : '';
1075 // Prepare form for upload or upload/copy
1076 if( $wgAllowCopyUploads && $wgUser->isAllowed( 'upload_by_url' ) ) {
1078 "<input type='radio' id='wpSourceTypeFile' name='wpSourceType' value='file' " .
1079 "onchange='toggle_element_activation(\"wpUploadFileURL\",\"wpUploadFile\")' checked='checked' />" .
1080 "<input tabindex='1' type='file' name='wpUploadFile' id='wpUploadFile' " .
1082 "toggle_element_activation(\"wpUploadFileURL\",\"wpUploadFile\");" .
1083 "toggle_element_check(\"wpSourceTypeFile\",\"wpSourceTypeURL\")' " .
1084 "onchange='fillDestFilename(\"wpUploadFile\")' size='60' />" .
1085 wfMsgHTML( 'upload_source_file' ) . "<br/>" .
1086 "<input type='radio' id='wpSourceTypeURL' name='wpSourceType' value='web' " .
1087 "onchange='toggle_element_activation(\"wpUploadFile\",\"wpUploadFileURL\")' />" .
1088 "<input tabindex='1' type='text' name='wpUploadFileURL' id='wpUploadFileURL' " .
1090 "toggle_element_activation(\"wpUploadFile\",\"wpUploadFileURL\");" .
1091 "toggle_element_check(\"wpSourceTypeURL\",\"wpSourceTypeFile\")' " .
1092 "onchange='fillDestFilename(\"wpUploadFileURL\")' size='60' disabled='disabled' />" .
1093 wfMsgHtml( 'upload_source_url' ) ;
1096 "<input tabindex='1' type='file' name='wpUploadFile' id='wpUploadFile' " .
1097 ($this->mDesiredDestName?
"":"onchange='fillDestFilename(\"wpUploadFile\")' ") .
1099 "<input type='hidden' name='wpSourceType' value='file' />" ;
1101 if ( $useAjaxDestCheck ) {
1102 $warningRow = "<tr><td colspan='2' id='wpDestFile-warning'> </td></tr>";
1103 $destOnkeyup = 'onkeyup="wgUploadWarningObj.keypress();"';
1109 $encComment = htmlspecialchars( $this->mComment
);
1112 Xml
::openElement( 'form', array( 'method' => 'post', 'action' => $titleObj->getLocalURL(),
1113 'enctype' => 'multipart/form-data', 'id' => 'mw-upload-form' ) ) .
1114 Xml
::openElement( 'fieldset' ) .
1115 Xml
::element( 'legend', null, wfMsg( 'upload' ) ) .
1116 Xml
::openElement( 'table', array( 'border' => '0', 'id' => 'mw-upload-table' ) ) .
1118 {$this->uploadFormTextTop}
1119 <td class='mw-label'>
1120 <label for='wpUploadFile'>{$sourcefilename}</label>
1122 <td class='mw-input'>
1134 <td class='mw-label'>
1135 <label for='wpDestFile'>{$destfilename}</label>
1137 <td class='mw-input'>
1138 <input tabindex='2' type='text' name='wpDestFile' id='wpDestFile' size='60'
1139 value=\"{$encDestName}\" onchange='toggleFilenameFiller()' $destOnkeyup />
1143 <td class='mw-label'>
1144 <label for='wpUploadDescription'>{$summary}</label>
1146 <td class='mw-input'>
1147 <textarea tabindex='3' name='wpUploadDescription' id='wpUploadDescription' rows='6'
1148 cols='{$cols}'{$width}>$encComment</textarea>
1149 {$this->uploadFormTextAfterSummary}
1155 if ( $licenseshtml != '' ) {
1156 global $wgStylePath;
1158 <td class='mw-label'>
1159 <label for='wpLicense'>$license</label>
1161 <td class='mw-input'>
1162 <select name='wpLicense' id='wpLicense' tabindex='4'
1163 onchange='licenseSelectorCheck()'>
1164 <option value=''>$nolicense</option>
1171 if( $useAjaxLicensePreview ) {
1174 <td id=\"mw-license-preview\"></td>
1181 if ( $wgUseCopyrightUpload ) {
1182 $filestatus = wfMsgExt( 'filestatus', 'escapenoentities' );
1183 $copystatus = htmlspecialchars( $this->mCopyrightStatus
);
1184 $filesource = wfMsgExt( 'filesource', 'escapenoentities' );
1185 $uploadsource = htmlspecialchars( $this->mCopyrightSource
);
1188 <td class='mw-label' style='white-space: nowrap;'>
1189 <label for='wpUploadCopyStatus'>$filestatus</label></td>
1190 <td class='mw-input'>
1191 <input tabindex='5' type='text' name='wpUploadCopyStatus' id='wpUploadCopyStatus'
1192 value=\"$copystatus\" size='60' />
1196 <td class='mw-label'>
1197 <label for='wpUploadCopyStatus'>$filesource</label>
1199 <td class='mw-input'>
1200 <input tabindex='6' type='text' name='wpUploadSource' id='wpUploadCopyStatus'
1201 value=\"$uploadsource\" size='60' />
1211 <input tabindex='7' type='checkbox' name='wpWatchthis' id='wpWatchthis' $watchChecked value='true' />
1212 <label for='wpWatchthis'>" . wfMsgHtml( 'watchthisupload' ) . "</label>
1213 <input tabindex='8' type='checkbox' name='wpIgnoreWarning' id='wpIgnoreWarning' value='true' $warningChecked/>
1214 <label for='wpIgnoreWarning'>" . wfMsgHtml( 'ignorewarnings' ) . "</label>
1220 <td class='mw-input'>
1221 <input tabindex='9' type='submit' name='wpUpload' value=\"{$ulb}\"" . $wgUser->getSkin()->tooltipAndAccesskey( 'upload' ) . " />
1226 <td class='mw-input'>"
1228 $wgOut->addWikiText( wfMsgForContent( 'edittools' ) );
1232 Xml
::closeElement( 'table' ) .
1233 Xml
::hidden( 'wpDestFileWarningAck', '', array( 'id' => 'wpDestFileWarningAck' ) ) .
1234 Xml
::closeElement( 'fieldset' ) .
1235 Xml
::closeElement( 'form' )
1237 $uploadfooter = wfMsgNoTrans( 'uploadfooter' );
1238 if( $uploadfooter != '-' && !wfEmptyMsg( 'uploadfooter', $uploadfooter ) ){
1239 $wgOut->addWikiText( '<div id="mw-upload-footer-message">' . $uploadfooter . '</div>' );
1243 /* -------------------------------------------------------------- */
1246 * See if we should check the 'watch this page' checkbox on the form
1247 * based on the user's preferences and whether we're being asked
1248 * to create a new file or update an existing one.
1250 * In the case where 'watch edits' is off but 'watch creations' is on,
1251 * we'll leave the box unchecked.
1253 * Note that the page target can be changed *on the form*, so our check
1254 * state can get out of sync.
1256 function watchCheck() {
1258 if( $wgUser->getOption( 'watchdefault' ) ) {
1263 $local = wfLocalFile( $this->mDesiredDestName
);
1264 if( $local && $local->exists() ) {
1265 // We're uploading a new version of an existing file.
1266 // No creation, so don't watch it if we're not already.
1267 return $local->getTitle()->userIsWatching();
1269 // New page should get watched if that's our option.
1270 return $wgUser->getOption( 'watchcreations' );
1275 * Split a file into a base name and all dot-delimited 'extensions'
1276 * on the end. Some web server configurations will fall back to
1277 * earlier pseudo-'extensions' to determine type and execute
1278 * scripts, so the blacklist needs to check them all.
1282 function splitExtensions( $filename ) {
1283 $bits = explode( '.', $filename );
1284 $basename = array_shift( $bits );
1285 return array( $basename, $bits );
1289 * Perform case-insensitive match against a list of file extensions.
1290 * Returns true if the extension is in the list.
1292 * @param string $ext
1293 * @param array $list
1296 function checkFileExtension( $ext, $list ) {
1297 return in_array( strtolower( $ext ), $list );
1301 * Perform case-insensitive match against a list of file extensions.
1302 * Returns true if any of the extensions are in the list.
1305 * @param array $list
1308 function checkFileExtensionList( $ext, $list ) {
1309 foreach( $ext as $e ) {
1310 if( in_array( strtolower( $e ), $list ) ) {
1318 * Verifies that it's ok to include the uploaded file
1320 * @param string $tmpfile the full path of the temporary file to verify
1321 * @param string $extension The filename extension that the file is to be served with
1322 * @return mixed true of the file is verified, a WikiError object otherwise.
1324 function verify( $tmpfile, $extension ) {
1325 #magically determine mime type
1326 $magic = MimeMagic
::singleton();
1327 $mime = $magic->guessMimeType($tmpfile,false);
1329 #check mime type, if desired
1330 global $wgVerifyMimeType;
1331 if ($wgVerifyMimeType) {
1333 wfDebug ( "\n\nmime: <$mime> extension: <$extension>\n\n");
1334 #check mime type against file extension
1335 if( !self
::verifyExtension( $mime, $extension ) ) {
1336 return new WikiErrorMsg( 'uploadcorrupt' );
1339 #check mime type blacklist
1340 global $wgMimeTypeBlacklist;
1341 if( isset($wgMimeTypeBlacklist) && !is_null($wgMimeTypeBlacklist)
1342 && $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
1343 return new WikiErrorMsg( 'filetype-badmime', htmlspecialchars( $mime ) );
1347 #check for htmlish code and javascript
1348 if( $this->detectScript ( $tmpfile, $mime, $extension ) ) {
1349 return new WikiErrorMsg( 'uploadscripted' );
1353 * Scan the uploaded file for viruses
1355 $virus= $this->detectVirus($tmpfile);
1357 return new WikiErrorMsg( 'uploadvirus', htmlspecialchars($virus) );
1360 wfDebug( __METHOD__
.": all clear; passing.\n" );
1365 * Checks if the mime type of the uploaded file matches the file extension.
1367 * @param string $mime the mime type of the uploaded file
1368 * @param string $extension The filename extension that the file is to be served with
1371 static function verifyExtension( $mime, $extension ) {
1372 $magic = MimeMagic
::singleton();
1374 if ( ! $mime ||
$mime == 'unknown' ||
$mime == 'unknown/unknown' )
1375 if ( ! $magic->isRecognizableExtension( $extension ) ) {
1376 wfDebug( __METHOD__
.": passing file with unknown detected mime type; " .
1377 "unrecognized extension '$extension', can't verify\n" );
1380 wfDebug( __METHOD__
.": rejecting file with unknown detected mime type; ".
1381 "recognized extension '$extension', so probably invalid file\n" );
1385 $match= $magic->isMatchingExtension($extension,$mime);
1387 if ($match===NULL) {
1388 wfDebug( __METHOD__
.": no file extension known for mime type $mime, passing file\n" );
1390 } elseif ($match===true) {
1391 wfDebug( __METHOD__
.": mime type $mime matches extension $extension, passing file\n" );
1393 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
1397 wfDebug( __METHOD__
.": mime type $mime mismatches file extension $extension, rejecting file\n" );
1403 * Heuristic for detecting files that *could* contain JavaScript instructions or
1404 * things that may look like HTML to a browser and are thus
1405 * potentially harmful. The present implementation will produce false positives in some situations.
1407 * @param string $file Pathname to the temporary upload file
1408 * @param string $mime The mime type of the file
1409 * @param string $extension The extension of the file
1410 * @return bool true if the file contains something looking like embedded scripts
1412 function detectScript($file, $mime, $extension) {
1413 global $wgAllowTitlesInSVG;
1415 #ugly hack: for text files, always look at the entire file.
1416 #For binarie field, just check the first K.
1418 if (strpos($mime,'text/')===0) $chunk = file_get_contents( $file );
1420 $fp = fopen( $file, 'rb' );
1421 $chunk = fread( $fp, 1024 );
1425 $chunk= strtolower( $chunk );
1427 if (!$chunk) return false;
1429 #decode from UTF-16 if needed (could be used for obfuscation).
1430 if (substr($chunk,0,2)=="\xfe\xff") $enc= "UTF-16BE";
1431 elseif (substr($chunk,0,2)=="\xff\xfe") $enc= "UTF-16LE";
1434 if ($enc) $chunk= iconv($enc,"ASCII//IGNORE",$chunk);
1436 $chunk= trim($chunk);
1438 #FIXME: convert from UTF-16 if necessarry!
1440 wfDebug("SpecialUpload::detectScript: checking for embedded scripts and HTML stuff\n");
1442 #check for HTML doctype
1443 if (eregi("<!DOCTYPE *X?HTML",$chunk)) return true;
1446 * Internet Explorer for Windows performs some really stupid file type
1447 * autodetection which can cause it to interpret valid image files as HTML
1448 * and potentially execute JavaScript, creating a cross-site scripting
1451 * Apple's Safari browser also performs some unsafe file type autodetection
1452 * which can cause legitimate files to be interpreted as HTML if the
1453 * web server is not correctly configured to send the right content-type
1454 * (or if you're really uploading plain text and octet streams!)
1456 * Returns true if IE is likely to mistake the given file for HTML.
1457 * Also returns true if Safari would mistake the given file for HTML
1458 * when served with a generic content-type.
1464 '<html', #also in safari
1467 '<script', #also in safari
1470 if( ! $wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
1474 foreach( $tags as $tag ) {
1475 if( false !== strpos( $chunk, $tag ) ) {
1481 * look for javascript
1484 #resolve entity-refs to look at attributes. may be harsh on big files... cache result?
1485 $chunk = Sanitizer
::decodeCharReferences( $chunk );
1487 #look for script-types
1488 if (preg_match('!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim',$chunk)) return true;
1490 #look for html-style script-urls
1491 if (preg_match('!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim',$chunk)) return true;
1493 #look for css-style script-urls
1494 if (preg_match('!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim',$chunk)) return true;
1496 wfDebug("SpecialUpload::detectScript: no scripts found\n");
1501 * Generic wrapper function for a virus scanner program.
1502 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
1503 * $wgAntivirusRequired may be used to deny upload if the scan fails.
1505 * @param string $file Pathname to the temporary upload file
1506 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
1507 * or a string containing feedback from the virus scanner if a virus was found.
1508 * If textual feedback is missing but a virus was found, this function returns true.
1510 function detectVirus($file) {
1511 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
1513 if ( !$wgAntivirus ) {
1514 wfDebug( __METHOD__
.": virus scanner disabled\n");
1518 if ( !$wgAntivirusSetup[$wgAntivirus] ) {
1519 wfDebug( __METHOD__
.": unknown virus scanner: $wgAntivirus\n" );
1520 $wgOut->wrapWikiMsg( '<div class="error">$1</div>', array( 'virus-badscanner', $wgAntivirus ) );
1521 return wfMsg('virus-unknownscanner') . " $wgAntivirus";
1524 # look up scanner configuration
1525 $command = $wgAntivirusSetup[$wgAntivirus]["command"];
1526 $exitCodeMap = $wgAntivirusSetup[$wgAntivirus]["codemap"];
1527 $msgPattern = isset( $wgAntivirusSetup[$wgAntivirus]["messagepattern"] ) ?
1528 $wgAntivirusSetup[$wgAntivirus]["messagepattern"] : null;
1530 if ( strpos( $command,"%f" ) === false ) {
1531 # simple pattern: append file to scan
1532 $command .= " " . wfEscapeShellArg( $file );
1534 # complex pattern: replace "%f" with file to scan
1535 $command = str_replace( "%f", wfEscapeShellArg( $file ), $command );
1538 wfDebug( __METHOD__
.": running virus scan: $command \n" );
1540 # execute virus scanner
1543 #NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
1544 # that does not seem to be worth the pain.
1545 # Ask me (Duesentrieb) about it if it's ever needed.
1547 if ( wfIsWindows() ) {
1548 exec( "$command", $output, $exitCode );
1550 exec( "$command 2>&1", $output, $exitCode );
1553 # map exit code to AV_xxx constants.
1554 $mappedCode = $exitCode;
1555 if ( $exitCodeMap ) {
1556 if ( isset( $exitCodeMap[$exitCode] ) ) {
1557 $mappedCode = $exitCodeMap[$exitCode];
1558 } elseif ( isset( $exitCodeMap["*"] ) ) {
1559 $mappedCode = $exitCodeMap["*"];
1563 if ( $mappedCode === AV_SCAN_FAILED
) {
1564 # scan failed (code was mapped to false by $exitCodeMap)
1565 wfDebug( __METHOD__
.": failed to scan $file (code $exitCode).\n" );
1567 if ( $wgAntivirusRequired ) {
1568 return wfMsg('virus-scanfailed', array( $exitCode ) );
1572 } else if ( $mappedCode === AV_SCAN_ABORTED
) {
1573 # scan failed because filetype is unknown (probably imune)
1574 wfDebug( __METHOD__
.": unsupported file type $file (code $exitCode).\n" );
1576 } else if ( $mappedCode === AV_NO_VIRUS
) {
1578 wfDebug( __METHOD__
.": file passed virus scan.\n" );
1581 $output = join( "\n", $output );
1582 $output = trim( $output );
1585 $output = true; #if there's no output, return true
1586 } elseif ( $msgPattern ) {
1588 if ( preg_match( $msgPattern, $output, $groups ) ) {
1590 $output = $groups[1];
1595 wfDebug( __METHOD__
.": FOUND VIRUS! scanner feedback: $output" );
1601 * Check if the temporary file is MacBinary-encoded, as some uploads
1602 * from Internet Explorer on Mac OS Classic and Mac OS X will be.
1603 * If so, the data fork will be extracted to a second temporary file,
1604 * which will then be checked for validity and either kept or discarded.
1608 function checkMacBinary() {
1609 $macbin = new MacBinary( $this->mTempPath
);
1610 if( $macbin->isValid() ) {
1611 $dataFile = tempnam( wfTempDir(), "WikiMacBinary" );
1612 $dataHandle = fopen( $dataFile, 'wb' );
1614 wfDebug( "SpecialUpload::checkMacBinary: Extracting MacBinary data fork to $dataFile\n" );
1615 $macbin->extractData( $dataHandle );
1617 $this->mTempPath
= $dataFile;
1618 $this->mFileSize
= $macbin->dataForkLength();
1620 // We'll have to manually remove the new file if it's not kept.
1621 $this->mRemoveTempFile
= true;
1627 * If we've modified the upload file we need to manually remove it
1628 * on exit to clean up.
1631 function cleanupTempFile() {
1632 if ( $this->mRemoveTempFile
&& file_exists( $this->mTempPath
) ) {
1633 wfDebug( "SpecialUpload::cleanupTempFile: Removing temporary file {$this->mTempPath}\n" );
1634 unlink( $this->mTempPath
);
1639 * Check if there's an overwrite conflict and, if so, if restrictions
1640 * forbid this user from performing the upload.
1642 * @return mixed true on success, WikiError on failure
1645 function checkOverwrite( $name ) {
1646 $img = wfFindFile( $name );
1650 global $wgUser, $wgOut;
1651 if( $img->isLocal() ) {
1652 if( !self
::userCanReUpload( $wgUser, $img->name
) ) {
1653 $error = 'fileexists-forbidden';
1656 if( !$wgUser->isAllowed( 'reupload' ) ||
1657 !$wgUser->isAllowed( 'reupload-shared' ) ) {
1658 $error = "fileexists-shared-forbidden";
1664 $errorText = wfMsg( $error, wfEscapeWikiText( $img->getName() ) );
1668 // Rockin', go ahead and upload
1673 * Check if a user is the last uploader
1676 * @param string $img, image name
1679 public static function userCanReUpload( User
$user, $img ) {
1680 if( $user->isAllowed( 'reupload' ) )
1681 return true; // non-conditional
1682 if( !$user->isAllowed( 'reupload-own' ) )
1685 $dbr = wfGetDB( DB_SLAVE
);
1686 $row = $dbr->selectRow('image',
1687 /* SELECT */ 'img_user',
1688 /* WHERE */ array( 'img_name' => $img )
1693 return $user->getId() == $row->img_user
;
1697 * Display an error with a wikitext description
1699 function showError( $description ) {
1701 $wgOut->setPageTitle( wfMsg( "internalerror" ) );
1702 $wgOut->setRobotPolicy( "noindex,nofollow" );
1703 $wgOut->setArticleRelated( false );
1704 $wgOut->enableClientCache( false );
1705 $wgOut->addWikiText( $description );
1709 * Get the initial image page text based on a comment and optional file status information
1711 static function getInitialPageText( $comment, $license, $copyStatus, $source ) {
1712 global $wgUseCopyrightUpload;
1713 if ( $wgUseCopyrightUpload ) {
1714 if ( $license != '' ) {
1715 $licensetxt = '== ' . wfMsgForContent( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1717 $pageText = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $comment . "\n" .
1718 '== ' . wfMsgForContent ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
1720 '== ' . wfMsgForContent ( 'filesource' ) . " ==\n" . $source ;
1722 if ( $license != '' ) {
1723 $filedesc = $comment == '' ?
'' : '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $comment . "\n";
1724 $pageText = $filedesc .
1725 '== ' . wfMsgForContent ( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1727 $pageText = $comment;
1734 * If there are rows in the deletion log for this file, show them,
1735 * along with a nice little note for the user
1737 * @param OutputPage $out
1738 * @param string filename
1740 private function showDeletionLog( $out, $filename ) {
1742 $loglist = new LogEventsList( $wgUser->getSkin(), $out );
1743 $pager = new LogPager( $loglist, 'delete', false, $filename );
1744 if( $pager->getNumRows() > 0 ) {
1745 $out->addHtml( '<div id="mw-upload-deleted-warn">' );
1746 $out->addWikiMsg( 'upload-wasdeleted' );
1748 $loglist->beginLogEventsList() .
1750 $loglist->endLogEventsList()
1752 $out->addHtml( '</div>' );