768c14fd7a8f3b6367839d9b143ffe17cb40a442
5 * @subpackage SpecialPage
12 function wfSpecialUpload() {
14 $form = new UploadForm( $wgRequest );
21 * @subpackage SpecialPage
27 var $mUploadFile, $mUploadDescription, $mLicense ,$mIgnoreWarning, $mUploadError;
28 var $mUploadSaveName, $mUploadTempName, $mUploadSize, $mUploadOldVersion;
29 var $mUploadCopyStatus, $mUploadSource, $mReUpload, $mAction, $mUpload;
30 var $mOname, $mSessionKey, $mStashed, $mDestFile, $mRemoveTempFile, $mSourceType;
31 var $mUploadTempFileSize = 0;
35 * Constructor : initialise object
36 * Get data POSTed through the form and assign them to the object
37 * @param $request Data posted.
39 function UploadForm( &$request ) {
40 global $wgAllowCopyUploads;
41 $this->mDestFile
= $request->getText( 'wpDestFile' );
43 if( !$request->wasPosted() ) {
44 # GET requests just give the main form; no data except wpDestfile.
48 $this->mIgnoreWarning
= $request->getCheck( 'wpIgnoreWarning' );
49 $this->mReUpload
= $request->getCheck( 'wpReUpload' );
50 $this->mUpload
= $request->getCheck( 'wpUpload' );
52 $this->mUploadDescription
= $request->getText( 'wpUploadDescription' );
53 $this->mLicense
= $request->getText( 'wpLicense' );
54 $this->mUploadCopyStatus
= $request->getText( 'wpUploadCopyStatus' );
55 $this->mUploadSource
= $request->getText( 'wpUploadSource' );
56 $this->mWatchthis
= $request->getBool( 'wpWatchthis' );
57 $this->mSourceType
= $request->getText( 'wpSourceType' );
58 wfDebug( "UploadForm: watchthis is: '$this->mWatchthis'\n" );
60 $this->mAction
= $request->getVal( 'action' );
62 $this->mSessionKey
= $request->getInt( 'wpSessionKey' );
63 if( !empty( $this->mSessionKey
) &&
64 isset( $_SESSION['wsUploadData'][$this->mSessionKey
] ) ) {
66 * Confirming a temporarily stashed upload.
67 * We don't want path names to be forged, so we keep
68 * them in the session on the server and just give
69 * an opaque key to the user agent.
71 $data = $_SESSION['wsUploadData'][$this->mSessionKey
];
72 $this->mUploadTempName
= $data['mUploadTempName'];
73 $this->mUploadSize
= $data['mUploadSize'];
74 $this->mOname
= $data['mOname'];
75 $this->mUploadError
= 0/*UPLOAD_ERR_OK*/;
76 $this->mStashed
= true;
77 $this->mRemoveTempFile
= false;
80 *Check for a newly uploaded file.
82 if( $wgAllowCopyUploads && $this->mSourceType
== 'web' ) {
83 $this->initializeFromUrl( $request );
85 $this->initializeFromUpload( $request );
91 * Initialize the uploaded file from PHP data
94 function initializeFromUpload( $request ) {
95 $this->mUploadTempName
= $request->getFileTempName( 'wpUploadFile' );
96 $this->mUploadSize
= $request->getFileSize( 'wpUploadFile' );
97 $this->mOname
= $request->getFileName( 'wpUploadFile' );
98 $this->mUploadError
= $request->getUploadError( 'wpUploadFile' );
99 $this->mSessionKey
= false;
100 $this->mStashed
= false;
101 $this->mRemoveTempFile
= false; // PHP will handle this
105 * Copy a web file to a temporary file
108 function initializeFromUrl( $request ) {
109 global $wgTmpDirectory, $wgMaxUploadSize;
110 $url = $request->getText( 'wpUploadFileURL' );
111 $local_file = tempnam( $wgTmpDirectory, 'WEBUPLOAD' );
113 $this->mUploadTempName
= $local_file;
114 $this->mUploadError
= $this->curlCopy( $url, $local_file );
115 $this->mUploadSize
= $this->mUploadTempFileSize
;
116 $this->mOname
= array_pop( explode( '/', $url ) );
117 $this->mSessionKey
= false;
118 $this->mStashed
= false;
120 // PHP won't auto-cleanup the file
121 $this->mRemoveTempFile
= file_exists( $local_file );
126 * Returns true if there was an error, false otherwise
128 private function curlCopy( $url, $dest ) {
129 global $wgMaxUploadSize, $wgUser, $wgOut;
131 if( !$wgUser->isAllowed( 'upload_by_url' ) ) {
132 $wgOut->permissionRequired( 'upload_by_url' );
136 # Maybe remove some pasting blanks :-)
138 if( stripos($url, 'http://') !== 0 && stripos($url, 'ftp://') !== 0 ) {
139 # Only HTTP or FTP URLs
140 $wgOut->errorPage( 'upload-proto-error', 'upload-proto-error-text' );
144 # Open temporary file
145 $this->mUploadTempFile
= @fopen
( $this->mUploadTempName
, "wb" );
146 if( $this->mUploadTempFile
=== false ) {
147 # Could not open temporary file to write in
148 $wgOut->errorPage( 'upload-file-error', 'upload-file-error-text');
153 curl_setopt( $ch, CURLOPT_HTTP_VERSION
, 1.0); # Probably not needed, but apparently can work around some bug
154 curl_setopt( $ch, CURLOPT_TIMEOUT
, 10); # 10 seconds timeout
155 curl_setopt( $ch, CURLOPT_LOW_SPEED_LIMIT
, 512); # 0.5KB per second minimum transfer speed
156 curl_setopt( $ch, CURLOPT_URL
, $url);
157 curl_setopt( $ch, CURLOPT_WRITEFUNCTION
, array( $this, 'uploadCurlCallback' ) );
159 $error = curl_errno( $ch ) ?
true : false;
160 $errornum = curl_errno( $ch );
161 // if ( $error ) print curl_error ( $ch ) ; # Debugging output
164 fclose( $this->mUploadTempFile
);
165 unset( $this->mUploadTempFile
);
168 if( wfEmptyMsg( "upload-curl-error$errornum", wfMsg("upload-curl-error$errornum") ) )
169 $wgOut->errorPage( 'upload-misc-error', 'upload-misc-error-text' );
171 $wgOut->errorPage( "upload-curl-error$errornum", "upload-curl-error$errornum-text" );
178 * Callback function for CURL-based web transfer
179 * Write data to file unless we've passed the length limit;
180 * if so, abort immediately.
183 function uploadCurlCallback( $ch, $data ) {
184 global $wgMaxUploadSize;
185 $length = strlen( $data );
186 $this->mUploadTempFileSize +
= $length;
187 if( $this->mUploadTempFileSize
> $wgMaxUploadSize ) {
190 fwrite( $this->mUploadTempFile
, $data );
199 global $wgUser, $wgOut;
200 global $wgEnableUploads, $wgUploadDirectory;
202 # Check uploading enabled
203 if( !$wgEnableUploads ) {
204 $wgOut->showErrorPage( 'uploaddisabled', 'uploaddisabledtext' );
209 if( !$wgUser->isAllowed( 'upload' ) ) {
210 if( !$wgUser->isLoggedIn() ) {
211 $wgOut->showErrorPage( 'uploadnologin', 'uploadnologintext' );
213 $wgOut->permissionRequired( 'upload' );
219 if( $wgUser->isBlocked() ) {
220 $wgOut->blockedPage();
225 $wgOut->readOnlyPage();
229 /** Check if the image directory is writeable, this is a common mistake */
230 if( !is_writeable( $wgUploadDirectory ) ) {
231 $wgOut->addWikiText( wfMsg( 'upload_directory_read_only', $wgUploadDirectory ) );
235 if( $this->mReUpload
) {
236 if( !$this->unsaveUploadedFile() ) {
239 $this->mainUploadForm();
240 } else if( 'submit' == $this->mAction ||
$this->mUpload
) {
241 $this->processUpload();
243 $this->mainUploadForm();
246 $this->cleanupTempFile();
249 /* -------------------------------------------------------------- */
252 * Really do the upload
253 * Checks are made in SpecialUpload::execute()
256 function processUpload() {
257 global $wgUser, $wgOut;
259 /* Check for PHP error if any, requires php 4.2 or newer */
260 if( $this->mUploadError
== 1/*UPLOAD_ERR_INI_SIZE*/ ) {
261 $this->mainUploadForm( wfMsgHtml( 'largefileserver' ) );
266 * If there was no filename or a zero size given, give up quick.
268 if( trim( $this->mOname
) == '' ||
empty( $this->mUploadSize
) ) {
269 $this->mainUploadForm( wfMsgHtml( 'emptyfile' ) );
273 # Chop off any directories in the given filename
274 if( $this->mDestFile
) {
275 $basename = wfBaseName( $this->mDestFile
);
277 $basename = wfBaseName( $this->mOname
);
281 * We'll want to blacklist against *any* 'extension', and use
282 * only the final one for the whitelist.
284 list( $partname, $ext ) = $this->splitExtensions( $basename );
286 if( count( $ext ) ) {
287 $finalExt = $ext[count( $ext ) - 1];
291 $fullExt = implode( '.', $ext );
293 # If there was more than one "extension", reassemble the base
294 # filename to prevent bogus complaints about length
295 if( count( $ext ) > 1 ) {
296 for( $i = 0; $i < count( $ext ) - 1; $i++
)
297 $partname .= '.' . $ext[$i];
300 if( strlen( $partname ) < 3 ) {
301 $this->mainUploadForm( wfMsgHtml( 'minlength' ) );
306 * Filter out illegal characters, and try to make a legible name
307 * out of it. We'll strip some silently that Title would die on.
309 $filtered = preg_replace ( "/[^".Title
::legalChars()."]|:/", '-', $basename );
310 $nt = Title
::newFromText( $filtered );
311 if( is_null( $nt ) ) {
312 $this->uploadError( wfMsgWikiHtml( 'illegalfilename', htmlspecialchars( $filtered ) ) );
315 $nt =& Title
::makeTitle( NS_IMAGE
, $nt->getDBkey() );
316 $this->mUploadSaveName
= $nt->getDBkey();
319 * If the image is protected, non-sysop users won't be able
320 * to modify it by uploading a new revision.
322 if( !$nt->userCanEdit() ) {
323 return $this->uploadError( wfMsgWikiHtml( 'protectedpage' ) );
327 * In some cases we may forbid overwriting of existing files.
329 $overwrite = $this->checkOverwrite( $this->mUploadSaveName
);
330 if( WikiError
::isError( $overwrite ) ) {
331 return $this->uploadError( $overwrite->toString() );
334 /* Don't allow users to override the blacklist (check file extension) */
335 global $wgStrictFileExtensions;
336 global $wgFileExtensions, $wgFileBlacklist;
337 if( $this->checkFileExtensionList( $ext, $wgFileBlacklist ) ||
338 ($wgStrictFileExtensions &&
339 !$this->checkFileExtension( $finalExt, $wgFileExtensions ) ) ) {
340 return $this->uploadError( wfMsgHtml( 'badfiletype', htmlspecialchars( $fullExt ) ) );
344 * Look at the contents of the file; if we can recognize the
345 * type but it's corrupt or data of the wrong type, we should
346 * probably not accept it.
348 if( !$this->mStashed
) {
349 $this->checkMacBinary();
350 $veri = $this->verify( $this->mUploadTempName
, $finalExt );
352 if( $veri !== true ) { //it's a wiki error...
353 return $this->uploadError( $veri->toString() );
358 * Provide an opportunity for extensions to add futher checks
361 if( !wfRunHooks( 'UploadVerification',
362 array( $this->mUploadSaveName
, $this->mUploadTempName
, &$error ) ) ) {
363 return $this->uploadError( $error );
367 * Check for non-fatal conditions
369 if ( ! $this->mIgnoreWarning
) {
372 global $wgCapitalLinks;
373 if( $wgCapitalLinks ) {
374 $filtered = ucfirst( $filtered );
376 if( $this->mUploadSaveName
!= $filtered ) {
377 $warning .= '<li>'.wfMsgHtml( 'badfilename', htmlspecialchars( $this->mUploadSaveName
) ).'</li>';
380 global $wgCheckFileExtensions;
381 if ( $wgCheckFileExtensions ) {
382 if ( ! $this->checkFileExtension( $finalExt, $wgFileExtensions ) ) {
383 $warning .= '<li>'.wfMsgHtml( 'badfiletype', htmlspecialchars( $fullExt ) ).'</li>';
387 global $wgUploadSizeWarning;
388 if ( $wgUploadSizeWarning && ( $this->mUploadSize
> $wgUploadSizeWarning ) ) {
389 # TODO: Format $wgUploadSizeWarning to something that looks better than the raw byte
390 # value, perhaps add GB,MB and KB suffixes?
391 $warning .= '<li>'.wfMsgHtml( 'largefile', $wgUploadSizeWarning, $this->mUploadSize
).'</li>';
393 if ( $this->mUploadSize
== 0 ) {
394 $warning .= '<li>'.wfMsgHtml( 'emptyfile' ).'</li>';
397 if( $nt->getArticleID() ) {
399 $sk = $wgUser->getSkin();
400 $dlink = $sk->makeKnownLinkObj( $nt );
401 $warning .= '<li>'.wfMsgHtml( 'fileexists', $dlink ).'</li>';
403 # If the file existed before and was deleted, warn the user of this
404 # Don't bother doing so if the image exists now, however
405 $image = new Image( $nt );
406 if( $image->wasDeleted() ) {
407 $skin = $wgUser->getSkin();
408 $ltitle = SpecialPage
::getTitleFor( 'Log' );
409 $llink = $skin->makeKnownLinkObj( $ltitle, wfMsgHtml( 'deletionlog' ), 'type=delete&page=' . $nt->getPrefixedUrl() );
410 $warning .= wfOpenElement( 'li' ) . wfMsgWikiHtml( 'filewasdeleted', $llink ) . wfCloseElement( 'li' );
414 if( $warning != '' ) {
416 * Stash the file in a temporary location; the user can choose
417 * to let it through and we'll complete the upload then.
419 return $this->uploadWarning( $warning );
424 * Try actually saving the thing...
425 * It will show an error form on failure.
427 $hasBeenMunged = !empty( $this->mSessionKey
) ||
$this->mRemoveTempFile
;
428 if( $this->saveUploadedFile( $this->mUploadSaveName
,
429 $this->mUploadTempName
,
432 * Update the upload log and create the description page
433 * if it's a new file.
435 $img = Image
::newFromName( $this->mUploadSaveName
);
436 $success = $img->recordUpload( $this->mUploadOldVersion
,
437 $this->mUploadDescription
,
439 $this->mUploadCopyStatus
,
440 $this->mUploadSource
,
444 $this->showSuccess();
445 wfRunHooks( 'UploadComplete', array( &$img ) );
447 // Image::recordUpload() fails if the image went missing, which is
448 // unlikely, hence the lack of a specialised message
449 $wgOut->showFileNotFoundError( $this->mUploadSaveName
);
455 * Move the uploaded file from its temporary location to the final
456 * destination. If a previous version of the file exists, move
457 * it into the archive subdirectory.
459 * @todo If the later save fails, we may have disappeared the original file.
461 * @param string $saveName
462 * @param string $tempName full path to the temporary file
463 * @param bool $useRename if true, doesn't check that the source file
464 * is a PHP-managed upload temporary
466 function saveUploadedFile( $saveName, $tempName, $useRename = false ) {
467 global $wgOut, $wgAllowCopyUploads;
469 if ( !$useRename AND $wgAllowCopyUploads AND $this->mSourceType
== 'web' ) $useRename = true;
471 $fname= "SpecialUpload::saveUploadedFile";
473 $dest = wfImageDir( $saveName );
474 $archive = wfImageArchiveDir( $saveName );
475 if ( !is_dir( $dest ) ) wfMkdirParents( $dest );
476 if ( !is_dir( $archive ) ) wfMkdirParents( $archive );
478 $this->mSavedFile
= "{$dest}/{$saveName}";
480 if( is_file( $this->mSavedFile
) ) {
481 $this->mUploadOldVersion
= gmdate( 'YmdHis' ) . "!{$saveName}";
482 wfSuppressWarnings();
483 $success = rename( $this->mSavedFile
, "${archive}/{$this->mUploadOldVersion}" );
487 $wgOut->showFileRenameError( $this->mSavedFile
,
488 "${archive}/{$this->mUploadOldVersion}" );
491 else wfDebug("$fname: moved file ".$this->mSavedFile
." to ${archive}/{$this->mUploadOldVersion}\n");
494 $this->mUploadOldVersion
= '';
497 wfSuppressWarnings();
498 $success = $useRename
499 ?
rename( $tempName, $this->mSavedFile
)
500 : move_uploaded_file( $tempName, $this->mSavedFile
);
504 $wgOut->showFileCopyError( $tempName, $this->mSavedFile
);
507 wfDebug("$fname: wrote tempfile $tempName to ".$this->mSavedFile
."\n");
510 chmod( $this->mSavedFile
, 0644 );
515 * Stash a file in a temporary directory for later processing
516 * after the user has confirmed it.
518 * If the user doesn't explicitly cancel or accept, these files
519 * can accumulate in the temp directory.
521 * @param string $saveName - the destination filename
522 * @param string $tempName - the source temporary file to save
523 * @return string - full path the stashed file, or false on failure
526 function saveTempUploadedFile( $saveName, $tempName ) {
528 $archive = wfImageArchiveDir( $saveName, 'temp' );
529 if ( !is_dir ( $archive ) ) wfMkdirParents( $archive );
530 $stash = $archive . '/' . gmdate( "YmdHis" ) . '!' . $saveName;
532 $success = $this->mRemoveTempFile
533 ?
rename( $tempName, $stash )
534 : move_uploaded_file( $tempName, $stash );
536 $wgOut->showFileCopyError( $tempName, $stash );
544 * Stash a file in a temporary directory for later processing,
545 * and save the necessary descriptive info into the session.
546 * Returns a key value which will be passed through a form
547 * to pick up the path info on a later invocation.
552 function stashSession() {
553 $stash = $this->saveTempUploadedFile(
554 $this->mUploadSaveName
, $this->mUploadTempName
);
557 # Couldn't save the file.
561 $key = mt_rand( 0, 0x7fffffff );
562 $_SESSION['wsUploadData'][$key] = array(
563 'mUploadTempName' => $stash,
564 'mUploadSize' => $this->mUploadSize
,
565 'mOname' => $this->mOname
);
570 * Remove a temporarily kept file stashed by saveTempUploadedFile().
574 function unsaveUploadedFile() {
576 wfSuppressWarnings();
577 $success = unlink( $this->mUploadTempName
);
580 $wgOut->showFileDeleteError( $this->mUploadTempName
);
587 /* -------------------------------------------------------------- */
590 * Show some text and linkage on successful upload.
593 function showSuccess() {
594 global $wgUser, $wgOut, $wgContLang;
596 $sk = $wgUser->getSkin();
597 $ilink = $sk->makeMediaLink( $this->mUploadSaveName
, Image
::imageUrl( $this->mUploadSaveName
) );
598 $dname = $wgContLang->getNsText( NS_IMAGE
) . ':'.$this->mUploadSaveName
;
599 $dlink = $sk->makeKnownLink( $dname, $dname );
601 $wgOut->addHTML( '<h2>' . wfMsgHtml( 'successfulupload' ) . "</h2>\n" );
602 $text = wfMsgWikiHtml( 'fileuploaded', $ilink, $dlink );
603 $wgOut->addHTML( $text );
604 $wgOut->returnToMain( false );
608 * @param string $error as HTML
611 function uploadError( $error ) {
613 $wgOut->addHTML( "<h2>" . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
614 $wgOut->addHTML( "<span class='error'>{$error}</span>\n" );
618 * There's something wrong with this file, not enough to reject it
619 * totally but we require manual intervention to save it for real.
620 * Stash it away, then present a form asking to confirm or cancel.
622 * @param string $warning as HTML
625 function uploadWarning( $warning ) {
627 global $wgUseCopyrightUpload;
629 $this->mSessionKey
= $this->stashSession();
630 if( !$this->mSessionKey
) {
631 # Couldn't save file; an error has been displayed so let's go.
635 $wgOut->addHTML( "<h2>" . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
636 $wgOut->addHTML( "<ul class='warning'>{$warning}</ul><br />\n" );
638 $save = wfMsgHtml( 'savefile' );
639 $reupload = wfMsgHtml( 'reupload' );
640 $iw = wfMsgWikiHtml( 'ignorewarning' );
641 $reup = wfMsgWikiHtml( 'reuploaddesc' );
642 $titleObj = SpecialPage
::getTitleFor( 'Upload' );
643 $action = $titleObj->escapeLocalURL( 'action=submit' );
645 if ( $wgUseCopyrightUpload )
648 <input type='hidden' name='wpUploadCopyStatus' value=\"" . htmlspecialchars( $this->mUploadCopyStatus
) . "\" />
649 <input type='hidden' name='wpUploadSource' value=\"" . htmlspecialchars( $this->mUploadSource
) . "\" />
656 <form id='uploadwarning' method='post' enctype='multipart/form-data' action='$action'>
657 <input type='hidden' name='wpIgnoreWarning' value='1' />
658 <input type='hidden' name='wpSessionKey' value=\"" . htmlspecialchars( $this->mSessionKey
) . "\" />
659 <input type='hidden' name='wpUploadDescription' value=\"" . htmlspecialchars( $this->mUploadDescription
) . "\" />
660 <input type='hidden' name='wpLicense' value=\"" . htmlspecialchars( $this->mLicense
) . "\" />
661 <input type='hidden' name='wpDestFile' value=\"" . htmlspecialchars( $this->mDestFile
) . "\" />
662 <input type='hidden' name='wpWatchthis' value=\"" . htmlspecialchars( intval( $this->mWatchthis
) ) . "\" />
668 <input tabindex='2' type='submit' name='wpUpload' value=\"$save\" />
670 <td align='left'>$iw</td>
674 <input tabindex='2' type='submit' name='wpReUpload' value=\"{$reupload}\" />
676 <td align='left'>$reup</td>
679 </table></form>\n" );
683 * Displays the main upload form, optionally with a highlighted
684 * error message up at the top.
686 * @param string $msg as HTML
689 function mainUploadForm( $msg='' ) {
690 global $wgOut, $wgUser;
691 global $wgUseCopyrightUpload;
692 global $wgRequest, $wgAllowCopyUploads;
694 $cols = intval($wgUser->getOption( 'cols' ));
695 $ew = $wgUser->getOption( 'editwidth' );
696 if ( $ew ) $ew = " style=\"width:100%\"";
700 $sub = wfMsgHtml( 'uploaderror' );
701 $wgOut->addHTML( "<h2>{$sub}</h2>\n" .
702 "<span class='error'>{$msg}</span>\n" );
704 $wgOut->addHTML( '<div id="uploadtext">' );
705 $wgOut->addWikiText( wfMsg( 'uploadtext' ) );
706 $wgOut->addHTML( '</div>' );
707 $sk = $wgUser->getSkin();
710 $sourcefilename = wfMsgHtml( 'sourcefilename' );
711 $destfilename = wfMsgHtml( 'destfilename' );
712 $summary = wfMsgWikiHtml( 'fileuploadsummary' );
714 $licenses = new Licenses();
715 $license = wfMsgHtml( 'license' );
716 $nolicense = wfMsgHtml( 'nolicense' );
717 $licenseshtml = $licenses->getHtml();
719 $ulb = wfMsgHtml( 'uploadbtn' );
722 $titleObj = SpecialPage
::getTitleFor( 'Upload' );
723 $action = $titleObj->escapeLocalURL();
725 $encDestFile = htmlspecialchars( $this->mDestFile
);
728 ( $wgUser->getOption( 'watchdefault' ) ||
729 ( $wgUser->getOption( 'watchcreations' ) && $this->mDestFile
== '' ) )
730 ?
'checked="checked"'
733 // Prepare form for upload or upload/copy
734 if( $wgAllowCopyUploads && $wgUser->isAllowed( 'upload_by_url' ) ) {
735 $source_comment = wfMsgHtml( 'upload_source_url' );
737 "<input type='radio' id='wpSourceTypeFile' name='wpSourceType' value='file' onchange='toggle_element_activation(\"wpUploadFileURL\",\"wpUploadFile\")' checked />" .
738 "<input tabindex='1' type='file' name='wpUploadFile' id='wpUploadFile' onfocus='toggle_element_activation(\"wpUploadFileURL\",\"wpUploadFile\");toggle_element_check(\"wpSourceTypeFile\",\"wpSourceTypeURL\")'" .
739 ($this->mDestFile?
"":"onchange='fillDestFilename(\"wpUploadFile\")' ") . "size='40' />" .
740 wfMsgHTML( 'upload_source_file' ) . "<br/>" .
741 "<input type='radio' id='wpSourceTypeURL' name='wpSourceType' value='web' onchange='toggle_element_activation(\"wpUploadFile\",\"wpUploadFileURL\")' />" .
742 "<input tabindex='1' type='text' name='wpUploadFileURL' id='wpUploadFileURL' onfocus='toggle_element_activation(\"wpUploadFile\",\"wpUploadFileURL\");toggle_element_check(\"wpSourceTypeURL\",\"wpSourceTypeFile\")'" .
743 ($this->mDestFile?
"":"onchange='fillDestFilename(\"wpUploadFileURL\")' ") . "size='40' DISABLED />" .
744 wfMsgHtml( 'upload_source_url' ) ;
747 "<input tabindex='1' type='file' name='wpUploadFile' id='wpUploadFile' " .
748 ($this->mDestFile?
"":"onchange='fillDestFilename(\"wpUploadFile\")' ") .
750 "<input type='hidden' name='wpSourceType' value='file' />" ;
754 <form id='upload' method='post' enctype='multipart/form-data' action=\"$action\">
757 <td align='right' valign='top'><label for='wpUploadFile'>{$sourcefilename}:</label></td>
763 <td align='right'><label for='wpDestFile'>{$destfilename}:</label></td>
765 <input tabindex='2' type='text' name='wpDestFile' id='wpDestFile' size='40' value=\"$encDestFile\" />
769 <td align='right'><label for='wpUploadDescription'>{$summary}</label></td>
771 <textarea tabindex='3' name='wpUploadDescription' id='wpUploadDescription' rows='6' cols='{$cols}'{$ew}>" . htmlspecialchars( $this->mUploadDescription
) . "</textarea>
776 if ( $licenseshtml != '' ) {
779 <td align='right'><label for='wpLicense'>$license:</label></td>
781 <script type='text/javascript' src=\"$wgStylePath/common/upload.js\"></script>
782 <select name='wpLicense' id='wpLicense' tabindex='4'
783 onchange='licenseSelectorCheck()'>
784 <option value=''>$nolicense</option>
793 if ( $wgUseCopyrightUpload ) {
794 $filestatus = wfMsgHtml ( 'filestatus' );
795 $copystatus = htmlspecialchars( $this->mUploadCopyStatus
);
796 $filesource = wfMsgHtml ( 'filesource' );
797 $uploadsource = htmlspecialchars( $this->mUploadSource
);
800 <td align='right' nowrap='nowrap'><label for='wpUploadCopyStatus'>$filestatus:</label></td>
801 <td><input tabindex='5' type='text' name='wpUploadCopyStatus' id='wpUploadCopyStatus' value=\"$copystatus\" size='40' /></td>
804 <td align='right'><label for='wpUploadCopyStatus'>$filesource:</label></td>
805 <td><input tabindex='6' type='text' name='wpUploadSource' id='wpUploadCopyStatus' value=\"$uploadsource\" size='40' /></td>
815 <input tabindex='7' type='checkbox' name='wpWatchthis' id='wpWatchthis' $watchChecked value='true' />
816 <label for='wpWatchthis'>" . wfMsgHtml( 'watchthisupload' ) . "</label>
817 <input tabindex='8' type='checkbox' name='wpIgnoreWarning' id='wpIgnoreWarning' value='true' />
818 <label for='wpIgnoreWarning'>" . wfMsgHtml( 'ignorewarnings' ) . "</label>
826 <td align='left'><input tabindex='9' type='submit' name='wpUpload' value=\"{$ulb}\" /></td>
833 $wgOut->addWikiText( wfMsgForContent( 'edittools' ) );
842 /* -------------------------------------------------------------- */
845 * Split a file into a base name and all dot-delimited 'extensions'
846 * on the end. Some web server configurations will fall back to
847 * earlier pseudo-'extensions' to determine type and execute
848 * scripts, so the blacklist needs to check them all.
852 function splitExtensions( $filename ) {
853 $bits = explode( '.', $filename );
854 $basename = array_shift( $bits );
855 return array( $basename, $bits );
859 * Perform case-insensitive match against a list of file extensions.
860 * Returns true if the extension is in the list.
866 function checkFileExtension( $ext, $list ) {
867 return in_array( strtolower( $ext ), $list );
871 * Perform case-insensitive match against a list of file extensions.
872 * Returns true if any of the extensions are in the list.
878 function checkFileExtensionList( $ext, $list ) {
879 foreach( $ext as $e ) {
880 if( in_array( strtolower( $e ), $list ) ) {
888 * Verifies that it's ok to include the uploaded file
890 * @param string $tmpfile the full path of the temporary file to verify
891 * @param string $extension The filename extension that the file is to be served with
892 * @return mixed true of the file is verified, a WikiError object otherwise.
894 function verify( $tmpfile, $extension ) {
895 #magically determine mime type
896 $magic=& MimeMagic
::singleton();
897 $mime= $magic->guessMimeType($tmpfile,false);
899 $fname= "SpecialUpload::verify";
901 #check mime type, if desired
902 global $wgVerifyMimeType;
903 if ($wgVerifyMimeType) {
905 #check mime type against file extension
906 if( !$this->verifyExtension( $mime, $extension ) ) {
907 return new WikiErrorMsg( 'uploadcorrupt' );
910 #check mime type blacklist
911 global $wgMimeTypeBlacklist;
912 if( isset($wgMimeTypeBlacklist) && !is_null($wgMimeTypeBlacklist)
913 && $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
914 return new WikiErrorMsg( 'badfiletype', htmlspecialchars( $mime ) );
918 #check for htmlish code and javascript
919 if( $this->detectScript ( $tmpfile, $mime, $extension ) ) {
920 return new WikiErrorMsg( 'uploadscripted' );
924 * Scan the uploaded file for viruses
926 $virus= $this->detectVirus($tmpfile);
928 return new WikiErrorMsg( 'uploadvirus', htmlspecialchars($virus) );
931 wfDebug( "$fname: all clear; passing.\n" );
936 * Checks if the mime type of the uploaded file matches the file extension.
938 * @param string $mime the mime type of the uploaded file
939 * @param string $extension The filename extension that the file is to be served with
942 function verifyExtension( $mime, $extension ) {
943 $fname = 'SpecialUpload::verifyExtension';
945 $magic =& MimeMagic
::singleton();
947 if ( ! $mime ||
$mime == 'unknown' ||
$mime == 'unknown/unknown' )
948 if ( ! $magic->isRecognizableExtension( $extension ) ) {
949 wfDebug( "$fname: passing file with unknown detected mime type; unrecognized extension '$extension', can't verify\n" );
952 wfDebug( "$fname: rejecting file with unknown detected mime type; recognized extension '$extension', so probably invalid file\n" );
956 $match= $magic->isMatchingExtension($extension,$mime);
959 wfDebug( "$fname: no file extension known for mime type $mime, passing file\n" );
961 } elseif ($match===true) {
962 wfDebug( "$fname: mime type $mime matches extension $extension, passing file\n" );
964 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
968 wfDebug( "$fname: mime type $mime mismatches file extension $extension, rejecting file\n" );
973 /** Heuristig for detecting files that *could* contain JavaScript instructions or
974 * things that may look like HTML to a browser and are thus
975 * potentially harmful. The present implementation will produce false positives in some situations.
977 * @param string $file Pathname to the temporary upload file
978 * @param string $mime The mime type of the file
979 * @param string $extension The extension of the file
980 * @return bool true if the file contains something looking like embedded scripts
982 function detectScript($file, $mime, $extension) {
983 global $wgAllowTitlesInSVG;
985 #ugly hack: for text files, always look at the entire file.
986 #For binarie field, just check the first K.
988 if (strpos($mime,'text/')===0) $chunk = file_get_contents( $file );
990 $fp = fopen( $file, 'rb' );
991 $chunk = fread( $fp, 1024 );
995 $chunk= strtolower( $chunk );
997 if (!$chunk) return false;
999 #decode from UTF-16 if needed (could be used for obfuscation).
1000 if (substr($chunk,0,2)=="\xfe\xff") $enc= "UTF-16BE";
1001 elseif (substr($chunk,0,2)=="\xff\xfe") $enc= "UTF-16LE";
1004 if ($enc) $chunk= iconv($enc,"ASCII//IGNORE",$chunk);
1006 $chunk= trim($chunk);
1008 #FIXME: convert from UTF-16 if necessarry!
1010 wfDebug("SpecialUpload::detectScript: checking for embedded scripts and HTML stuff\n");
1012 #check for HTML doctype
1013 if (eregi("<!DOCTYPE *X?HTML",$chunk)) return true;
1016 * Internet Explorer for Windows performs some really stupid file type
1017 * autodetection which can cause it to interpret valid image files as HTML
1018 * and potentially execute JavaScript, creating a cross-site scripting
1021 * Apple's Safari browser also performs some unsafe file type autodetection
1022 * which can cause legitimate files to be interpreted as HTML if the
1023 * web server is not correctly configured to send the right content-type
1024 * (or if you're really uploading plain text and octet streams!)
1026 * Returns true if IE is likely to mistake the given file for HTML.
1027 * Also returns true if Safari would mistake the given file for HTML
1028 * when served with a generic content-type.
1034 '<html', #also in safari
1037 '<script', #also in safari
1040 if( ! $wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
1044 foreach( $tags as $tag ) {
1045 if( false !== strpos( $chunk, $tag ) ) {
1051 * look for javascript
1054 #resolve entity-refs to look at attributes. may be harsh on big files... cache result?
1055 $chunk = Sanitizer
::decodeCharReferences( $chunk );
1057 #look for script-types
1058 if (preg_match("!type\s*=\s*['\"]?\s*(\w*/)?(ecma|java)!sim",$chunk)) return true;
1060 #look for html-style script-urls
1061 if (preg_match("!(href|src|data)\s*=\s*['\"]?\s*(ecma|java)script:!sim",$chunk)) return true;
1063 #look for css-style script-urls
1064 if (preg_match("!url\s*\(\s*['\"]?\s*(ecma|java)script:!sim",$chunk)) return true;
1066 wfDebug("SpecialUpload::detectScript: no scripts found\n");
1070 /** Generic wrapper function for a virus scanner program.
1071 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
1072 * $wgAntivirusRequired may be used to deny upload if the scan fails.
1074 * @param string $file Pathname to the temporary upload file
1075 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
1076 * or a string containing feedback from the virus scanner if a virus was found.
1077 * If textual feedback is missing but a virus was found, this function returns true.
1079 function detectVirus($file) {
1080 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
1082 $fname= "SpecialUpload::detectVirus";
1084 if (!$wgAntivirus) { #disabled?
1085 wfDebug("$fname: virus scanner disabled\n");
1090 if (!$wgAntivirusSetup[$wgAntivirus]) {
1091 wfDebug("$fname: unknown virus scanner: $wgAntivirus\n");
1093 $wgOut->addHTML( "<div class='error'>Bad configuration: unknown virus scanner: <i>$wgAntivirus</i></div>\n" ); #LOCALIZE
1095 return "unknown antivirus: $wgAntivirus";
1098 #look up scanner configuration
1099 $virus_scanner= $wgAntivirusSetup[$wgAntivirus]["command"]; #command pattern
1100 $virus_scanner_codes= $wgAntivirusSetup[$wgAntivirus]["codemap"]; #exit-code map
1101 $msg_pattern= $wgAntivirusSetup[$wgAntivirus]["messagepattern"]; #message pattern
1103 $scanner= $virus_scanner; #copy, so we can resolve the pattern
1105 if (strpos($scanner,"%f")===false) $scanner.= " ".wfEscapeShellArg($file); #simple pattern: append file to scan
1106 else $scanner= str_replace("%f",wfEscapeShellArg($file),$scanner); #complex pattern: replace "%f" with file to scan
1108 wfDebug("$fname: running virus scan: $scanner \n");
1110 #execute virus scanner
1113 #NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
1114 # that does not seem to be worth the pain.
1115 # Ask me (Duesentrieb) about it if it's ever needed.
1116 if (wfIsWindows()) exec("$scanner",$output,$code);
1117 else exec("$scanner 2>&1",$output,$code);
1119 $exit_code= $code; #remeber for user feedback
1121 if ($virus_scanner_codes) { #map exit code to AV_xxx constants.
1122 if (isset($virus_scanner_codes[$code])) $code= $virus_scanner_codes[$code]; #explicite mapping
1123 else if (isset($virus_scanner_codes["*"])) $code= $virus_scanner_codes["*"]; #fallback mapping
1126 if ($code===AV_SCAN_FAILED
) { #scan failed (code was mapped to false by $virus_scanner_codes)
1127 wfDebug("$fname: failed to scan $file (code $exit_code).\n");
1129 if ($wgAntivirusRequired) return "scan failed (code $exit_code)";
1132 else if ($code===AV_SCAN_ABORTED
) { #scan failed because filetype is unknown (probably imune)
1133 wfDebug("$fname: unsupported file type $file (code $exit_code).\n");
1136 else if ($code===AV_NO_VIRUS
) {
1137 wfDebug("$fname: file passed virus scan.\n");
1138 return false; #no virus found
1141 $output= join("\n",$output);
1142 $output= trim($output);
1144 if (!$output) $output= true; #if ther's no output, return true
1145 else if ($msg_pattern) {
1147 if (preg_match($msg_pattern,$output,$groups)) {
1148 if ($groups[1]) $output= $groups[1];
1152 wfDebug("$fname: FOUND VIRUS! scanner feedback: $output");
1158 * Check if the temporary file is MacBinary-encoded, as some uploads
1159 * from Internet Explorer on Mac OS Classic and Mac OS X will be.
1160 * If so, the data fork will be extracted to a second temporary file,
1161 * which will then be checked for validity and either kept or discarded.
1165 function checkMacBinary() {
1166 $macbin = new MacBinary( $this->mUploadTempName
);
1167 if( $macbin->isValid() ) {
1168 $dataFile = tempnam( wfTempDir(), "WikiMacBinary" );
1169 $dataHandle = fopen( $dataFile, 'wb' );
1171 wfDebug( "SpecialUpload::checkMacBinary: Extracting MacBinary data fork to $dataFile\n" );
1172 $macbin->extractData( $dataHandle );
1174 $this->mUploadTempName
= $dataFile;
1175 $this->mUploadSize
= $macbin->dataForkLength();
1177 // We'll have to manually remove the new file if it's not kept.
1178 $this->mRemoveTempFile
= true;
1184 * If we've modified the upload file we need to manually remove it
1185 * on exit to clean up.
1188 function cleanupTempFile() {
1189 if( $this->mRemoveTempFile
&& file_exists( $this->mUploadTempName
) ) {
1190 wfDebug( "SpecialUpload::cleanupTempFile: Removing temporary file $this->mUploadTempName\n" );
1191 unlink( $this->mUploadTempName
);
1196 * Check if there's an overwrite conflict and, if so, if restrictions
1197 * forbid this user from performing the upload.
1199 * @return mixed true on success, WikiError on failure
1202 function checkOverwrite( $name ) {
1203 $img = Image
::newFromName( $name );
1204 if( is_null( $img ) ) {
1205 // Uh... this shouldn't happen ;)
1206 // But if it does, fall through to previous behavior
1211 if( $img->exists() ) {
1212 global $wgUser, $wgOut;
1213 if( $img->isLocal() ) {
1214 if( !$wgUser->isAllowed( 'reupload' ) ) {
1215 $error = 'fileexists-forbidden';
1218 if( !$wgUser->isAllowed( 'reupload' ) ||
1219 !$wgUser->isAllowed( 'reupload-shared' ) ) {
1220 $error = "fileexists-shared-forbidden";
1226 $errorText = wfMsg( $error, wfEscapeWikiText( $img->getName() ) );
1227 return new WikiError( $wgOut->parse( $errorText ) );
1230 // Rockin', go ahead and upload