4 * @addtogroup SpecialPage
11 function wfSpecialUpload() {
13 $form = new UploadForm( $wgRequest );
18 * implements Special:Upload
19 * @addtogroup SpecialPage
25 var $mUploadFile, $mUploadDescription, $mLicense ,$mIgnoreWarning, $mUploadError;
26 var $mUploadSaveName, $mUploadTempName, $mUploadSize, $mUploadOldVersion;
27 var $mUploadCopyStatus, $mUploadSource, $mReUpload, $mAction, $mUpload;
28 var $mOname, $mSessionKey, $mStashed, $mDestFile, $mRemoveTempFile, $mSourceType;
29 var $mUploadTempFileSize = 0;
31 # Placeholders for text injection by hooks (must be HTML)
32 # extensions should take care to _append_ to the present value
33 var $uploadFormTextTop;
34 var $uploadFormTextAfterSummary;
39 * Constructor : initialise object
40 * Get data POSTed through the form and assign them to the object
41 * @param $request Data posted.
43 function UploadForm( &$request ) {
44 global $wgAllowCopyUploads;
45 $this->mDestFile
= $request->getText( 'wpDestFile' );
47 if( !$request->wasPosted() ) {
48 # GET requests just give the main form; no data except wpDestfile.
52 # Placeholders for text injection by hooks (empty per default)
53 $this->uploadFormTextTop
= "";
54 $this->uploadFormTextAfterSummary
= "";
56 $this->mIgnoreWarning
= $request->getCheck( 'wpIgnoreWarning' );
57 $this->mReUpload
= $request->getCheck( 'wpReUpload' );
58 $this->mUpload
= $request->getCheck( 'wpUpload' );
60 $this->mUploadDescription
= $request->getText( 'wpUploadDescription' );
61 $this->mLicense
= $request->getText( 'wpLicense' );
62 $this->mUploadCopyStatus
= $request->getText( 'wpUploadCopyStatus' );
63 $this->mUploadSource
= $request->getText( 'wpUploadSource' );
64 $this->mWatchthis
= $request->getBool( 'wpWatchthis' );
65 $this->mSourceType
= $request->getText( 'wpSourceType' );
66 wfDebug( "UploadForm: watchthis is: '$this->mWatchthis'\n" );
68 $this->mAction
= $request->getVal( 'action' );
70 $this->mSessionKey
= $request->getInt( 'wpSessionKey' );
71 if( !empty( $this->mSessionKey
) &&
72 isset( $_SESSION['wsUploadData'][$this->mSessionKey
] ) ) {
74 * Confirming a temporarily stashed upload.
75 * We don't want path names to be forged, so we keep
76 * them in the session on the server and just give
77 * an opaque key to the user agent.
79 $data = $_SESSION['wsUploadData'][$this->mSessionKey
];
80 $this->mUploadTempName
= $data['mUploadTempName'];
81 $this->mUploadSize
= $data['mUploadSize'];
82 $this->mOname
= $data['mOname'];
83 $this->mUploadError
= 0/*UPLOAD_ERR_OK*/;
84 $this->mStashed
= true;
85 $this->mRemoveTempFile
= false;
88 *Check for a newly uploaded file.
90 if( $wgAllowCopyUploads && $this->mSourceType
== 'web' ) {
91 $this->initializeFromUrl( $request );
93 $this->initializeFromUpload( $request );
99 * Initialize the uploaded file from PHP data
102 function initializeFromUpload( $request ) {
103 $this->mUploadTempName
= $request->getFileTempName( 'wpUploadFile' );
104 $this->mUploadSize
= $request->getFileSize( 'wpUploadFile' );
105 $this->mOname
= $request->getFileName( 'wpUploadFile' );
106 $this->mUploadError
= $request->getUploadError( 'wpUploadFile' );
107 $this->mSessionKey
= false;
108 $this->mStashed
= false;
109 $this->mRemoveTempFile
= false; // PHP will handle this
113 * Copy a web file to a temporary file
116 function initializeFromUrl( $request ) {
117 global $wgTmpDirectory;
118 $url = $request->getText( 'wpUploadFileURL' );
119 $local_file = tempnam( $wgTmpDirectory, 'WEBUPLOAD' );
121 $this->mUploadTempName
= $local_file;
122 $this->mUploadError
= $this->curlCopy( $url, $local_file );
123 $this->mUploadSize
= $this->mUploadTempFileSize
;
124 $this->mOname
= array_pop( explode( '/', $url ) );
125 $this->mSessionKey
= false;
126 $this->mStashed
= false;
128 // PHP won't auto-cleanup the file
129 $this->mRemoveTempFile
= file_exists( $local_file );
134 * Returns true if there was an error, false otherwise
136 private function curlCopy( $url, $dest ) {
137 global $wgUser, $wgOut;
139 if( !$wgUser->isAllowed( 'upload_by_url' ) ) {
140 $wgOut->permissionRequired( 'upload_by_url' );
144 # Maybe remove some pasting blanks :-)
146 if( stripos($url, 'http://') !== 0 && stripos($url, 'ftp://') !== 0 ) {
147 # Only HTTP or FTP URLs
148 $wgOut->errorPage( 'upload-proto-error', 'upload-proto-error-text' );
152 # Open temporary file
153 $this->mUploadTempFile
= @fopen
( $this->mUploadTempName
, "wb" );
154 if( $this->mUploadTempFile
=== false ) {
155 # Could not open temporary file to write in
156 $wgOut->errorPage( 'upload-file-error', 'upload-file-error-text');
161 curl_setopt( $ch, CURLOPT_HTTP_VERSION
, 1.0); # Probably not needed, but apparently can work around some bug
162 curl_setopt( $ch, CURLOPT_TIMEOUT
, 10); # 10 seconds timeout
163 curl_setopt( $ch, CURLOPT_LOW_SPEED_LIMIT
, 512); # 0.5KB per second minimum transfer speed
164 curl_setopt( $ch, CURLOPT_URL
, $url);
165 curl_setopt( $ch, CURLOPT_WRITEFUNCTION
, array( $this, 'uploadCurlCallback' ) );
167 $error = curl_errno( $ch ) ?
true : false;
168 $errornum = curl_errno( $ch );
169 // if ( $error ) print curl_error ( $ch ) ; # Debugging output
172 fclose( $this->mUploadTempFile
);
173 unset( $this->mUploadTempFile
);
176 if( wfEmptyMsg( "upload-curl-error$errornum", wfMsg("upload-curl-error$errornum") ) )
177 $wgOut->errorPage( 'upload-misc-error', 'upload-misc-error-text' );
179 $wgOut->errorPage( "upload-curl-error$errornum", "upload-curl-error$errornum-text" );
186 * Callback function for CURL-based web transfer
187 * Write data to file unless we've passed the length limit;
188 * if so, abort immediately.
191 function uploadCurlCallback( $ch, $data ) {
192 global $wgMaxUploadSize;
193 $length = strlen( $data );
194 $this->mUploadTempFileSize +
= $length;
195 if( $this->mUploadTempFileSize
> $wgMaxUploadSize ) {
198 fwrite( $this->mUploadTempFile
, $data );
207 global $wgUser, $wgOut;
208 global $wgEnableUploads, $wgUploadDirectory;
210 # Check uploading enabled
211 if( !$wgEnableUploads ) {
212 $wgOut->showErrorPage( 'uploaddisabled', 'uploaddisabledtext' );
217 if( !$wgUser->isAllowed( 'upload' ) ) {
218 if( !$wgUser->isLoggedIn() ) {
219 $wgOut->showErrorPage( 'uploadnologin', 'uploadnologintext' );
221 $wgOut->permissionRequired( 'upload' );
227 if( $wgUser->isBlocked() ) {
228 $wgOut->blockedPage();
233 $wgOut->readOnlyPage();
237 /** Check if the image directory is writeable, this is a common mistake */
238 if( !is_writeable( $wgUploadDirectory ) ) {
239 $wgOut->addWikiText( wfMsg( 'upload_directory_read_only', $wgUploadDirectory ) );
243 if( $this->mReUpload
) {
244 if( !$this->unsaveUploadedFile() ) {
247 $this->mainUploadForm();
248 } else if( 'submit' == $this->mAction ||
$this->mUpload
) {
249 $this->processUpload();
251 $this->mainUploadForm();
254 $this->cleanupTempFile();
257 /* -------------------------------------------------------------- */
260 * Really do the upload
261 * Checks are made in SpecialUpload::execute()
264 function processUpload() {
265 global $wgUser, $wgOut;
267 if( !wfRunHooks( 'UploadForm:BeforeProcessing', array( &$this ) ) )
269 wfDebug( "Hook 'UploadForm:BeforeProcessing' broke processing the file." );
273 /* Check for PHP error if any, requires php 4.2 or newer */
274 if( $this->mUploadError
== 1/*UPLOAD_ERR_INI_SIZE*/ ) {
275 $this->mainUploadForm( wfMsgHtml( 'largefileserver' ) );
280 * If there was no filename or a zero size given, give up quick.
282 if( trim( $this->mOname
) == '' ||
empty( $this->mUploadSize
) ) {
283 $this->mainUploadForm( wfMsgHtml( 'emptyfile' ) );
287 # Chop off any directories in the given filename
288 if( $this->mDestFile
) {
289 $basename = wfBaseName( $this->mDestFile
);
291 $basename = wfBaseName( $this->mOname
);
295 * We'll want to blacklist against *any* 'extension', and use
296 * only the final one for the whitelist.
298 list( $partname, $ext ) = $this->splitExtensions( $basename );
300 if( count( $ext ) ) {
301 $finalExt = $ext[count( $ext ) - 1];
306 # If there was more than one "extension", reassemble the base
307 # filename to prevent bogus complaints about length
308 if( count( $ext ) > 1 ) {
309 for( $i = 0; $i < count( $ext ) - 1; $i++
)
310 $partname .= '.' . $ext[$i];
313 if( strlen( $partname ) < 3 ) {
314 $this->mainUploadForm( wfMsgHtml( 'minlength' ) );
319 * Filter out illegal characters, and try to make a legible name
320 * out of it. We'll strip some silently that Title would die on.
322 $filtered = preg_replace ( "/[^".Title
::legalChars()."]|:/", '-', $basename );
323 $nt = Title
::newFromText( $filtered );
324 if( is_null( $nt ) ) {
325 $this->uploadError( wfMsgWikiHtml( 'illegalfilename', htmlspecialchars( $filtered ) ) );
328 $nt =& Title
::makeTitle( NS_IMAGE
, $nt->getDBkey() );
329 $this->mUploadSaveName
= $nt->getDBkey();
332 * If the image is protected, non-sysop users won't be able
333 * to modify it by uploading a new revision.
335 if( !$nt->userCan( 'edit' ) ) {
336 return $this->uploadError( wfMsgWikiHtml( 'protectedpage' ) );
340 * In some cases we may forbid overwriting of existing files.
342 $overwrite = $this->checkOverwrite( $this->mUploadSaveName
);
343 if( WikiError
::isError( $overwrite ) ) {
344 return $this->uploadError( $overwrite->toString() );
347 /* Don't allow users to override the blacklist (check file extension) */
348 global $wgStrictFileExtensions;
349 global $wgFileExtensions, $wgFileBlacklist;
350 if ($finalExt == '') {
351 return $this->uploadError( wfMsgExt( 'filetype-missing', array ( 'parseinline' ) ) );
352 } elseif ( $this->checkFileExtensionList( $ext, $wgFileBlacklist ) ||
353 ($wgStrictFileExtensions &&
354 !$this->checkFileExtension( $finalExt, $wgFileExtensions ) ) ) {
355 return $this->uploadError( wfMsgExt( 'filetype-badtype', array ( 'parseinline' ), htmlspecialchars( $finalExt ), implode ( ', ', $wgFileExtensions ) ) );
359 * Look at the contents of the file; if we can recognize the
360 * type but it's corrupt or data of the wrong type, we should
361 * probably not accept it.
363 if( !$this->mStashed
) {
364 $this->checkMacBinary();
365 $veri = $this->verify( $this->mUploadTempName
, $finalExt );
367 if( $veri !== true ) { //it's a wiki error...
368 return $this->uploadError( $veri->toString() );
373 * Provide an opportunity for extensions to add futher checks
376 if( !wfRunHooks( 'UploadVerification',
377 array( $this->mUploadSaveName
, $this->mUploadTempName
, &$error ) ) ) {
378 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->mUploadSaveName
!= $filtered ) {
392 $warning .= '<li>'.wfMsgHtml( 'badfilename', htmlspecialchars( $this->mUploadSaveName
) ).'</li>';
395 global $wgCheckFileExtensions;
396 if ( $wgCheckFileExtensions ) {
397 if ( ! $this->checkFileExtension( $finalExt, $wgFileExtensions ) ) {
398 $warning .= '<li>'.wfMsgExt( 'filetype-badtype', array ( 'parseinline' ), htmlspecialchars( $finalExt ), implode ( ', ', $wgFileExtensions ) ).'</li>';
402 global $wgUploadSizeWarning;
403 if ( $wgUploadSizeWarning && ( $this->mUploadSize
> $wgUploadSizeWarning ) ) {
404 $skin = $wgUser->getSkin();
405 $wsize = $skin->formatSize( $wgUploadSizeWarning );
406 $asize = $skin->formatSize( $this->mUploadSize
);
407 $warning .= '<li>' . wfMsgHtml( 'large-file', $wsize, $asize ) . '</li>';
409 if ( $this->mUploadSize
== 0 ) {
410 $warning .= '<li>'.wfMsgHtml( 'emptyfile' ).'</li>';
414 $sk = $wgUser->getSkin();
415 $image = new Image( $nt );
417 // Check for uppercase extension. We allow these filenames but check if an image
418 // with lowercase extension exists already
419 if ( $finalExt != strtolower( $finalExt ) ) {
420 $nt_lc = Title
::newFromText( $partname . '.' . strtolower( $finalExt ) );
421 $image_lc = new Image( $nt_lc );
424 if( $image->exists() ) {
425 $dlink = $sk->makeKnownLinkObj( $nt );
426 if ( $image->allowInlineDisplay() ) {
427 $dlink2 = $sk->makeImageLinkObj( $nt, wfMsgExt( 'fileexists-thumb', 'parseinline', $dlink ), $nt->getText(), 'right', array(), false, true );
428 } elseif ( !$image->allowInlineDisplay() && $image->isSafeFile() ) {
429 $icon = $image->iconThumb();
430 $dlink2 = '<div style="float:right" id="mw-media-icon"><a href="' . $image->getURL() . '">' . $icon->toHtml() . '</a><br />' . $dlink . '</div>';
435 $warning .= '<li>' . wfMsgExt( 'fileexists', 'parseline', $dlink ) . '</li>' . $dlink2;
437 } elseif ( isset( $image_lc) && $image_lc->exists() ) {
438 # Check if image with lowercase extension exists.
439 # It's not forbidden but in 99% it makes no sense to upload the same filename with uppercase extension
440 $dlink = $sk->makeKnownLinkObj( $nt_lc );
441 if ( $image_lc->allowInlineDisplay() ) {
442 $dlink2 = $sk->makeImageLinkObj( $nt_lc, wfMsgExt( 'fileexists-thumb', 'parseinline', $dlink ), $nt_lc->getText(), 'right', array(), false, true );
443 } elseif ( !$image_lc->allowInlineDisplay() && $image_lc->isSafeFile() ) {
444 $icon = $image_lc->iconThumb();
445 $dlink2 = '<div style="float:right" id="mw-media-icon"><a href="' . $image_lc->getURL() . '">' . $icon->toHtml() . '</a><br />' . $dlink . '</div>';
450 $warning .= '<li>' . wfMsgExt( 'fileexists-extension', 'parsemag' , $partname . '.' . $finalExt , $dlink ) . '</li>' . $dlink2;
452 } elseif ( ( substr( $partname , 3, 3 ) == 'px-' ||
substr( $partname , 2, 3 ) == 'px-' ) && ereg( "[0-9]{2}" , substr( $partname , 0, 2) ) ) {
453 # Check for filenames like 50px- or 180px-, these are mostly thumbnails
454 $nt_thb = Title
::newFromText( substr( $partname , strpos( $partname , '-' ) +
1 ) . '.' . $finalExt );
455 $image_thb = new Image( $nt_thb );
456 if ($image_thb->exists() ) {
457 # Check if an image without leading '180px-' (or similiar) exists
458 $dlink = $sk->makeKnownLinkObj( $nt_thb);
459 if ( $image_thb->allowInlineDisplay() ) {
460 $dlink2 = $sk->makeImageLinkObj( $nt_thb, wfMsgExt( 'fileexists-thumb', 'parseinline', $dlink ), $nt_thb->getText(), 'right', array(), false, true );
461 } elseif ( !$image_thb->allowInlineDisplay() && $image_thb->isSafeFile() ) {
462 $icon = $image_thb->iconThumb();
463 $dlink2 = '<div style="float:right" id="mw-media-icon"><a href="' . $image_thb->getURL() . '">' . $icon->toHtml() . '</a><br />' . $dlink . '</div>';
468 $warning .= '<li>' . wfMsgExt( 'fileexists-thumbnail-yes', 'parsemag', $dlink ) . '</li>' . $dlink2;
470 # Image w/o '180px-' does not exists, but we do not like these filenames
471 $warning .= '<li>' . wfMsgExt( 'file-thumbnail-no', 'parseinline' , substr( $partname , 0, strpos( $partname , '-' ) +
1 ) ) . '</li>';
474 if ( $image->wasDeleted() ) {
475 # If the file existed before and was deleted, warn the user of this
476 # Don't bother doing so if the image exists now, however
477 $ltitle = SpecialPage
::getTitleFor( 'Log' );
478 $llink = $sk->makeKnownLinkObj( $ltitle, wfMsgHtml( 'deletionlog' ), 'type=delete&page=' . $nt->getPrefixedUrl() );
479 $warning .= wfOpenElement( 'li' ) . wfMsgWikiHtml( 'filewasdeleted', $llink ) . wfCloseElement( 'li' );
482 if( $warning != '' ) {
484 * Stash the file in a temporary location; the user can choose
485 * to let it through and we'll complete the upload then.
487 return $this->uploadWarning( $warning );
492 * Try actually saving the thing...
493 * It will show an error form on failure.
495 $hasBeenMunged = !empty( $this->mSessionKey
) ||
$this->mRemoveTempFile
;
496 if( $this->saveUploadedFile( $this->mUploadSaveName
,
497 $this->mUploadTempName
,
500 * Update the upload log and create the description page
501 * if it's a new file.
503 $img = Image
::newFromName( $this->mUploadSaveName
);
504 $success = $img->recordUpload( $this->mUploadOldVersion
,
505 $this->mUploadDescription
,
507 $this->mUploadCopyStatus
,
508 $this->mUploadSource
,
512 $this->showSuccess();
513 wfRunHooks( 'UploadComplete', array( &$img ) );
515 // Image::recordUpload() fails if the image went missing, which is
516 // unlikely, hence the lack of a specialised message
517 $wgOut->showFileNotFoundError( $this->mUploadSaveName
);
523 * Move the uploaded file from its temporary location to the final
524 * destination. If a previous version of the file exists, move
525 * it into the archive subdirectory.
527 * @todo If the later save fails, we may have disappeared the original file.
529 * @param string $saveName
530 * @param string $tempName full path to the temporary file
531 * @param bool $useRename if true, doesn't check that the source file
532 * is a PHP-managed upload temporary
534 function saveUploadedFile( $saveName, $tempName, $useRename = false ) {
535 global $wgOut, $wgAllowCopyUploads;
537 if ( !$useRename AND $wgAllowCopyUploads AND $this->mSourceType
== 'web' ) $useRename = true;
539 $fname= "SpecialUpload::saveUploadedFile";
541 $dest = wfImageDir( $saveName );
542 $archive = wfImageArchiveDir( $saveName );
543 if ( !is_dir( $dest ) ) wfMkdirParents( $dest );
544 if ( !is_dir( $archive ) ) wfMkdirParents( $archive );
546 $this->mSavedFile
= "{$dest}/{$saveName}";
548 if( is_file( $this->mSavedFile
) ) {
549 $this->mUploadOldVersion
= gmdate( 'YmdHis' ) . "!{$saveName}";
550 wfSuppressWarnings();
551 $success = rename( $this->mSavedFile
, "${archive}/{$this->mUploadOldVersion}" );
555 $wgOut->showFileRenameError( $this->mSavedFile
,
556 "${archive}/{$this->mUploadOldVersion}" );
559 else wfDebug("$fname: moved file ".$this->mSavedFile
." to ${archive}/{$this->mUploadOldVersion}\n");
562 $this->mUploadOldVersion
= '';
565 wfSuppressWarnings();
566 $success = $useRename
567 ?
rename( $tempName, $this->mSavedFile
)
568 : move_uploaded_file( $tempName, $this->mSavedFile
);
572 $wgOut->showFileCopyError( $tempName, $this->mSavedFile
);
575 wfDebug("$fname: wrote tempfile $tempName to ".$this->mSavedFile
."\n");
578 chmod( $this->mSavedFile
, 0644 );
583 * Stash a file in a temporary directory for later processing
584 * after the user has confirmed it.
586 * If the user doesn't explicitly cancel or accept, these files
587 * can accumulate in the temp directory.
589 * @param string $saveName - the destination filename
590 * @param string $tempName - the source temporary file to save
591 * @return string - full path the stashed file, or false on failure
594 function saveTempUploadedFile( $saveName, $tempName ) {
596 $archive = wfImageArchiveDir( $saveName, 'temp' );
597 if ( !is_dir ( $archive ) ) wfMkdirParents( $archive );
598 $stash = $archive . '/' . gmdate( "YmdHis" ) . '!' . $saveName;
600 $success = $this->mRemoveTempFile
601 ?
rename( $tempName, $stash )
602 : move_uploaded_file( $tempName, $stash );
604 $wgOut->showFileCopyError( $tempName, $stash );
612 * Stash a file in a temporary directory for later processing,
613 * and save the necessary descriptive info into the session.
614 * Returns a key value which will be passed through a form
615 * to pick up the path info on a later invocation.
620 function stashSession() {
621 $stash = $this->saveTempUploadedFile(
622 $this->mUploadSaveName
, $this->mUploadTempName
);
625 # Couldn't save the file.
629 $key = mt_rand( 0, 0x7fffffff );
630 $_SESSION['wsUploadData'][$key] = array(
631 'mUploadTempName' => $stash,
632 'mUploadSize' => $this->mUploadSize
,
633 'mOname' => $this->mOname
);
638 * Remove a temporarily kept file stashed by saveTempUploadedFile().
642 function unsaveUploadedFile() {
644 wfSuppressWarnings();
645 $success = unlink( $this->mUploadTempName
);
648 $wgOut->showFileDeleteError( $this->mUploadTempName
);
655 /* -------------------------------------------------------------- */
658 * Show some text and linkage on successful upload.
661 function showSuccess() {
662 global $wgUser, $wgOut, $wgContLang;
664 $sk = $wgUser->getSkin();
665 $ilink = $sk->makeMediaLink( $this->mUploadSaveName
, Image
::imageUrl( $this->mUploadSaveName
) );
666 $dname = $wgContLang->getNsText( NS_IMAGE
) . ':'.$this->mUploadSaveName
;
667 $dlink = $sk->makeKnownLink( $dname, $dname );
669 $wgOut->addHTML( '<h2>' . wfMsgHtml( 'successfulupload' ) . "</h2>\n" );
670 $text = wfMsgWikiHtml( 'fileuploaded', $ilink, $dlink );
671 $wgOut->addHTML( $text );
672 $wgOut->returnToMain( false );
676 * @param string $error as HTML
679 function uploadError( $error ) {
681 $wgOut->addHTML( "<h2>" . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
682 $wgOut->addHTML( "<span class='error'>{$error}</span>\n" );
686 * There's something wrong with this file, not enough to reject it
687 * totally but we require manual intervention to save it for real.
688 * Stash it away, then present a form asking to confirm or cancel.
690 * @param string $warning as HTML
693 function uploadWarning( $warning ) {
695 global $wgUseCopyrightUpload;
697 $this->mSessionKey
= $this->stashSession();
698 if( !$this->mSessionKey
) {
699 # Couldn't save file; an error has been displayed so let's go.
703 $wgOut->addHTML( "<h2>" . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
704 $wgOut->addHTML( "<ul class='warning'>{$warning}</ul><br />\n" );
706 $save = wfMsgHtml( 'savefile' );
707 $reupload = wfMsgHtml( 'reupload' );
708 $iw = wfMsgWikiHtml( 'ignorewarning' );
709 $reup = wfMsgWikiHtml( 'reuploaddesc' );
710 $titleObj = SpecialPage
::getTitleFor( 'Upload' );
711 $action = $titleObj->escapeLocalURL( 'action=submit' );
713 if ( $wgUseCopyrightUpload )
716 <input type='hidden' name='wpUploadCopyStatus' value=\"" . htmlspecialchars( $this->mUploadCopyStatus
) . "\" />
717 <input type='hidden' name='wpUploadSource' value=\"" . htmlspecialchars( $this->mUploadSource
) . "\" />
724 <form id='uploadwarning' method='post' enctype='multipart/form-data' action='$action'>
725 <input type='hidden' name='wpIgnoreWarning' value='1' />
726 <input type='hidden' name='wpSessionKey' value=\"" . htmlspecialchars( $this->mSessionKey
) . "\" />
727 <input type='hidden' name='wpUploadDescription' value=\"" . htmlspecialchars( $this->mUploadDescription
) . "\" />
728 <input type='hidden' name='wpLicense' value=\"" . htmlspecialchars( $this->mLicense
) . "\" />
729 <input type='hidden' name='wpDestFile' value=\"" . htmlspecialchars( $this->mDestFile
) . "\" />
730 <input type='hidden' name='wpWatchthis' value=\"" . htmlspecialchars( intval( $this->mWatchthis
) ) . "\" />
736 <input tabindex='2' type='submit' name='wpUpload' value=\"$save\" />
738 <td align='left'>$iw</td>
742 <input tabindex='2' type='submit' name='wpReUpload' value=\"{$reupload}\" />
744 <td align='left'>$reup</td>
747 </table></form>\n" );
751 * Displays the main upload form, optionally with a highlighted
752 * error message up at the top.
754 * @param string $msg as HTML
757 function mainUploadForm( $msg='' ) {
758 global $wgOut, $wgUser;
759 global $wgUseCopyrightUpload;
760 global $wgRequest, $wgAllowCopyUploads;
762 if( !wfRunHooks( 'UploadForm:initial', array( &$this ) ) )
764 wfDebug( "Hook 'UploadForm:initial' broke output of the upload form" );
768 $cols = intval($wgUser->getOption( 'cols' ));
769 $ew = $wgUser->getOption( 'editwidth' );
770 if ( $ew ) $ew = " style=\"width:100%\"";
774 $sub = wfMsgHtml( 'uploaderror' );
775 $wgOut->addHTML( "<h2>{$sub}</h2>\n" .
776 "<span class='error'>{$msg}</span>\n" );
778 $wgOut->addHTML( '<div id="uploadtext">' );
779 $wgOut->addWikiText( wfMsgNoTrans( 'uploadtext', $this->mDestFile
) );
780 $wgOut->addHTML( '</div>' );
782 $sourcefilename = wfMsgHtml( 'sourcefilename' );
783 $destfilename = wfMsgHtml( 'destfilename' );
784 $summary = wfMsgWikiHtml( 'fileuploadsummary' );
786 $licenses = new Licenses();
787 $license = wfMsgHtml( 'license' );
788 $nolicense = wfMsgHtml( 'nolicense' );
789 $licenseshtml = $licenses->getHtml();
791 $ulb = wfMsgHtml( 'uploadbtn' );
794 $titleObj = SpecialPage
::getTitleFor( 'Upload' );
795 $action = $titleObj->escapeLocalURL();
797 $encDestFile = htmlspecialchars( $this->mDestFile
);
800 ( $wgUser->getOption( 'watchdefault' ) ||
801 ( $wgUser->getOption( 'watchcreations' ) && $this->mDestFile
== '' ) )
802 ?
'checked="checked"'
805 // Prepare form for upload or upload/copy
806 if( $wgAllowCopyUploads && $wgUser->isAllowed( 'upload_by_url' ) ) {
808 "<input type='radio' id='wpSourceTypeFile' name='wpSourceType' value='file' onchange='toggle_element_activation(\"wpUploadFileURL\",\"wpUploadFile\")' checked />" .
809 "<input tabindex='1' type='file' name='wpUploadFile' id='wpUploadFile' onfocus='toggle_element_activation(\"wpUploadFileURL\",\"wpUploadFile\");toggle_element_check(\"wpSourceTypeFile\",\"wpSourceTypeURL\")'" .
810 ($this->mDestFile?
"":"onchange='fillDestFilename(\"wpUploadFile\")' ") . "size='40' />" .
811 wfMsgHTML( 'upload_source_file' ) . "<br/>" .
812 "<input type='radio' id='wpSourceTypeURL' name='wpSourceType' value='web' onchange='toggle_element_activation(\"wpUploadFile\",\"wpUploadFileURL\")' />" .
813 "<input tabindex='1' type='text' name='wpUploadFileURL' id='wpUploadFileURL' onfocus='toggle_element_activation(\"wpUploadFile\",\"wpUploadFileURL\");toggle_element_check(\"wpSourceTypeURL\",\"wpSourceTypeFile\")'" .
814 ($this->mDestFile?
"":"onchange='fillDestFilename(\"wpUploadFileURL\")' ") . "size='40' DISABLED />" .
815 wfMsgHtml( 'upload_source_url' ) ;
818 "<input tabindex='1' type='file' name='wpUploadFile' id='wpUploadFile' " .
819 ($this->mDestFile?
"":"onchange='fillDestFilename(\"wpUploadFile\")' ") .
821 "<input type='hidden' name='wpSourceType' value='file' />" ;
825 <form id='upload' method='post' enctype='multipart/form-data' action=\"$action\">
828 {$this->uploadFormTextTop}
829 <td align='right' valign='top'><label for='wpUploadFile'>{$sourcefilename}:</label></td>
835 <td align='right'><label for='wpDestFile'>{$destfilename}:</label></td>
837 <input tabindex='2' type='text' name='wpDestFile' id='wpDestFile' size='40' value=\"$encDestFile\" />
841 <td align='right'><label for='wpUploadDescription'>{$summary}</label></td>
843 <textarea tabindex='3' name='wpUploadDescription' id='wpUploadDescription' rows='6' cols='{$cols}'{$ew}>" . htmlspecialchars( $this->mUploadDescription
) . "</textarea>
844 {$this->uploadFormTextAfterSummary}
849 if ( $licenseshtml != '' ) {
852 <td align='right'><label for='wpLicense'>$license:</label></td>
854 <script type='text/javascript' src=\"$wgStylePath/common/upload.js\"></script>
855 <select name='wpLicense' id='wpLicense' tabindex='4'
856 onchange='licenseSelectorCheck()'>
857 <option value=''>$nolicense</option>
866 if ( $wgUseCopyrightUpload ) {
867 $filestatus = wfMsgHtml ( 'filestatus' );
868 $copystatus = htmlspecialchars( $this->mUploadCopyStatus
);
869 $filesource = wfMsgHtml ( 'filesource' );
870 $uploadsource = htmlspecialchars( $this->mUploadSource
);
873 <td align='right' nowrap='nowrap'><label for='wpUploadCopyStatus'>$filestatus:</label></td>
874 <td><input tabindex='5' type='text' name='wpUploadCopyStatus' id='wpUploadCopyStatus' value=\"$copystatus\" size='40' /></td>
877 <td align='right'><label for='wpUploadCopyStatus'>$filesource:</label></td>
878 <td><input tabindex='6' type='text' name='wpUploadSource' id='wpUploadCopyStatus' value=\"$uploadsource\" size='40' /></td>
888 <input tabindex='7' type='checkbox' name='wpWatchthis' id='wpWatchthis' $watchChecked value='true' />
889 <label for='wpWatchthis'>" . wfMsgHtml( 'watchthisupload' ) . "</label>
890 <input tabindex='8' type='checkbox' name='wpIgnoreWarning' id='wpIgnoreWarning' value='true' />
891 <label for='wpIgnoreWarning'>" . wfMsgHtml( 'ignorewarnings' ) . "</label>
896 <td align='left'><input tabindex='9' type='submit' name='wpUpload' value=\"{$ulb}\" /></td>
903 $wgOut->addWikiText( wfMsgForContent( 'edittools' ) );
912 /* -------------------------------------------------------------- */
915 * Split a file into a base name and all dot-delimited 'extensions'
916 * on the end. Some web server configurations will fall back to
917 * earlier pseudo-'extensions' to determine type and execute
918 * scripts, so the blacklist needs to check them all.
922 function splitExtensions( $filename ) {
923 $bits = explode( '.', $filename );
924 $basename = array_shift( $bits );
925 return array( $basename, $bits );
929 * Perform case-insensitive match against a list of file extensions.
930 * Returns true if the extension is in the list.
936 function checkFileExtension( $ext, $list ) {
937 return in_array( strtolower( $ext ), $list );
941 * Perform case-insensitive match against a list of file extensions.
942 * Returns true if any of the extensions are in the list.
948 function checkFileExtensionList( $ext, $list ) {
949 foreach( $ext as $e ) {
950 if( in_array( strtolower( $e ), $list ) ) {
958 * Verifies that it's ok to include the uploaded file
960 * @param string $tmpfile the full path of the temporary file to verify
961 * @param string $extension The filename extension that the file is to be served with
962 * @return mixed true of the file is verified, a WikiError object otherwise.
964 function verify( $tmpfile, $extension ) {
965 #magically determine mime type
966 $magic=& MimeMagic
::singleton();
967 $mime= $magic->guessMimeType($tmpfile,false);
969 $fname= "SpecialUpload::verify";
971 #check mime type, if desired
972 global $wgVerifyMimeType;
973 if ($wgVerifyMimeType) {
975 #check mime type against file extension
976 if( !$this->verifyExtension( $mime, $extension ) ) {
977 return new WikiErrorMsg( 'uploadcorrupt' );
980 #check mime type blacklist
981 global $wgMimeTypeBlacklist;
982 if( isset($wgMimeTypeBlacklist) && !is_null($wgMimeTypeBlacklist)
983 && $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
984 return new WikiErrorMsg( 'filetype-badmime', htmlspecialchars( $mime ) );
988 #check for htmlish code and javascript
989 if( $this->detectScript ( $tmpfile, $mime, $extension ) ) {
990 return new WikiErrorMsg( 'uploadscripted' );
994 * Scan the uploaded file for viruses
996 $virus= $this->detectVirus($tmpfile);
998 return new WikiErrorMsg( 'uploadvirus', htmlspecialchars($virus) );
1001 wfDebug( "$fname: all clear; passing.\n" );
1006 * Checks if the mime type of the uploaded file matches the file extension.
1008 * @param string $mime the mime type of the uploaded file
1009 * @param string $extension The filename extension that the file is to be served with
1012 function verifyExtension( $mime, $extension ) {
1013 $fname = 'SpecialUpload::verifyExtension';
1015 $magic =& MimeMagic
::singleton();
1017 if ( ! $mime ||
$mime == 'unknown' ||
$mime == 'unknown/unknown' )
1018 if ( ! $magic->isRecognizableExtension( $extension ) ) {
1019 wfDebug( "$fname: passing file with unknown detected mime type; unrecognized extension '$extension', can't verify\n" );
1022 wfDebug( "$fname: rejecting file with unknown detected mime type; recognized extension '$extension', so probably invalid file\n" );
1026 $match= $magic->isMatchingExtension($extension,$mime);
1028 if ($match===NULL) {
1029 wfDebug( "$fname: no file extension known for mime type $mime, passing file\n" );
1031 } elseif ($match===true) {
1032 wfDebug( "$fname: mime type $mime matches extension $extension, passing file\n" );
1034 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
1038 wfDebug( "$fname: mime type $mime mismatches file extension $extension, rejecting file\n" );
1043 /** Heuristig for detecting files that *could* contain JavaScript instructions or
1044 * things that may look like HTML to a browser and are thus
1045 * potentially harmful. The present implementation will produce false positives in some situations.
1047 * @param string $file Pathname to the temporary upload file
1048 * @param string $mime The mime type of the file
1049 * @param string $extension The extension of the file
1050 * @return bool true if the file contains something looking like embedded scripts
1052 function detectScript($file, $mime, $extension) {
1053 global $wgAllowTitlesInSVG;
1055 #ugly hack: for text files, always look at the entire file.
1056 #For binarie field, just check the first K.
1058 if (strpos($mime,'text/')===0) $chunk = file_get_contents( $file );
1060 $fp = fopen( $file, 'rb' );
1061 $chunk = fread( $fp, 1024 );
1065 $chunk= strtolower( $chunk );
1067 if (!$chunk) return false;
1069 #decode from UTF-16 if needed (could be used for obfuscation).
1070 if (substr($chunk,0,2)=="\xfe\xff") $enc= "UTF-16BE";
1071 elseif (substr($chunk,0,2)=="\xff\xfe") $enc= "UTF-16LE";
1074 if ($enc) $chunk= iconv($enc,"ASCII//IGNORE",$chunk);
1076 $chunk= trim($chunk);
1078 #FIXME: convert from UTF-16 if necessarry!
1080 wfDebug("SpecialUpload::detectScript: checking for embedded scripts and HTML stuff\n");
1082 #check for HTML doctype
1083 if (eregi("<!DOCTYPE *X?HTML",$chunk)) return true;
1086 * Internet Explorer for Windows performs some really stupid file type
1087 * autodetection which can cause it to interpret valid image files as HTML
1088 * and potentially execute JavaScript, creating a cross-site scripting
1091 * Apple's Safari browser also performs some unsafe file type autodetection
1092 * which can cause legitimate files to be interpreted as HTML if the
1093 * web server is not correctly configured to send the right content-type
1094 * (or if you're really uploading plain text and octet streams!)
1096 * Returns true if IE is likely to mistake the given file for HTML.
1097 * Also returns true if Safari would mistake the given file for HTML
1098 * when served with a generic content-type.
1104 '<html', #also in safari
1107 '<script', #also in safari
1110 if( ! $wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
1114 foreach( $tags as $tag ) {
1115 if( false !== strpos( $chunk, $tag ) ) {
1121 * look for javascript
1124 #resolve entity-refs to look at attributes. may be harsh on big files... cache result?
1125 $chunk = Sanitizer
::decodeCharReferences( $chunk );
1127 #look for script-types
1128 if (preg_match('!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim',$chunk)) return true;
1130 #look for html-style script-urls
1131 if (preg_match('!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim',$chunk)) return true;
1133 #look for css-style script-urls
1134 if (preg_match('!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim',$chunk)) return true;
1136 wfDebug("SpecialUpload::detectScript: no scripts found\n");
1140 /** Generic wrapper function for a virus scanner program.
1141 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
1142 * $wgAntivirusRequired may be used to deny upload if the scan fails.
1144 * @param string $file Pathname to the temporary upload file
1145 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
1146 * or a string containing feedback from the virus scanner if a virus was found.
1147 * If textual feedback is missing but a virus was found, this function returns true.
1149 function detectVirus($file) {
1150 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
1152 $fname= "SpecialUpload::detectVirus";
1154 if (!$wgAntivirus) { #disabled?
1155 wfDebug("$fname: virus scanner disabled\n");
1160 if (!$wgAntivirusSetup[$wgAntivirus]) {
1161 wfDebug("$fname: unknown virus scanner: $wgAntivirus\n");
1163 $wgOut->addHTML( "<div class='error'>Bad configuration: unknown virus scanner: <i>$wgAntivirus</i></div>\n" ); #LOCALIZE
1165 return "unknown antivirus: $wgAntivirus";
1168 #look up scanner configuration
1169 $virus_scanner= $wgAntivirusSetup[$wgAntivirus]["command"]; #command pattern
1170 $virus_scanner_codes= $wgAntivirusSetup[$wgAntivirus]["codemap"]; #exit-code map
1171 $msg_pattern= $wgAntivirusSetup[$wgAntivirus]["messagepattern"]; #message pattern
1173 $scanner= $virus_scanner; #copy, so we can resolve the pattern
1175 if (strpos($scanner,"%f")===false) $scanner.= " ".wfEscapeShellArg($file); #simple pattern: append file to scan
1176 else $scanner= str_replace("%f",wfEscapeShellArg($file),$scanner); #complex pattern: replace "%f" with file to scan
1178 wfDebug("$fname: running virus scan: $scanner \n");
1180 #execute virus scanner
1183 #NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
1184 # that does not seem to be worth the pain.
1185 # Ask me (Duesentrieb) about it if it's ever needed.
1187 if (wfIsWindows()) exec("$scanner",$output,$code);
1188 else exec("$scanner 2>&1",$output,$code);
1190 $exit_code= $code; #remember for user feedback
1192 if ($virus_scanner_codes) { #map exit code to AV_xxx constants.
1193 if (isset($virus_scanner_codes[$code])) {
1194 $code= $virus_scanner_codes[$code]; # explicit mapping
1195 } else if (isset($virus_scanner_codes["*"])) {
1196 $code= $virus_scanner_codes["*"]; # fallback mapping
1200 if ($code===AV_SCAN_FAILED
) { #scan failed (code was mapped to false by $virus_scanner_codes)
1201 wfDebug("$fname: failed to scan $file (code $exit_code).\n");
1203 if ($wgAntivirusRequired) { return "scan failed (code $exit_code)"; }
1204 else { return NULL; }
1206 else if ($code===AV_SCAN_ABORTED
) { #scan failed because filetype is unknown (probably imune)
1207 wfDebug("$fname: unsupported file type $file (code $exit_code).\n");
1210 else if ($code===AV_NO_VIRUS
) {
1211 wfDebug("$fname: file passed virus scan.\n");
1212 return false; #no virus found
1215 $output= join("\n",$output);
1216 $output= trim($output);
1218 if (!$output) $output= true; #if there's no output, return true
1219 else if ($msg_pattern) {
1221 if (preg_match($msg_pattern,$output,$groups)) {
1222 if ($groups[1]) $output= $groups[1];
1226 wfDebug("$fname: FOUND VIRUS! scanner feedback: $output");
1232 * Check if the temporary file is MacBinary-encoded, as some uploads
1233 * from Internet Explorer on Mac OS Classic and Mac OS X will be.
1234 * If so, the data fork will be extracted to a second temporary file,
1235 * which will then be checked for validity and either kept or discarded.
1239 function checkMacBinary() {
1240 $macbin = new MacBinary( $this->mUploadTempName
);
1241 if( $macbin->isValid() ) {
1242 $dataFile = tempnam( wfTempDir(), "WikiMacBinary" );
1243 $dataHandle = fopen( $dataFile, 'wb' );
1245 wfDebug( "SpecialUpload::checkMacBinary: Extracting MacBinary data fork to $dataFile\n" );
1246 $macbin->extractData( $dataHandle );
1248 $this->mUploadTempName
= $dataFile;
1249 $this->mUploadSize
= $macbin->dataForkLength();
1251 // We'll have to manually remove the new file if it's not kept.
1252 $this->mRemoveTempFile
= true;
1258 * If we've modified the upload file we need to manually remove it
1259 * on exit to clean up.
1262 function cleanupTempFile() {
1263 if( $this->mRemoveTempFile
&& file_exists( $this->mUploadTempName
) ) {
1264 wfDebug( "SpecialUpload::cleanupTempFile: Removing temporary file $this->mUploadTempName\n" );
1265 unlink( $this->mUploadTempName
);
1270 * Check if there's an overwrite conflict and, if so, if restrictions
1271 * forbid this user from performing the upload.
1273 * @return mixed true on success, WikiError on failure
1276 function checkOverwrite( $name ) {
1277 $img = Image
::newFromName( $name );
1278 if( is_null( $img ) ) {
1279 // Uh... this shouldn't happen ;)
1280 // But if it does, fall through to previous behavior
1285 if( $img->exists() ) {
1286 global $wgUser, $wgOut;
1287 if( $img->isLocal() ) {
1288 if( !$this->userCanReUpload( $wgUser, $img->name
) ) {
1289 $error = 'fileexists-forbidden';
1292 if( !$wgUser->isAllowed( 'reupload' ) ||
1293 !$wgUser->isAllowed( 'reupload-shared' ) ) {
1294 $error = "fileexists-shared-forbidden";
1300 $errorText = wfMsg( $error, wfEscapeWikiText( $img->getName() ) );
1301 return new WikiError( $wgOut->parse( $errorText ) );
1304 // Rockin', go ahead and upload
1309 * Check if a user is the last uploader
1312 * @param string $img, image name
1316 function userCanReUpload( $user, $img ) {
1317 if( $user->isAllowed('reupload' ) )
1318 return true; // non-conditional
1319 if( !$user->isAllowed('reupload-own') )
1322 $dbr = wfGetDB( DB_SLAVE
);
1323 $row = $dbr->selectRow(
1325 /* SELECT */ 'img_user',
1326 /* WHERE */ array( 'img_name' => $img )
1331 return $user->getID() == $row->img_user
;