4 * @addtogroup SpecialPage
11 function wfSpecialUpload() {
13 $form = new UploadForm( $wgRequest );
18 * implements Special:Upload
19 * @addtogroup SpecialPage
25 var $mComment, $mLicense, $mIgnoreWarning, $mCurlError;
26 var $mDestName, $mTempPath, $mFileSize, $mFileProps;
27 var $mCopyrightStatus, $mCopyrightSource, $mReUpload, $mAction, $mUploadClicked;
28 var $mSrcName, $mSessionKey, $mStashed, $mDesiredDestName, $mRemoveTempFile, $mSourceType;
29 var $mDestWarningAck, $mCurlDestHandle;
32 # Placeholders for text injection by hooks (must be HTML)
33 # extensions should take care to _append_ to the present value
34 var $uploadFormTextTop;
35 var $uploadFormTextAfterSummary;
37 const SESSION_VERSION
= 1;
41 * Constructor : initialise object
42 * Get data POSTed through the form and assign them to the object
43 * @param $request Data posted.
45 function UploadForm( &$request ) {
46 global $wgAllowCopyUploads;
47 $this->mDesiredDestName
= $request->getText( 'wpDestFile' );
48 $this->mIgnoreWarning
= $request->getCheck( 'wpIgnoreWarning' );
50 if( !$request->wasPosted() ) {
51 # GET requests just give the main form; no data except wpDestfile.
55 # Placeholders for text injection by hooks (empty per default)
56 $this->uploadFormTextTop
= "";
57 $this->uploadFormTextAfterSummary
= "";
59 $this->mReUpload
= $request->getCheck( 'wpReUpload' );
60 $this->mUploadClicked
= $request->getCheck( 'wpUpload' );
62 $this->mComment
= $request->getText( 'wpUploadDescription' );
63 $this->mLicense
= $request->getText( 'wpLicense' );
64 $this->mCopyrightStatus
= $request->getText( 'wpUploadCopyStatus' );
65 $this->mCopyrightSource
= $request->getText( 'wpUploadSource' );
66 $this->mWatchthis
= $request->getBool( 'wpWatchthis' );
67 $this->mSourceType
= $request->getText( 'wpSourceType' );
68 $this->mDestWarningAck
= $request->getText( 'wpDestFileWarningAck' );
70 $this->mAction
= $request->getVal( 'action' );
72 $this->mSessionKey
= $request->getInt( 'wpSessionKey' );
73 if( !empty( $this->mSessionKey
) &&
74 isset( $_SESSION['wsUploadData'][$this->mSessionKey
]['version'] ) &&
75 $_SESSION['wsUploadData'][$this->mSessionKey
]['version'] == self
::SESSION_VERSION
) {
77 * Confirming a temporarily stashed upload.
78 * We don't want path names to be forged, so we keep
79 * them in the session on the server and just give
80 * an opaque key to the user agent.
82 $data = $_SESSION['wsUploadData'][$this->mSessionKey
];
83 $this->mTempPath
= $data['mTempPath'];
84 $this->mFileSize
= $data['mFileSize'];
85 $this->mSrcName
= $data['mSrcName'];
86 $this->mFileProps
= $data['mFileProps'];
87 $this->mCurlError
= 0/*UPLOAD_ERR_OK*/;
88 $this->mStashed
= true;
89 $this->mRemoveTempFile
= false;
92 *Check for a newly uploaded file.
94 if( $wgAllowCopyUploads && $this->mSourceType
== 'web' ) {
95 $this->initializeFromUrl( $request );
97 $this->initializeFromUpload( $request );
103 * Initialize the uploaded file from PHP data
106 function initializeFromUpload( $request ) {
107 $this->mTempPath
= $request->getFileTempName( 'wpUploadFile' );
108 $this->mFileSize
= $request->getFileSize( 'wpUploadFile' );
109 $this->mSrcName
= $request->getFileName( 'wpUploadFile' );
110 $this->mCurlError
= $request->getUploadError( 'wpUploadFile' );
111 $this->mSessionKey
= false;
112 $this->mStashed
= false;
113 $this->mRemoveTempFile
= false; // PHP will handle this
117 * Copy a web file to a temporary file
120 function initializeFromUrl( $request ) {
121 global $wgTmpDirectory;
122 $url = $request->getText( 'wpUploadFileURL' );
123 $local_file = tempnam( $wgTmpDirectory, 'WEBUPLOAD' );
125 $this->mTempPath
= $local_file;
126 $this->mFileSize
= 0; # Will be set by curlCopy
127 $this->mCurlError
= $this->curlCopy( $url, $local_file );
128 $this->mSrcName
= array_pop( explode( '/', $url ) );
129 $this->mSessionKey
= false;
130 $this->mStashed
= false;
132 // PHP won't auto-cleanup the file
133 $this->mRemoveTempFile
= file_exists( $local_file );
138 * Returns true if there was an error, false otherwise
140 private function curlCopy( $url, $dest ) {
141 global $wgUser, $wgOut;
143 if( !$wgUser->isAllowed( 'upload_by_url' ) ) {
144 $wgOut->permissionRequired( 'upload_by_url' );
148 # Maybe remove some pasting blanks :-)
150 if( stripos($url, 'http://') !== 0 && stripos($url, 'ftp://') !== 0 ) {
151 # Only HTTP or FTP URLs
152 $wgOut->errorPage( 'upload-proto-error', 'upload-proto-error-text' );
156 # Open temporary file
157 $this->mCurlDestHandle
= @fopen
( $this->mTempPath
, "wb" );
158 if( $this->mCurlDestHandle
=== false ) {
159 # Could not open temporary file to write in
160 $wgOut->errorPage( 'upload-file-error', 'upload-file-error-text');
165 curl_setopt( $ch, CURLOPT_HTTP_VERSION
, 1.0); # Probably not needed, but apparently can work around some bug
166 curl_setopt( $ch, CURLOPT_TIMEOUT
, 10); # 10 seconds timeout
167 curl_setopt( $ch, CURLOPT_LOW_SPEED_LIMIT
, 512); # 0.5KB per second minimum transfer speed
168 curl_setopt( $ch, CURLOPT_URL
, $url);
169 curl_setopt( $ch, CURLOPT_WRITEFUNCTION
, array( $this, 'uploadCurlCallback' ) );
171 $error = curl_errno( $ch ) ?
true : false;
172 $errornum = curl_errno( $ch );
173 // if ( $error ) print curl_error ( $ch ) ; # Debugging output
176 fclose( $this->mCurlDestHandle
);
177 unset( $this->mCurlDestHandle
);
180 if( wfEmptyMsg( "upload-curl-error$errornum", wfMsg("upload-curl-error$errornum") ) )
181 $wgOut->errorPage( 'upload-misc-error', 'upload-misc-error-text' );
183 $wgOut->errorPage( "upload-curl-error$errornum", "upload-curl-error$errornum-text" );
190 * Callback function for CURL-based web transfer
191 * Write data to file unless we've passed the length limit;
192 * if so, abort immediately.
195 function uploadCurlCallback( $ch, $data ) {
196 global $wgMaxUploadSize;
197 $length = strlen( $data );
198 $this->mFileSize +
= $length;
199 if( $this->mFileSize
> $wgMaxUploadSize ) {
202 fwrite( $this->mCurlDestHandle
, $data );
211 global $wgUser, $wgOut;
212 global $wgEnableUploads;
214 # Check uploading enabled
215 if( !$wgEnableUploads ) {
216 $wgOut->showErrorPage( 'uploaddisabled', 'uploaddisabledtext', array( $this->mDesiredDestName
) );
221 if( !$wgUser->isAllowed( 'upload' ) ) {
222 if( !$wgUser->isLoggedIn() ) {
223 $wgOut->showErrorPage( 'uploadnologin', 'uploadnologintext' );
225 $wgOut->permissionRequired( 'upload' );
231 if( $wgUser->isBlocked() ) {
232 $wgOut->blockedPage();
237 $wgOut->readOnlyPage();
241 if( $this->mReUpload
) {
242 if( !$this->unsaveUploadedFile() ) {
245 $this->mainUploadForm();
246 } else if( 'submit' == $this->mAction ||
$this->mUploadClicked
) {
247 $this->processUpload();
249 $this->mainUploadForm();
252 $this->cleanupTempFile();
255 /* -------------------------------------------------------------- */
258 * Really do the upload
259 * Checks are made in SpecialUpload::execute()
262 function processUpload() {
263 global $wgUser, $wgOut;
265 if( !wfRunHooks( 'UploadForm:BeforeProcessing', array( &$this ) ) )
267 wfDebug( "Hook 'UploadForm:BeforeProcessing' broke processing the file." );
271 /* Check for PHP error if any, requires php 4.2 or newer */
272 if( $this->mCurlError
== 1/*UPLOAD_ERR_INI_SIZE*/ ) {
273 $this->mainUploadForm( wfMsgHtml( 'largefileserver' ) );
278 * If there was no filename or a zero size given, give up quick.
280 if( trim( $this->mSrcName
) == '' ||
empty( $this->mFileSize
) ) {
281 $this->mainUploadForm( wfMsgHtml( 'emptyfile' ) );
285 # Chop off any directories in the given filename
286 if( $this->mDesiredDestName
) {
287 $basename = wfBaseName( $this->mDesiredDestName
);
289 $basename = wfBaseName( $this->mSrcName
);
293 * We'll want to blacklist against *any* 'extension', and use
294 * only the final one for the whitelist.
296 list( $partname, $ext ) = $this->splitExtensions( $basename );
298 if( count( $ext ) ) {
299 $finalExt = $ext[count( $ext ) - 1];
304 # If there was more than one "extension", reassemble the base
305 # filename to prevent bogus complaints about length
306 if( count( $ext ) > 1 ) {
307 for( $i = 0; $i < count( $ext ) - 1; $i++
)
308 $partname .= '.' . $ext[$i];
311 if( strlen( $partname ) < 1 ) {
312 $this->mainUploadForm( wfMsgHtml( 'minlength1' ) );
317 * Filter out illegal characters, and try to make a legible name
318 * out of it. We'll strip some silently that Title would die on.
320 $filtered = preg_replace ( "/[^".Title
::legalChars()."]|:/", '-', $basename );
321 $nt = Title
::makeTitleSafe( NS_IMAGE
, $filtered );
322 if( is_null( $nt ) ) {
323 $this->uploadError( wfMsgWikiHtml( 'illegalfilename', htmlspecialchars( $filtered ) ) );
326 $this->mLocalFile
= wfLocalFile( $nt );
327 $this->mDestName
= $this->mLocalFile
->getName();
330 * If the image is protected, non-sysop users won't be able
331 * to modify it by uploading a new revision.
333 if( !$nt->userCan( 'edit' ) ) {
334 return $this->uploadError( wfMsgWikiHtml( 'protectedpage' ) );
338 * In some cases we may forbid overwriting of existing files.
340 $overwrite = $this->checkOverwrite( $this->mDestName
);
341 if( WikiError
::isError( $overwrite ) ) {
342 return $this->uploadError( $overwrite->toString() );
345 /* Don't allow users to override the blacklist (check file extension) */
346 global $wgStrictFileExtensions;
347 global $wgFileExtensions, $wgFileBlacklist;
348 if ($finalExt == '') {
349 return $this->uploadError( wfMsgExt( 'filetype-missing', array ( 'parseinline' ) ) );
350 } elseif ( $this->checkFileExtensionList( $ext, $wgFileBlacklist ) ||
351 ($wgStrictFileExtensions && !$this->checkFileExtension( $finalExt, $wgFileExtensions ) ) ) {
352 return $this->uploadError( wfMsgExt( 'filetype-badtype', array ( 'parseinline' ),
353 htmlspecialchars( $finalExt ), implode ( ', ', $wgFileExtensions ) ) );
357 * Look at the contents of the file; if we can recognize the
358 * type but it's corrupt or data of the wrong type, we should
359 * probably not accept it.
361 if( !$this->mStashed
) {
362 $this->mFileProps
= File
::getPropsFromPath( $this->mTempPath
, $finalExt );
363 $this->checkMacBinary();
364 $veri = $this->verify( $this->mTempPath
, $finalExt );
366 if( $veri !== true ) { //it's a wiki error...
367 return $this->uploadError( $veri->toString() );
371 * Provide an opportunity for extensions to add futher checks
374 if( !wfRunHooks( 'UploadVerification',
375 array( $this->mDestName
, $this->mTempPath
, &$error ) ) ) {
376 return $this->uploadError( $error );
382 * Check for non-fatal conditions
384 if ( ! $this->mIgnoreWarning
) {
387 global $wgCapitalLinks;
388 if( $wgCapitalLinks ) {
389 $filtered = ucfirst( $filtered );
391 if( $this->mDestName
!= $filtered ) {
392 $warning .= '<li>'.wfMsgHtml( 'badfilename', htmlspecialchars( $this->mDestName
) ).'</li>';
395 global $wgCheckFileExtensions;
396 if ( $wgCheckFileExtensions ) {
397 if ( ! $this->checkFileExtension( $finalExt, $wgFileExtensions ) ) {
398 $warning .= '<li>'.wfMsgExt( 'filetype-badtype', array ( 'parseinline' ),
399 htmlspecialchars( $finalExt ), implode ( ', ', $wgFileExtensions ) ).'</li>';
403 global $wgUploadSizeWarning;
404 if ( $wgUploadSizeWarning && ( $this->mFileSize
> $wgUploadSizeWarning ) ) {
405 $skin = $wgUser->getSkin();
406 $wsize = $skin->formatSize( $wgUploadSizeWarning );
407 $asize = $skin->formatSize( $this->mFileSize
);
408 $warning .= '<li>' . wfMsgHtml( 'large-file', $wsize, $asize ) . '</li>';
410 if ( $this->mFileSize
== 0 ) {
411 $warning .= '<li>'.wfMsgHtml( 'emptyfile' ).'</li>';
414 if ( !$this->mDestWarningAck
) {
415 $warning .= self
::getExistsWarning( $this->mLocalFile
);
417 if( $warning != '' ) {
419 * Stash the file in a temporary location; the user can choose
420 * to let it through and we'll complete the upload then.
422 return $this->uploadWarning( $warning );
427 * Try actually saving the thing...
428 * It will show an error form on failure.
430 $pageText = self
::getInitialPageText( $this->mComment
, $this->mLicense
,
431 $this->mCopyrightStatus
, $this->mCopyrightSource
);
433 $status = $this->mLocalFile
->upload( $this->mTempPath
, $this->mComment
, $pageText,
434 File
::DELETE_SOURCE
, $this->mFileProps
);
435 if ( WikiError
::isError( $status ) ) {
436 $this->showError( $status );
438 if ( $this->mWatchthis
) {
440 $wgUser->addWatch( $this->mLocalFile
->getTitle() );
442 // Success, redirect to description page
443 $wgOut->redirect( $this->mLocalFile
->getTitle()->getFullURL() );
444 wfRunHooks( 'UploadComplete', array( &$img ) );
449 * Do existence checks on a file and produce a warning
450 * This check is static and can be done pre-upload via AJAX
451 * Returns an HTML fragment consisting of one or more LI elements if there is a warning
452 * Returns an empty string if there is no warning
454 static function getExistsWarning( $file ) {
456 // Check for uppercase extension. We allow these filenames but check if an image
457 // with lowercase extension exists already
459 $ext = $file->getExtension();
460 $sk = $wgUser->getSkin();
462 $partname = substr( $file->getName(), 0, -strlen( $ext ) - 1 );
464 $partname = $file->getName();
467 if ( $ext != strtolower( $ext ) ) {
468 $nt_lc = Title
::newFromText( $partname . '.' . strtolower( $ext ) );
469 $file_lc = wfLocalFile( $nt_lc );
474 if( $file->exists() ) {
475 $dlink = $sk->makeKnownLinkObj( $file->getTitle() );
476 if ( $file->allowInlineDisplay() ) {
477 $dlink2 = $sk->makeImageLinkObj( $file->getTitle(), wfMsgExt( 'fileexists-thumb', 'parseinline', $dlink ),
478 $file->getName(), 'right', array(), false, true );
479 } elseif ( !$file->allowInlineDisplay() && $file->isSafeFile() ) {
480 $icon = $file->iconThumb();
481 $dlink2 = '<div style="float:right" id="mw-media-icon"><a href="' . $file->getURL() . '">' .
482 $icon->toHtml() . '</a><br />' . $dlink . '</div>';
487 $warning .= '<li>' . wfMsgExt( 'fileexists', 'parseline', $dlink ) . '</li>' . $dlink2;
489 } elseif ( $file_lc && $file_lc->exists() ) {
490 # Check if image with lowercase extension exists.
491 # It's not forbidden but in 99% it makes no sense to upload the same filename with uppercase extension
492 $dlink = $sk->makeKnownLinkObj( $nt_lc );
493 if ( $file_lc->allowInlineDisplay() ) {
494 $dlink2 = $sk->makeImageLinkObj( $nt_lc, wfMsgExt( 'fileexists-thumb', 'parseinline', $dlink ),
495 $nt_lc->getText(), 'right', array(), false, true );
496 } elseif ( !$file_lc->allowInlineDisplay() && $file_lc->isSafeFile() ) {
497 $icon = $file_lc->iconThumb();
498 $dlink2 = '<div style="float:right" id="mw-media-icon"><a href="' . $file_lc->getURL() . '">' .
499 $icon->toHtml() . '</a><br />' . $dlink . '</div>';
504 $warning .= '<li>' . wfMsgExt( 'fileexists-extension', 'parsemag' , $partname . '.'
505 . $ext , $dlink ) . '</li>' . $dlink2;
507 } elseif ( ( substr( $partname , 3, 3 ) == 'px-' ||
substr( $partname , 2, 3 ) == 'px-' )
508 && ereg( "[0-9]{2}" , substr( $partname , 0, 2) ) )
510 # Check for filenames like 50px- or 180px-, these are mostly thumbnails
511 $nt_thb = Title
::newFromText( substr( $partname , strpos( $partname , '-' ) +
1 ) . '.' . $ext );
512 $file_thb = wfLocalFile( $nt_thb );
513 if ($file_thb->exists() ) {
514 # Check if an image without leading '180px-' (or similiar) exists
515 $dlink = $sk->makeKnownLinkObj( $nt_thb);
516 if ( $file_thb->allowInlineDisplay() ) {
517 $dlink2 = $sk->makeImageLinkObj( $nt_thb,
518 wfMsgExt( 'fileexists-thumb', 'parseinline', $dlink ),
519 $nt_thb->getText(), 'right', array(), false, true );
520 } elseif ( !$file_thb->allowInlineDisplay() && $file_thb->isSafeFile() ) {
521 $icon = $file_thb->iconThumb();
522 $dlink2 = '<div style="float:right" id="mw-media-icon"><a href="' .
523 $file_thb->getURL() . '">' . $icon->toHtml() . '</a><br />' .
529 $warning .= '<li>' . wfMsgExt( 'fileexists-thumbnail-yes', 'parsemag', $dlink ) .
532 # Image w/o '180px-' does not exists, but we do not like these filenames
533 $warning .= '<li>' . wfMsgExt( 'file-thumbnail-no', 'parseinline' ,
534 substr( $partname , 0, strpos( $partname , '-' ) +
1 ) ) . '</li>';
537 if ( $file->wasDeleted() ) {
538 # If the file existed before and was deleted, warn the user of this
539 # Don't bother doing so if the image exists now, however
540 $ltitle = SpecialPage
::getTitleFor( 'Log' );
541 $llink = $sk->makeKnownLinkObj( $ltitle, wfMsgHtml( 'deletionlog' ),
542 'type=delete&page=' . $file->getTitle()->getPrefixedUrl() );
543 $warning .= '<li>' . wfMsgWikiHtml( 'filewasdeleted', $llink ) . '</li>';
548 static function ajaxGetExistsWarning( $filename ) {
549 $file = wfFindFile( $filename );
552 $warning = self
::getExistsWarning( $file );
553 if ( $warning !== '' ) {
554 $s = "<ul>$warning</ul>";
561 * Stash a file in a temporary directory for later processing
562 * after the user has confirmed it.
564 * If the user doesn't explicitly cancel or accept, these files
565 * can accumulate in the temp directory.
567 * @param string $saveName - the destination filename
568 * @param string $tempName - the source temporary file to save
569 * @return string - full path the stashed file, or false on failure
572 function saveTempUploadedFile( $saveName, $tempName ) {
574 $repo = RepoGroup
::singleton()->getLocalRepo();
575 $result = $repo->storeTemp( $saveName, $tempName );
576 if ( WikiError
::isError( $result ) ) {
577 $this->showError( $result );
585 * Stash a file in a temporary directory for later processing,
586 * and save the necessary descriptive info into the session.
587 * Returns a key value which will be passed through a form
588 * to pick up the path info on a later invocation.
593 function stashSession() {
594 $stash = $this->saveTempUploadedFile( $this->mDestName
, $this->mTempPath
);
597 # Couldn't save the file.
601 $key = mt_rand( 0, 0x7fffffff );
602 $_SESSION['wsUploadData'][$key] = array(
603 'mTempPath' => $stash,
604 'mFileSize' => $this->mFileSize
,
605 'mSrcName' => $this->mSrcName
,
606 'mFileProps' => $this->mFileProps
,
607 'version' => self
::SESSION_VERSION
,
613 * Remove a temporarily kept file stashed by saveTempUploadedFile().
617 function unsaveUploadedFile() {
619 $repo = RepoGroup
::singleton()->getLocalRepo();
620 $success = $repo->freeTemp( $this->mTempPath
);
622 $wgOut->showFileDeleteError( $this->mTempPath
);
629 /* -------------------------------------------------------------- */
632 * @param string $error as HTML
635 function uploadError( $error ) {
637 $wgOut->addHTML( "<h2>" . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
638 $wgOut->addHTML( "<span class='error'>{$error}</span>\n" );
642 * There's something wrong with this file, not enough to reject it
643 * totally but we require manual intervention to save it for real.
644 * Stash it away, then present a form asking to confirm or cancel.
646 * @param string $warning as HTML
649 function uploadWarning( $warning ) {
651 global $wgUseCopyrightUpload;
653 $this->mSessionKey
= $this->stashSession();
654 if( !$this->mSessionKey
) {
655 # Couldn't save file; an error has been displayed so let's go.
659 $wgOut->addHTML( "<h2>" . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
660 $wgOut->addHTML( "<ul class='warning'>{$warning}</ul><br />\n" );
662 $save = wfMsgHtml( 'savefile' );
663 $reupload = wfMsgHtml( 'reupload' );
664 $iw = wfMsgWikiHtml( 'ignorewarning' );
665 $reup = wfMsgWikiHtml( 'reuploaddesc' );
666 $titleObj = SpecialPage
::getTitleFor( 'Upload' );
667 $action = $titleObj->escapeLocalURL( 'action=submit' );
669 if ( $wgUseCopyrightUpload )
672 <input type='hidden' name='wpUploadCopyStatus' value=\"" . htmlspecialchars( $this->mCopyrightStatus
) . "\" />
673 <input type='hidden' name='wpUploadSource' value=\"" . htmlspecialchars( $this->mCopyrightSource
) . "\" />
680 <form id='uploadwarning' method='post' enctype='multipart/form-data' action='$action'>
681 <input type='hidden' name='wpIgnoreWarning' value='1' />
682 <input type='hidden' name='wpSessionKey' value=\"" . htmlspecialchars( $this->mSessionKey
) . "\" />
683 <input type='hidden' name='wpUploadDescription' value=\"" . htmlspecialchars( $this->mComment
) . "\" />
684 <input type='hidden' name='wpLicense' value=\"" . htmlspecialchars( $this->mLicense
) . "\" />
685 <input type='hidden' name='wpDestFile' value=\"" . htmlspecialchars( $this->mDesiredDestName
) . "\" />
686 <input type='hidden' name='wpWatchthis' value=\"" . htmlspecialchars( intval( $this->mWatchthis
) ) . "\" />
692 <input tabindex='2' type='submit' name='wpUpload' value=\"$save\" />
694 <td align='left'>$iw</td>
698 <input tabindex='2' type='submit' name='wpReUpload' value=\"{$reupload}\" />
700 <td align='left'>$reup</td>
703 </table></form>\n" );
707 * Displays the main upload form, optionally with a highlighted
708 * error message up at the top.
710 * @param string $msg as HTML
713 function mainUploadForm( $msg='' ) {
714 global $wgOut, $wgUser;
715 global $wgUseCopyrightUpload, $wgAjaxUploadDestCheck, $wgUseAjax;
716 global $wgRequest, $wgAllowCopyUploads, $wgEnableAPI;
719 $useAjax = $wgAjaxUploadDestCheck && $wgUseAjax;
722 "<script type='text/javascript'>wgAjaxUploadDestCheck = " .
723 ($useAjax ?
'true' : 'false' ) . ";</script>\n" .
724 "<script type='text/javascript' src=\"$wgStylePath/common/upload.js?1\"></script>\n"
727 if( !wfRunHooks( 'UploadForm:initial', array( &$this ) ) )
729 wfDebug( "Hook 'UploadForm:initial' broke output of the upload form" );
733 $cols = intval($wgUser->getOption( 'cols' ));
734 $ew = $wgUser->getOption( 'editwidth' );
735 if ( $ew ) $ew = " style=\"width:100%\"";
739 $sub = wfMsgHtml( 'uploaderror' );
740 $wgOut->addHTML( "<h2>{$sub}</h2>\n" .
741 "<span class='error'>{$msg}</span>\n" );
743 $wgOut->addHTML( '<div id="uploadtext">' );
744 $wgOut->addWikiText( wfMsgNoTrans( 'uploadtext', $this->mDesiredDestName
) );
745 $wgOut->addHTML( '</div>' );
747 $sourcefilename = wfMsgHtml( 'sourcefilename' );
748 $destfilename = wfMsgHtml( 'destfilename' );
749 $summary = wfMsgWikiHtml( 'fileuploadsummary' );
751 $licenses = new Licenses();
752 $license = wfMsgExt( 'license', array( 'parseinline' ) );
753 $nolicense = wfMsgHtml( 'nolicense' );
754 $licenseshtml = $licenses->getHtml();
756 $ulb = wfMsgHtml( 'uploadbtn' );
759 $titleObj = SpecialPage
::getTitleFor( 'Upload' );
760 $action = $titleObj->escapeLocalURL();
762 $encDestName = htmlspecialchars( $this->mDesiredDestName
);
765 ( $wgUser->getOption( 'watchdefault' ) ||
766 ( $wgUser->getOption( 'watchcreations' ) && $this->mDesiredDestName
== '' ) )
767 ?
'checked="checked"'
769 $warningChecked = $this->mIgnoreWarning ?
'checked' : '';
771 // Prepare form for upload or upload/copy
772 if( $wgAllowCopyUploads && $wgUser->isAllowed( 'upload_by_url' ) ) {
774 "<input type='radio' id='wpSourceTypeFile' name='wpSourceType' value='file' " .
775 "onchange='toggle_element_activation(\"wpUploadFileURL\",\"wpUploadFile\")' checked />" .
776 "<input tabindex='1' type='file' name='wpUploadFile' id='wpUploadFile' " .
778 "toggle_element_activation(\"wpUploadFileURL\",\"wpUploadFile\");" .
779 "toggle_element_check(\"wpSourceTypeFile\",\"wpSourceTypeURL\")'" .
780 ($this->mDesiredDestName?
"":"onchange='fillDestFilename(\"wpUploadFile\")' ") . "size='40' />" .
781 wfMsgHTML( 'upload_source_file' ) . "<br/>" .
782 "<input type='radio' id='wpSourceTypeURL' name='wpSourceType' value='web' " .
783 "onchange='toggle_element_activation(\"wpUploadFile\",\"wpUploadFileURL\")' />" .
784 "<input tabindex='1' type='text' name='wpUploadFileURL' id='wpUploadFileURL' " .
786 "toggle_element_activation(\"wpUploadFile\",\"wpUploadFileURL\");" .
787 "toggle_element_check(\"wpSourceTypeURL\",\"wpSourceTypeFile\")'" .
788 ($this->mDesiredDestName?
"":"onchange='fillDestFilename(\"wpUploadFileURL\")' ") . "size='40' DISABLED />" .
789 wfMsgHtml( 'upload_source_url' ) ;
792 "<input tabindex='1' type='file' name='wpUploadFile' id='wpUploadFile' " .
793 ($this->mDesiredDestName?
"":"onchange='fillDestFilename(\"wpUploadFile\")' ") .
795 "<input type='hidden' name='wpSourceType' value='file' />" ;
798 $warningRow = "<tr><td colspan='2' id='wpDestFile-warning'> </td></tr>";
799 $destOnkeyup = 'onkeyup="wgUploadWarningObj.keypress();"';
805 $encComment = htmlspecialchars( $this->mComment
);
807 $wgOut->addHTML( <<<EOT
808 <form id='upload' method='post' enctype='multipart/form-data' action="$action">
811 {$this->uploadFormTextTop}
812 <td align='right' valign='top'><label for='wpUploadFile'>{$sourcefilename}:</label></td>
818 <td align='right'><label for='wpDestFile'>{$destfilename}:</label></td>
820 <input tabindex='2' type='text' name='wpDestFile' id='wpDestFile' size='40'
821 value="$encDestName" $destOnkeyup />
825 <td align='right'><label for='wpUploadDescription'>{$summary}</label></td>
827 <textarea tabindex='3' name='wpUploadDescription' id='wpUploadDescription' rows='6'
828 cols='{$cols}'{$ew}>$encComment</textarea>
829 {$this->uploadFormTextAfterSummary}
836 if ( $licenseshtml != '' ) {
839 <td align='right'><label for='wpLicense'>$license:</label></td>
841 <select name='wpLicense' id='wpLicense' tabindex='4'
842 onchange='licenseSelectorCheck()'>
843 <option value=''>$nolicense</option>
852 if ( $wgUseCopyrightUpload ) {
853 $filestatus = wfMsgHtml ( 'filestatus' );
854 $copystatus = htmlspecialchars( $this->mCopyrightStatus
);
855 $filesource = wfMsgHtml ( 'filesource' );
856 $uploadsource = htmlspecialchars( $this->mCopyrightSource
);
859 <td align='right' nowrap='nowrap'><label for='wpUploadCopyStatus'>$filestatus:</label></td>
860 <td><input tabindex='5' type='text' name='wpUploadCopyStatus' id='wpUploadCopyStatus'
861 value=\"$copystatus\" size='40' /></td>
864 <td align='right'><label for='wpUploadCopyStatus'>$filesource:</label></td>
865 <td><input tabindex='6' type='text' name='wpUploadSource' id='wpUploadCopyStatus'
866 value=\"$uploadsource\" size='40' /></td>
875 <input tabindex='7' type='checkbox' name='wpWatchthis' id='wpWatchthis' $watchChecked value='true' />
876 <label for='wpWatchthis'>" . wfMsgHtml( 'watchthisupload' ) . "</label>
877 <input tabindex='8' type='checkbox' name='wpIgnoreWarning' id='wpIgnoreWarning' value='true' $warningChecked/>
878 <label for='wpIgnoreWarning'>" . wfMsgHtml( 'ignorewarnings' ) . "</label>
884 <td align='left'><input tabindex='9' type='submit' name='wpUpload' value=\"{$ulb}\" /></td>
890 $wgOut->addWikiText( wfMsgForContent( 'edittools' ) );
896 <input type='hidden' name='wpDestFileWarningAck' id='wpDestFileWarningAck' value=''/>
900 /* -------------------------------------------------------------- */
903 * Split a file into a base name and all dot-delimited 'extensions'
904 * on the end. Some web server configurations will fall back to
905 * earlier pseudo-'extensions' to determine type and execute
906 * scripts, so the blacklist needs to check them all.
910 function splitExtensions( $filename ) {
911 $bits = explode( '.', $filename );
912 $basename = array_shift( $bits );
913 return array( $basename, $bits );
917 * Perform case-insensitive match against a list of file extensions.
918 * Returns true if the extension is in the list.
924 function checkFileExtension( $ext, $list ) {
925 return in_array( strtolower( $ext ), $list );
929 * Perform case-insensitive match against a list of file extensions.
930 * Returns true if any of the extensions are in the list.
936 function checkFileExtensionList( $ext, $list ) {
937 foreach( $ext as $e ) {
938 if( in_array( strtolower( $e ), $list ) ) {
946 * Verifies that it's ok to include the uploaded file
948 * @param string $tmpfile the full path of the temporary file to verify
949 * @param string $extension The filename extension that the file is to be served with
950 * @return mixed true of the file is verified, a WikiError object otherwise.
952 function verify( $tmpfile, $extension ) {
953 #magically determine mime type
954 $magic=& MimeMagic
::singleton();
955 $mime= $magic->guessMimeType($tmpfile,false);
957 #check mime type, if desired
958 global $wgVerifyMimeType;
959 if ($wgVerifyMimeType) {
961 #check mime type against file extension
962 if( !$this->verifyExtension( $mime, $extension ) ) {
963 return new WikiErrorMsg( 'uploadcorrupt' );
966 #check mime type blacklist
967 global $wgMimeTypeBlacklist;
968 if( isset($wgMimeTypeBlacklist) && !is_null($wgMimeTypeBlacklist)
969 && $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
970 return new WikiErrorMsg( 'filetype-badmime', htmlspecialchars( $mime ) );
974 #check for htmlish code and javascript
975 if( $this->detectScript ( $tmpfile, $mime, $extension ) ) {
976 return new WikiErrorMsg( 'uploadscripted' );
980 * Scan the uploaded file for viruses
982 $virus= $this->detectVirus($tmpfile);
984 return new WikiErrorMsg( 'uploadvirus', htmlspecialchars($virus) );
987 wfDebug( __METHOD__
.": all clear; passing.\n" );
992 * Checks if the mime type of the uploaded file matches the file extension.
994 * @param string $mime the mime type of the uploaded file
995 * @param string $extension The filename extension that the file is to be served with
998 function verifyExtension( $mime, $extension ) {
999 $magic =& MimeMagic
::singleton();
1001 if ( ! $mime ||
$mime == 'unknown' ||
$mime == 'unknown/unknown' )
1002 if ( ! $magic->isRecognizableExtension( $extension ) ) {
1003 wfDebug( __METHOD__
.": passing file with unknown detected mime type; " .
1004 "unrecognized extension '$extension', can't verify\n" );
1007 wfDebug( __METHOD__
.": rejecting file with unknown detected mime type; ".
1008 "recognized extension '$extension', so probably invalid file\n" );
1012 $match= $magic->isMatchingExtension($extension,$mime);
1014 if ($match===NULL) {
1015 wfDebug( __METHOD__
.": no file extension known for mime type $mime, passing file\n" );
1017 } elseif ($match===true) {
1018 wfDebug( __METHOD__
.": mime type $mime matches extension $extension, passing file\n" );
1020 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
1024 wfDebug( __METHOD__
.": mime type $mime mismatches file extension $extension, rejecting file\n" );
1030 * Heuristic for detecting files that *could* contain JavaScript instructions or
1031 * things that may look like HTML to a browser and are thus
1032 * potentially harmful. The present implementation will produce false positives in some situations.
1034 * @param string $file Pathname to the temporary upload file
1035 * @param string $mime The mime type of the file
1036 * @param string $extension The extension of the file
1037 * @return bool true if the file contains something looking like embedded scripts
1039 function detectScript($file, $mime, $extension) {
1040 global $wgAllowTitlesInSVG;
1042 #ugly hack: for text files, always look at the entire file.
1043 #For binarie field, just check the first K.
1045 if (strpos($mime,'text/')===0) $chunk = file_get_contents( $file );
1047 $fp = fopen( $file, 'rb' );
1048 $chunk = fread( $fp, 1024 );
1052 $chunk= strtolower( $chunk );
1054 if (!$chunk) return false;
1056 #decode from UTF-16 if needed (could be used for obfuscation).
1057 if (substr($chunk,0,2)=="\xfe\xff") $enc= "UTF-16BE";
1058 elseif (substr($chunk,0,2)=="\xff\xfe") $enc= "UTF-16LE";
1061 if ($enc) $chunk= iconv($enc,"ASCII//IGNORE",$chunk);
1063 $chunk= trim($chunk);
1065 #FIXME: convert from UTF-16 if necessarry!
1067 wfDebug("SpecialUpload::detectScript: checking for embedded scripts and HTML stuff\n");
1069 #check for HTML doctype
1070 if (eregi("<!DOCTYPE *X?HTML",$chunk)) return true;
1073 * Internet Explorer for Windows performs some really stupid file type
1074 * autodetection which can cause it to interpret valid image files as HTML
1075 * and potentially execute JavaScript, creating a cross-site scripting
1078 * Apple's Safari browser also performs some unsafe file type autodetection
1079 * which can cause legitimate files to be interpreted as HTML if the
1080 * web server is not correctly configured to send the right content-type
1081 * (or if you're really uploading plain text and octet streams!)
1083 * Returns true if IE is likely to mistake the given file for HTML.
1084 * Also returns true if Safari would mistake the given file for HTML
1085 * when served with a generic content-type.
1091 '<html', #also in safari
1094 '<script', #also in safari
1097 if( ! $wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
1101 foreach( $tags as $tag ) {
1102 if( false !== strpos( $chunk, $tag ) ) {
1108 * look for javascript
1111 #resolve entity-refs to look at attributes. may be harsh on big files... cache result?
1112 $chunk = Sanitizer
::decodeCharReferences( $chunk );
1114 #look for script-types
1115 if (preg_match('!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim',$chunk)) return true;
1117 #look for html-style script-urls
1118 if (preg_match('!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim',$chunk)) return true;
1120 #look for css-style script-urls
1121 if (preg_match('!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim',$chunk)) return true;
1123 wfDebug("SpecialUpload::detectScript: no scripts found\n");
1128 * Generic wrapper function for a virus scanner program.
1129 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
1130 * $wgAntivirusRequired may be used to deny upload if the scan fails.
1132 * @param string $file Pathname to the temporary upload file
1133 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
1134 * or a string containing feedback from the virus scanner if a virus was found.
1135 * If textual feedback is missing but a virus was found, this function returns true.
1137 function detectVirus($file) {
1138 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
1140 if ( !$wgAntivirus ) {
1141 wfDebug( __METHOD__
.": virus scanner disabled\n");
1145 if ( !$wgAntivirusSetup[$wgAntivirus] ) {
1146 wfDebug( __METHOD__
.": unknown virus scanner: $wgAntivirus\n" );
1148 $wgOut->addHTML( "<div class='error'>Bad configuration: unknown virus scanner: <i>$wgAntivirus</i></div>\n" );
1149 return "unknown antivirus: $wgAntivirus";
1152 # look up scanner configuration
1153 $command = $wgAntivirusSetup[$wgAntivirus]["command"];
1154 $exitCodeMap = $wgAntivirusSetup[$wgAntivirus]["codemap"];
1155 $msgPattern = isset( $wgAntivirusSetup[$wgAntivirus]["messagepattern"] ) ?
1156 $wgAntivirusSetup[$wgAntivirus]["messagepattern"] : null;
1158 if ( strpos( $command,"%f" ) === false ) {
1159 # simple pattern: append file to scan
1160 $command .= " " . wfEscapeShellArg( $file );
1162 # complex pattern: replace "%f" with file to scan
1163 $command = str_replace( "%f", wfEscapeShellArg( $file ), $command );
1166 wfDebug( __METHOD__
.": running virus scan: $command \n" );
1168 # execute virus scanner
1171 #NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
1172 # that does not seem to be worth the pain.
1173 # Ask me (Duesentrieb) about it if it's ever needed.
1175 if ( wfIsWindows() ) {
1176 exec( "$command", $output, $exitCode );
1178 exec( "$command 2>&1", $output, $exitCode );
1181 # map exit code to AV_xxx constants.
1182 $mappedCode = $exitCode;
1183 if ( $exitCodeMap ) {
1184 if ( isset( $exitCodeMap[$exitCode] ) ) {
1185 $mappedCode = $exitCodeMap[$exitCode];
1186 } elseif ( isset( $exitCodeMap["*"] ) ) {
1187 $mappedCode = $exitCodeMap["*"];
1191 if ( $mappedCode === AV_SCAN_FAILED
) {
1192 # scan failed (code was mapped to false by $exitCodeMap)
1193 wfDebug( __METHOD__
.": failed to scan $file (code $exitCode).\n" );
1195 if ( $wgAntivirusRequired ) {
1196 return "scan failed (code $exitCode)";
1200 } else if ( $mappedCode === AV_SCAN_ABORTED
) {
1201 # scan failed because filetype is unknown (probably imune)
1202 wfDebug( __METHOD__
.": unsupported file type $file (code $exitCode).\n" );
1204 } else if ( $mappedCode === AV_NO_VIRUS
) {
1206 wfDebug( __METHOD__
.": file passed virus scan.\n" );
1209 $output = join( "\n", $output );
1210 $output = trim( $output );
1213 $output = true; #if there's no output, return true
1214 } elseif ( $msgPattern ) {
1216 if ( preg_match( $msgPattern, $output, $groups ) ) {
1218 $output = $groups[1];
1223 wfDebug( __METHOD__
.": FOUND VIRUS! scanner feedback: $output" );
1229 * Check if the temporary file is MacBinary-encoded, as some uploads
1230 * from Internet Explorer on Mac OS Classic and Mac OS X will be.
1231 * If so, the data fork will be extracted to a second temporary file,
1232 * which will then be checked for validity and either kept or discarded.
1236 function checkMacBinary() {
1237 $macbin = new MacBinary( $this->mTempPath
);
1238 if( $macbin->isValid() ) {
1239 $dataFile = tempnam( wfTempDir(), "WikiMacBinary" );
1240 $dataHandle = fopen( $dataFile, 'wb' );
1242 wfDebug( "SpecialUpload::checkMacBinary: Extracting MacBinary data fork to $dataFile\n" );
1243 $macbin->extractData( $dataHandle );
1245 $this->mTempPath
= $dataFile;
1246 $this->mFileSize
= $macbin->dataForkLength();
1248 // We'll have to manually remove the new file if it's not kept.
1249 $this->mRemoveTempFile
= true;
1255 * If we've modified the upload file we need to manually remove it
1256 * on exit to clean up.
1259 function cleanupTempFile() {
1260 if ( $this->mRemoveTempFile
&& file_exists( $this->mTempPath
) ) {
1261 wfDebug( "SpecialUpload::cleanupTempFile: Removing temporary file {$this->mTempPath}\n" );
1262 unlink( $this->mTempPath
);
1267 * Check if there's an overwrite conflict and, if so, if restrictions
1268 * forbid this user from performing the upload.
1270 * @return mixed true on success, WikiError on failure
1273 function checkOverwrite( $name ) {
1274 $img = wfFindFile( $name );
1278 global $wgUser, $wgOut;
1279 if( $img->isLocal() ) {
1280 if( !self
::userCanReUpload( $wgUser, $img->name
) ) {
1281 $error = 'fileexists-forbidden';
1284 if( !$wgUser->isAllowed( 'reupload' ) ||
1285 !$wgUser->isAllowed( 'reupload-shared' ) ) {
1286 $error = "fileexists-shared-forbidden";
1292 $errorText = wfMsg( $error, wfEscapeWikiText( $img->getName() ) );
1293 return new WikiError( $wgOut->parse( $errorText ) );
1296 // Rockin', go ahead and upload
1301 * Check if a user is the last uploader
1304 * @param string $img, image name
1307 public static function userCanReUpload( User
$user, $img ) {
1308 if( $user->isAllowed( 'reupload' ) )
1309 return true; // non-conditional
1310 if( !$user->isAllowed( 'reupload-own' ) )
1313 $dbr = wfGetDB( DB_SLAVE
);
1314 $row = $dbr->selectRow('image',
1315 /* SELECT */ 'img_user',
1316 /* WHERE */ array( 'img_name' => $img )
1321 return $user->getID() == $row->img_user
;
1325 * Display an error from a wikitext-formatted WikiError object
1327 function showError( WikiError
$error ) {
1329 $wgOut->setPageTitle( wfMsg( "internalerror" ) );
1330 $wgOut->setRobotpolicy( "noindex,nofollow" );
1331 $wgOut->setArticleRelated( false );
1332 $wgOut->enableClientCache( false );
1333 $wgOut->addWikiText( $error->getMessage() );
1337 * Get the initial image page text based on a comment and optional file status information
1339 static function getInitialPageText( $comment, $license, $copyStatus, $source ) {
1340 global $wgUseCopyrightUpload;
1341 if ( $wgUseCopyrightUpload ) {
1342 if ( $license != '' ) {
1343 $licensetxt = '== ' . wfMsgForContent( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1345 $pageText = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $comment . "\n" .
1346 '== ' . wfMsgForContent ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
1348 '== ' . wfMsgForContent ( 'filesource' ) . " ==\n" . $source ;
1350 if ( $license != '' ) {
1351 $filedesc = $comment == '' ?
'' : '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $comment . "\n";
1352 $pageText = $filedesc .
1353 '== ' . wfMsgForContent ( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1355 $pageText = $comment;