5 * @subpackage SpecialPage
11 require_once 'Image.php';
15 function wfSpecialUpload() {
17 $form = new UploadForm( $wgRequest );
24 * @subpackage SpecialPage
30 var $mUploadFile, $mUploadDescription, $mLicense ,$mIgnoreWarning, $mUploadError;
31 var $mUploadSaveName, $mUploadTempName, $mUploadSize, $mUploadOldVersion;
32 var $mUploadCopyStatus, $mUploadSource, $mReUpload, $mAction, $mUpload;
33 var $mOname, $mSessionKey, $mStashed, $mDestFile, $mRemoveTempFile, $mSourceType;
37 * Constructor : initialise object
38 * Get data POSTed through the form and assign them to the object
39 * @param $request Data posted.
41 function UploadForm( &$request ) {
42 global $wgAllowCopyUploads;
43 $this->mDestFile
= $request->getText( 'wpDestFile' );
45 if( !$request->wasPosted() ) {
46 # GET requests just give the main form; no data except wpDestfile.
50 $this->mIgnoreWarning
= $request->getCheck( 'wpIgnoreWarning' );
51 $this->mReUpload
= $request->getCheck( 'wpReUpload' );
52 $this->mUpload
= $request->getCheck( 'wpUpload' );
54 $this->mUploadDescription
= $request->getText( 'wpUploadDescription' );
55 $this->mLicense
= $request->getText( 'wpLicense' );
56 $this->mUploadCopyStatus
= $request->getText( 'wpUploadCopyStatus' );
57 $this->mUploadSource
= $request->getText( 'wpUploadSource' );
58 $this->mWatchthis
= $request->getBool( 'wpWatchthis' );
59 $this->mSourceType
= $request->getText( 'wpSourceType' );
60 wfDebug( "UploadForm: watchthis is: '$this->mWatchthis'\n" );
62 $this->mAction
= $request->getVal( 'action' );
64 $this->mSessionKey
= $request->getInt( 'wpSessionKey' );
65 if( !empty( $this->mSessionKey
) &&
66 isset( $_SESSION['wsUploadData'][$this->mSessionKey
] ) ) {
68 * Confirming a temporarily stashed upload.
69 * We don't want path names to be forged, so we keep
70 * them in the session on the server and just give
71 * an opaque key to the user agent.
73 $data = $_SESSION['wsUploadData'][$this->mSessionKey
];
74 $this->mUploadTempName
= $data['mUploadTempName'];
75 $this->mUploadSize
= $data['mUploadSize'];
76 $this->mOname
= $data['mOname'];
77 $this->mUploadError
= 0/*UPLOAD_ERR_OK*/;
78 $this->mStashed
= true;
79 $this->mRemoveTempFile
= false;
82 *Check for a newly uploaded file.
84 if( $wgAllowCopyUploads && $this->mSourceType
== 'web' ) {
85 $this->initializeFromUrl( $request );
87 $this->initializeFromUpload( $request );
93 * Initialize the uploaded file from PHP data
96 function initializeFromUpload( $request ) {
97 $this->mUploadTempName
= $request->getFileTempName( 'wpUploadFile' );
98 $this->mUploadSize
= $request->getFileSize( 'wpUploadFile' );
99 $this->mOname
= $request->getFileName( 'wpUploadFile' );
100 $this->mUploadError
= $request->getUploadError( 'wpUploadFile' );
101 $this->mSessionKey
= false;
102 $this->mStashed
= false;
103 $this->mRemoveTempFile
= false; // PHP will handle this
107 * Copy a web file to a temporary file
110 function initializeFromUrl( $request ) {
111 global $wgTmpDirectory, $wgMaxUploadSize;
112 $url = $request->getText( 'wpUploadFileURL' );
113 $local_file = tempnam( $wgTmpDirectory, 'WEBUPLOAD' );
115 $this->mUploadTempName
= $local_file;
116 $this->mUploadError
= $this->curlCopy( $url, $local_file );
117 $this->mUploadSize
= $this->mUploadTempFileSize
;
118 $this->mOname
= array_pop( explode( '/', $url ) );
119 $this->mSessionKey
= false;
120 $this->mStashed
= false;
122 // PHP won't auto-cleanup the file
123 $this->mRemoveTempFile
= file_exists( $local_file );
128 * Returns true if there was an error, false otherwise
130 private function curlCopy( $url, $dest ) {
131 global $wgMaxUploadSize, $wgUser;
133 if( !$wgUser->isAllowed( 'upload_by_url' ) ) {
134 $wgOut->permissionRequired( 'upload_by_url' );
138 # Maybe remove some pasting blanks :-)
139 $url = strtolower( trim( $url ) );
140 if( substr( $url, 0, 7 ) != 'http://' && substr( $url, 0, 6 ) != 'ftp://' ) {
141 # Only HTTP or FTP URLs
145 # Open temporary file
146 $this->mUploadTempFileSize
= 0;
147 $this->mUploadTempFile
= @fopen
( $this->mUploadTempName
, "wb" );
148 if( $this->mUploadTempFile
=== false ) {
149 # Could not open temporary file to write in
154 curl_setopt( $ch, CURLOPT_HTTP_VERSION
, 1.0); # Probably not needed, but apparently can work around some bug
155 curl_setopt( $ch, CURLOPT_TIMEOUT
, 10); # 10 seconds timeout
156 curl_setopt( $ch, CURLOPT_LOW_SPEED_LIMIT
, 512); # 0.5KB per second minimum transfer speed
157 curl_setopt( $ch, CURLOPT_URL
, $url);
158 curl_setopt( $ch, CURLOPT_WRITEFUNCTION
, array( $this, 'uploadCurlCallback' ) );
160 $error = curl_errno( $ch ) ?
true : false;
161 # if ( $error ) print curl_error ( $ch ) ; # Debugging output
164 fclose( $this->mUploadTempFile
);
165 unset( $this->mUploadTempFile
);
174 * Callback function for CURL-based web transfer
175 * Write data to file unless we've passed the length limit;
176 * if so, abort immediately.
179 function uploadCurlCallback( $ch, $data ) {
180 global $wgMaxUploadSize;
181 $length = strlen( $data );
182 $this->mUploadTempFileSize +
= $length;
183 if( $this->mUploadTempFileSize
> $wgMaxUploadSize ) {
186 fwrite( $this->mUploadTempFile
, $data );
195 global $wgUser, $wgOut;
196 global $wgEnableUploads, $wgUploadDirectory;
198 # Check uploading enabled
199 if( !$wgEnableUploads ) {
200 $wgOut->showErrorPage( 'uploaddisabled', 'uploaddisabledtext' );
205 if( !$wgUser->isAllowed( 'upload' ) ) {
206 if( !$wgUser->isLoggedIn() ) {
207 $wgOut->showErrorPage( 'uploadnologin', 'uploadnologintext' );
209 $wgOut->permissionRequired( 'upload' );
215 if( $wgUser->isBlocked() ) {
216 $wgOut->blockedPage();
221 $wgOut->readOnlyPage();
225 /** Check if the image directory is writeable, this is a common mistake */
226 if( !is_writeable( $wgUploadDirectory ) ) {
227 $wgOut->addWikiText( wfMsg( 'upload_directory_read_only', $wgUploadDirectory ) );
231 if( $this->mReUpload
) {
232 if( !$this->unsaveUploadedFile() ) {
235 $this->mainUploadForm();
236 } else if( 'submit' == $this->mAction ||
$this->mUpload
) {
237 $this->processUpload();
239 $this->mainUploadForm();
242 $this->cleanupTempFile();
245 /* -------------------------------------------------------------- */
248 * Really do the upload
249 * Checks are made in SpecialUpload::execute()
252 function processUpload() {
253 global $wgUser, $wgOut;
255 /* Check for PHP error if any, requires php 4.2 or newer */
256 if( $this->mUploadError
== 1/*UPLOAD_ERR_INI_SIZE*/ ) {
257 $this->mainUploadForm( wfMsgHtml( 'largefileserver' ) );
262 * If there was no filename or a zero size given, give up quick.
264 if( trim( $this->mOname
) == '' ||
empty( $this->mUploadSize
) ) {
265 $this->mainUploadForm( wfMsgHtml( 'emptyfile' ) );
269 # Chop off any directories in the given filename
270 if( $this->mDestFile
) {
271 $basename = wfBaseName( $this->mDestFile
);
273 $basename = wfBaseName( $this->mOname
);
277 * We'll want to blacklist against *any* 'extension', and use
278 * only the final one for the whitelist.
280 list( $partname, $ext ) = $this->splitExtensions( $basename );
282 if( count( $ext ) ) {
283 $finalExt = $ext[count( $ext ) - 1];
287 $fullExt = implode( '.', $ext );
289 # If there was more than one "extension", reassemble the base
290 # filename to prevent bogus complaints about length
291 if( count( $ext ) > 1 ) {
292 for( $i = 0; $i < count( $ext ) - 1; $i++
)
293 $partname .= '.' . $ext[$i];
296 if( strlen( $partname ) < 3 ) {
297 $this->mainUploadForm( wfMsgHtml( 'minlength' ) );
302 * Filter out illegal characters, and try to make a legible name
303 * out of it. We'll strip some silently that Title would die on.
305 $filtered = preg_replace ( "/[^".Title
::legalChars()."]|:/", '-', $basename );
306 $nt = Title
::newFromText( $filtered );
307 if( is_null( $nt ) ) {
308 $this->uploadError( wfMsgWikiHtml( 'illegalfilename', htmlspecialchars( $filtered ) ) );
311 $nt =& Title
::makeTitle( NS_IMAGE
, $nt->getDBkey() );
312 $this->mUploadSaveName
= $nt->getDBkey();
315 * If the image is protected, non-sysop users won't be able
316 * to modify it by uploading a new revision.
318 if( !$nt->userCanEdit() ) {
319 return $this->uploadError( wfMsgWikiHtml( 'protectedpage' ) );
323 * In some cases we may forbid overwriting of existing files.
325 $overwrite = $this->checkOverwrite( $this->mUploadSaveName
);
326 if( WikiError
::isError( $overwrite ) ) {
327 return $this->uploadError( $overwrite->toString() );
330 /* Don't allow users to override the blacklist (check file extension) */
331 global $wgStrictFileExtensions;
332 global $wgFileExtensions, $wgFileBlacklist;
333 if( $this->checkFileExtensionList( $ext, $wgFileBlacklist ) ||
334 ($wgStrictFileExtensions &&
335 !$this->checkFileExtension( $finalExt, $wgFileExtensions ) ) ) {
336 return $this->uploadError( wfMsgHtml( 'badfiletype', htmlspecialchars( $fullExt ) ) );
340 * Look at the contents of the file; if we can recognize the
341 * type but it's corrupt or data of the wrong type, we should
342 * probably not accept it.
344 if( !$this->mStashed
) {
345 $this->checkMacBinary();
346 $veri = $this->verify( $this->mUploadTempName
, $finalExt );
348 if( $veri !== true ) { //it's a wiki error...
349 return $this->uploadError( $veri->toString() );
354 * Provide an opportunity for extensions to add futher checks
357 if( !wfRunHooks( 'UploadVerification',
358 array( $this->mUploadSaveName
, $this->mUploadTempName
, &$error ) ) ) {
359 return $this->uploadError( $error );
363 * Check for non-fatal conditions
365 if ( ! $this->mIgnoreWarning
) {
368 global $wgCapitalLinks;
369 if( $wgCapitalLinks ) {
370 $filtered = ucfirst( $filtered );
372 if( $this->mUploadSaveName
!= $filtered ) {
373 $warning .= '<li>'.wfMsgHtml( 'badfilename', htmlspecialchars( $this->mUploadSaveName
) ).'</li>';
376 global $wgCheckFileExtensions;
377 if ( $wgCheckFileExtensions ) {
378 if ( ! $this->checkFileExtension( $finalExt, $wgFileExtensions ) ) {
379 $warning .= '<li>'.wfMsgHtml( 'badfiletype', htmlspecialchars( $fullExt ) ).'</li>';
383 global $wgUploadSizeWarning;
384 if ( $wgUploadSizeWarning && ( $this->mUploadSize
> $wgUploadSizeWarning ) ) {
385 # TODO: Format $wgUploadSizeWarning to something that looks better than the raw byte
386 # value, perhaps add GB,MB and KB suffixes?
387 $warning .= '<li>'.wfMsgHtml( 'largefile', $wgUploadSizeWarning, $this->mUploadSize
).'</li>';
389 if ( $this->mUploadSize
== 0 ) {
390 $warning .= '<li>'.wfMsgHtml( 'emptyfile' ).'</li>';
393 if( $nt->getArticleID() ) {
395 $sk = $wgUser->getSkin();
396 $dlink = $sk->makeKnownLinkObj( $nt );
397 $warning .= '<li>'.wfMsgHtml( 'fileexists', $dlink ).'</li>';
399 # If the file existed before and was deleted, warn the user of this
400 # Don't bother doing so if the image exists now, however
401 $image = new Image( $nt );
402 if( $image->wasDeleted() ) {
403 $skin = $wgUser->getSkin();
404 $ltitle = Title
::makeTitle( NS_SPECIAL
, 'Log' );
405 $llink = $skin->makeKnownLinkObj( $ltitle, wfMsgHtml( 'deletionlog' ), 'type=delete&page=' . $nt->getPrefixedUrl() );
406 $warning .= wfOpenElement( 'li' ) . wfMsgWikiHtml( 'filewasdeleted', $llink ) . wfCloseElement( 'li' );
410 if( $warning != '' ) {
412 * Stash the file in a temporary location; the user can choose
413 * to let it through and we'll complete the upload then.
415 return $this->uploadWarning( $warning );
420 * Try actually saving the thing...
421 * It will show an error form on failure.
423 $hasBeenMunged = !empty( $this->mSessionKey
) ||
$this->mRemoveTempFile
;
424 if( $this->saveUploadedFile( $this->mUploadSaveName
,
425 $this->mUploadTempName
,
428 * Update the upload log and create the description page
429 * if it's a new file.
431 $img = Image
::newFromName( $this->mUploadSaveName
);
432 $success = $img->recordUpload( $this->mUploadOldVersion
,
433 $this->mUploadDescription
,
435 $this->mUploadCopyStatus
,
436 $this->mUploadSource
,
440 $this->showSuccess();
441 wfRunHooks( 'UploadComplete', array( &$img ) );
443 // Image::recordUpload() fails if the image went missing, which is
444 // unlikely, hence the lack of a specialised message
445 $wgOut->showFileNotFoundError( $this->mUploadSaveName
);
451 * Move the uploaded file from its temporary location to the final
452 * destination. If a previous version of the file exists, move
453 * it into the archive subdirectory.
455 * @todo If the later save fails, we may have disappeared the original file.
457 * @param string $saveName
458 * @param string $tempName full path to the temporary file
459 * @param bool $useRename if true, doesn't check that the source file
460 * is a PHP-managed upload temporary
462 function saveUploadedFile( $saveName, $tempName, $useRename = false ) {
463 global $wgOut, $wgAllowCopyUploads;
465 if ( !$useRename AND $wgAllowCopyUploads AND $this->mSourceType
== 'web' ) $useRename = true;
467 $fname= "SpecialUpload::saveUploadedFile";
469 $dest = wfImageDir( $saveName );
470 $archive = wfImageArchiveDir( $saveName );
471 if ( !is_dir( $dest ) ) wfMkdirParents( $dest );
472 if ( !is_dir( $archive ) ) wfMkdirParents( $archive );
474 $this->mSavedFile
= "{$dest}/{$saveName}";
476 if( is_file( $this->mSavedFile
) ) {
477 $this->mUploadOldVersion
= gmdate( 'YmdHis' ) . "!{$saveName}";
478 wfSuppressWarnings();
479 $success = rename( $this->mSavedFile
, "${archive}/{$this->mUploadOldVersion}" );
483 $wgOut->showFileRenameError( $this->mSavedFile
,
484 "${archive}/{$this->mUploadOldVersion}" );
487 else wfDebug("$fname: moved file ".$this->mSavedFile
." to ${archive}/{$this->mUploadOldVersion}\n");
490 $this->mUploadOldVersion
= '';
493 wfSuppressWarnings();
494 $success = $useRename
495 ?
rename( $tempName, $this->mSavedFile
)
496 : move_uploaded_file( $tempName, $this->mSavedFile
);
500 $wgOut->showFileCopyError( $tempName, $this->mSavedFile
);
503 wfDebug("$fname: wrote tempfile $tempName to ".$this->mSavedFile
."\n");
506 chmod( $this->mSavedFile
, 0644 );
511 * Stash a file in a temporary directory for later processing
512 * after the user has confirmed it.
514 * If the user doesn't explicitly cancel or accept, these files
515 * can accumulate in the temp directory.
517 * @param string $saveName - the destination filename
518 * @param string $tempName - the source temporary file to save
519 * @return string - full path the stashed file, or false on failure
522 function saveTempUploadedFile( $saveName, $tempName ) {
524 $archive = wfImageArchiveDir( $saveName, 'temp' );
525 if ( !is_dir ( $archive ) ) wfMkdirParents( $archive );
526 $stash = $archive . '/' . gmdate( "YmdHis" ) . '!' . $saveName;
528 $success = $this->mRemoveTempFile
529 ?
rename( $tempName, $stash )
530 : move_uploaded_file( $tempName, $stash );
532 $wgOut->showFileCopyError( $tempName, $stash );
540 * Stash a file in a temporary directory for later processing,
541 * and save the necessary descriptive info into the session.
542 * Returns a key value which will be passed through a form
543 * to pick up the path info on a later invocation.
548 function stashSession() {
549 $stash = $this->saveTempUploadedFile(
550 $this->mUploadSaveName
, $this->mUploadTempName
);
553 # Couldn't save the file.
557 $key = mt_rand( 0, 0x7fffffff );
558 $_SESSION['wsUploadData'][$key] = array(
559 'mUploadTempName' => $stash,
560 'mUploadSize' => $this->mUploadSize
,
561 'mOname' => $this->mOname
);
566 * Remove a temporarily kept file stashed by saveTempUploadedFile().
570 function unsaveUploadedFile() {
572 wfSuppressWarnings();
573 $success = unlink( $this->mUploadTempName
);
576 $wgOut->showFileDeleteError( $this->mUploadTempName
);
583 /* -------------------------------------------------------------- */
586 * Show some text and linkage on successful upload.
589 function showSuccess() {
590 global $wgUser, $wgOut, $wgContLang;
592 $sk = $wgUser->getSkin();
593 $ilink = $sk->makeMediaLink( $this->mUploadSaveName
, Image
::imageUrl( $this->mUploadSaveName
) );
594 $dname = $wgContLang->getNsText( NS_IMAGE
) . ':'.$this->mUploadSaveName
;
595 $dlink = $sk->makeKnownLink( $dname, $dname );
597 $wgOut->addHTML( '<h2>' . wfMsgHtml( 'successfulupload' ) . "</h2>\n" );
598 $text = wfMsgWikiHtml( 'fileuploaded', $ilink, $dlink );
599 $wgOut->addHTML( $text );
600 $wgOut->returnToMain( false );
604 * @param string $error as HTML
607 function uploadError( $error ) {
609 $wgOut->addHTML( "<h2>" . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
610 $wgOut->addHTML( "<span class='error'>{$error}</span>\n" );
614 * There's something wrong with this file, not enough to reject it
615 * totally but we require manual intervention to save it for real.
616 * Stash it away, then present a form asking to confirm or cancel.
618 * @param string $warning as HTML
621 function uploadWarning( $warning ) {
623 global $wgUseCopyrightUpload;
625 $this->mSessionKey
= $this->stashSession();
626 if( !$this->mSessionKey
) {
627 # Couldn't save file; an error has been displayed so let's go.
631 $wgOut->addHTML( "<h2>" . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
632 $wgOut->addHTML( "<ul class='warning'>{$warning}</ul><br />\n" );
634 $save = wfMsgHtml( 'savefile' );
635 $reupload = wfMsgHtml( 'reupload' );
636 $iw = wfMsgWikiHtml( 'ignorewarning' );
637 $reup = wfMsgWikiHtml( 'reuploaddesc' );
638 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Upload' );
639 $action = $titleObj->escapeLocalURL( 'action=submit' );
641 if ( $wgUseCopyrightUpload )
644 <input type='hidden' name='wpUploadCopyStatus' value=\"" . htmlspecialchars( $this->mUploadCopyStatus
) . "\" />
645 <input type='hidden' name='wpUploadSource' value=\"" . htmlspecialchars( $this->mUploadSource
) . "\" />
652 <form id='uploadwarning' method='post' enctype='multipart/form-data' action='$action'>
653 <input type='hidden' name='wpIgnoreWarning' value='1' />
654 <input type='hidden' name='wpSessionKey' value=\"" . htmlspecialchars( $this->mSessionKey
) . "\" />
655 <input type='hidden' name='wpUploadDescription' value=\"" . htmlspecialchars( $this->mUploadDescription
) . "\" />
656 <input type='hidden' name='wpLicense' value=\"" . htmlspecialchars( $this->mLicense
) . "\" />
657 <input type='hidden' name='wpDestFile' value=\"" . htmlspecialchars( $this->mDestFile
) . "\" />
658 <input type='hidden' name='wpWatchthis' value=\"" . htmlspecialchars( intval( $this->mWatchthis
) ) . "\" />
664 <input tabindex='2' type='submit' name='wpUpload' value=\"$save\" />
666 <td align='left'>$iw</td>
670 <input tabindex='2' type='submit' name='wpReUpload' value=\"{$reupload}\" />
672 <td align='left'>$reup</td>
675 </table></form>\n" );
679 * Displays the main upload form, optionally with a highlighted
680 * error message up at the top.
682 * @param string $msg as HTML
685 function mainUploadForm( $msg='' ) {
686 global $wgOut, $wgUser;
687 global $wgUseCopyrightUpload;
688 global $wgRequest, $wgAllowCopyUploads;
690 $cols = intval($wgUser->getOption( 'cols' ));
691 $ew = $wgUser->getOption( 'editwidth' );
692 if ( $ew ) $ew = " style=\"width:100%\"";
696 $sub = wfMsgHtml( 'uploaderror' );
697 $wgOut->addHTML( "<h2>{$sub}</h2>\n" .
698 "<span class='error'>{$msg}</span>\n" );
700 $wgOut->addHTML( '<div id="uploadtext">' );
701 $wgOut->addWikiText( wfMsg( 'uploadtext' ) );
702 $wgOut->addHTML( '</div>' );
703 $sk = $wgUser->getSkin();
706 $sourcefilename = wfMsgHtml( 'sourcefilename' );
707 $destfilename = wfMsgHtml( 'destfilename' );
708 $summary = wfMsgWikiHtml( 'fileuploadsummary' );
710 $licenses = new Licenses();
711 $license = wfMsgHtml( 'license' );
712 $nolicense = wfMsgHtml( 'nolicense' );
713 $licenseshtml = $licenses->getHtml();
715 $ulb = wfMsgHtml( 'uploadbtn' );
718 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Upload' );
719 $action = $titleObj->escapeLocalURL();
721 $encDestFile = htmlspecialchars( $this->mDestFile
);
723 $watchChecked = $wgUser->getOption( 'watchdefault' )
724 ?
'checked="checked"'
727 // Prepare form for upload or upload/copy
728 if( $wgAllowCopyUploads && $wgUser->isAllowed( 'upload_by_url' ) ) {
729 $source_comment = wfMsgHtml( 'upload_source_url' );
731 "<input type='radio' id='wpSourceTypeFile' name='wpSourceType' value='file' onchange='toggle_element_activation(\"wpUploadFileURL\",\"wpUploadFile\")' checked />" .
732 "<input tabindex='1' type='file' name='wpUploadFile' id='wpUploadFile' onfocus='toggle_element_activation(\"wpUploadFileURL\",\"wpUploadFile\");toggle_element_check(\"wpSourceTypeFile\",\"wpSourceTypeURL\")'" .
733 ($this->mDestFile?
"":"onchange='fillDestFilename(\"wpUploadFile\")' ") . "size='40' />" .
734 wfMsgHTML( 'upload_source_file' ) . "<br/>" .
735 "<input type='radio' id='wpSourceTypeURL' name='wpSourceType' value='web' onchange='toggle_element_activation(\"wpUploadFile\",\"wpUploadFileURL\")' />" .
736 "<input tabindex='1' type='text' name='wpUploadFileURL' id='wpUploadFileURL' onfocus='toggle_element_activation(\"wpUploadFile\",\"wpUploadFileURL\");toggle_element_check(\"wpSourceTypeURL\",\"wpSourceTypeFile\")'" .
737 ($this->mDestFile?
"":"onchange='fillDestFilename(\"wpUploadFileURL\")' ") . "size='40' DISABLED />" .
738 wfMsgHtml( 'upload_source_url' ) ;
741 "<input tabindex='1' type='file' name='wpUploadFile' id='wpUploadFile' " .
742 ($this->mDestFile?
"":"onchange='fillDestFilename(\"wpUploadFile\")' ") .
744 "<input type='hidden' name='wpSourceType' value='file' />" ;
748 <form id='upload' method='post' enctype='multipart/form-data' action=\"$action\">
751 <td align='right' valign='top'><label for='wpUploadFile'>{$sourcefilename}:</label></td>
757 <td align='right'><label for='wpDestFile'>{$destfilename}:</label></td>
759 <input tabindex='2' type='text' name='wpDestFile' id='wpDestFile' size='40' value=\"$encDestFile\" />
763 <td align='right'><label for='wpUploadDescription'>{$summary}</label></td>
765 <textarea tabindex='3' name='wpUploadDescription' id='wpUploadDescription' rows='6' cols='{$cols}'{$ew}>" . htmlspecialchars( $this->mUploadDescription
) . "</textarea>
770 if ( $licenseshtml != '' ) {
773 <td align='right'><label for='wpLicense'>$license:</label></td>
775 <script type='text/javascript' src=\"$wgStylePath/common/upload.js\"></script>
776 <select name='wpLicense' id='wpLicense' tabindex='4'
777 onchange='licenseSelectorCheck()'>
778 <option value=''>$nolicense</option>
787 if ( $wgUseCopyrightUpload ) {
788 $filestatus = wfMsgHtml ( 'filestatus' );
789 $copystatus = htmlspecialchars( $this->mUploadCopyStatus
);
790 $filesource = wfMsgHtml ( 'filesource' );
791 $uploadsource = htmlspecialchars( $this->mUploadSource
);
794 <td align='right' nowrap='nowrap'><label for='wpUploadCopyStatus'>$filestatus:</label></td>
795 <td><input tabindex='5' type='text' name='wpUploadCopyStatus' id='wpUploadCopyStatus' value=\"$copystatus\" size='40' /></td>
798 <td align='right'><label for='wpUploadCopyStatus'>$filesource:</label></td>
799 <td><input tabindex='6' type='text' name='wpUploadSource' id='wpUploadCopyStatus' value=\"$uploadsource\" size='40' /></td>
809 <input tabindex='7' type='checkbox' name='wpWatchthis' id='wpWatchthis' $watchChecked value='true' />
810 <label for='wpWatchthis'>" . wfMsgHtml( 'watchthisupload' ) . "</label>
811 <input tabindex='8' type='checkbox' name='wpIgnoreWarning' id='wpIgnoreWarning' value='true' />
812 <label for='wpIgnoreWarning'>" . wfMsgHtml( 'ignorewarnings' ) . "</label>
820 <td align='left'><input tabindex='9' type='submit' name='wpUpload' value=\"{$ulb}\" /></td>
827 $wgOut->addWikiText( wfMsgForContent( 'edittools' ) );
836 /* -------------------------------------------------------------- */
839 * Split a file into a base name and all dot-delimited 'extensions'
840 * on the end. Some web server configurations will fall back to
841 * earlier pseudo-'extensions' to determine type and execute
842 * scripts, so the blacklist needs to check them all.
846 function splitExtensions( $filename ) {
847 $bits = explode( '.', $filename );
848 $basename = array_shift( $bits );
849 return array( $basename, $bits );
853 * Perform case-insensitive match against a list of file extensions.
854 * Returns true if the extension is in the list.
860 function checkFileExtension( $ext, $list ) {
861 return in_array( strtolower( $ext ), $list );
865 * Perform case-insensitive match against a list of file extensions.
866 * Returns true if any of the extensions are in the list.
872 function checkFileExtensionList( $ext, $list ) {
873 foreach( $ext as $e ) {
874 if( in_array( strtolower( $e ), $list ) ) {
882 * Verifies that it's ok to include the uploaded file
884 * @param string $tmpfile the full path of the temporary file to verify
885 * @param string $extension The filename extension that the file is to be served with
886 * @return mixed true of the file is verified, a WikiError object otherwise.
888 function verify( $tmpfile, $extension ) {
889 #magically determine mime type
890 $magic=& wfGetMimeMagic();
891 $mime= $magic->guessMimeType($tmpfile,false);
893 $fname= "SpecialUpload::verify";
895 #check mime type, if desired
896 global $wgVerifyMimeType;
897 if ($wgVerifyMimeType) {
899 #check mime type against file extension
900 if( !$this->verifyExtension( $mime, $extension ) ) {
901 return new WikiErrorMsg( 'uploadcorrupt' );
904 #check mime type blacklist
905 global $wgMimeTypeBlacklist;
906 if( isset($wgMimeTypeBlacklist) && !is_null($wgMimeTypeBlacklist)
907 && $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
908 return new WikiErrorMsg( 'badfiletype', htmlspecialchars( $mime ) );
912 #check for htmlish code and javascript
913 if( $this->detectScript ( $tmpfile, $mime, $extension ) ) {
914 return new WikiErrorMsg( 'uploadscripted' );
918 * Scan the uploaded file for viruses
920 $virus= $this->detectVirus($tmpfile);
922 return new WikiErrorMsg( 'uploadvirus', htmlspecialchars($virus) );
925 wfDebug( "$fname: all clear; passing.\n" );
930 * Checks if the mime type of the uploaded file matches the file extension.
932 * @param string $mime the mime type of the uploaded file
933 * @param string $extension The filename extension that the file is to be served with
936 function verifyExtension( $mime, $extension ) {
937 $fname = 'SpecialUpload::verifyExtension';
939 $magic =& wfGetMimeMagic();
941 if ( ! $mime ||
$mime == 'unknown' ||
$mime == 'unknown/unknown' )
942 if ( ! $magic->isRecognizableExtension( $extension ) ) {
943 wfDebug( "$fname: passing file with unknown detected mime type; unrecognized extension '$extension', can't verify\n" );
946 wfDebug( "$fname: rejecting file with unknown detected mime type; recognized extension '$extension', so probably invalid file\n" );
950 $match= $magic->isMatchingExtension($extension,$mime);
953 wfDebug( "$fname: no file extension known for mime type $mime, passing file\n" );
955 } elseif ($match===true) {
956 wfDebug( "$fname: mime type $mime matches extension $extension, passing file\n" );
958 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
962 wfDebug( "$fname: mime type $mime mismatches file extension $extension, rejecting file\n" );
967 /** Heuristig for detecting files that *could* contain JavaScript instructions or
968 * things that may look like HTML to a browser and are thus
969 * potentially harmful. The present implementation will produce false positives in some situations.
971 * @param string $file Pathname to the temporary upload file
972 * @param string $mime The mime type of the file
973 * @param string $extension The extension of the file
974 * @return bool true if the file contains something looking like embedded scripts
976 function detectScript($file, $mime, $extension) {
977 global $wgAllowTitlesInSVG;
979 #ugly hack: for text files, always look at the entire file.
980 #For binarie field, just check the first K.
982 if (strpos($mime,'text/')===0) $chunk = file_get_contents( $file );
984 $fp = fopen( $file, 'rb' );
985 $chunk = fread( $fp, 1024 );
989 $chunk= strtolower( $chunk );
991 if (!$chunk) return false;
993 #decode from UTF-16 if needed (could be used for obfuscation).
994 if (substr($chunk,0,2)=="\xfe\xff") $enc= "UTF-16BE";
995 elseif (substr($chunk,0,2)=="\xff\xfe") $enc= "UTF-16LE";
998 if ($enc) $chunk= iconv($enc,"ASCII//IGNORE",$chunk);
1000 $chunk= trim($chunk);
1002 #FIXME: convert from UTF-16 if necessarry!
1004 wfDebug("SpecialUpload::detectScript: checking for embedded scripts and HTML stuff\n");
1006 #check for HTML doctype
1007 if (eregi("<!DOCTYPE *X?HTML",$chunk)) return true;
1010 * Internet Explorer for Windows performs some really stupid file type
1011 * autodetection which can cause it to interpret valid image files as HTML
1012 * and potentially execute JavaScript, creating a cross-site scripting
1015 * Apple's Safari browser also performs some unsafe file type autodetection
1016 * which can cause legitimate files to be interpreted as HTML if the
1017 * web server is not correctly configured to send the right content-type
1018 * (or if you're really uploading plain text and octet streams!)
1020 * Returns true if IE is likely to mistake the given file for HTML.
1021 * Also returns true if Safari would mistake the given file for HTML
1022 * when served with a generic content-type.
1028 '<html', #also in safari
1031 '<script', #also in safari
1034 if( ! $wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
1038 foreach( $tags as $tag ) {
1039 if( false !== strpos( $chunk, $tag ) ) {
1045 * look for javascript
1048 #resolve entity-refs to look at attributes. may be harsh on big files... cache result?
1049 $chunk = Sanitizer
::decodeCharReferences( $chunk );
1051 #look for script-types
1052 if (preg_match("!type\s*=\s*['\"]?\s*(\w*/)?(ecma|java)!sim",$chunk)) return true;
1054 #look for html-style script-urls
1055 if (preg_match("!(href|src|data)\s*=\s*['\"]?\s*(ecma|java)script:!sim",$chunk)) return true;
1057 #look for css-style script-urls
1058 if (preg_match("!url\s*\(\s*['\"]?\s*(ecma|java)script:!sim",$chunk)) return true;
1060 wfDebug("SpecialUpload::detectScript: no scripts found\n");
1064 /** Generic wrapper function for a virus scanner program.
1065 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
1066 * $wgAntivirusRequired may be used to deny upload if the scan fails.
1068 * @param string $file Pathname to the temporary upload file
1069 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
1070 * or a string containing feedback from the virus scanner if a virus was found.
1071 * If textual feedback is missing but a virus was found, this function returns true.
1073 function detectVirus($file) {
1074 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
1076 $fname= "SpecialUpload::detectVirus";
1078 if (!$wgAntivirus) { #disabled?
1079 wfDebug("$fname: virus scanner disabled\n");
1084 if (!$wgAntivirusSetup[$wgAntivirus]) {
1085 wfDebug("$fname: unknown virus scanner: $wgAntivirus\n");
1087 $wgOut->addHTML( "<div class='error'>Bad configuration: unknown virus scanner: <i>$wgAntivirus</i></div>\n" ); #LOCALIZE
1089 return "unknown antivirus: $wgAntivirus";
1092 #look up scanner configuration
1093 $virus_scanner= $wgAntivirusSetup[$wgAntivirus]["command"]; #command pattern
1094 $virus_scanner_codes= $wgAntivirusSetup[$wgAntivirus]["codemap"]; #exit-code map
1095 $msg_pattern= $wgAntivirusSetup[$wgAntivirus]["messagepattern"]; #message pattern
1097 $scanner= $virus_scanner; #copy, so we can resolve the pattern
1099 if (strpos($scanner,"%f")===false) $scanner.= " ".wfEscapeShellArg($file); #simple pattern: append file to scan
1100 else $scanner= str_replace("%f",wfEscapeShellArg($file),$scanner); #complex pattern: replace "%f" with file to scan
1102 wfDebug("$fname: running virus scan: $scanner \n");
1104 #execute virus scanner
1107 #NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
1108 # that does not seem to be worth the pain.
1109 # Ask me (Duesentrieb) about it if it's ever needed.
1110 if (wfIsWindows()) exec("$scanner",$output,$code);
1111 else exec("$scanner 2>&1",$output,$code);
1113 $exit_code= $code; #remeber for user feedback
1115 if ($virus_scanner_codes) { #map exit code to AV_xxx constants.
1116 if (isset($virus_scanner_codes[$code])) $code= $virus_scanner_codes[$code]; #explicite mapping
1117 else if (isset($virus_scanner_codes["*"])) $code= $virus_scanner_codes["*"]; #fallback mapping
1120 if ($code===AV_SCAN_FAILED
) { #scan failed (code was mapped to false by $virus_scanner_codes)
1121 wfDebug("$fname: failed to scan $file (code $exit_code).\n");
1123 if ($wgAntivirusRequired) return "scan failed (code $exit_code)";
1126 else if ($code===AV_SCAN_ABORTED
) { #scan failed because filetype is unknown (probably imune)
1127 wfDebug("$fname: unsupported file type $file (code $exit_code).\n");
1130 else if ($code===AV_NO_VIRUS
) {
1131 wfDebug("$fname: file passed virus scan.\n");
1132 return false; #no virus found
1135 $output= join("\n",$output);
1136 $output= trim($output);
1138 if (!$output) $output= true; #if ther's no output, return true
1139 else if ($msg_pattern) {
1141 if (preg_match($msg_pattern,$output,$groups)) {
1142 if ($groups[1]) $output= $groups[1];
1146 wfDebug("$fname: FOUND VIRUS! scanner feedback: $output");
1152 * Check if the temporary file is MacBinary-encoded, as some uploads
1153 * from Internet Explorer on Mac OS Classic and Mac OS X will be.
1154 * If so, the data fork will be extracted to a second temporary file,
1155 * which will then be checked for validity and either kept or discarded.
1159 function checkMacBinary() {
1160 $macbin = new MacBinary( $this->mUploadTempName
);
1161 if( $macbin->isValid() ) {
1162 $dataFile = tempnam( wfTempDir(), "WikiMacBinary" );
1163 $dataHandle = fopen( $dataFile, 'wb' );
1165 wfDebug( "SpecialUpload::checkMacBinary: Extracting MacBinary data fork to $dataFile\n" );
1166 $macbin->extractData( $dataHandle );
1168 $this->mUploadTempName
= $dataFile;
1169 $this->mUploadSize
= $macbin->dataForkLength();
1171 // We'll have to manually remove the new file if it's not kept.
1172 $this->mRemoveTempFile
= true;
1178 * If we've modified the upload file we need to manually remove it
1179 * on exit to clean up.
1182 function cleanupTempFile() {
1183 if( $this->mRemoveTempFile
&& file_exists( $this->mUploadTempName
) ) {
1184 wfDebug( "SpecialUpload::cleanupTempFile: Removing temporary file $this->mUploadTempName\n" );
1185 unlink( $this->mUploadTempName
);
1190 * Check if there's an overwrite conflict and, if so, if restrictions
1191 * forbid this user from performing the upload.
1193 * @return mixed true on success, WikiError on failure
1196 function checkOverwrite( $name ) {
1197 $img = Image
::newFromName( $name );
1198 if( is_null( $img ) ) {
1199 // Uh... this shouldn't happen ;)
1200 // But if it does, fall through to previous behavior
1205 if( $img->exists() ) {
1206 global $wgUser, $wgOut;
1207 if( $img->isLocal() ) {
1208 if( !$wgUser->isAllowed( 'reupload' ) ) {
1209 $error = 'fileexists-forbidden';
1212 if( !$wgUser->isAllowed( 'reupload' ) ||
1213 !$wgUser->isAllowed( 'reupload-shared' ) ) {
1214 $error = "fileexists-shared-forbidden";
1220 $errorText = wfMsg( $error, wfEscapeWikiText( $img->getName() ) );
1221 return new WikiError( $wgOut->parse( $errorText ) );
1224 // Rockin', go ahead and upload