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 /* Check for PHP error if any, requires php 4.2 or newer */
270 if( $this->mUploadError
== 1/*UPLOAD_ERR_INI_SIZE*/ ) {
271 $this->mainUploadForm( wfMsgHtml( 'largefileserver' ) );
276 * If there was no filename or a zero size given, give up quick.
278 if( trim( $this->mOname
) == '' ||
empty( $this->mUploadSize
) ) {
279 $this->mainUploadForm( wfMsgHtml( 'emptyfile' ) );
283 # Chop off any directories in the given filename
284 if( $this->mDestFile
) {
285 $basename = wfBaseName( $this->mDestFile
);
287 $basename = wfBaseName( $this->mOname
);
291 * We'll want to blacklist against *any* 'extension', and use
292 * only the final one for the whitelist.
294 list( $partname, $ext ) = $this->splitExtensions( $basename );
296 if( count( $ext ) ) {
297 $finalExt = $ext[count( $ext ) - 1];
301 $fullExt = implode( '.', $ext );
303 # If there was more than one "extension", reassemble the base
304 # filename to prevent bogus complaints about length
305 if( count( $ext ) > 1 ) {
306 for( $i = 0; $i < count( $ext ) - 1; $i++
)
307 $partname .= '.' . $ext[$i];
310 if( strlen( $partname ) < 3 ) {
311 $this->mainUploadForm( wfMsgHtml( 'minlength' ) );
316 * Filter out illegal characters, and try to make a legible name
317 * out of it. We'll strip some silently that Title would die on.
319 $filtered = preg_replace ( "/[^".Title
::legalChars()."]|:/", '-', $basename );
320 $nt = Title
::newFromText( $filtered );
321 if( is_null( $nt ) ) {
322 $this->uploadError( wfMsgWikiHtml( 'illegalfilename', htmlspecialchars( $filtered ) ) );
325 $nt =& Title
::makeTitle( NS_IMAGE
, $nt->getDBkey() );
326 $this->mUploadSaveName
= $nt->getDBkey();
329 * If the image is protected, non-sysop users won't be able
330 * to modify it by uploading a new revision.
332 if( !$nt->userCanEdit() ) {
333 return $this->uploadError( wfMsgWikiHtml( 'protectedpage' ) );
337 * In some cases we may forbid overwriting of existing files.
339 $overwrite = $this->checkOverwrite( $this->mUploadSaveName
);
340 if( WikiError
::isError( $overwrite ) ) {
341 return $this->uploadError( $overwrite->toString() );
344 /* Don't allow users to override the blacklist (check file extension) */
345 global $wgStrictFileExtensions;
346 global $wgFileExtensions, $wgFileBlacklist;
347 if( $this->checkFileExtensionList( $ext, $wgFileBlacklist ) ||
348 ($wgStrictFileExtensions &&
349 !$this->checkFileExtension( $finalExt, $wgFileExtensions ) ) ) {
350 return $this->uploadError( wfMsgHtml( 'badfiletype', htmlspecialchars( $fullExt ) ) );
354 * Look at the contents of the file; if we can recognize the
355 * type but it's corrupt or data of the wrong type, we should
356 * probably not accept it.
358 if( !$this->mStashed
) {
359 $this->checkMacBinary();
360 $veri = $this->verify( $this->mUploadTempName
, $finalExt );
362 if( $veri !== true ) { //it's a wiki error...
363 return $this->uploadError( $veri->toString() );
368 * Provide an opportunity for extensions to add futher checks
371 if( !wfRunHooks( 'UploadVerification',
372 array( $this->mUploadSaveName
, $this->mUploadTempName
, &$error ) ) ) {
373 return $this->uploadError( $error );
377 * Check for non-fatal conditions
379 if ( ! $this->mIgnoreWarning
) {
382 global $wgCapitalLinks;
383 if( $wgCapitalLinks ) {
384 $filtered = ucfirst( $filtered );
386 if( $this->mUploadSaveName
!= $filtered ) {
387 $warning .= '<li>'.wfMsgHtml( 'badfilename', htmlspecialchars( $this->mUploadSaveName
) ).'</li>';
390 global $wgCheckFileExtensions;
391 if ( $wgCheckFileExtensions ) {
392 if ( ! $this->checkFileExtension( $finalExt, $wgFileExtensions ) ) {
393 $warning .= '<li>'.wfMsgHtml( 'badfiletype', htmlspecialchars( $fullExt ) ).'</li>';
397 global $wgUploadSizeWarning;
398 if ( $wgUploadSizeWarning && ( $this->mUploadSize
> $wgUploadSizeWarning ) ) {
399 # TODO: Format $wgUploadSizeWarning to something that looks better than the raw byte
400 # value, perhaps add GB,MB and KB suffixes?
401 $warning .= '<li>'.wfMsgHtml( 'largefile', $wgUploadSizeWarning, $this->mUploadSize
).'</li>';
403 if ( $this->mUploadSize
== 0 ) {
404 $warning .= '<li>'.wfMsgHtml( 'emptyfile' ).'</li>';
407 if( $nt->getArticleID() ) {
409 $sk = $wgUser->getSkin();
410 $dlink = $sk->makeKnownLinkObj( $nt );
411 $warning .= '<li>'.wfMsgHtml( 'fileexists', $dlink ).'</li>';
413 # If the file existed before and was deleted, warn the user of this
414 # Don't bother doing so if the image exists now, however
415 $image = new Image( $nt );
416 if( $image->wasDeleted() ) {
417 $skin = $wgUser->getSkin();
418 $ltitle = SpecialPage
::getTitleFor( 'Log' );
419 $llink = $skin->makeKnownLinkObj( $ltitle, wfMsgHtml( 'deletionlog' ), 'type=delete&page=' . $nt->getPrefixedUrl() );
420 $warning .= wfOpenElement( 'li' ) . wfMsgWikiHtml( 'filewasdeleted', $llink ) . wfCloseElement( 'li' );
424 if( $warning != '' ) {
426 * Stash the file in a temporary location; the user can choose
427 * to let it through and we'll complete the upload then.
429 return $this->uploadWarning( $warning );
434 * Try actually saving the thing...
435 * It will show an error form on failure.
437 $hasBeenMunged = !empty( $this->mSessionKey
) ||
$this->mRemoveTempFile
;
438 if( $this->saveUploadedFile( $this->mUploadSaveName
,
439 $this->mUploadTempName
,
442 * Update the upload log and create the description page
443 * if it's a new file.
445 $img = Image
::newFromName( $this->mUploadSaveName
);
446 $success = $img->recordUpload( $this->mUploadOldVersion
,
447 $this->mUploadDescription
,
449 $this->mUploadCopyStatus
,
450 $this->mUploadSource
,
454 $this->showSuccess();
455 wfRunHooks( 'UploadComplete', array( &$img ) );
457 // Image::recordUpload() fails if the image went missing, which is
458 // unlikely, hence the lack of a specialised message
459 $wgOut->showFileNotFoundError( $this->mUploadSaveName
);
465 * Move the uploaded file from its temporary location to the final
466 * destination. If a previous version of the file exists, move
467 * it into the archive subdirectory.
469 * @todo If the later save fails, we may have disappeared the original file.
471 * @param string $saveName
472 * @param string $tempName full path to the temporary file
473 * @param bool $useRename if true, doesn't check that the source file
474 * is a PHP-managed upload temporary
476 function saveUploadedFile( $saveName, $tempName, $useRename = false ) {
477 global $wgOut, $wgAllowCopyUploads;
479 if ( !$useRename AND $wgAllowCopyUploads AND $this->mSourceType
== 'web' ) $useRename = true;
481 $fname= "SpecialUpload::saveUploadedFile";
483 $dest = wfImageDir( $saveName );
484 $archive = wfImageArchiveDir( $saveName );
485 if ( !is_dir( $dest ) ) wfMkdirParents( $dest );
486 if ( !is_dir( $archive ) ) wfMkdirParents( $archive );
488 $this->mSavedFile
= "{$dest}/{$saveName}";
490 if( is_file( $this->mSavedFile
) ) {
491 $this->mUploadOldVersion
= gmdate( 'YmdHis' ) . "!{$saveName}";
492 wfSuppressWarnings();
493 $success = rename( $this->mSavedFile
, "${archive}/{$this->mUploadOldVersion}" );
497 $wgOut->showFileRenameError( $this->mSavedFile
,
498 "${archive}/{$this->mUploadOldVersion}" );
501 else wfDebug("$fname: moved file ".$this->mSavedFile
." to ${archive}/{$this->mUploadOldVersion}\n");
504 $this->mUploadOldVersion
= '';
507 wfSuppressWarnings();
508 $success = $useRename
509 ?
rename( $tempName, $this->mSavedFile
)
510 : move_uploaded_file( $tempName, $this->mSavedFile
);
514 $wgOut->showFileCopyError( $tempName, $this->mSavedFile
);
517 wfDebug("$fname: wrote tempfile $tempName to ".$this->mSavedFile
."\n");
520 chmod( $this->mSavedFile
, 0644 );
525 * Stash a file in a temporary directory for later processing
526 * after the user has confirmed it.
528 * If the user doesn't explicitly cancel or accept, these files
529 * can accumulate in the temp directory.
531 * @param string $saveName - the destination filename
532 * @param string $tempName - the source temporary file to save
533 * @return string - full path the stashed file, or false on failure
536 function saveTempUploadedFile( $saveName, $tempName ) {
538 $archive = wfImageArchiveDir( $saveName, 'temp' );
539 if ( !is_dir ( $archive ) ) wfMkdirParents( $archive );
540 $stash = $archive . '/' . gmdate( "YmdHis" ) . '!' . $saveName;
542 $success = $this->mRemoveTempFile
543 ?
rename( $tempName, $stash )
544 : move_uploaded_file( $tempName, $stash );
546 $wgOut->showFileCopyError( $tempName, $stash );
554 * Stash a file in a temporary directory for later processing,
555 * and save the necessary descriptive info into the session.
556 * Returns a key value which will be passed through a form
557 * to pick up the path info on a later invocation.
562 function stashSession() {
563 $stash = $this->saveTempUploadedFile(
564 $this->mUploadSaveName
, $this->mUploadTempName
);
567 # Couldn't save the file.
571 $key = mt_rand( 0, 0x7fffffff );
572 $_SESSION['wsUploadData'][$key] = array(
573 'mUploadTempName' => $stash,
574 'mUploadSize' => $this->mUploadSize
,
575 'mOname' => $this->mOname
);
580 * Remove a temporarily kept file stashed by saveTempUploadedFile().
584 function unsaveUploadedFile() {
586 wfSuppressWarnings();
587 $success = unlink( $this->mUploadTempName
);
590 $wgOut->showFileDeleteError( $this->mUploadTempName
);
597 /* -------------------------------------------------------------- */
600 * Show some text and linkage on successful upload.
603 function showSuccess() {
604 global $wgUser, $wgOut, $wgContLang;
606 $sk = $wgUser->getSkin();
607 $ilink = $sk->makeMediaLink( $this->mUploadSaveName
, Image
::imageUrl( $this->mUploadSaveName
) );
608 $dname = $wgContLang->getNsText( NS_IMAGE
) . ':'.$this->mUploadSaveName
;
609 $dlink = $sk->makeKnownLink( $dname, $dname );
611 $wgOut->addHTML( '<h2>' . wfMsgHtml( 'successfulupload' ) . "</h2>\n" );
612 $text = wfMsgWikiHtml( 'fileuploaded', $ilink, $dlink );
613 $wgOut->addHTML( $text );
614 $wgOut->returnToMain( false );
618 * @param string $error as HTML
621 function uploadError( $error ) {
623 $wgOut->addHTML( "<h2>" . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
624 $wgOut->addHTML( "<span class='error'>{$error}</span>\n" );
628 * There's something wrong with this file, not enough to reject it
629 * totally but we require manual intervention to save it for real.
630 * Stash it away, then present a form asking to confirm or cancel.
632 * @param string $warning as HTML
635 function uploadWarning( $warning ) {
637 global $wgUseCopyrightUpload;
639 $this->mSessionKey
= $this->stashSession();
640 if( !$this->mSessionKey
) {
641 # Couldn't save file; an error has been displayed so let's go.
645 $wgOut->addHTML( "<h2>" . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
646 $wgOut->addHTML( "<ul class='warning'>{$warning}</ul><br />\n" );
648 $save = wfMsgHtml( 'savefile' );
649 $reupload = wfMsgHtml( 'reupload' );
650 $iw = wfMsgWikiHtml( 'ignorewarning' );
651 $reup = wfMsgWikiHtml( 'reuploaddesc' );
652 $titleObj = SpecialPage
::getTitleFor( 'Upload' );
653 $action = $titleObj->escapeLocalURL( 'action=submit' );
655 if ( $wgUseCopyrightUpload )
658 <input type='hidden' name='wpUploadCopyStatus' value=\"" . htmlspecialchars( $this->mUploadCopyStatus
) . "\" />
659 <input type='hidden' name='wpUploadSource' value=\"" . htmlspecialchars( $this->mUploadSource
) . "\" />
666 <form id='uploadwarning' method='post' enctype='multipart/form-data' action='$action'>
667 <input type='hidden' name='wpIgnoreWarning' value='1' />
668 <input type='hidden' name='wpSessionKey' value=\"" . htmlspecialchars( $this->mSessionKey
) . "\" />
669 <input type='hidden' name='wpUploadDescription' value=\"" . htmlspecialchars( $this->mUploadDescription
) . "\" />
670 <input type='hidden' name='wpLicense' value=\"" . htmlspecialchars( $this->mLicense
) . "\" />
671 <input type='hidden' name='wpDestFile' value=\"" . htmlspecialchars( $this->mDestFile
) . "\" />
672 <input type='hidden' name='wpWatchthis' value=\"" . htmlspecialchars( intval( $this->mWatchthis
) ) . "\" />
678 <input tabindex='2' type='submit' name='wpUpload' value=\"$save\" />
680 <td align='left'>$iw</td>
684 <input tabindex='2' type='submit' name='wpReUpload' value=\"{$reupload}\" />
686 <td align='left'>$reup</td>
689 </table></form>\n" );
693 * Displays the main upload form, optionally with a highlighted
694 * error message up at the top.
696 * @param string $msg as HTML
699 function mainUploadForm( $msg='' ) {
700 global $wgOut, $wgUser;
701 global $wgUseCopyrightUpload;
702 global $wgRequest, $wgAllowCopyUploads;
704 if( !wfRunHooks( 'UploadForm:initial', array( &$this ) ) )
706 wfDebug( "Hook 'UploadForm:initial' broke output of the upload form" );
710 $cols = intval($wgUser->getOption( 'cols' ));
711 $ew = $wgUser->getOption( 'editwidth' );
712 if ( $ew ) $ew = " style=\"width:100%\"";
716 $sub = wfMsgHtml( 'uploaderror' );
717 $wgOut->addHTML( "<h2>{$sub}</h2>\n" .
718 "<span class='error'>{$msg}</span>\n" );
720 $wgOut->addHTML( '<div id="uploadtext">' );
721 $wgOut->addWikiText( wfMsg( 'uploadtext' ) );
722 $wgOut->addHTML( '</div>' );
724 $sourcefilename = wfMsgHtml( 'sourcefilename' );
725 $destfilename = wfMsgHtml( 'destfilename' );
726 $summary = wfMsgWikiHtml( 'fileuploadsummary' );
728 $licenses = new Licenses();
729 $license = wfMsgHtml( 'license' );
730 $nolicense = wfMsgHtml( 'nolicense' );
731 $licenseshtml = $licenses->getHtml();
733 $ulb = wfMsgHtml( 'uploadbtn' );
736 $titleObj = SpecialPage
::getTitleFor( 'Upload' );
737 $action = $titleObj->escapeLocalURL();
739 $encDestFile = htmlspecialchars( $this->mDestFile
);
742 ( $wgUser->getOption( 'watchdefault' ) ||
743 ( $wgUser->getOption( 'watchcreations' ) && $this->mDestFile
== '' ) )
744 ?
'checked="checked"'
747 // Prepare form for upload or upload/copy
748 if( $wgAllowCopyUploads && $wgUser->isAllowed( 'upload_by_url' ) ) {
750 "<input type='radio' id='wpSourceTypeFile' name='wpSourceType' value='file' onchange='toggle_element_activation(\"wpUploadFileURL\",\"wpUploadFile\")' checked />" .
751 "<input tabindex='1' type='file' name='wpUploadFile' id='wpUploadFile' onfocus='toggle_element_activation(\"wpUploadFileURL\",\"wpUploadFile\");toggle_element_check(\"wpSourceTypeFile\",\"wpSourceTypeURL\")'" .
752 ($this->mDestFile?
"":"onchange='fillDestFilename(\"wpUploadFile\")' ") . "size='40' />" .
753 wfMsgHTML( 'upload_source_file' ) . "<br/>" .
754 "<input type='radio' id='wpSourceTypeURL' name='wpSourceType' value='web' onchange='toggle_element_activation(\"wpUploadFile\",\"wpUploadFileURL\")' />" .
755 "<input tabindex='1' type='text' name='wpUploadFileURL' id='wpUploadFileURL' onfocus='toggle_element_activation(\"wpUploadFile\",\"wpUploadFileURL\");toggle_element_check(\"wpSourceTypeURL\",\"wpSourceTypeFile\")'" .
756 ($this->mDestFile?
"":"onchange='fillDestFilename(\"wpUploadFileURL\")' ") . "size='40' DISABLED />" .
757 wfMsgHtml( 'upload_source_url' ) ;
760 "<input tabindex='1' type='file' name='wpUploadFile' id='wpUploadFile' " .
761 ($this->mDestFile?
"":"onchange='fillDestFilename(\"wpUploadFile\")' ") .
763 "<input type='hidden' name='wpSourceType' value='file' />" ;
767 <form id='upload' method='post' enctype='multipart/form-data' action=\"$action\">
770 {$this->uploadFormTextTop}
771 <td align='right' valign='top'><label for='wpUploadFile'>{$sourcefilename}:</label></td>
777 <td align='right'><label for='wpDestFile'>{$destfilename}:</label></td>
779 <input tabindex='2' type='text' name='wpDestFile' id='wpDestFile' size='40' value=\"$encDestFile\" />
783 <td align='right'><label for='wpUploadDescription'>{$summary}</label></td>
785 <textarea tabindex='3' name='wpUploadDescription' id='wpUploadDescription' rows='6' cols='{$cols}'{$ew}>" . htmlspecialchars( $this->mUploadDescription
) . "</textarea>
786 {$this->uploadFormTextAfterSummary}
791 if ( $licenseshtml != '' ) {
794 <td align='right'><label for='wpLicense'>$license:</label></td>
796 <script type='text/javascript' src=\"$wgStylePath/common/upload.js\"></script>
797 <select name='wpLicense' id='wpLicense' tabindex='4'
798 onchange='licenseSelectorCheck()'>
799 <option value=''>$nolicense</option>
808 if ( $wgUseCopyrightUpload ) {
809 $filestatus = wfMsgHtml ( 'filestatus' );
810 $copystatus = htmlspecialchars( $this->mUploadCopyStatus
);
811 $filesource = wfMsgHtml ( 'filesource' );
812 $uploadsource = htmlspecialchars( $this->mUploadSource
);
815 <td align='right' nowrap='nowrap'><label for='wpUploadCopyStatus'>$filestatus:</label></td>
816 <td><input tabindex='5' type='text' name='wpUploadCopyStatus' id='wpUploadCopyStatus' value=\"$copystatus\" size='40' /></td>
819 <td align='right'><label for='wpUploadCopyStatus'>$filesource:</label></td>
820 <td><input tabindex='6' type='text' name='wpUploadSource' id='wpUploadCopyStatus' value=\"$uploadsource\" size='40' /></td>
830 <input tabindex='7' type='checkbox' name='wpWatchthis' id='wpWatchthis' $watchChecked value='true' />
831 <label for='wpWatchthis'>" . wfMsgHtml( 'watchthisupload' ) . "</label>
832 <input tabindex='8' type='checkbox' name='wpIgnoreWarning' id='wpIgnoreWarning' value='true' />
833 <label for='wpIgnoreWarning'>" . wfMsgHtml( 'ignorewarnings' ) . "</label>
841 <td align='left'><input tabindex='9' type='submit' name='wpUpload' value=\"{$ulb}\" /></td>
848 $wgOut->addWikiText( wfMsgForContent( 'edittools' ) );
857 /* -------------------------------------------------------------- */
860 * Split a file into a base name and all dot-delimited 'extensions'
861 * on the end. Some web server configurations will fall back to
862 * earlier pseudo-'extensions' to determine type and execute
863 * scripts, so the blacklist needs to check them all.
867 function splitExtensions( $filename ) {
868 $bits = explode( '.', $filename );
869 $basename = array_shift( $bits );
870 return array( $basename, $bits );
874 * Perform case-insensitive match against a list of file extensions.
875 * Returns true if the extension is in the list.
881 function checkFileExtension( $ext, $list ) {
882 return in_array( strtolower( $ext ), $list );
886 * Perform case-insensitive match against a list of file extensions.
887 * Returns true if any of the extensions are in the list.
893 function checkFileExtensionList( $ext, $list ) {
894 foreach( $ext as $e ) {
895 if( in_array( strtolower( $e ), $list ) ) {
903 * Verifies that it's ok to include the uploaded file
905 * @param string $tmpfile the full path of the temporary file to verify
906 * @param string $extension The filename extension that the file is to be served with
907 * @return mixed true of the file is verified, a WikiError object otherwise.
909 function verify( $tmpfile, $extension ) {
910 #magically determine mime type
911 $magic=& MimeMagic
::singleton();
912 $mime= $magic->guessMimeType($tmpfile,false);
914 $fname= "SpecialUpload::verify";
916 #check mime type, if desired
917 global $wgVerifyMimeType;
918 if ($wgVerifyMimeType) {
920 #check mime type against file extension
921 if( !$this->verifyExtension( $mime, $extension ) ) {
922 return new WikiErrorMsg( 'uploadcorrupt' );
925 #check mime type blacklist
926 global $wgMimeTypeBlacklist;
927 if( isset($wgMimeTypeBlacklist) && !is_null($wgMimeTypeBlacklist)
928 && $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
929 return new WikiErrorMsg( 'badfiletype', htmlspecialchars( $mime ) );
933 #check for htmlish code and javascript
934 if( $this->detectScript ( $tmpfile, $mime, $extension ) ) {
935 return new WikiErrorMsg( 'uploadscripted' );
939 * Scan the uploaded file for viruses
941 $virus= $this->detectVirus($tmpfile);
943 return new WikiErrorMsg( 'uploadvirus', htmlspecialchars($virus) );
946 wfDebug( "$fname: all clear; passing.\n" );
951 * Checks if the mime type of the uploaded file matches the file extension.
953 * @param string $mime the mime type of the uploaded file
954 * @param string $extension The filename extension that the file is to be served with
957 function verifyExtension( $mime, $extension ) {
958 $fname = 'SpecialUpload::verifyExtension';
960 $magic =& MimeMagic
::singleton();
962 if ( ! $mime ||
$mime == 'unknown' ||
$mime == 'unknown/unknown' )
963 if ( ! $magic->isRecognizableExtension( $extension ) ) {
964 wfDebug( "$fname: passing file with unknown detected mime type; unrecognized extension '$extension', can't verify\n" );
967 wfDebug( "$fname: rejecting file with unknown detected mime type; recognized extension '$extension', so probably invalid file\n" );
971 $match= $magic->isMatchingExtension($extension,$mime);
974 wfDebug( "$fname: no file extension known for mime type $mime, passing file\n" );
976 } elseif ($match===true) {
977 wfDebug( "$fname: mime type $mime matches extension $extension, passing file\n" );
979 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
983 wfDebug( "$fname: mime type $mime mismatches file extension $extension, rejecting file\n" );
988 /** Heuristig for detecting files that *could* contain JavaScript instructions or
989 * things that may look like HTML to a browser and are thus
990 * potentially harmful. The present implementation will produce false positives in some situations.
992 * @param string $file Pathname to the temporary upload file
993 * @param string $mime The mime type of the file
994 * @param string $extension The extension of the file
995 * @return bool true if the file contains something looking like embedded scripts
997 function detectScript($file, $mime, $extension) {
998 global $wgAllowTitlesInSVG;
1000 #ugly hack: for text files, always look at the entire file.
1001 #For binarie field, just check the first K.
1003 if (strpos($mime,'text/')===0) $chunk = file_get_contents( $file );
1005 $fp = fopen( $file, 'rb' );
1006 $chunk = fread( $fp, 1024 );
1010 $chunk= strtolower( $chunk );
1012 if (!$chunk) return false;
1014 #decode from UTF-16 if needed (could be used for obfuscation).
1015 if (substr($chunk,0,2)=="\xfe\xff") $enc= "UTF-16BE";
1016 elseif (substr($chunk,0,2)=="\xff\xfe") $enc= "UTF-16LE";
1019 if ($enc) $chunk= iconv($enc,"ASCII//IGNORE",$chunk);
1021 $chunk= trim($chunk);
1023 #FIXME: convert from UTF-16 if necessarry!
1025 wfDebug("SpecialUpload::detectScript: checking for embedded scripts and HTML stuff\n");
1027 #check for HTML doctype
1028 if (eregi("<!DOCTYPE *X?HTML",$chunk)) return true;
1031 * Internet Explorer for Windows performs some really stupid file type
1032 * autodetection which can cause it to interpret valid image files as HTML
1033 * and potentially execute JavaScript, creating a cross-site scripting
1036 * Apple's Safari browser also performs some unsafe file type autodetection
1037 * which can cause legitimate files to be interpreted as HTML if the
1038 * web server is not correctly configured to send the right content-type
1039 * (or if you're really uploading plain text and octet streams!)
1041 * Returns true if IE is likely to mistake the given file for HTML.
1042 * Also returns true if Safari would mistake the given file for HTML
1043 * when served with a generic content-type.
1049 '<html', #also in safari
1052 '<script', #also in safari
1055 if( ! $wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
1059 foreach( $tags as $tag ) {
1060 if( false !== strpos( $chunk, $tag ) ) {
1066 * look for javascript
1069 #resolve entity-refs to look at attributes. may be harsh on big files... cache result?
1070 $chunk = Sanitizer
::decodeCharReferences( $chunk );
1072 #look for script-types
1073 if (preg_match('!type\s*=\s*[\'"]?\s*(\w*/)?(ecma|java)!sim',$chunk)) return true;
1075 #look for html-style script-urls
1076 if (preg_match('!(href|src|data)\s*=\s*[\'"]?\s*(ecma|java)script:!sim',$chunk)) return true;
1078 #look for css-style script-urls
1079 if (preg_match('!url\s*\(\s*[\'"]?\s*(ecma|java)script:!sim',$chunk)) return true;
1081 wfDebug("SpecialUpload::detectScript: no scripts found\n");
1085 /** Generic wrapper function for a virus scanner program.
1086 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
1087 * $wgAntivirusRequired may be used to deny upload if the scan fails.
1089 * @param string $file Pathname to the temporary upload file
1090 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
1091 * or a string containing feedback from the virus scanner if a virus was found.
1092 * If textual feedback is missing but a virus was found, this function returns true.
1094 function detectVirus($file) {
1095 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
1097 $fname= "SpecialUpload::detectVirus";
1099 if (!$wgAntivirus) { #disabled?
1100 wfDebug("$fname: virus scanner disabled\n");
1105 if (!$wgAntivirusSetup[$wgAntivirus]) {
1106 wfDebug("$fname: unknown virus scanner: $wgAntivirus\n");
1108 $wgOut->addHTML( "<div class='error'>Bad configuration: unknown virus scanner: <i>$wgAntivirus</i></div>\n" ); #LOCALIZE
1110 return "unknown antivirus: $wgAntivirus";
1113 #look up scanner configuration
1114 $virus_scanner= $wgAntivirusSetup[$wgAntivirus]["command"]; #command pattern
1115 $virus_scanner_codes= $wgAntivirusSetup[$wgAntivirus]["codemap"]; #exit-code map
1116 $msg_pattern= $wgAntivirusSetup[$wgAntivirus]["messagepattern"]; #message pattern
1118 $scanner= $virus_scanner; #copy, so we can resolve the pattern
1120 if (strpos($scanner,"%f")===false) $scanner.= " ".wfEscapeShellArg($file); #simple pattern: append file to scan
1121 else $scanner= str_replace("%f",wfEscapeShellArg($file),$scanner); #complex pattern: replace "%f" with file to scan
1123 wfDebug("$fname: running virus scan: $scanner \n");
1125 #execute virus scanner
1128 #NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
1129 # that does not seem to be worth the pain.
1130 # Ask me (Duesentrieb) about it if it's ever needed.
1132 if (wfIsWindows()) exec("$scanner",$output,$code);
1133 else exec("$scanner 2>&1",$output,$code);
1135 $exit_code= $code; #remember for user feedback
1137 if ($virus_scanner_codes) { #map exit code to AV_xxx constants.
1138 if (isset($virus_scanner_codes[$code])) {
1139 $code= $virus_scanner_codes[$code]; # explicit mapping
1140 } else if (isset($virus_scanner_codes["*"])) {
1141 $code= $virus_scanner_codes["*"]; # fallback mapping
1145 if ($code===AV_SCAN_FAILED
) { #scan failed (code was mapped to false by $virus_scanner_codes)
1146 wfDebug("$fname: failed to scan $file (code $exit_code).\n");
1148 if ($wgAntivirusRequired) { return "scan failed (code $exit_code)"; }
1149 else { return NULL; }
1151 else if ($code===AV_SCAN_ABORTED
) { #scan failed because filetype is unknown (probably imune)
1152 wfDebug("$fname: unsupported file type $file (code $exit_code).\n");
1155 else if ($code===AV_NO_VIRUS
) {
1156 wfDebug("$fname: file passed virus scan.\n");
1157 return false; #no virus found
1160 $output= join("\n",$output);
1161 $output= trim($output);
1163 if (!$output) $output= true; #if there's no output, return true
1164 else if ($msg_pattern) {
1166 if (preg_match($msg_pattern,$output,$groups)) {
1167 if ($groups[1]) $output= $groups[1];
1171 wfDebug("$fname: FOUND VIRUS! scanner feedback: $output");
1177 * Check if the temporary file is MacBinary-encoded, as some uploads
1178 * from Internet Explorer on Mac OS Classic and Mac OS X will be.
1179 * If so, the data fork will be extracted to a second temporary file,
1180 * which will then be checked for validity and either kept or discarded.
1184 function checkMacBinary() {
1185 $macbin = new MacBinary( $this->mUploadTempName
);
1186 if( $macbin->isValid() ) {
1187 $dataFile = tempnam( wfTempDir(), "WikiMacBinary" );
1188 $dataHandle = fopen( $dataFile, 'wb' );
1190 wfDebug( "SpecialUpload::checkMacBinary: Extracting MacBinary data fork to $dataFile\n" );
1191 $macbin->extractData( $dataHandle );
1193 $this->mUploadTempName
= $dataFile;
1194 $this->mUploadSize
= $macbin->dataForkLength();
1196 // We'll have to manually remove the new file if it's not kept.
1197 $this->mRemoveTempFile
= true;
1203 * If we've modified the upload file we need to manually remove it
1204 * on exit to clean up.
1207 function cleanupTempFile() {
1208 if( $this->mRemoveTempFile
&& file_exists( $this->mUploadTempName
) ) {
1209 wfDebug( "SpecialUpload::cleanupTempFile: Removing temporary file $this->mUploadTempName\n" );
1210 unlink( $this->mUploadTempName
);
1215 * Check if there's an overwrite conflict and, if so, if restrictions
1216 * forbid this user from performing the upload.
1218 * @return mixed true on success, WikiError on failure
1221 function checkOverwrite( $name ) {
1222 $img = Image
::newFromName( $name );
1223 if( is_null( $img ) ) {
1224 // Uh... this shouldn't happen ;)
1225 // But if it does, fall through to previous behavior
1230 if( $img->exists() ) {
1231 global $wgUser, $wgOut;
1232 if( $img->isLocal() ) {
1233 if( !$wgUser->isAllowed( 'reupload' ) ) {
1234 $error = 'fileexists-forbidden';
1237 if( !$wgUser->isAllowed( 'reupload' ) ||
1238 !$wgUser->isAllowed( 'reupload-shared' ) ) {
1239 $error = "fileexists-shared-forbidden";
1245 $errorText = wfMsg( $error, wfEscapeWikiText( $img->getName() ) );
1246 return new WikiError( $wgOut->parse( $errorText ) );
1249 // Rockin', go ahead and upload