Update messages.inc and rebuild MessagesEn.php
[mediawiki.git] / includes / SpecialUpload.php
blobac52d44559a651168c276ac38f90352ccec7db3d
1 <?php
2 /**
3 * @file
4 * @ingroup SpecialPage
5 */
8 /**
9 * Entry point
11 function wfSpecialUpload() {
12 global $wgRequest;
13 $form = new UploadForm( $wgRequest );
14 $form->execute();
17 /**
18 * implements Special:Upload
19 * @ingroup SpecialPage
21 class UploadForm {
22 const SUCCESS = 0;
23 const BEFORE_PROCESSING = 1;
24 const LARGE_FILE_SERVER = 2;
25 const EMPTY_FILE = 3;
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;
37 /**#@+
38 * @access private
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;
45 var $mLocalFile;
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;
53 /**#@-*/
55 /**
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
69 return;
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 ) {
92 /**
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;
106 } else {
108 *Check for a newly uploaded file.
110 if( $wgAllowCopyUploads && $this->mSourceType == 'web' ) {
111 $this->initializeFromUrl( $request );
112 } else {
113 $this->initializeFromUpload( $request );
119 * Initialize the uploaded file from PHP data
120 * @access private
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
134 * @access private
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 );
154 * Safe copy from URL
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' );
162 return true;
165 # Maybe remove some pasting blanks :-)
166 $url = trim( $url );
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' );
170 return true;
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');
178 return true;
181 $ch = curl_init();
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' ) );
187 curl_exec( $ch );
188 $error = curl_errno( $ch ) ? true : false;
189 $errornum = curl_errno( $ch );
190 // if ( $error ) print curl_error ( $ch ) ; # Debugging output
191 curl_close( $ch );
193 fclose( $this->mCurlDestHandle );
194 unset( $this->mCurlDestHandle );
195 if( $error ) {
196 unlink( $dest );
197 if( wfEmptyMsg( "upload-curl-error$errornum", wfMsg("upload-curl-error$errornum") ) )
198 $wgOut->showErrorPage( 'upload-misc-error', 'upload-misc-error-text' );
199 else
200 $wgOut->showErrorPage( "upload-curl-error$errornum", "upload-curl-error$errornum-text" );
203 return $error;
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.
210 * @access private
212 function uploadCurlCallback( $ch, $data ) {
213 global $wgMaxUploadSize;
214 $length = strlen( $data );
215 $this->mFileSize += $length;
216 if( $this->mFileSize > $wgMaxUploadSize ) {
217 return 0;
219 fwrite( $this->mCurlDestHandle, $data );
220 return $length;
224 * Start doing stuff
225 * @access public
227 function execute() {
228 global $wgUser, $wgOut;
229 global $wgEnableUploads;
231 # Check uploading enabled
232 if( !$wgEnableUploads ) {
233 $wgOut->showErrorPage( 'uploaddisabled', 'uploaddisabledtext', array( $this->mDesiredDestName ) );
234 return;
237 # Check permissions
238 if( !$wgUser->isAllowed( 'upload' ) ) {
239 if( !$wgUser->isLoggedIn() ) {
240 $wgOut->showErrorPage( 'uploadnologin', 'uploadnologintext' );
241 } else {
242 $wgOut->permissionRequired( 'upload' );
244 return;
247 # Check blocks
248 if( $wgUser->isBlocked() ) {
249 $wgOut->blockedPage();
250 return;
253 if( wfReadOnly() ) {
254 $wgOut->readOnlyPage();
255 return;
258 if( $this->mReUpload ) {
259 if( !$this->unsaveUploadedFile() ) {
260 return;
262 $this->mainUploadForm();
263 } else if( 'submit' == $this->mAction || $this->mUploadClicked ) {
264 $this->processUpload();
265 } else {
266 $this->mainUploadForm();
269 $this->cleanupTempFile();
273 * Do the upload
274 * Checks are made in SpecialUpload::execute()
276 * @access private
278 function processUpload(){
279 global $wgUser, $wgOut, $wgFileExtensions;
280 $details = null;
281 $value = null;
282 $value = $this->internalProcessUpload( $details );
284 switch($value) {
285 case self::SUCCESS:
286 $wgOut->redirect( $this->mLocalFile->getTitle()->getFullURL() );
287 break;
289 case self::BEFORE_PROCESSING:
290 break;
292 case self::LARGE_FILE_SERVER:
293 $this->mainUploadForm( wfMsgHtml( 'largefileserver' ) );
294 break;
296 case self::EMPTY_FILE:
297 $this->mainUploadForm( wfMsgHtml( 'emptyfile' ) );
298 break;
300 case self::MIN_LENGHT_PARTNAME:
301 $this->mainUploadForm( wfMsgHtml( 'minlength1' ) );
302 break;
304 case self::ILLEGAL_FILENAME:
305 $filtered = $details['filtered'];
306 $this->uploadError( wfMsgWikiHtml( 'illegalfilename', htmlspecialchars( $filtered ) ) );
307 break;
309 case self::PROTECTED_PAGE:
310 $wgOut->showPermissionsErrorPage( $details['permissionserrors'] );
311 break;
313 case self::OVERWRITE_EXISTING_FILE:
314 $errorText = $details['overwrite'];
315 $overwrite = new WikiError( $wgOut->parse( $errorText ) );
316 $this->uploadError( $overwrite->toString() );
317 break;
319 case self::FILETYPE_MISSING:
320 $this->uploadError( wfMsgExt( 'filetype-missing', array ( 'parseinline' ) ) );
321 break;
323 case self::FILETYPE_BADTYPE:
324 $finalExt = $details['finalExt'];
325 $this->uploadError(
326 wfMsgExt( 'filetype-banned-type',
327 array( 'parseinline' ),
328 htmlspecialchars( $finalExt ),
329 implode(
330 wfMsgExt( 'comma-separator', array( 'escapenoentities' ) ),
331 $wgFileExtensions
335 break;
337 case self::VERIFICATION_ERROR:
338 $veri = $details['veri'];
339 $this->uploadError( $veri->toString() );
340 break;
342 case self::UPLOAD_VERIFICATION_ERROR:
343 $error = $details['error'];
344 $this->uploadError( $error );
345 break;
347 case self::UPLOAD_WARNING:
348 $warning = $details['warning'];
349 $this->uploadWarning( $warning );
350 break;
352 case self::INTERNAL_ERROR:
353 $internal = $details['internal'];
354 $this->showError( $internal );
355 break;
357 default:
358 throw new MWException( __METHOD__ . ": Unknown value `{$value}`" );
363 * Really do the upload
364 * Checks are made in SpecialUpload::execute()
366 * @param array $resultDetails contains result-specific dict of additional values
368 * @access private
370 function internalProcessUpload( &$resultDetails ) {
371 global $wgUser;
373 if( !wfRunHooks( 'UploadForm:BeforeProcessing', array( &$this ) ) )
375 wfDebug( "Hook 'UploadForm:BeforeProcessing' broke processing the file." );
376 return self::BEFORE_PROCESSING;
380 * If there was no filename or a zero size given, give up quick.
382 if( trim( $this->mSrcName ) == '' || empty( $this->mFileSize ) ) {
383 return self::EMPTY_FILE;
386 /* Check for curl error */
387 if( $this->mCurlError ) {
388 return self::BEFORE_PROCESSING;
391 # Chop off any directories in the given filename
392 if( $this->mDesiredDestName ) {
393 $basename = $this->mDesiredDestName;
394 } else {
395 $basename = $this->mSrcName;
397 $filtered = wfBaseName( $basename );
400 * We'll want to blacklist against *any* 'extension', and use
401 * only the final one for the whitelist.
403 list( $partname, $ext ) = $this->splitExtensions( $filtered );
405 if( count( $ext ) ) {
406 $finalExt = $ext[count( $ext ) - 1];
407 } else {
408 $finalExt = '';
411 # If there was more than one "extension", reassemble the base
412 # filename to prevent bogus complaints about length
413 if( count( $ext ) > 1 ) {
414 for( $i = 0; $i < count( $ext ) - 1; $i++ )
415 $partname .= '.' . $ext[$i];
418 if( strlen( $partname ) < 1 ) {
419 return self::MIN_LENGHT_PARTNAME;
423 * Filter out illegal characters, and try to make a legible name
424 * out of it. We'll strip some silently that Title would die on.
426 $filtered = preg_replace ( "/[^".Title::legalChars()."]|:/", '-', $filtered );
427 $nt = Title::makeTitleSafe( NS_IMAGE, $filtered );
428 if( is_null( $nt ) ) {
429 $resultDetails = array( 'filtered' => $filtered );
430 return self::ILLEGAL_FILENAME;
432 $this->mLocalFile = wfLocalFile( $nt );
433 $this->mDestName = $this->mLocalFile->getName();
436 * If the image is protected, non-sysop users won't be able
437 * to modify it by uploading a new revision.
439 $permErrors = $nt->getUserPermissionsErrors( 'edit', $wgUser );
440 $permErrorsUpload = $nt->getUserPermissionsErrors( 'upload', $wgUser );
441 $permErrorsCreate = ( $nt->exists() ? array() : $nt->getUserPermissionsErrors( 'create', $wgUser ) );
443 if( $permErrors || $permErrorsUpload || $permErrorsCreate ) {
444 // merge all the problems into one list, avoiding duplicates
445 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsUpload, $permErrors ) );
446 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsCreate, $permErrors ) );
447 $resultDetails = array( 'permissionserrors' => $permErrors );
448 return self::PROTECTED_PAGE;
452 * In some cases we may forbid overwriting of existing files.
454 $overwrite = $this->checkOverwrite( $this->mDestName );
455 if( $overwrite !== true ) {
456 $resultDetails = array( 'overwrite' => $overwrite );
457 return self::OVERWRITE_EXISTING_FILE;
460 /* Don't allow users to override the blacklist (check file extension) */
461 global $wgCheckFileExtensions, $wgStrictFileExtensions;
462 global $wgFileExtensions, $wgFileBlacklist;
463 if ($finalExt == '') {
464 return self::FILETYPE_MISSING;
465 } elseif ( $this->checkFileExtensionList( $ext, $wgFileBlacklist ) ||
466 ($wgCheckFileExtensions && $wgStrictFileExtensions &&
467 !$this->checkFileExtension( $finalExt, $wgFileExtensions ) ) ) {
468 $resultDetails = array( 'finalExt' => $finalExt );
469 return self::FILETYPE_BADTYPE;
473 * Look at the contents of the file; if we can recognize the
474 * type but it's corrupt or data of the wrong type, we should
475 * probably not accept it.
477 if( !$this->mStashed ) {
478 $this->mFileProps = File::getPropsFromPath( $this->mTempPath, $finalExt );
479 $this->checkMacBinary();
480 $veri = $this->verify( $this->mTempPath, $finalExt );
482 if( $veri !== true ) { //it's a wiki error...
483 $resultDetails = array( 'veri' => $veri );
484 return self::VERIFICATION_ERROR;
488 * Provide an opportunity for extensions to add further checks
490 $error = '';
491 if( !wfRunHooks( 'UploadVerification',
492 array( $this->mDestName, $this->mTempPath, &$error ) ) ) {
493 $resultDetails = array( 'error' => $error );
494 return self::UPLOAD_VERIFICATION_ERROR;
500 * Check for non-fatal conditions
502 if ( ! $this->mIgnoreWarning ) {
503 $warning = '';
505 global $wgCapitalLinks;
506 if( $wgCapitalLinks ) {
507 $filtered = ucfirst( $filtered );
509 if( $basename != $filtered ) {
510 $warning .= '<li>'.wfMsgHtml( 'badfilename', htmlspecialchars( $this->mDestName ) ).'</li>';
513 global $wgCheckFileExtensions;
514 if ( $wgCheckFileExtensions ) {
515 if ( !$this->checkFileExtension( $finalExt, $wgFileExtensions ) ) {
516 $warning .= '<li>' .
517 wfMsgExt( 'filetype-unwanted-type',
518 array( 'parseinline' ),
519 htmlspecialchars( $finalExt ),
520 implode(
521 wfMsgExt( 'comma-separator', array( 'escapenoentities' ) ),
522 $wgFileExtensions
524 ) . '</li>';
528 global $wgUploadSizeWarning;
529 if ( $wgUploadSizeWarning && ( $this->mFileSize > $wgUploadSizeWarning ) ) {
530 $skin = $wgUser->getSkin();
531 $wsize = $skin->formatSize( $wgUploadSizeWarning );
532 $asize = $skin->formatSize( $this->mFileSize );
533 $warning .= '<li>' . wfMsgHtml( 'large-file', $wsize, $asize ) . '</li>';
535 if ( $this->mFileSize == 0 ) {
536 $warning .= '<li>'.wfMsgHtml( 'emptyfile' ).'</li>';
539 if ( !$this->mDestWarningAck ) {
540 $warning .= self::getExistsWarning( $this->mLocalFile );
542 if( $warning != '' ) {
544 * Stash the file in a temporary location; the user can choose
545 * to let it through and we'll complete the upload then.
547 $resultDetails = array( 'warning' => $warning );
548 return self::UPLOAD_WARNING;
553 * Try actually saving the thing...
554 * It will show an error form on failure.
556 $pageText = self::getInitialPageText( $this->mComment, $this->mLicense,
557 $this->mCopyrightStatus, $this->mCopyrightSource );
559 $status = $this->mLocalFile->upload( $this->mTempPath, $this->mComment, $pageText,
560 File::DELETE_SOURCE, $this->mFileProps );
561 if ( !$status->isGood() ) {
562 $resultDetails = array( 'internal' => $status->getWikiText() );
563 return self::INTERNAL_ERROR;
564 } else {
565 if ( $this->mWatchthis ) {
566 global $wgUser;
567 $wgUser->addWatch( $this->mLocalFile->getTitle() );
569 // Success, redirect to description page
570 $img = null; // @todo: added to avoid passing a ref to null - should this be defined somewhere?
571 wfRunHooks( 'UploadComplete', array( &$this ) );
572 return self::SUCCESS;
577 * Do existence checks on a file and produce a warning
578 * This check is static and can be done pre-upload via AJAX
579 * Returns an HTML fragment consisting of one or more LI elements if there is a warning
580 * Returns an empty string if there is no warning
582 static function getExistsWarning( $file ) {
583 global $wgUser, $wgContLang;
584 // Check for uppercase extension. We allow these filenames but check if an image
585 // with lowercase extension exists already
586 $warning = '';
587 $align = $wgContLang->isRtl() ? 'left' : 'right';
589 if( strpos( $file->getName(), '.' ) == false ) {
590 $partname = $file->getName();
591 $rawExtension = '';
592 } else {
593 $n = strrpos( $file->getName(), '.' );
594 $rawExtension = substr( $file->getName(), $n + 1 );
595 $partname = substr( $file->getName(), 0, $n );
598 $sk = $wgUser->getSkin();
600 if ( $rawExtension != $file->getExtension() ) {
601 // We're not using the normalized form of the extension.
602 // Normal form is lowercase, using most common of alternate
603 // extensions (eg 'jpg' rather than 'JPEG').
605 // Check for another file using the normalized form...
606 $nt_lc = Title::makeTitle( NS_IMAGE, $partname . '.' . $file->getExtension() );
607 $file_lc = wfLocalFile( $nt_lc );
608 } else {
609 $file_lc = false;
612 if( $file->exists() ) {
613 $dlink = $sk->makeKnownLinkObj( $file->getTitle() );
614 if ( $file->allowInlineDisplay() ) {
615 $dlink2 = $sk->makeImageLinkObj( $file->getTitle(), wfMsgExt( 'fileexists-thumb', 'parseinline' ),
616 $file->getName(), $align, array(), false, true );
617 } elseif ( !$file->allowInlineDisplay() && $file->isSafeFile() ) {
618 $icon = $file->iconThumb();
619 $dlink2 = '<div style="float:' . $align . '" id="mw-media-icon">' .
620 $icon->toHtml( array( 'desc-link' => true ) ) . '<br />' . $dlink . '</div>';
621 } else {
622 $dlink2 = '';
625 $warning .= '<li>' . wfMsgExt( 'fileexists', array('parseinline','replaceafter'), $dlink ) . '</li>' . $dlink2;
627 } elseif( $file->getTitle()->getArticleID() ) {
628 $lnk = $sk->makeKnownLinkObj( $file->getTitle(), '', 'redirect=no' );
629 $warning .= '<li>' . wfMsgExt( 'filepageexists', array( 'parseinline', 'replaceafter' ), $lnk ) . '</li>';
630 } elseif ( $file_lc && $file_lc->exists() ) {
631 # Check if image with lowercase extension exists.
632 # It's not forbidden but in 99% it makes no sense to upload the same filename with uppercase extension
633 $dlink = $sk->makeKnownLinkObj( $nt_lc );
634 if ( $file_lc->allowInlineDisplay() ) {
635 $dlink2 = $sk->makeImageLinkObj( $nt_lc, wfMsgExt( 'fileexists-thumb', 'parseinline' ),
636 $nt_lc->getText(), $align, array(), false, true );
637 } elseif ( !$file_lc->allowInlineDisplay() && $file_lc->isSafeFile() ) {
638 $icon = $file_lc->iconThumb();
639 $dlink2 = '<div style="float:' . $align . '" id="mw-media-icon">' .
640 $icon->toHtml( array( 'desc-link' => true ) ) . '<br />' . $dlink . '</div>';
641 } else {
642 $dlink2 = '';
645 $warning .= '<li>' .
646 wfMsgExt( 'fileexists-extension', 'parsemag',
647 $file->getTitle()->getPrefixedText(), $dlink ) .
648 '</li>' . $dlink2;
650 } elseif ( ( substr( $partname , 3, 3 ) == 'px-' || substr( $partname , 2, 3 ) == 'px-' )
651 && ereg( "[0-9]{2}" , substr( $partname , 0, 2) ) )
653 # Check for filenames like 50px- or 180px-, these are mostly thumbnails
654 $nt_thb = Title::newFromText( substr( $partname , strpos( $partname , '-' ) +1 ) . '.' . $rawExtension );
655 $file_thb = wfLocalFile( $nt_thb );
656 if ($file_thb->exists() ) {
657 # Check if an image without leading '180px-' (or similiar) exists
658 $dlink = $sk->makeKnownLinkObj( $nt_thb);
659 if ( $file_thb->allowInlineDisplay() ) {
660 $dlink2 = $sk->makeImageLinkObj( $nt_thb,
661 wfMsgExt( 'fileexists-thumb', 'parseinline' ),
662 $nt_thb->getText(), $align, array(), false, true );
663 } elseif ( !$file_thb->allowInlineDisplay() && $file_thb->isSafeFile() ) {
664 $icon = $file_thb->iconThumb();
665 $dlink2 = '<div style="float:' . $align . '" id="mw-media-icon">' .
666 $icon->toHtml( array( 'desc-link' => true ) ) . '<br />' .
667 $dlink . '</div>';
668 } else {
669 $dlink2 = '';
672 $warning .= '<li>' . wfMsgExt( 'fileexists-thumbnail-yes', 'parsemag', $dlink ) .
673 '</li>' . $dlink2;
674 } else {
675 # Image w/o '180px-' does not exists, but we do not like these filenames
676 $warning .= '<li>' . wfMsgExt( 'file-thumbnail-no', 'parseinline' ,
677 substr( $partname , 0, strpos( $partname , '-' ) +1 ) ) . '</li>';
681 $filenamePrefixBlacklist = self::getFilenamePrefixBlacklist();
682 # Do the match
683 foreach( $filenamePrefixBlacklist as $prefix ) {
684 if ( substr( $partname, 0, strlen( $prefix ) ) == $prefix ) {
685 $warning .= '<li>' . wfMsgExt( 'filename-bad-prefix', 'parseinline', $prefix ) . '</li>';
686 break;
690 if ( $file->wasDeleted() && !$file->exists() ) {
691 # If the file existed before and was deleted, warn the user of this
692 # Don't bother doing so if the file exists now, however
693 $ltitle = SpecialPage::getTitleFor( 'Log' );
694 $llink = $sk->makeKnownLinkObj( $ltitle, wfMsgHtml( 'deletionlog' ),
695 'type=delete&page=' . $file->getTitle()->getPrefixedUrl() );
696 $warning .= '<li>' . wfMsgWikiHtml( 'filewasdeleted', $llink ) . '</li>';
698 return $warning;
702 * Get a list of warnings
704 * @param string local filename, e.g. 'file exists', 'non-descriptive filename'
705 * @return array list of warning messages
707 static function ajaxGetExistsWarning( $filename ) {
708 $file = wfFindFile( $filename );
709 if( !$file ) {
710 // Force local file so we have an object to do further checks against
711 // if there isn't an exact match...
712 $file = wfLocalFile( $filename );
714 $s = '&nbsp;';
715 if ( $file ) {
716 $warning = self::getExistsWarning( $file );
717 if ( $warning !== '' ) {
718 $s = "<ul>$warning</ul>";
721 return $s;
725 * Render a preview of a given license for the AJAX preview on upload
727 * @param string $license
728 * @return string
730 public static function ajaxGetLicensePreview( $license ) {
731 global $wgParser, $wgUser;
732 $text = '{{' . $license . '}}';
733 $title = Title::makeTitle( NS_IMAGE, 'Sample.jpg' );
734 $options = ParserOptions::newFromUser( $wgUser );
736 // Expand subst: first, then live templates...
737 $text = $wgParser->preSaveTransform( $text, $title, $wgUser, $options );
738 $output = $wgParser->parse( $text, $title, $options );
740 return $output->getText();
744 * Get a list of blacklisted filename prefixes from [[MediaWiki:filename-prefix-blacklist]]
746 * @return array list of prefixes
748 public static function getFilenamePrefixBlacklist() {
749 $blacklist = array();
750 $message = wfMsgForContent( 'filename-prefix-blacklist' );
751 if( $message && !( wfEmptyMsg( 'filename-prefix-blacklist', $message ) || $message == '-' ) ) {
752 $lines = explode( "\n", $message );
753 foreach( $lines as $line ) {
754 // Remove comment lines
755 $comment = substr( trim( $line ), 0, 1 );
756 if ( $comment == '#' || $comment == '' ) {
757 continue;
759 // Remove additional comments after a prefix
760 $comment = strpos( $line, '#' );
761 if ( $comment > 0 ) {
762 $line = substr( $line, 0, $comment-1 );
764 $blacklist[] = trim( $line );
767 return $blacklist;
771 * Stash a file in a temporary directory for later processing
772 * after the user has confirmed it.
774 * If the user doesn't explicitly cancel or accept, these files
775 * can accumulate in the temp directory.
777 * @param string $saveName - the destination filename
778 * @param string $tempName - the source temporary file to save
779 * @return string - full path the stashed file, or false on failure
780 * @access private
782 function saveTempUploadedFile( $saveName, $tempName ) {
783 global $wgOut;
784 $repo = RepoGroup::singleton()->getLocalRepo();
785 $status = $repo->storeTemp( $saveName, $tempName );
786 if ( !$status->isGood() ) {
787 $this->showError( $status->getWikiText() );
788 return false;
789 } else {
790 return $status->value;
795 * Stash a file in a temporary directory for later processing,
796 * and save the necessary descriptive info into the session.
797 * Returns a key value which will be passed through a form
798 * to pick up the path info on a later invocation.
800 * @return int
801 * @access private
803 function stashSession() {
804 $stash = $this->saveTempUploadedFile( $this->mDestName, $this->mTempPath );
806 if( !$stash ) {
807 # Couldn't save the file.
808 return false;
811 $key = mt_rand( 0, 0x7fffffff );
812 $_SESSION['wsUploadData'][$key] = array(
813 'mTempPath' => $stash,
814 'mFileSize' => $this->mFileSize,
815 'mSrcName' => $this->mSrcName,
816 'mFileProps' => $this->mFileProps,
817 'version' => self::SESSION_VERSION,
819 return $key;
823 * Remove a temporarily kept file stashed by saveTempUploadedFile().
824 * @access private
825 * @return success
827 function unsaveUploadedFile() {
828 global $wgOut;
829 $repo = RepoGroup::singleton()->getLocalRepo();
830 $success = $repo->freeTemp( $this->mTempPath );
831 if ( ! $success ) {
832 $wgOut->showFileDeleteError( $this->mTempPath );
833 return false;
834 } else {
835 return true;
839 /* -------------------------------------------------------------- */
842 * @param string $error as HTML
843 * @access private
845 function uploadError( $error ) {
846 global $wgOut;
847 $wgOut->addHTML( Xml::element( 'h2', null, wfMsg( 'uploadwarning' ) . "\n" ) );
848 $wgOut->addHTML( Xml::tags( 'span', array( 'class' => 'error' ), $error ) );
852 * There's something wrong with this file, not enough to reject it
853 * totally but we require manual intervention to save it for real.
854 * Stash it away, then present a form asking to confirm or cancel.
856 * @param string $warning as HTML
857 * @access private
859 function uploadWarning( $warning ) {
860 global $wgOut;
861 global $wgUseCopyrightUpload;
863 $this->mSessionKey = $this->stashSession();
864 if( !$this->mSessionKey ) {
865 # Couldn't save file; an error has been displayed so let's go.
866 return;
869 $wgOut->addHTML( Xml::element( 'h2', null, wfMsg( 'uploadwarning' ) ) . "\n" );
870 $wgOut->addHTML( Xml::tags( 'ul', array( 'class' => 'warning' ), $warning ) . "\n" );
872 $titleObj = SpecialPage::getTitleFor( 'Upload' );
874 if ( $wgUseCopyrightUpload ) {
875 $copyright = Xml::hidden( 'wpUploadCopyStatus', $this->mCopyrightStatus ) . "\n" .
876 Xml::hidden( 'wpUploadSource', $this->mCopyrightSource ) . "\n";
877 } else {
878 $copyright = '';
881 $wgOut->addHTML(
882 Xml::openElement( 'form', array( 'method' => 'post', 'action' => $titleObj->getLocalURL( 'action=submit' ),
883 'enctype' => 'multipart/form-data', 'id' => 'uploadwarning' ) ) . "\n" .
884 Xml::hidden( 'wpIgnoreWarning', '1' ) . "\n" .
885 Xml::hidden( 'wpSessionKey', $this->mSessionKey ) . "\n" .
886 Xml::hidden( 'wpUploadDescription', $this->mComment ) . "\n" .
887 Xml::hidden( 'wpLicense', $this->mLicense ) . "\n" .
888 Xml::hidden( 'wpDestFile', $this->mDesiredDestName ) . "\n" .
889 Xml::hidden( 'wpWatchthis', $this->mWatchthis ) . "\n" .
890 "{$copyright}<br />" .
891 Xml::submitButton( wfMsg( 'ignorewarning' ), array ( 'name' => 'wpUpload', 'id' => 'wpUpload', 'checked' => 'checked' ) ) . ' ' .
892 Xml::submitButton( wfMsg( 'reuploaddesc' ), array ( 'name' => 'wpReUpload', 'id' => 'wpReUpload' ) ) .
893 Xml::closeElement( 'form' ) . "\n"
898 * Displays the main upload form, optionally with a highlighted
899 * error message up at the top.
901 * @param string $msg as HTML
902 * @access private
904 function mainUploadForm( $msg='' ) {
905 global $wgOut, $wgUser, $wgLang, $wgMaxUploadSize;
906 global $wgUseCopyrightUpload, $wgUseAjax, $wgAjaxUploadDestCheck, $wgAjaxLicensePreview;
907 global $wgRequest, $wgAllowCopyUploads;
908 global $wgStylePath, $wgStyleVersion;
910 $useAjaxDestCheck = $wgUseAjax && $wgAjaxUploadDestCheck;
911 $useAjaxLicensePreview = $wgUseAjax && $wgAjaxLicensePreview;
913 $adc = wfBoolToStr( $useAjaxDestCheck );
914 $alp = wfBoolToStr( $useAjaxLicensePreview );
915 $autofill = wfBoolToStr( $this->mDesiredDestName == '' );
917 $wgOut->addScript( "<script type=\"text/javascript\">
918 wgAjaxUploadDestCheck = {$adc};
919 wgAjaxLicensePreview = {$alp};
920 wgUploadAutoFill = {$autofill};
921 </script>" );
922 $wgOut->addScriptFile( 'upload.js' );
923 $wgOut->addScriptFile( 'edit.js' ); // For <charinsert> support
925 if( !wfRunHooks( 'UploadForm:initial', array( &$this ) ) )
927 wfDebug( "Hook 'UploadForm:initial' broke output of the upload form" );
928 return false;
931 if( $this->mDesiredDestName ) {
932 $title = Title::makeTitleSafe( NS_IMAGE, $this->mDesiredDestName );
933 // Show a subtitle link to deleted revisions (to sysops et al only)
934 if( $title instanceof Title && ( $count = $title->isDeleted() ) > 0 && $wgUser->isAllowed( 'deletedhistory' ) ) {
935 $link = wfMsgExt(
936 $wgUser->isAllowed( 'delete' ) ? 'thisisdeleted' : 'viewdeleted',
937 array( 'parse', 'replaceafter' ),
938 $wgUser->getSkin()->makeKnownLinkObj(
939 SpecialPage::getTitleFor( 'Undelete', $title->getPrefixedText() ),
940 wfMsgExt( 'restorelink', array( 'parsemag', 'escape' ), $count )
943 $wgOut->addHtml( "<div id=\"contentSub2\">{$link}</div>" );
946 // Show the relevant lines from deletion log (for still deleted files only)
947 if( $title instanceof Title && $title->isDeleted() > 0 && !$title->exists() ) {
948 $this->showDeletionLog( $wgOut, $title->getPrefixedText() );
952 $cols = intval($wgUser->getOption( 'cols' ));
954 if( $wgUser->getOption( 'editwidth' ) ) {
955 $width = " style=\"width:100%\"";
956 } else {
957 $width = '';
960 if ( '' != $msg ) {
961 $sub = wfMsgHtml( 'uploaderror' );
962 $wgOut->addHTML( "<h2>{$sub}</h2>\n" .
963 "<span class='error'>{$msg}</span>\n" );
965 $wgOut->addHTML( '<div id="uploadtext">' );
966 $wgOut->addWikiMsg( 'uploadtext', $this->mDesiredDestName );
967 $wgOut->addHTML( "</div>\n" );
969 # Print a list of allowed file extensions, if so configured. We ignore
970 # MIME type here, it's incomprehensible to most people and too long.
971 global $wgCheckFileExtensions, $wgStrictFileExtensions,
972 $wgFileExtensions, $wgFileBlacklist;
974 $allowedExtensions = '';
975 if( $wgCheckFileExtensions ) {
976 $delim = wfMsgExt( 'comma-separator', array( 'escapenoentities' ) );
977 if( $wgStrictFileExtensions ) {
978 # Everything not permitted is banned
979 $extensionsList =
980 '<div id="mw-upload-permitted">' .
981 wfMsgWikiHtml( 'upload-permitted', implode( $wgFileExtensions, $delim ) ) .
982 "</div>\n";
983 } else {
984 # We have to list both preferred and prohibited
985 $extensionsList =
986 '<div id="mw-upload-preferred">' .
987 wfMsgWikiHtml( 'upload-preferred', implode( $wgFileExtensions, $delim ) ) .
988 "</div>\n" .
989 '<div id="mw-upload-prohibited">' .
990 wfMsgWikiHtml( 'upload-prohibited', implode( $wgFileBlacklist, $delim ) ) .
991 "</div>\n";
993 } else {
994 # Everything is permitted.
995 $extensionsList = '';
998 # Get the maximum file size from php.ini as $wgMaxUploadSize works for uploads from URL via CURL only
999 # See http://www.php.net/manual/en/ini.core.php#ini.upload-max-filesize for possible values of upload_max_filesize
1000 $val = trim( ini_get( 'upload_max_filesize' ) );
1001 $last = strtoupper( ( substr( $val, -1 ) ) );
1002 switch( $last ) {
1003 case 'G':
1004 $val2 = substr( $val, 0, -1 ) * 1024 * 1024 * 1024;
1005 break;
1006 case 'M':
1007 $val2 = substr( $val, 0, -1 ) * 1024 * 1024;
1008 break;
1009 case 'K':
1010 $val2 = substr( $val, 0, -1 ) * 1024;
1011 break;
1012 default:
1013 $val2 = $val;
1015 $val2 = $wgAllowCopyUploads ? min( $wgMaxUploadSize, $val2 ) : $val2;
1016 $maxUploadSize = wfMsgExt( 'upload-maxfilesize', array( 'parseinline', 'escapenoentities' ), $wgLang->formatSize( $val2 ) );
1018 $sourcefilename = wfMsgExt( 'sourcefilename', 'escapenoentities' );
1019 $destfilename = wfMsgExt( 'destfilename', 'escapenoentities' );
1020 $summary = wfMsgExt( 'fileuploadsummary', 'parseinline' );
1022 $licenses = new Licenses();
1023 $license = wfMsgExt( 'license', array( 'parseinline' ) );
1024 $nolicense = wfMsgHtml( 'nolicense' );
1025 $licenseshtml = $licenses->getHtml();
1027 $ulb = wfMsgHtml( 'uploadbtn' );
1030 $titleObj = SpecialPage::getTitleFor( 'Upload' );
1032 $encDestName = htmlspecialchars( $this->mDesiredDestName );
1034 $watchChecked = $this->watchCheck()
1035 ? 'checked="checked"'
1036 : '';
1037 $warningChecked = $this->mIgnoreWarning ? 'checked' : '';
1039 // Prepare form for upload or upload/copy
1040 if( $wgAllowCopyUploads && $wgUser->isAllowed( 'upload_by_url' ) ) {
1041 $filename_form =
1042 "<input type='radio' id='wpSourceTypeFile' name='wpSourceType' value='file' " .
1043 "onchange='toggle_element_activation(\"wpUploadFileURL\",\"wpUploadFile\")' checked='checked' />" .
1044 "<input tabindex='1' type='file' name='wpUploadFile' id='wpUploadFile' " .
1045 "onfocus='" .
1046 "toggle_element_activation(\"wpUploadFileURL\",\"wpUploadFile\");" .
1047 "toggle_element_check(\"wpSourceTypeFile\",\"wpSourceTypeURL\")' " .
1048 "onchange='fillDestFilename(\"wpUploadFile\")' size='60' />" .
1049 wfMsgHTML( 'upload_source_file' ) . "<br/>" .
1050 "<input type='radio' id='wpSourceTypeURL' name='wpSourceType' value='web' " .
1051 "onchange='toggle_element_activation(\"wpUploadFile\",\"wpUploadFileURL\")' />" .
1052 "<input tabindex='1' type='text' name='wpUploadFileURL' id='wpUploadFileURL' " .
1053 "onfocus='" .
1054 "toggle_element_activation(\"wpUploadFile\",\"wpUploadFileURL\");" .
1055 "toggle_element_check(\"wpSourceTypeURL\",\"wpSourceTypeFile\")' " .
1056 "onchange='fillDestFilename(\"wpUploadFileURL\")' size='60' disabled='disabled' />" .
1057 wfMsgHtml( 'upload_source_url' ) ;
1058 } else {
1059 $filename_form =
1060 "<input tabindex='1' type='file' name='wpUploadFile' id='wpUploadFile' " .
1061 ($this->mDesiredDestName?"":"onchange='fillDestFilename(\"wpUploadFile\")' ") .
1062 "size='60' />" .
1063 "<input type='hidden' name='wpSourceType' value='file' />" ;
1065 if ( $useAjaxDestCheck ) {
1066 $warningRow = "<tr><td colspan='2' id='wpDestFile-warning'>&nbsp;</td></tr>";
1067 $destOnkeyup = 'onkeyup="wgUploadWarningObj.keypress();"';
1068 } else {
1069 $warningRow = '';
1070 $destOnkeyup = '';
1073 $encComment = htmlspecialchars( $this->mComment );
1075 $wgOut->addHTML(
1076 Xml::openElement( 'form', array( 'method' => 'post', 'action' => $titleObj->getLocalURL(),
1077 'enctype' => 'multipart/form-data', 'id' => 'mw-upload-form' ) ) .
1078 Xml::openElement( 'fieldset' ) .
1079 Xml::element( 'legend', null, wfMsg( 'upload' ) ) .
1080 Xml::openElement( 'table', array( 'border' => '0', 'id' => 'mw-upload-table' ) ) .
1081 "<tr>
1082 {$this->uploadFormTextTop}
1083 <td class='mw-label'>
1084 <label for='wpUploadFile'>{$sourcefilename}</label>
1085 </td>
1086 <td class='mw-input'>
1087 {$filename_form}
1088 </td>
1089 </tr>
1090 <tr>
1091 <td></td>
1092 <td>
1093 {$maxUploadSize}
1094 {$extensionsList}
1095 </td>
1096 </tr>
1097 <tr>
1098 <td class='mw-label'>
1099 <label for='wpDestFile'>{$destfilename}</label>
1100 </td>
1101 <td class='mw-input'>
1102 <input tabindex='2' type='text' name='wpDestFile' id='wpDestFile' size='60'
1103 value=\"{$encDestName}\" onchange='toggleFilenameFiller()' $destOnkeyup />
1104 </td>
1105 </tr>
1106 <tr>
1107 <td class='mw-label'>
1108 <label for='wpUploadDescription'>{$summary}</label>
1109 </td>
1110 <td class='mw-input'>
1111 <textarea tabindex='3' name='wpUploadDescription' id='wpUploadDescription' rows='6'
1112 cols='{$cols}'{$width}>$encComment</textarea>
1113 {$this->uploadFormTextAfterSummary}
1114 </td>
1115 </tr>
1116 <tr>"
1119 if ( $licenseshtml != '' ) {
1120 global $wgStylePath;
1121 $wgOut->addHTML( "
1122 <td class='mw-label'>
1123 <label for='wpLicense'>$license</label>
1124 </td>
1125 <td class='mw-input'>
1126 <select name='wpLicense' id='wpLicense' tabindex='4'
1127 onchange='licenseSelectorCheck()'>
1128 <option value=''>$nolicense</option>
1129 $licenseshtml
1130 </select>
1131 </td>
1132 </tr>
1133 <tr>"
1135 if( $useAjaxLicensePreview ) {
1136 $wgOut->addHtml( "
1137 <td></td>
1138 <td id=\"mw-license-preview\"></td>
1139 </tr>
1140 <tr>"
1145 if ( $wgUseCopyrightUpload ) {
1146 $filestatus = wfMsgExt( 'filestatus', 'escapenoentities' );
1147 $copystatus = htmlspecialchars( $this->mCopyrightStatus );
1148 $filesource = wfMsgExt( 'filesource', 'escapenoentities' );
1149 $uploadsource = htmlspecialchars( $this->mCopyrightSource );
1151 $wgOut->addHTML( "
1152 <td class='mw-label' style='white-space: nowrap;'>
1153 <label for='wpUploadCopyStatus'>$filestatus</label></td>
1154 <td class='mw-input'>
1155 <input tabindex='5' type='text' name='wpUploadCopyStatus' id='wpUploadCopyStatus'
1156 value=\"$copystatus\" size='60' />
1157 </td>
1158 </tr>
1159 <tr>
1160 <td class='mw-label'>
1161 <label for='wpUploadCopyStatus'>$filesource</label>
1162 </td>
1163 <td class='mw-input'>
1164 <input tabindex='6' type='text' name='wpUploadSource' id='wpUploadCopyStatus'
1165 value=\"$uploadsource\" size='60' />
1166 </td>
1167 </tr>
1168 <tr>"
1172 $wgOut->addHtml( "
1173 <td></td>
1174 <td>
1175 <input tabindex='7' type='checkbox' name='wpWatchthis' id='wpWatchthis' $watchChecked value='true' />
1176 <label for='wpWatchthis'>" . wfMsgHtml( 'watchthisupload' ) . "</label>
1177 <input tabindex='8' type='checkbox' name='wpIgnoreWarning' id='wpIgnoreWarning' value='true' $warningChecked/>
1178 <label for='wpIgnoreWarning'>" . wfMsgHtml( 'ignorewarnings' ) . "</label>
1179 </td>
1180 </tr>
1181 $warningRow
1182 <tr>
1183 <td></td>
1184 <td class='mw-input'>
1185 <input tabindex='9' type='submit' name='wpUpload' value=\"{$ulb}\"" . $wgUser->getSkin()->tooltipAndAccesskey( 'upload' ) . " />
1186 </td>
1187 </tr>
1188 <tr>
1189 <td></td>
1190 <td class='mw-input'>"
1192 $wgOut->addWikiText( wfMsgForContent( 'edittools' ) );
1193 $wgOut->addHTML( "
1194 </td>
1195 </tr>" .
1196 Xml::closeElement( 'table' ) .
1197 Xml::hidden( 'wpDestFileWarningAck', '', array( 'id' => 'wpDestFileWarningAck' ) ) .
1198 Xml::closeElement( 'fieldset' ) .
1199 Xml::closeElement( 'form' )
1201 $uploadfooter = wfMsgNoTrans( 'uploadfooter' );
1202 if( $uploadfooter != '-' && !wfEmptyMsg( 'uploadfooter', $uploadfooter ) ){
1203 $wgOut->addWikiText( Xml::tags( 'div',
1204 array( 'id' => 'mw-upload-footer-message' ), $uploadfooter ) );
1208 /* -------------------------------------------------------------- */
1211 * See if we should check the 'watch this page' checkbox on the form
1212 * based on the user's preferences and whether we're being asked
1213 * to create a new file or update an existing one.
1215 * In the case where 'watch edits' is off but 'watch creations' is on,
1216 * we'll leave the box unchecked.
1218 * Note that the page target can be changed *on the form*, so our check
1219 * state can get out of sync.
1221 function watchCheck() {
1222 global $wgUser;
1223 if( $wgUser->getOption( 'watchdefault' ) ) {
1224 // Watch all edits!
1225 return true;
1228 $local = wfLocalFile( $this->mDesiredDestName );
1229 if( $local && $local->exists() ) {
1230 // We're uploading a new version of an existing file.
1231 // No creation, so don't watch it if we're not already.
1232 return $local->getTitle()->userIsWatching();
1233 } else {
1234 // New page should get watched if that's our option.
1235 return $wgUser->getOption( 'watchcreations' );
1240 * Split a file into a base name and all dot-delimited 'extensions'
1241 * on the end. Some web server configurations will fall back to
1242 * earlier pseudo-'extensions' to determine type and execute
1243 * scripts, so the blacklist needs to check them all.
1245 * @return array
1247 function splitExtensions( $filename ) {
1248 $bits = explode( '.', $filename );
1249 $basename = array_shift( $bits );
1250 return array( $basename, $bits );
1254 * Perform case-insensitive match against a list of file extensions.
1255 * Returns true if the extension is in the list.
1257 * @param string $ext
1258 * @param array $list
1259 * @return bool
1261 function checkFileExtension( $ext, $list ) {
1262 return in_array( strtolower( $ext ), $list );
1266 * Perform case-insensitive match against a list of file extensions.
1267 * Returns true if any of the extensions are in the list.
1269 * @param array $ext
1270 * @param array $list
1271 * @return bool
1273 function checkFileExtensionList( $ext, $list ) {
1274 foreach( $ext as $e ) {
1275 if( in_array( strtolower( $e ), $list ) ) {
1276 return true;
1279 return false;
1283 * Verifies that it's ok to include the uploaded file
1285 * @param string $tmpfile the full path of the temporary file to verify
1286 * @param string $extension The filename extension that the file is to be served with
1287 * @return mixed true of the file is verified, a WikiError object otherwise.
1289 function verify( $tmpfile, $extension ) {
1290 #magically determine mime type
1291 $magic = MimeMagic::singleton();
1292 $mime = $magic->guessMimeType($tmpfile,false);
1294 #check mime type, if desired
1295 global $wgVerifyMimeType;
1296 if ($wgVerifyMimeType) {
1298 wfDebug ( "\n\nmime: <$mime> extension: <$extension>\n\n");
1299 #check mime type against file extension
1300 if( !$this->verifyExtension( $mime, $extension ) ) {
1301 return new WikiErrorMsg( 'uploadcorrupt' );
1304 #check mime type blacklist
1305 global $wgMimeTypeBlacklist;
1306 if( isset($wgMimeTypeBlacklist) && !is_null($wgMimeTypeBlacklist)
1307 && $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
1308 return new WikiErrorMsg( 'filetype-badmime', htmlspecialchars( $mime ) );
1312 #check for htmlish code and javascript
1313 if( $this->detectScript ( $tmpfile, $mime, $extension ) ) {
1314 return new WikiErrorMsg( 'uploadscripted' );
1318 * Scan the uploaded file for viruses
1320 $virus= $this->detectVirus($tmpfile);
1321 if ( $virus ) {
1322 return new WikiErrorMsg( 'uploadvirus', htmlspecialchars($virus) );
1325 wfDebug( __METHOD__.": all clear; passing.\n" );
1326 return true;
1330 * Checks if the mime type of the uploaded file matches the file extension.
1332 * @param string $mime the mime type of the uploaded file
1333 * @param string $extension The filename extension that the file is to be served with
1334 * @return bool
1336 function verifyExtension( $mime, $extension ) {
1337 $magic = MimeMagic::singleton();
1339 if ( ! $mime || $mime == 'unknown' || $mime == 'unknown/unknown' )
1340 if ( ! $magic->isRecognizableExtension( $extension ) ) {
1341 wfDebug( __METHOD__.": passing file with unknown detected mime type; " .
1342 "unrecognized extension '$extension', can't verify\n" );
1343 return true;
1344 } else {
1345 wfDebug( __METHOD__.": rejecting file with unknown detected mime type; ".
1346 "recognized extension '$extension', so probably invalid file\n" );
1347 return false;
1350 $match= $magic->isMatchingExtension($extension,$mime);
1352 if ($match===NULL) {
1353 wfDebug( __METHOD__.": no file extension known for mime type $mime, passing file\n" );
1354 return true;
1355 } elseif ($match===true) {
1356 wfDebug( __METHOD__.": mime type $mime matches extension $extension, passing file\n" );
1358 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
1359 return true;
1361 } else {
1362 wfDebug( __METHOD__.": mime type $mime mismatches file extension $extension, rejecting file\n" );
1363 return false;
1368 * Heuristic for detecting files that *could* contain JavaScript instructions or
1369 * things that may look like HTML to a browser and are thus
1370 * potentially harmful. The present implementation will produce false positives in some situations.
1372 * @param string $file Pathname to the temporary upload file
1373 * @param string $mime The mime type of the file
1374 * @param string $extension The extension of the file
1375 * @return bool true if the file contains something looking like embedded scripts
1377 function detectScript($file, $mime, $extension) {
1378 global $wgAllowTitlesInSVG;
1380 #ugly hack: for text files, always look at the entire file.
1381 #For binarie field, just check the first K.
1383 if (strpos($mime,'text/')===0) $chunk = file_get_contents( $file );
1384 else {
1385 $fp = fopen( $file, 'rb' );
1386 $chunk = fread( $fp, 1024 );
1387 fclose( $fp );
1390 $chunk= strtolower( $chunk );
1392 if (!$chunk) return false;
1394 #decode from UTF-16 if needed (could be used for obfuscation).
1395 if (substr($chunk,0,2)=="\xfe\xff") $enc= "UTF-16BE";
1396 elseif (substr($chunk,0,2)=="\xff\xfe") $enc= "UTF-16LE";
1397 else $enc= NULL;
1399 if ($enc) $chunk= iconv($enc,"ASCII//IGNORE",$chunk);
1401 $chunk= trim($chunk);
1403 #FIXME: convert from UTF-16 if necessarry!
1405 wfDebug("SpecialUpload::detectScript: checking for embedded scripts and HTML stuff\n");
1407 #check for HTML doctype
1408 if (eregi("<!DOCTYPE *X?HTML",$chunk)) return true;
1411 * Internet Explorer for Windows performs some really stupid file type
1412 * autodetection which can cause it to interpret valid image files as HTML
1413 * and potentially execute JavaScript, creating a cross-site scripting
1414 * attack vectors.
1416 * Apple's Safari browser also performs some unsafe file type autodetection
1417 * which can cause legitimate files to be interpreted as HTML if the
1418 * web server is not correctly configured to send the right content-type
1419 * (or if you're really uploading plain text and octet streams!)
1421 * Returns true if IE is likely to mistake the given file for HTML.
1422 * Also returns true if Safari would mistake the given file for HTML
1423 * when served with a generic content-type.
1426 $tags = array(
1427 '<body',
1428 '<head',
1429 '<html', #also in safari
1430 '<img',
1431 '<pre',
1432 '<script', #also in safari
1433 '<table'
1435 if( ! $wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
1436 $tags[] = '<title';
1439 foreach( $tags as $tag ) {
1440 if( false !== strpos( $chunk, $tag ) ) {
1441 return true;
1446 * look for javascript
1449 #resolve entity-refs to look at attributes. may be harsh on big files... cache result?
1450 $chunk = Sanitizer::decodeCharReferences( $chunk );
1452 #look for script-types
1453 if (preg_match('!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim',$chunk)) return true;
1455 #look for html-style script-urls
1456 if (preg_match('!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim',$chunk)) return true;
1458 #look for css-style script-urls
1459 if (preg_match('!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim',$chunk)) return true;
1461 wfDebug("SpecialUpload::detectScript: no scripts found\n");
1462 return false;
1466 * Generic wrapper function for a virus scanner program.
1467 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
1468 * $wgAntivirusRequired may be used to deny upload if the scan fails.
1470 * @param string $file Pathname to the temporary upload file
1471 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
1472 * or a string containing feedback from the virus scanner if a virus was found.
1473 * If textual feedback is missing but a virus was found, this function returns true.
1475 function detectVirus($file) {
1476 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
1478 if ( !$wgAntivirus ) {
1479 wfDebug( __METHOD__.": virus scanner disabled\n");
1480 return NULL;
1483 if ( !$wgAntivirusSetup[$wgAntivirus] ) {
1484 wfDebug( __METHOD__.": unknown virus scanner: $wgAntivirus\n" );
1485 # @TODO: localise
1486 $wgOut->addHTML( "<div class='error'>Bad configuration: unknown virus scanner: <i>$wgAntivirus</i></div>\n" );
1487 return "unknown antivirus: $wgAntivirus";
1490 # look up scanner configuration
1491 $command = $wgAntivirusSetup[$wgAntivirus]["command"];
1492 $exitCodeMap = $wgAntivirusSetup[$wgAntivirus]["codemap"];
1493 $msgPattern = isset( $wgAntivirusSetup[$wgAntivirus]["messagepattern"] ) ?
1494 $wgAntivirusSetup[$wgAntivirus]["messagepattern"] : null;
1496 if ( strpos( $command,"%f" ) === false ) {
1497 # simple pattern: append file to scan
1498 $command .= " " . wfEscapeShellArg( $file );
1499 } else {
1500 # complex pattern: replace "%f" with file to scan
1501 $command = str_replace( "%f", wfEscapeShellArg( $file ), $command );
1504 wfDebug( __METHOD__.": running virus scan: $command \n" );
1506 # execute virus scanner
1507 $exitCode = false;
1509 #NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
1510 # that does not seem to be worth the pain.
1511 # Ask me (Duesentrieb) about it if it's ever needed.
1512 $output = array();
1513 if ( wfIsWindows() ) {
1514 exec( "$command", $output, $exitCode );
1515 } else {
1516 exec( "$command 2>&1", $output, $exitCode );
1519 # map exit code to AV_xxx constants.
1520 $mappedCode = $exitCode;
1521 if ( $exitCodeMap ) {
1522 if ( isset( $exitCodeMap[$exitCode] ) ) {
1523 $mappedCode = $exitCodeMap[$exitCode];
1524 } elseif ( isset( $exitCodeMap["*"] ) ) {
1525 $mappedCode = $exitCodeMap["*"];
1529 if ( $mappedCode === AV_SCAN_FAILED ) {
1530 # scan failed (code was mapped to false by $exitCodeMap)
1531 wfDebug( __METHOD__.": failed to scan $file (code $exitCode).\n" );
1533 if ( $wgAntivirusRequired ) {
1534 return "scan failed (code $exitCode)";
1535 } else {
1536 return NULL;
1538 } else if ( $mappedCode === AV_SCAN_ABORTED ) {
1539 # scan failed because filetype is unknown (probably imune)
1540 wfDebug( __METHOD__.": unsupported file type $file (code $exitCode).\n" );
1541 return NULL;
1542 } else if ( $mappedCode === AV_NO_VIRUS ) {
1543 # no virus found
1544 wfDebug( __METHOD__.": file passed virus scan.\n" );
1545 return false;
1546 } else {
1547 $output = join( "\n", $output );
1548 $output = trim( $output );
1550 if ( !$output ) {
1551 $output = true; #if there's no output, return true
1552 } elseif ( $msgPattern ) {
1553 $groups = array();
1554 if ( preg_match( $msgPattern, $output, $groups ) ) {
1555 if ( $groups[1] ) {
1556 $output = $groups[1];
1561 wfDebug( __METHOD__.": FOUND VIRUS! scanner feedback: $output" );
1562 return $output;
1567 * Check if the temporary file is MacBinary-encoded, as some uploads
1568 * from Internet Explorer on Mac OS Classic and Mac OS X will be.
1569 * If so, the data fork will be extracted to a second temporary file,
1570 * which will then be checked for validity and either kept or discarded.
1572 * @access private
1574 function checkMacBinary() {
1575 $macbin = new MacBinary( $this->mTempPath );
1576 if( $macbin->isValid() ) {
1577 $dataFile = tempnam( wfTempDir(), "WikiMacBinary" );
1578 $dataHandle = fopen( $dataFile, 'wb' );
1580 wfDebug( "SpecialUpload::checkMacBinary: Extracting MacBinary data fork to $dataFile\n" );
1581 $macbin->extractData( $dataHandle );
1583 $this->mTempPath = $dataFile;
1584 $this->mFileSize = $macbin->dataForkLength();
1586 // We'll have to manually remove the new file if it's not kept.
1587 $this->mRemoveTempFile = true;
1589 $macbin->close();
1593 * If we've modified the upload file we need to manually remove it
1594 * on exit to clean up.
1595 * @access private
1597 function cleanupTempFile() {
1598 if ( $this->mRemoveTempFile && file_exists( $this->mTempPath ) ) {
1599 wfDebug( "SpecialUpload::cleanupTempFile: Removing temporary file {$this->mTempPath}\n" );
1600 unlink( $this->mTempPath );
1605 * Check if there's an overwrite conflict and, if so, if restrictions
1606 * forbid this user from performing the upload.
1608 * @return mixed true on success, WikiError on failure
1609 * @access private
1611 function checkOverwrite( $name ) {
1612 $img = wfFindFile( $name );
1614 $error = '';
1615 if( $img ) {
1616 global $wgUser, $wgOut;
1617 if( $img->isLocal() ) {
1618 if( !self::userCanReUpload( $wgUser, $img->name ) ) {
1619 $error = 'fileexists-forbidden';
1621 } else {
1622 if( !$wgUser->isAllowed( 'reupload' ) ||
1623 !$wgUser->isAllowed( 'reupload-shared' ) ) {
1624 $error = "fileexists-shared-forbidden";
1629 if( $error ) {
1630 $errorText = wfMsg( $error, wfEscapeWikiText( $img->getName() ) );
1631 return $errorText;
1634 // Rockin', go ahead and upload
1635 return true;
1639 * Check if a user is the last uploader
1641 * @param User $user
1642 * @param string $img, image name
1643 * @return bool
1645 public static function userCanReUpload( User $user, $img ) {
1646 if( $user->isAllowed( 'reupload' ) )
1647 return true; // non-conditional
1648 if( !$user->isAllowed( 'reupload-own' ) )
1649 return false;
1651 $dbr = wfGetDB( DB_SLAVE );
1652 $row = $dbr->selectRow('image',
1653 /* SELECT */ 'img_user',
1654 /* WHERE */ array( 'img_name' => $img )
1656 if ( !$row )
1657 return false;
1659 return $user->getId() == $row->img_user;
1663 * Display an error with a wikitext description
1665 function showError( $description ) {
1666 global $wgOut;
1667 $wgOut->setPageTitle( wfMsg( "internalerror" ) );
1668 $wgOut->setRobotpolicy( "noindex,nofollow" );
1669 $wgOut->setArticleRelated( false );
1670 $wgOut->enableClientCache( false );
1671 $wgOut->addWikiText( $description );
1675 * Get the initial image page text based on a comment and optional file status information
1677 static function getInitialPageText( $comment, $license, $copyStatus, $source ) {
1678 global $wgUseCopyrightUpload;
1679 if ( $wgUseCopyrightUpload ) {
1680 if ( $license != '' ) {
1681 $licensetxt = '== ' . wfMsgForContent( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1683 $pageText = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $comment . "\n" .
1684 '== ' . wfMsgForContent ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
1685 "$licensetxt" .
1686 '== ' . wfMsgForContent ( 'filesource' ) . " ==\n" . $source ;
1687 } else {
1688 if ( $license != '' ) {
1689 $filedesc = $comment == '' ? '' : '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $comment . "\n";
1690 $pageText = $filedesc .
1691 '== ' . wfMsgForContent ( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1692 } else {
1693 $pageText = $comment;
1696 return $pageText;
1700 * If there are rows in the deletion log for this file, show them,
1701 * along with a nice little note for the user
1703 * @param OutputPage $out
1704 * @param string filename
1706 private function showDeletionLog( $out, $filename ) {
1707 global $wgUser;
1708 $loglist = new LogEventsList( $wgUser->getSkin(), $out );
1709 $pager = new LogPager( $loglist, 'delete', false, $filename );
1710 if( $pager->getNumRows() > 0 ) {
1711 $out->addHtml( '<div id="mw-upload-deleted-warn">' );
1712 $out->addWikiMsg( 'upload-wasdeleted' );
1713 $out->addHTML(
1714 $loglist->beginLogEventsList() .
1715 $pager->getBody() .
1716 $loglist->endLogEventsList()
1718 $out->addHtml( '</div>' );