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;
33 # Placeholders for text injection by hooks (must be HTML)
34 # extensions should take care to _append_ to the present value
35 var $uploadFormTextTop;
36 var $uploadFormTextAfterSummary;
41 * Constructor : initialise object
42 * Get data POSTed through the form and assign them to the object
43 * @param $request Data posted.
45 function UploadForm( &$request ) {
46 global $wgAllowCopyUploads;
47 $this->mDestFile
= $request->getText( 'wpDestFile' );
49 if( !$request->wasPosted() ) {
50 # GET requests just give the main form; no data except wpDestfile.
54 # Placeholders for text injection by hooks (empty per default)
55 $this->uploadFormTextTop
= "";
56 $this->uploadFormTextAfterSummary
= "";
58 $this->mIgnoreWarning
= $request->getCheck( 'wpIgnoreWarning' );
59 $this->mReUpload
= $request->getCheck( 'wpReUpload' );
60 $this->mUpload
= $request->getCheck( 'wpUpload' );
62 $this->mUploadDescription
= $request->getText( 'wpUploadDescription' );
63 $this->mLicense
= $request->getText( 'wpLicense' );
64 $this->mUploadCopyStatus
= $request->getText( 'wpUploadCopyStatus' );
65 $this->mUploadSource
= $request->getText( 'wpUploadSource' );
66 $this->mWatchthis
= $request->getBool( 'wpWatchthis' );
67 $this->mSourceType
= $request->getText( 'wpSourceType' );
68 wfDebug( "UploadForm: watchthis is: '$this->mWatchthis'\n" );
70 $this->mAction
= $request->getVal( 'action' );
72 $this->mSessionKey
= $request->getInt( 'wpSessionKey' );
73 if( !empty( $this->mSessionKey
) &&
74 isset( $_SESSION['wsUploadData'][$this->mSessionKey
] ) ) {
76 * Confirming a temporarily stashed upload.
77 * We don't want path names to be forged, so we keep
78 * them in the session on the server and just give
79 * an opaque key to the user agent.
81 $data = $_SESSION['wsUploadData'][$this->mSessionKey
];
82 $this->mUploadTempName
= $data['mUploadTempName'];
83 $this->mUploadSize
= $data['mUploadSize'];
84 $this->mOname
= $data['mOname'];
85 $this->mUploadError
= 0/*UPLOAD_ERR_OK*/;
86 $this->mStashed
= true;
87 $this->mRemoveTempFile
= false;
90 *Check for a newly uploaded file.
92 if( $wgAllowCopyUploads && $this->mSourceType
== 'web' ) {
93 $this->initializeFromUrl( $request );
95 $this->initializeFromUpload( $request );
101 * Initialize the uploaded file from PHP data
104 function initializeFromUpload( $request ) {
105 $this->mUploadTempName
= $request->getFileTempName( 'wpUploadFile' );
106 $this->mUploadSize
= $request->getFileSize( 'wpUploadFile' );
107 $this->mOname
= $request->getFileName( 'wpUploadFile' );
108 $this->mUploadError
= $request->getUploadError( 'wpUploadFile' );
109 $this->mSessionKey
= false;
110 $this->mStashed
= false;
111 $this->mRemoveTempFile
= false; // PHP will handle this
115 * Copy a web file to a temporary file
118 function initializeFromUrl( $request ) {
119 global $wgTmpDirectory;
120 $url = $request->getText( 'wpUploadFileURL' );
121 $local_file = tempnam( $wgTmpDirectory, 'WEBUPLOAD' );
123 $this->mUploadTempName
= $local_file;
124 $this->mUploadError
= $this->curlCopy( $url, $local_file );
125 $this->mUploadSize
= $this->mUploadTempFileSize
;
126 $this->mOname
= array_pop( explode( '/', $url ) );
127 $this->mSessionKey
= false;
128 $this->mStashed
= false;
130 // PHP won't auto-cleanup the file
131 $this->mRemoveTempFile
= file_exists( $local_file );
136 * Returns true if there was an error, false otherwise
138 private function curlCopy( $url, $dest ) {
139 global $wgUser, $wgOut;
141 if( !$wgUser->isAllowed( 'upload_by_url' ) ) {
142 $wgOut->permissionRequired( 'upload_by_url' );
146 # Maybe remove some pasting blanks :-)
148 if( stripos($url, 'http://') !== 0 && stripos($url, 'ftp://') !== 0 ) {
149 # Only HTTP or FTP URLs
150 $wgOut->errorPage( 'upload-proto-error', 'upload-proto-error-text' );
154 # Open temporary file
155 $this->mUploadTempFile
= @fopen
( $this->mUploadTempName
, "wb" );
156 if( $this->mUploadTempFile
=== false ) {
157 # Could not open temporary file to write in
158 $wgOut->errorPage( 'upload-file-error', 'upload-file-error-text');
163 curl_setopt( $ch, CURLOPT_HTTP_VERSION
, 1.0); # Probably not needed, but apparently can work around some bug
164 curl_setopt( $ch, CURLOPT_TIMEOUT
, 10); # 10 seconds timeout
165 curl_setopt( $ch, CURLOPT_LOW_SPEED_LIMIT
, 512); # 0.5KB per second minimum transfer speed
166 curl_setopt( $ch, CURLOPT_URL
, $url);
167 curl_setopt( $ch, CURLOPT_WRITEFUNCTION
, array( $this, 'uploadCurlCallback' ) );
169 $error = curl_errno( $ch ) ?
true : false;
170 $errornum = curl_errno( $ch );
171 // if ( $error ) print curl_error ( $ch ) ; # Debugging output
174 fclose( $this->mUploadTempFile
);
175 unset( $this->mUploadTempFile
);
178 if( wfEmptyMsg( "upload-curl-error$errornum", wfMsg("upload-curl-error$errornum") ) )
179 $wgOut->errorPage( 'upload-misc-error', 'upload-misc-error-text' );
181 $wgOut->errorPage( "upload-curl-error$errornum", "upload-curl-error$errornum-text" );
188 * Callback function for CURL-based web transfer
189 * Write data to file unless we've passed the length limit;
190 * if so, abort immediately.
193 function uploadCurlCallback( $ch, $data ) {
194 global $wgMaxUploadSize;
195 $length = strlen( $data );
196 $this->mUploadTempFileSize +
= $length;
197 if( $this->mUploadTempFileSize
> $wgMaxUploadSize ) {
200 fwrite( $this->mUploadTempFile
, $data );
209 global $wgUser, $wgOut;
210 global $wgEnableUploads, $wgUploadDirectory;
212 # Check uploading enabled
213 if( !$wgEnableUploads ) {
214 $wgOut->showErrorPage( 'uploaddisabled', 'uploaddisabledtext' );
219 if( !$wgUser->isAllowed( 'upload' ) ) {
220 if( !$wgUser->isLoggedIn() ) {
221 $wgOut->showErrorPage( 'uploadnologin', 'uploadnologintext' );
223 $wgOut->permissionRequired( 'upload' );
229 if( $wgUser->isBlocked() ) {
230 $wgOut->blockedPage();
235 $wgOut->readOnlyPage();
239 /** Check if the image directory is writeable, this is a common mistake */
240 if( !is_writeable( $wgUploadDirectory ) ) {
241 $wgOut->addWikiText( wfMsg( 'upload_directory_read_only', $wgUploadDirectory ) );
245 if( $this->mReUpload
) {
246 if( !$this->unsaveUploadedFile() ) {
249 $this->mainUploadForm();
250 } else if( 'submit' == $this->mAction ||
$this->mUpload
) {
251 $this->processUpload();
253 $this->mainUploadForm();
256 $this->cleanupTempFile();
259 /* -------------------------------------------------------------- */
262 * Really do the upload
263 * Checks are made in SpecialUpload::execute()
266 function processUpload() {
267 global $wgUser, $wgOut;
269 if( !wfRunHooks( 'UploadForm:BeforeProcessing', array( &$this ) ) )
271 wfDebug( "Hook 'UploadForm:BeforeProcessing' broke processing the file." );
275 /* Check for PHP error if any, requires php 4.2 or newer */
276 if( $this->mUploadError
== 1/*UPLOAD_ERR_INI_SIZE*/ ) {
277 $this->mainUploadForm( wfMsgHtml( 'largefileserver' ) );
282 * If there was no filename or a zero size given, give up quick.
284 if( trim( $this->mOname
) == '' ||
empty( $this->mUploadSize
) ) {
285 $this->mainUploadForm( wfMsgHtml( 'emptyfile' ) );
289 # Chop off any directories in the given filename
290 if( $this->mDestFile
) {
291 $basename = wfBaseName( $this->mDestFile
);
293 $basename = wfBaseName( $this->mOname
);
297 * We'll want to blacklist against *any* 'extension', and use
298 * only the final one for the whitelist.
300 list( $partname, $ext ) = $this->splitExtensions( $basename );
302 if( count( $ext ) ) {
303 $finalExt = $ext[count( $ext ) - 1];
307 $fullExt = implode( '.', $ext );
309 # If there was more than one "extension", reassemble the base
310 # filename to prevent bogus complaints about length
311 if( count( $ext ) > 1 ) {
312 for( $i = 0; $i < count( $ext ) - 1; $i++
)
313 $partname .= '.' . $ext[$i];
316 if( strlen( $partname ) < 3 ) {
317 $this->mainUploadForm( wfMsgHtml( 'minlength' ) );
322 * Filter out illegal characters, and try to make a legible name
323 * out of it. We'll strip some silently that Title would die on.
325 $filtered = preg_replace ( "/[^".Title
::legalChars()."]|:/", '-', $basename );
326 $nt = Title
::newFromText( $filtered );
327 if( is_null( $nt ) ) {
328 $this->uploadError( wfMsgWikiHtml( 'illegalfilename', htmlspecialchars( $filtered ) ) );
331 $nt =& Title
::makeTitle( NS_IMAGE
, $nt->getDBkey() );
332 $this->mUploadSaveName
= $nt->getDBkey();
335 * If the image is protected, non-sysop users won't be able
336 * to modify it by uploading a new revision.
338 if( !$nt->userCanEdit() ) {
339 return $this->uploadError( wfMsgWikiHtml( 'protectedpage' ) );
343 * In some cases we may forbid overwriting of existing files.
345 $overwrite = $this->checkOverwrite( $this->mUploadSaveName
);
346 if( WikiError
::isError( $overwrite ) ) {
347 return $this->uploadError( $overwrite->toString() );
350 /* Don't allow users to override the blacklist (check file extension) */
351 global $wgStrictFileExtensions;
352 global $wgFileExtensions, $wgFileBlacklist;
353 if( $this->checkFileExtensionList( $ext, $wgFileBlacklist ) ||
354 ($wgStrictFileExtensions &&
355 !$this->checkFileExtension( $finalExt, $wgFileExtensions ) ) ) {
356 return $this->uploadError( wfMsgHtml( 'badfiletype', htmlspecialchars( $finalExt ) ) );
360 * Look at the contents of the file; if we can recognize the
361 * type but it's corrupt or data of the wrong type, we should
362 * probably not accept it.
364 if( !$this->mStashed
) {
365 $this->checkMacBinary();
366 $veri = $this->verify( $this->mUploadTempName
, $finalExt );
368 if( $veri !== true ) { //it's a wiki error...
369 return $this->uploadError( $veri->toString() );
374 * Provide an opportunity for extensions to add futher checks
377 if( !wfRunHooks( 'UploadVerification',
378 array( $this->mUploadSaveName
, $this->mUploadTempName
, &$error ) ) ) {
379 return $this->uploadError( $error );
383 * Check for non-fatal conditions
385 if ( ! $this->mIgnoreWarning
) {
388 global $wgCapitalLinks;
389 if( $wgCapitalLinks ) {
390 $filtered = ucfirst( $filtered );
392 if( $this->mUploadSaveName
!= $filtered ) {
393 $warning .= '<li>'.wfMsgHtml( 'badfilename', htmlspecialchars( $this->mUploadSaveName
) ).'</li>';
396 global $wgCheckFileExtensions;
397 if ( $wgCheckFileExtensions ) {
398 if ( ! $this->checkFileExtension( $finalExt, $wgFileExtensions ) ) {
399 $warning .= '<li>'.wfMsgHtml( 'badfiletype', htmlspecialchars( $finalExt ) ).'</li>';
403 global $wgUploadSizeWarning;
404 if ( $wgUploadSizeWarning && ( $this->mUploadSize
> $wgUploadSizeWarning ) ) {
405 $skin =& $wgUser->getSkin();
406 $wsize = $skin->formatSize( $wgUploadSizeWarning );
407 $asize = $skin->formatSize( $this->mUploadSize
);
408 $warning .= '<li>' . wfMsgHtml( 'large-file', $wsize, $asize ) . '</li>';
410 if ( $this->mUploadSize
== 0 ) {
411 $warning .= '<li>'.wfMsgHtml( 'emptyfile' ).'</li>';
414 if( $nt->getArticleID() ) {
416 $sk = $wgUser->getSkin();
417 $dlink = $sk->makeKnownLinkObj( $nt );
418 $warning .= '<li>'.wfMsgHtml( 'fileexists', $dlink ).'</li>';
420 # If the file existed before and was deleted, warn the user of this
421 # Don't bother doing so if the image exists now, however
422 $image = new Image( $nt );
423 if( $image->wasDeleted() ) {
424 $skin = $wgUser->getSkin();
425 $ltitle = SpecialPage
::getTitleFor( 'Log' );
426 $llink = $skin->makeKnownLinkObj( $ltitle, wfMsgHtml( 'deletionlog' ), 'type=delete&page=' . $nt->getPrefixedUrl() );
427 $warning .= wfOpenElement( 'li' ) . wfMsgWikiHtml( 'filewasdeleted', $llink ) . wfCloseElement( 'li' );
431 if( $warning != '' ) {
433 * Stash the file in a temporary location; the user can choose
434 * to let it through and we'll complete the upload then.
436 return $this->uploadWarning( $warning );
441 * Try actually saving the thing...
442 * It will show an error form on failure.
444 $hasBeenMunged = !empty( $this->mSessionKey
) ||
$this->mRemoveTempFile
;
445 if( $this->saveUploadedFile( $this->mUploadSaveName
,
446 $this->mUploadTempName
,
449 * Update the upload log and create the description page
450 * if it's a new file.
452 $img = Image
::newFromName( $this->mUploadSaveName
);
453 $success = $img->recordUpload( $this->mUploadOldVersion
,
454 $this->mUploadDescription
,
456 $this->mUploadCopyStatus
,
457 $this->mUploadSource
,
461 $this->showSuccess();
462 wfRunHooks( 'UploadComplete', array( &$img ) );
464 // Image::recordUpload() fails if the image went missing, which is
465 // unlikely, hence the lack of a specialised message
466 $wgOut->showFileNotFoundError( $this->mUploadSaveName
);
472 * Move the uploaded file from its temporary location to the final
473 * destination. If a previous version of the file exists, move
474 * it into the archive subdirectory.
476 * @todo If the later save fails, we may have disappeared the original file.
478 * @param string $saveName
479 * @param string $tempName full path to the temporary file
480 * @param bool $useRename if true, doesn't check that the source file
481 * is a PHP-managed upload temporary
483 function saveUploadedFile( $saveName, $tempName, $useRename = false ) {
484 global $wgOut, $wgAllowCopyUploads;
486 if ( !$useRename AND $wgAllowCopyUploads AND $this->mSourceType
== 'web' ) $useRename = true;
488 $fname= "SpecialUpload::saveUploadedFile";
490 $dest = wfImageDir( $saveName );
491 $archive = wfImageArchiveDir( $saveName );
492 if ( !is_dir( $dest ) ) wfMkdirParents( $dest );
493 if ( !is_dir( $archive ) ) wfMkdirParents( $archive );
495 $this->mSavedFile
= "{$dest}/{$saveName}";
497 if( is_file( $this->mSavedFile
) ) {
498 $this->mUploadOldVersion
= gmdate( 'YmdHis' ) . "!{$saveName}";
499 wfSuppressWarnings();
500 $success = rename( $this->mSavedFile
, "${archive}/{$this->mUploadOldVersion}" );
504 $wgOut->showFileRenameError( $this->mSavedFile
,
505 "${archive}/{$this->mUploadOldVersion}" );
508 else wfDebug("$fname: moved file ".$this->mSavedFile
." to ${archive}/{$this->mUploadOldVersion}\n");
511 $this->mUploadOldVersion
= '';
514 wfSuppressWarnings();
515 $success = $useRename
516 ?
rename( $tempName, $this->mSavedFile
)
517 : move_uploaded_file( $tempName, $this->mSavedFile
);
521 $wgOut->showFileCopyError( $tempName, $this->mSavedFile
);
524 wfDebug("$fname: wrote tempfile $tempName to ".$this->mSavedFile
."\n");
527 chmod( $this->mSavedFile
, 0644 );
532 * Stash a file in a temporary directory for later processing
533 * after the user has confirmed it.
535 * If the user doesn't explicitly cancel or accept, these files
536 * can accumulate in the temp directory.
538 * @param string $saveName - the destination filename
539 * @param string $tempName - the source temporary file to save
540 * @return string - full path the stashed file, or false on failure
543 function saveTempUploadedFile( $saveName, $tempName ) {
545 $archive = wfImageArchiveDir( $saveName, 'temp' );
546 if ( !is_dir ( $archive ) ) wfMkdirParents( $archive );
547 $stash = $archive . '/' . gmdate( "YmdHis" ) . '!' . $saveName;
549 $success = $this->mRemoveTempFile
550 ?
rename( $tempName, $stash )
551 : move_uploaded_file( $tempName, $stash );
553 $wgOut->showFileCopyError( $tempName, $stash );
561 * Stash a file in a temporary directory for later processing,
562 * and save the necessary descriptive info into the session.
563 * Returns a key value which will be passed through a form
564 * to pick up the path info on a later invocation.
569 function stashSession() {
570 $stash = $this->saveTempUploadedFile(
571 $this->mUploadSaveName
, $this->mUploadTempName
);
574 # Couldn't save the file.
578 $key = mt_rand( 0, 0x7fffffff );
579 $_SESSION['wsUploadData'][$key] = array(
580 'mUploadTempName' => $stash,
581 'mUploadSize' => $this->mUploadSize
,
582 'mOname' => $this->mOname
);
587 * Remove a temporarily kept file stashed by saveTempUploadedFile().
591 function unsaveUploadedFile() {
593 wfSuppressWarnings();
594 $success = unlink( $this->mUploadTempName
);
597 $wgOut->showFileDeleteError( $this->mUploadTempName
);
604 /* -------------------------------------------------------------- */
607 * Show some text and linkage on successful upload.
610 function showSuccess() {
611 global $wgUser, $wgOut, $wgContLang;
613 $sk = $wgUser->getSkin();
614 $ilink = $sk->makeMediaLink( $this->mUploadSaveName
, Image
::imageUrl( $this->mUploadSaveName
) );
615 $dname = $wgContLang->getNsText( NS_IMAGE
) . ':'.$this->mUploadSaveName
;
616 $dlink = $sk->makeKnownLink( $dname, $dname );
618 $wgOut->addHTML( '<h2>' . wfMsgHtml( 'successfulupload' ) . "</h2>\n" );
619 $text = wfMsgWikiHtml( 'fileuploaded', $ilink, $dlink );
620 $wgOut->addHTML( $text );
621 $wgOut->returnToMain( false );
625 * @param string $error as HTML
628 function uploadError( $error ) {
630 $wgOut->addHTML( "<h2>" . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
631 $wgOut->addHTML( "<span class='error'>{$error}</span>\n" );
635 * There's something wrong with this file, not enough to reject it
636 * totally but we require manual intervention to save it for real.
637 * Stash it away, then present a form asking to confirm or cancel.
639 * @param string $warning as HTML
642 function uploadWarning( $warning ) {
644 global $wgUseCopyrightUpload;
646 $this->mSessionKey
= $this->stashSession();
647 if( !$this->mSessionKey
) {
648 # Couldn't save file; an error has been displayed so let's go.
652 $wgOut->addHTML( "<h2>" . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
653 $wgOut->addHTML( "<ul class='warning'>{$warning}</ul><br />\n" );
655 $save = wfMsgHtml( 'savefile' );
656 $reupload = wfMsgHtml( 'reupload' );
657 $iw = wfMsgWikiHtml( 'ignorewarning' );
658 $reup = wfMsgWikiHtml( 'reuploaddesc' );
659 $titleObj = SpecialPage
::getTitleFor( 'Upload' );
660 $action = $titleObj->escapeLocalURL( 'action=submit' );
662 if ( $wgUseCopyrightUpload )
665 <input type='hidden' name='wpUploadCopyStatus' value=\"" . htmlspecialchars( $this->mUploadCopyStatus
) . "\" />
666 <input type='hidden' name='wpUploadSource' value=\"" . htmlspecialchars( $this->mUploadSource
) . "\" />
673 <form id='uploadwarning' method='post' enctype='multipart/form-data' action='$action'>
674 <input type='hidden' name='wpIgnoreWarning' value='1' />
675 <input type='hidden' name='wpSessionKey' value=\"" . htmlspecialchars( $this->mSessionKey
) . "\" />
676 <input type='hidden' name='wpUploadDescription' value=\"" . htmlspecialchars( $this->mUploadDescription
) . "\" />
677 <input type='hidden' name='wpLicense' value=\"" . htmlspecialchars( $this->mLicense
) . "\" />
678 <input type='hidden' name='wpDestFile' value=\"" . htmlspecialchars( $this->mDestFile
) . "\" />
679 <input type='hidden' name='wpWatchthis' value=\"" . htmlspecialchars( intval( $this->mWatchthis
) ) . "\" />
685 <input tabindex='2' type='submit' name='wpUpload' value=\"$save\" />
687 <td align='left'>$iw</td>
691 <input tabindex='2' type='submit' name='wpReUpload' value=\"{$reupload}\" />
693 <td align='left'>$reup</td>
696 </table></form>\n" );
700 * Displays the main upload form, optionally with a highlighted
701 * error message up at the top.
703 * @param string $msg as HTML
706 function mainUploadForm( $msg='' ) {
707 global $wgOut, $wgUser;
708 global $wgUseCopyrightUpload;
709 global $wgRequest, $wgAllowCopyUploads;
711 if( !wfRunHooks( 'UploadForm:initial', array( &$this ) ) )
713 wfDebug( "Hook 'UploadForm:initial' broke output of the upload form" );
717 $cols = intval($wgUser->getOption( 'cols' ));
718 $ew = $wgUser->getOption( 'editwidth' );
719 if ( $ew ) $ew = " style=\"width:100%\"";
723 $sub = wfMsgHtml( 'uploaderror' );
724 $wgOut->addHTML( "<h2>{$sub}</h2>\n" .
725 "<span class='error'>{$msg}</span>\n" );
727 $wgOut->addHTML( '<div id="uploadtext">' );
728 $wgOut->addWikiText( wfMsg( 'uploadtext' ) );
729 $wgOut->addHTML( '</div>' );
731 $sourcefilename = wfMsgHtml( 'sourcefilename' );
732 $destfilename = wfMsgHtml( 'destfilename' );
733 $summary = wfMsgWikiHtml( 'fileuploadsummary' );
735 $licenses = new Licenses();
736 $license = wfMsgHtml( 'license' );
737 $nolicense = wfMsgHtml( 'nolicense' );
738 $licenseshtml = $licenses->getHtml();
740 $ulb = wfMsgHtml( 'uploadbtn' );
743 $titleObj = SpecialPage
::getTitleFor( 'Upload' );
744 $action = $titleObj->escapeLocalURL();
746 $encDestFile = htmlspecialchars( $this->mDestFile
);
749 ( $wgUser->getOption( 'watchdefault' ) ||
750 ( $wgUser->getOption( 'watchcreations' ) && $this->mDestFile
== '' ) )
751 ?
'checked="checked"'
754 // Prepare form for upload or upload/copy
755 if( $wgAllowCopyUploads && $wgUser->isAllowed( 'upload_by_url' ) ) {
757 "<input type='radio' id='wpSourceTypeFile' name='wpSourceType' value='file' onchange='toggle_element_activation(\"wpUploadFileURL\",\"wpUploadFile\")' checked />" .
758 "<input tabindex='1' type='file' name='wpUploadFile' id='wpUploadFile' onfocus='toggle_element_activation(\"wpUploadFileURL\",\"wpUploadFile\");toggle_element_check(\"wpSourceTypeFile\",\"wpSourceTypeURL\")'" .
759 ($this->mDestFile?
"":"onchange='fillDestFilename(\"wpUploadFile\")' ") . "size='40' />" .
760 wfMsgHTML( 'upload_source_file' ) . "<br/>" .
761 "<input type='radio' id='wpSourceTypeURL' name='wpSourceType' value='web' onchange='toggle_element_activation(\"wpUploadFile\",\"wpUploadFileURL\")' />" .
762 "<input tabindex='1' type='text' name='wpUploadFileURL' id='wpUploadFileURL' onfocus='toggle_element_activation(\"wpUploadFile\",\"wpUploadFileURL\");toggle_element_check(\"wpSourceTypeURL\",\"wpSourceTypeFile\")'" .
763 ($this->mDestFile?
"":"onchange='fillDestFilename(\"wpUploadFileURL\")' ") . "size='40' DISABLED />" .
764 wfMsgHtml( 'upload_source_url' ) ;
767 "<input tabindex='1' type='file' name='wpUploadFile' id='wpUploadFile' " .
768 ($this->mDestFile?
"":"onchange='fillDestFilename(\"wpUploadFile\")' ") .
770 "<input type='hidden' name='wpSourceType' value='file' />" ;
774 <form id='upload' method='post' enctype='multipart/form-data' action=\"$action\">
777 {$this->uploadFormTextTop}
778 <td align='right' valign='top'><label for='wpUploadFile'>{$sourcefilename}:</label></td>
784 <td align='right'><label for='wpDestFile'>{$destfilename}:</label></td>
786 <input tabindex='2' type='text' name='wpDestFile' id='wpDestFile' size='40' value=\"$encDestFile\" />
790 <td align='right'><label for='wpUploadDescription'>{$summary}</label></td>
792 <textarea tabindex='3' name='wpUploadDescription' id='wpUploadDescription' rows='6' cols='{$cols}'{$ew}>" . htmlspecialchars( $this->mUploadDescription
) . "</textarea>
793 {$this->uploadFormTextAfterSummary}
798 if ( $licenseshtml != '' ) {
801 <td align='right'><label for='wpLicense'>$license:</label></td>
803 <script type='text/javascript' src=\"$wgStylePath/common/upload.js\"></script>
804 <select name='wpLicense' id='wpLicense' tabindex='4'
805 onchange='licenseSelectorCheck()'>
806 <option value=''>$nolicense</option>
815 if ( $wgUseCopyrightUpload ) {
816 $filestatus = wfMsgHtml ( 'filestatus' );
817 $copystatus = htmlspecialchars( $this->mUploadCopyStatus
);
818 $filesource = wfMsgHtml ( 'filesource' );
819 $uploadsource = htmlspecialchars( $this->mUploadSource
);
822 <td align='right' nowrap='nowrap'><label for='wpUploadCopyStatus'>$filestatus:</label></td>
823 <td><input tabindex='5' type='text' name='wpUploadCopyStatus' id='wpUploadCopyStatus' value=\"$copystatus\" size='40' /></td>
826 <td align='right'><label for='wpUploadCopyStatus'>$filesource:</label></td>
827 <td><input tabindex='6' type='text' name='wpUploadSource' id='wpUploadCopyStatus' value=\"$uploadsource\" size='40' /></td>
837 <input tabindex='7' type='checkbox' name='wpWatchthis' id='wpWatchthis' $watchChecked value='true' />
838 <label for='wpWatchthis'>" . wfMsgHtml( 'watchthisupload' ) . "</label>
839 <input tabindex='8' type='checkbox' name='wpIgnoreWarning' id='wpIgnoreWarning' value='true' />
840 <label for='wpIgnoreWarning'>" . wfMsgHtml( 'ignorewarnings' ) . "</label>
845 <td align='left'><input tabindex='9' type='submit' name='wpUpload' value=\"{$ulb}\" /></td>
852 $wgOut->addWikiText( wfMsgForContent( 'edittools' ) );
861 /* -------------------------------------------------------------- */
864 * Split a file into a base name and all dot-delimited 'extensions'
865 * on the end. Some web server configurations will fall back to
866 * earlier pseudo-'extensions' to determine type and execute
867 * scripts, so the blacklist needs to check them all.
871 function splitExtensions( $filename ) {
872 $bits = explode( '.', $filename );
873 $basename = array_shift( $bits );
874 return array( $basename, $bits );
878 * Perform case-insensitive match against a list of file extensions.
879 * Returns true if the extension is in the list.
885 function checkFileExtension( $ext, $list ) {
886 return in_array( strtolower( $ext ), $list );
890 * Perform case-insensitive match against a list of file extensions.
891 * Returns true if any of the extensions are in the list.
897 function checkFileExtensionList( $ext, $list ) {
898 foreach( $ext as $e ) {
899 if( in_array( strtolower( $e ), $list ) ) {
907 * Verifies that it's ok to include the uploaded file
909 * @param string $tmpfile the full path of the temporary file to verify
910 * @param string $extension The filename extension that the file is to be served with
911 * @return mixed true of the file is verified, a WikiError object otherwise.
913 function verify( $tmpfile, $extension ) {
914 #magically determine mime type
915 $magic=& MimeMagic
::singleton();
916 $mime= $magic->guessMimeType($tmpfile,false);
918 $fname= "SpecialUpload::verify";
920 #check mime type, if desired
921 global $wgVerifyMimeType;
922 if ($wgVerifyMimeType) {
924 #check mime type against file extension
925 if( !$this->verifyExtension( $mime, $extension ) ) {
926 return new WikiErrorMsg( 'uploadcorrupt' );
929 #check mime type blacklist
930 global $wgMimeTypeBlacklist;
931 if( isset($wgMimeTypeBlacklist) && !is_null($wgMimeTypeBlacklist)
932 && $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
933 return new WikiErrorMsg( 'badfiletype', htmlspecialchars( $mime ) );
937 #check for htmlish code and javascript
938 if( $this->detectScript ( $tmpfile, $mime, $extension ) ) {
939 return new WikiErrorMsg( 'uploadscripted' );
943 * Scan the uploaded file for viruses
945 $virus= $this->detectVirus($tmpfile);
947 return new WikiErrorMsg( 'uploadvirus', htmlspecialchars($virus) );
950 wfDebug( "$fname: all clear; passing.\n" );
955 * Checks if the mime type of the uploaded file matches the file extension.
957 * @param string $mime the mime type of the uploaded file
958 * @param string $extension The filename extension that the file is to be served with
961 function verifyExtension( $mime, $extension ) {
962 $fname = 'SpecialUpload::verifyExtension';
964 $magic =& MimeMagic
::singleton();
966 if ( ! $mime ||
$mime == 'unknown' ||
$mime == 'unknown/unknown' )
967 if ( ! $magic->isRecognizableExtension( $extension ) ) {
968 wfDebug( "$fname: passing file with unknown detected mime type; unrecognized extension '$extension', can't verify\n" );
971 wfDebug( "$fname: rejecting file with unknown detected mime type; recognized extension '$extension', so probably invalid file\n" );
975 $match= $magic->isMatchingExtension($extension,$mime);
978 wfDebug( "$fname: no file extension known for mime type $mime, passing file\n" );
980 } elseif ($match===true) {
981 wfDebug( "$fname: mime type $mime matches extension $extension, passing file\n" );
983 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
987 wfDebug( "$fname: mime type $mime mismatches file extension $extension, rejecting file\n" );
992 /** Heuristig for detecting files that *could* contain JavaScript instructions or
993 * things that may look like HTML to a browser and are thus
994 * potentially harmful. The present implementation will produce false positives in some situations.
996 * @param string $file Pathname to the temporary upload file
997 * @param string $mime The mime type of the file
998 * @param string $extension The extension of the file
999 * @return bool true if the file contains something looking like embedded scripts
1001 function detectScript($file, $mime, $extension) {
1002 global $wgAllowTitlesInSVG;
1004 #ugly hack: for text files, always look at the entire file.
1005 #For binarie field, just check the first K.
1007 if (strpos($mime,'text/')===0) $chunk = file_get_contents( $file );
1009 $fp = fopen( $file, 'rb' );
1010 $chunk = fread( $fp, 1024 );
1014 $chunk= strtolower( $chunk );
1016 if (!$chunk) return false;
1018 #decode from UTF-16 if needed (could be used for obfuscation).
1019 if (substr($chunk,0,2)=="\xfe\xff") $enc= "UTF-16BE";
1020 elseif (substr($chunk,0,2)=="\xff\xfe") $enc= "UTF-16LE";
1023 if ($enc) $chunk= iconv($enc,"ASCII//IGNORE",$chunk);
1025 $chunk= trim($chunk);
1027 #FIXME: convert from UTF-16 if necessarry!
1029 wfDebug("SpecialUpload::detectScript: checking for embedded scripts and HTML stuff\n");
1031 #check for HTML doctype
1032 if (eregi("<!DOCTYPE *X?HTML",$chunk)) return true;
1035 * Internet Explorer for Windows performs some really stupid file type
1036 * autodetection which can cause it to interpret valid image files as HTML
1037 * and potentially execute JavaScript, creating a cross-site scripting
1040 * Apple's Safari browser also performs some unsafe file type autodetection
1041 * which can cause legitimate files to be interpreted as HTML if the
1042 * web server is not correctly configured to send the right content-type
1043 * (or if you're really uploading plain text and octet streams!)
1045 * Returns true if IE is likely to mistake the given file for HTML.
1046 * Also returns true if Safari would mistake the given file for HTML
1047 * when served with a generic content-type.
1053 '<html', #also in safari
1056 '<script', #also in safari
1059 if( ! $wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
1063 foreach( $tags as $tag ) {
1064 if( false !== strpos( $chunk, $tag ) ) {
1070 * look for javascript
1073 #resolve entity-refs to look at attributes. may be harsh on big files... cache result?
1074 $chunk = Sanitizer
::decodeCharReferences( $chunk );
1076 #look for script-types
1077 if (preg_match('!type\s*=\s*[\'"]?\s*(\w*/)?(ecma|java)!sim',$chunk)) return true;
1079 #look for html-style script-urls
1080 if (preg_match('!(href|src|data)\s*=\s*[\'"]?\s*(ecma|java)script:!sim',$chunk)) return true;
1082 #look for css-style script-urls
1083 if (preg_match('!url\s*\(\s*[\'"]?\s*(ecma|java)script:!sim',$chunk)) return true;
1085 wfDebug("SpecialUpload::detectScript: no scripts found\n");
1089 /** Generic wrapper function for a virus scanner program.
1090 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
1091 * $wgAntivirusRequired may be used to deny upload if the scan fails.
1093 * @param string $file Pathname to the temporary upload file
1094 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
1095 * or a string containing feedback from the virus scanner if a virus was found.
1096 * If textual feedback is missing but a virus was found, this function returns true.
1098 function detectVirus($file) {
1099 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
1101 $fname= "SpecialUpload::detectVirus";
1103 if (!$wgAntivirus) { #disabled?
1104 wfDebug("$fname: virus scanner disabled\n");
1109 if (!$wgAntivirusSetup[$wgAntivirus]) {
1110 wfDebug("$fname: unknown virus scanner: $wgAntivirus\n");
1112 $wgOut->addHTML( "<div class='error'>Bad configuration: unknown virus scanner: <i>$wgAntivirus</i></div>\n" ); #LOCALIZE
1114 return "unknown antivirus: $wgAntivirus";
1117 #look up scanner configuration
1118 $virus_scanner= $wgAntivirusSetup[$wgAntivirus]["command"]; #command pattern
1119 $virus_scanner_codes= $wgAntivirusSetup[$wgAntivirus]["codemap"]; #exit-code map
1120 $msg_pattern= $wgAntivirusSetup[$wgAntivirus]["messagepattern"]; #message pattern
1122 $scanner= $virus_scanner; #copy, so we can resolve the pattern
1124 if (strpos($scanner,"%f")===false) $scanner.= " ".wfEscapeShellArg($file); #simple pattern: append file to scan
1125 else $scanner= str_replace("%f",wfEscapeShellArg($file),$scanner); #complex pattern: replace "%f" with file to scan
1127 wfDebug("$fname: running virus scan: $scanner \n");
1129 #execute virus scanner
1132 #NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
1133 # that does not seem to be worth the pain.
1134 # Ask me (Duesentrieb) about it if it's ever needed.
1136 if (wfIsWindows()) exec("$scanner",$output,$code);
1137 else exec("$scanner 2>&1",$output,$code);
1139 $exit_code= $code; #remember for user feedback
1141 if ($virus_scanner_codes) { #map exit code to AV_xxx constants.
1142 if (isset($virus_scanner_codes[$code])) {
1143 $code= $virus_scanner_codes[$code]; # explicit mapping
1144 } else if (isset($virus_scanner_codes["*"])) {
1145 $code= $virus_scanner_codes["*"]; # fallback mapping
1149 if ($code===AV_SCAN_FAILED
) { #scan failed (code was mapped to false by $virus_scanner_codes)
1150 wfDebug("$fname: failed to scan $file (code $exit_code).\n");
1152 if ($wgAntivirusRequired) { return "scan failed (code $exit_code)"; }
1153 else { return NULL; }
1155 else if ($code===AV_SCAN_ABORTED
) { #scan failed because filetype is unknown (probably imune)
1156 wfDebug("$fname: unsupported file type $file (code $exit_code).\n");
1159 else if ($code===AV_NO_VIRUS
) {
1160 wfDebug("$fname: file passed virus scan.\n");
1161 return false; #no virus found
1164 $output= join("\n",$output);
1165 $output= trim($output);
1167 if (!$output) $output= true; #if there's no output, return true
1168 else if ($msg_pattern) {
1170 if (preg_match($msg_pattern,$output,$groups)) {
1171 if ($groups[1]) $output= $groups[1];
1175 wfDebug("$fname: FOUND VIRUS! scanner feedback: $output");
1181 * Check if the temporary file is MacBinary-encoded, as some uploads
1182 * from Internet Explorer on Mac OS Classic and Mac OS X will be.
1183 * If so, the data fork will be extracted to a second temporary file,
1184 * which will then be checked for validity and either kept or discarded.
1188 function checkMacBinary() {
1189 $macbin = new MacBinary( $this->mUploadTempName
);
1190 if( $macbin->isValid() ) {
1191 $dataFile = tempnam( wfTempDir(), "WikiMacBinary" );
1192 $dataHandle = fopen( $dataFile, 'wb' );
1194 wfDebug( "SpecialUpload::checkMacBinary: Extracting MacBinary data fork to $dataFile\n" );
1195 $macbin->extractData( $dataHandle );
1197 $this->mUploadTempName
= $dataFile;
1198 $this->mUploadSize
= $macbin->dataForkLength();
1200 // We'll have to manually remove the new file if it's not kept.
1201 $this->mRemoveTempFile
= true;
1207 * If we've modified the upload file we need to manually remove it
1208 * on exit to clean up.
1211 function cleanupTempFile() {
1212 if( $this->mRemoveTempFile
&& file_exists( $this->mUploadTempName
) ) {
1213 wfDebug( "SpecialUpload::cleanupTempFile: Removing temporary file $this->mUploadTempName\n" );
1214 unlink( $this->mUploadTempName
);
1219 * Check if there's an overwrite conflict and, if so, if restrictions
1220 * forbid this user from performing the upload.
1222 * @return mixed true on success, WikiError on failure
1225 function checkOverwrite( $name ) {
1226 $img = Image
::newFromName( $name );
1227 if( is_null( $img ) ) {
1228 // Uh... this shouldn't happen ;)
1229 // But if it does, fall through to previous behavior
1234 if( $img->exists() ) {
1235 global $wgUser, $wgOut;
1236 if( $img->isLocal() ) {
1237 if( !$wgUser->isAllowed( 'reupload' ) ) {
1238 $error = 'fileexists-forbidden';
1241 if( !$wgUser->isAllowed( 'reupload' ) ||
1242 !$wgUser->isAllowed( 'reupload-shared' ) ) {
1243 $error = "fileexists-shared-forbidden";
1249 $errorText = wfMsg( $error, wfEscapeWikiText( $img->getName() ) );
1250 return new WikiError( $wgOut->parse( $errorText ) );
1253 // Rockin', go ahead and upload