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->getBool( '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->initialize_web_file( $request );
87 $this->initialize_php_file( $request );
93 * Initialize the uploaded file from PHP data
96 function initialize_php_file( &$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 initialize_web_file( &$request ) {
111 global $wgTmpDirectory, $wgMaxUploadSize, $wgUploadTempFileSize;
112 $url = $request->getText( 'wpUploadFile' );
113 $local_file = tempnam( $wgTmpDirectory, 'WEBUPLOAD' );
115 $this->mUploadTempName
= $local_file;
116 $this->mUploadError
= $this->curl_copy( $url, $local_file );
117 $this->mUploadSize
= $wgUploadTempFileSize ;
118 $this->mOname
= array_pop( explode( '/', $url ) );
119 $this->mSessionKey
= false;
120 $this->mStashed
= false;
121 $this->mRemoveTempFile
= file_exists( $local_file ) ; // PHP will *not* handle this
126 * Returns true if there was an error, false otherwise
129 function curl_copy ( $url , $dest ) {
130 global $wgMaxUploadSize, $wgUploadTempFile, $wgUploadTempFileSize, $wgUser;
132 if( !$wgUser->isAllowed( 'upload_by_url' ) ) {
133 $wgOut->permissionRequired( 'upload_by_url' );
137 $url = trim ( $url ) ; # Maybe remove some pasting blanks :-)
138 $u = strtolower ( $url ) ;
139 if( substr( $u, 0, 7 ) != 'http://' AND substr( $u, 0, 6 ) != 'ftp://' ) return true ; # Only HTTP or FTP URLs
141 # Open temporary file
142 $wgUploadTempFileSize = 0 ;
143 $wgUploadTempFile = @fopen
( $this->mUploadTempName
, "wb" ) ;
144 if ( $wgUploadTempFile === false ) return true ; # Could not open temporary file to write in
147 curl_setopt ($ch, CURLOPT_HTTP_VERSION
, 1.0); # Probably not needed, but apparently can work around some bug
148 curl_setopt ($ch, CURLOPT_TIMEOUT
, 10); # 10 seconds timeout
149 curl_setopt ($ch, CURLOPT_LOW_SPEED_LIMIT
, 512); # 0.5KB per second minimum transfer speed
150 curl_setopt ($ch, CURLOPT_URL
, $url);
151 curl_setopt ($ch, CURLOPT_WRITEFUNCTION
, 'wfUploadCurlCallback' ) ;
153 $error = curl_errno ( $ch ) ?
true : false ;
154 # if ( $error ) print curl_error ( $ch ) ; # Debugging output
157 fclose ( $wgUploadTempFile ) ;
158 unset ( $wgUploadTempFile ) ;
159 if ( $error ) unlink ( $dest ) ;
169 global $wgUser, $wgOut;
170 global $wgEnableUploads, $wgUploadDirectory;
172 # Check uploading enabled
173 if( !$wgEnableUploads ) {
174 $wgOut->showErrorPage( 'uploaddisabled', 'uploaddisabledtext' );
179 if( $wgUser->isLoggedIn() ) {
180 if( !$wgUser->isAllowed( 'upload' ) ) {
181 $wgOut->permissionRequired( 'upload' );
185 $wgOut->showErrorPage( 'uploadnologin', 'uploadnologintext' );
190 if( $wgUser->isBlocked() ) {
191 $wgOut->blockedPage();
196 $wgOut->readOnlyPage();
200 /** Check if the image directory is writeable, this is a common mistake */
201 if( !is_writeable( $wgUploadDirectory ) ) {
202 $wgOut->addWikiText( wfMsg( 'upload_directory_read_only', $wgUploadDirectory ) );
206 if( $this->mReUpload
) {
207 if( !$this->unsaveUploadedFile() ) {
210 $this->mainUploadForm();
211 } else if( 'submit' == $this->mAction ||
$this->mUpload
) {
212 $this->processUpload();
214 $this->mainUploadForm();
217 $this->cleanupTempFile();
220 /* -------------------------------------------------------------- */
223 * Really do the upload
224 * Checks are made in SpecialUpload::execute()
227 function processUpload() {
228 global $wgUser, $wgOut;
230 /* Check for PHP error if any, requires php 4.2 or newer */
231 if( $this->mUploadError
== 1/*UPLOAD_ERR_INI_SIZE*/ ) {
232 $this->mainUploadForm( wfMsgHtml( 'largefileserver' ) );
237 * If there was no filename or a zero size given, give up quick.
239 if( trim( $this->mOname
) == '' ||
empty( $this->mUploadSize
) ) {
240 $this->mainUploadForm( wfMsgHtml( 'emptyfile' ) );
244 # Chop off any directories in the given filename
245 if( $this->mDestFile
) {
246 $basename = wfBaseName( $this->mDestFile
);
248 $basename = wfBaseName( $this->mOname
);
252 * We'll want to blacklist against *any* 'extension', and use
253 * only the final one for the whitelist.
255 list( $partname, $ext ) = $this->splitExtensions( $basename );
257 if( count( $ext ) ) {
258 $finalExt = $ext[count( $ext ) - 1];
262 $fullExt = implode( '.', $ext );
264 # If there was more than one "extension", reassemble the base
265 # filename to prevent bogus complaints about length
266 if( count( $ext ) > 1 ) {
267 for( $i = 0; $i < count( $ext ) - 1; $i++
)
268 $partname .= '.' . $ext[$i];
271 if( strlen( $partname ) < 3 ) {
272 $this->mainUploadForm( wfMsgHtml( 'minlength' ) );
277 * Filter out illegal characters, and try to make a legible name
278 * out of it. We'll strip some silently that Title would die on.
280 $filtered = preg_replace ( "/[^".Title
::legalChars()."]|:/", '-', $basename );
281 $nt = Title
::newFromText( $filtered );
282 if( is_null( $nt ) ) {
283 $this->uploadError( wfMsgWikiHtml( 'illegalfilename', htmlspecialchars( $filtered ) ) );
286 $nt =& Title
::makeTitle( NS_IMAGE
, $nt->getDBkey() );
287 $this->mUploadSaveName
= $nt->getDBkey();
290 * If the image is protected, non-sysop users won't be able
291 * to modify it by uploading a new revision.
293 if( !$nt->userCanEdit() ) {
294 return $this->uploadError( wfMsgWikiHtml( 'protectedpage' ) );
298 * In some cases we may forbid overwriting of existing files.
300 $overwrite = $this->checkOverwrite( $this->mUploadSaveName
);
301 if( WikiError
::isError( $overwrite ) ) {
302 return $this->uploadError( $overwrite->toString() );
305 /* Don't allow users to override the blacklist (check file extension) */
306 global $wgStrictFileExtensions;
307 global $wgFileExtensions, $wgFileBlacklist;
308 if( $this->checkFileExtensionList( $ext, $wgFileBlacklist ) ||
309 ($wgStrictFileExtensions &&
310 !$this->checkFileExtension( $finalExt, $wgFileExtensions ) ) ) {
311 return $this->uploadError( wfMsgHtml( 'badfiletype', htmlspecialchars( $fullExt ) ) );
315 * Look at the contents of the file; if we can recognize the
316 * type but it's corrupt or data of the wrong type, we should
317 * probably not accept it.
319 if( !$this->mStashed
) {
320 $this->checkMacBinary();
321 $veri = $this->verify( $this->mUploadTempName
, $finalExt );
323 if( $veri !== true ) { //it's a wiki error...
324 return $this->uploadError( $veri->toString() );
329 * Provide an opportunity for extensions to add futher checks
332 if( !wfRunHooks( 'UploadVerification',
333 array( $this->mUploadSaveName
, $this->mUploadTempName
, &$error ) ) ) {
334 return $this->uploadError( $error );
338 * Check for non-fatal conditions
340 if ( ! $this->mIgnoreWarning
) {
343 global $wgCapitalLinks;
344 if( $wgCapitalLinks ) {
345 $filtered = ucfirst( $filtered );
347 if( $this->mUploadSaveName
!= $filtered ) {
348 $warning .= '<li>'.wfMsgHtml( 'badfilename', htmlspecialchars( $this->mUploadSaveName
) ).'</li>';
351 global $wgCheckFileExtensions;
352 if ( $wgCheckFileExtensions ) {
353 if ( ! $this->checkFileExtension( $finalExt, $wgFileExtensions ) ) {
354 $warning .= '<li>'.wfMsgHtml( 'badfiletype', htmlspecialchars( $fullExt ) ).'</li>';
358 global $wgUploadSizeWarning;
359 if ( $wgUploadSizeWarning && ( $this->mUploadSize
> $wgUploadSizeWarning ) ) {
360 # TODO: Format $wgUploadSizeWarning to something that looks better than the raw byte
361 # value, perhaps add GB,MB and KB suffixes?
362 $warning .= '<li>'.wfMsgHtml( 'largefile', $wgUploadSizeWarning, $this->mUploadSize
).'</li>';
364 if ( $this->mUploadSize
== 0 ) {
365 $warning .= '<li>'.wfMsgHtml( 'emptyfile' ).'</li>';
368 if( $nt->getArticleID() ) {
370 $sk = $wgUser->getSkin();
371 $dlink = $sk->makeKnownLinkObj( $nt );
372 $warning .= '<li>'.wfMsgHtml( 'fileexists', $dlink ).'</li>';
374 # If the file existed before and was deleted, warn the user of this
375 # Don't bother doing so if the image exists now, however
376 $image = new Image( $nt );
377 if( $image->wasDeleted() ) {
378 $skin = $wgUser->getSkin();
379 $ltitle = Title
::makeTitle( NS_SPECIAL
, 'Log' );
380 $llink = $skin->makeKnownLinkObj( $ltitle, wfMsgHtml( 'deletionlog' ), 'type=delete&page=' . $nt->getPrefixedUrl() );
381 $warning .= wfOpenElement( 'li' ) . wfMsgWikiHtml( 'filewasdeleted', $llink ) . wfCloseElement( 'li' );
385 if( $warning != '' ) {
387 * Stash the file in a temporary location; the user can choose
388 * to let it through and we'll complete the upload then.
390 return $this->uploadWarning( $warning );
395 * Try actually saving the thing...
396 * It will show an error form on failure.
398 $hasBeenMunged = !empty( $this->mSessionKey
) ||
$this->mRemoveTempFile
;
399 if( $this->saveUploadedFile( $this->mUploadSaveName
,
400 $this->mUploadTempName
,
403 * Update the upload log and create the description page
404 * if it's a new file.
406 $img = Image
::newFromName( $this->mUploadSaveName
);
407 $success = $img->recordUpload( $this->mUploadOldVersion
,
408 $this->mUploadDescription
,
410 $this->mUploadCopyStatus
,
411 $this->mUploadSource
,
415 $this->showSuccess();
416 wfRunHooks( 'UploadComplete', array( &$img ) );
418 // Image::recordUpload() fails if the image went missing, which is
419 // unlikely, hence the lack of a specialised message
420 $wgOut->showFileNotFoundError( $this->mUploadSaveName
);
426 * Move the uploaded file from its temporary location to the final
427 * destination. If a previous version of the file exists, move
428 * it into the archive subdirectory.
430 * @todo If the later save fails, we may have disappeared the original file.
432 * @param string $saveName
433 * @param string $tempName full path to the temporary file
434 * @param bool $useRename if true, doesn't check that the source file
435 * is a PHP-managed upload temporary
437 function saveUploadedFile( $saveName, $tempName, $useRename = false ) {
438 global $wgOut, $wgAllowCopyUploads;
440 if ( !$useRename AND $wgAllowCopyUploads AND $this->mSourceType
== 'web' ) $useRename = true;
442 $fname= "SpecialUpload::saveUploadedFile";
444 $dest = wfImageDir( $saveName );
445 $archive = wfImageArchiveDir( $saveName );
446 if ( !is_dir( $dest ) ) wfMkdirParents( $dest );
447 if ( !is_dir( $archive ) ) wfMkdirParents( $archive );
449 $this->mSavedFile
= "{$dest}/{$saveName}";
451 if( is_file( $this->mSavedFile
) ) {
452 $this->mUploadOldVersion
= gmdate( 'YmdHis' ) . "!{$saveName}";
453 wfSuppressWarnings();
454 $success = rename( $this->mSavedFile
, "${archive}/{$this->mUploadOldVersion}" );
458 $wgOut->showFileRenameError( $this->mSavedFile
,
459 "${archive}/{$this->mUploadOldVersion}" );
462 else wfDebug("$fname: moved file ".$this->mSavedFile
." to ${archive}/{$this->mUploadOldVersion}\n");
465 $this->mUploadOldVersion
= '';
468 wfSuppressWarnings();
469 $success = $useRename
470 ?
rename( $tempName, $this->mSavedFile
)
471 : move_uploaded_file( $tempName, $this->mSavedFile
);
475 $wgOut->showFileCopyError( $tempName, $this->mSavedFile
);
478 wfDebug("$fname: wrote tempfile $tempName to ".$this->mSavedFile
."\n");
481 chmod( $this->mSavedFile
, 0644 );
486 * Stash a file in a temporary directory for later processing
487 * after the user has confirmed it.
489 * If the user doesn't explicitly cancel or accept, these files
490 * can accumulate in the temp directory.
492 * @param string $saveName - the destination filename
493 * @param string $tempName - the source temporary file to save
494 * @return string - full path the stashed file, or false on failure
497 function saveTempUploadedFile( $saveName, $tempName ) {
498 global $wgOut, $wgAllowCopyUploads;
499 $archive = wfImageArchiveDir( $saveName, 'temp' );
500 if ( !is_dir ( $archive ) ) wfMkdirParents( $archive );
501 $stash = $archive . '/' . gmdate( "YmdHis" ) . '!' . $saveName;
503 $remove_file = $this->mRemoveTempFile
;
504 if ( !$remove_file AND $wgAllowCopyUploads AND $this->mSourceType
== 'web' ) $remove_file = true;
506 $success = $remove_file
507 ?
rename( $tempName, $stash )
508 : move_uploaded_file( $tempName, $stash );
510 $wgOut->showFileCopyError( $tempName, $stash );
518 * Stash a file in a temporary directory for later processing,
519 * and save the necessary descriptive info into the session.
520 * Returns a key value which will be passed through a form
521 * to pick up the path info on a later invocation.
526 function stashSession() {
527 $stash = $this->saveTempUploadedFile(
528 $this->mUploadSaveName
, $this->mUploadTempName
);
531 # Couldn't save the file.
535 $key = mt_rand( 0, 0x7fffffff );
536 $_SESSION['wsUploadData'][$key] = array(
537 'mUploadTempName' => $stash,
538 'mUploadSize' => $this->mUploadSize
,
539 'mOname' => $this->mOname
);
544 * Remove a temporarily kept file stashed by saveTempUploadedFile().
548 function unsaveUploadedFile() {
550 wfSuppressWarnings();
551 $success = unlink( $this->mUploadTempName
);
554 $wgOut->showFileDeleteError( $this->mUploadTempName
);
561 /* -------------------------------------------------------------- */
564 * Show some text and linkage on successful upload.
567 function showSuccess() {
568 global $wgUser, $wgOut, $wgContLang;
570 $sk = $wgUser->getSkin();
571 $ilink = $sk->makeMediaLink( $this->mUploadSaveName
, Image
::imageUrl( $this->mUploadSaveName
) );
572 $dname = $wgContLang->getNsText( NS_IMAGE
) . ':'.$this->mUploadSaveName
;
573 $dlink = $sk->makeKnownLink( $dname, $dname );
575 $wgOut->addHTML( '<h2>' . wfMsgHtml( 'successfulupload' ) . "</h2>\n" );
576 $text = wfMsgWikiHtml( 'fileuploaded', $ilink, $dlink );
577 $wgOut->addHTML( $text );
578 $wgOut->returnToMain( false );
582 * @param string $error as HTML
585 function uploadError( $error ) {
587 $wgOut->addHTML( "<h2>" . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
588 $wgOut->addHTML( "<span class='error'>{$error}</span>\n" );
592 * There's something wrong with this file, not enough to reject it
593 * totally but we require manual intervention to save it for real.
594 * Stash it away, then present a form asking to confirm or cancel.
596 * @param string $warning as HTML
599 function uploadWarning( $warning ) {
601 global $wgUseCopyrightUpload;
603 $this->mSessionKey
= $this->stashSession();
604 if( !$this->mSessionKey
) {
605 # Couldn't save file; an error has been displayed so let's go.
609 $wgOut->addHTML( "<h2>" . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
610 $wgOut->addHTML( "<ul class='warning'>{$warning}</ul><br />\n" );
612 $save = wfMsgHtml( 'savefile' );
613 $reupload = wfMsgHtml( 'reupload' );
614 $iw = wfMsgWikiHtml( 'ignorewarning' );
615 $reup = wfMsgWikiHtml( 'reuploaddesc' );
616 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Upload' );
617 $action = $titleObj->escapeLocalURL( 'action=submit' );
619 if ( $wgUseCopyrightUpload )
622 <input type='hidden' name='wpUploadCopyStatus' value=\"" . htmlspecialchars( $this->mUploadCopyStatus
) . "\" />
623 <input type='hidden' name='wpUploadSource' value=\"" . htmlspecialchars( $this->mUploadSource
) . "\" />
630 <form id='uploadwarning' method='post' enctype='multipart/form-data' action='$action'>
631 <input type='hidden' name='wpIgnoreWarning' value='1' />
632 <input type='hidden' name='wpSessionKey' value=\"" . htmlspecialchars( $this->mSessionKey
) . "\" />
633 <input type='hidden' name='wpUploadDescription' value=\"" . htmlspecialchars( $this->mUploadDescription
) . "\" />
634 <input type='hidden' name='wpLicense' value=\"" . htmlspecialchars( $this->mLicense
) . "\" />
635 <input type='hidden' name='wpDestFile' value=\"" . htmlspecialchars( $this->mDestFile
) . "\" />
636 <input type='hidden' name='wpWatchthis' value=\"" . htmlspecialchars( intval( $this->mWatchthis
) ) . "\" />
642 <input tabindex='2' type='submit' name='wpUpload' value=\"$save\" />
644 <td align='left'>$iw</td>
648 <input tabindex='2' type='submit' name='wpReUpload' value=\"{$reupload}\" />
650 <td align='left'>$reup</td>
653 </table></form>\n" );
657 * Displays the main upload form, optionally with a highlighted
658 * error message up at the top.
660 * @param string $msg as HTML
663 function mainUploadForm( $msg='' ) {
664 global $wgOut, $wgUser;
665 global $wgUseCopyrightUpload;
666 global $wgRequest, $wgAllowCopyUploads;
668 $cols = intval($wgUser->getOption( 'cols' ));
669 $ew = $wgUser->getOption( 'editwidth' );
670 if ( $ew ) $ew = " style=\"width:100%\"";
674 $sub = wfMsgHtml( 'uploaderror' );
675 $wgOut->addHTML( "<h2>{$sub}</h2>\n" .
676 "<span class='error'>{$msg}</span>\n" );
678 $wgOut->addHTML( '<div id="uploadtext">' );
679 $wgOut->addWikiText( wfMsg( 'uploadtext' ) );
680 $wgOut->addHTML( '</div>' );
681 $sk = $wgUser->getSkin();
684 $sourcefilename = wfMsgHtml( 'sourcefilename' );
685 $destfilename = wfMsgHtml( 'destfilename' );
686 $summary = wfMsgWikiHtml( 'fileuploadsummary' );
688 $licenses = new Licenses();
689 $license = wfMsgHtml( 'license' );
690 $nolicense = wfMsgHtml( 'nolicense' );
691 $licenseshtml = $licenses->getHtml();
693 $ulb = wfMsgHtml( 'uploadbtn' );
696 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Upload' );
697 $action = $titleObj->escapeLocalURL();
699 $encDestFile = htmlspecialchars( $this->mDestFile
);
701 $watchChecked = $wgUser->getOption( 'watchdefault' )
702 ?
'checked="checked"'
705 if ( $wgAllowCopyUploads AND $wgRequest->getText('source') == 'web' AND $wgUser->isAllowed( 'upload_by_url' ) ) {
706 $sourcetype = 'text';
707 $source_comment = '<input type="hidden" name="wpSourceType" value="web"/>' . wfMsgHtml( 'upload_source_url' );
709 $sourcetype = 'file';
710 $source_comment = '';
714 <form id='upload' method='post' enctype='multipart/form-data' action=\"$action\">
717 <td align='right'><label for='wpUploadFile'>{$sourcefilename}:</label></td>
719 <input tabindex='1' type='{$sourcetype}' name='wpUploadFile' id='wpUploadFile' " . ($this->mDestFile?
"":"onchange='fillDestFilename()' ") . "size='40' />{$source_comment}
723 <td align='right'><label for='wpDestFile'>{$destfilename}:</label></td>
725 <input tabindex='2' type='text' name='wpDestFile' id='wpDestFile' size='40' value=\"$encDestFile\" />
729 <td align='right'><label for='wpUploadDescription'>{$summary}</label></td>
731 <textarea tabindex='3' name='wpUploadDescription' id='wpUploadDescription' rows='6' cols='{$cols}'{$ew}>" . htmlspecialchars( $this->mUploadDescription
) . "</textarea>
736 if ( $licenseshtml != '' ) {
739 <td align='right'><label for='wpLicense'>$license:</label></td>
741 <script type='text/javascript' src=\"$wgStylePath/common/upload.js\"></script>
742 <select name='wpLicense' id='wpLicense' tabindex='4'
743 onchange='licenseSelectorCheck()'>
744 <option value=''>$nolicense</option>
753 if ( $wgUseCopyrightUpload ) {
754 $filestatus = wfMsgHtml ( 'filestatus' );
755 $copystatus = htmlspecialchars( $this->mUploadCopyStatus
);
756 $filesource = wfMsgHtml ( 'filesource' );
757 $uploadsource = htmlspecialchars( $this->mUploadSource
);
760 <td align='right' nowrap='nowrap'><label for='wpUploadCopyStatus'>$filestatus:</label></td>
761 <td><input tabindex='5' type='text' name='wpUploadCopyStatus' id='wpUploadCopyStatus' value=\"$copystatus\" size='40' /></td>
764 <td align='right'><label for='wpUploadCopyStatus'>$filesource:</label></td>
765 <td><input tabindex='6' type='text' name='wpUploadSource' id='wpUploadCopyStatus' value=\"$uploadsource\" size='40' /></td>
775 <input tabindex='7' type='checkbox' name='wpWatchthis' id='wpWatchthis' $watchChecked value='true' />
776 <label for='wpWatchthis'>" . wfMsgHtml( 'watchthis' ) . "</label>
777 <input tabindex='8' type='checkbox' name='wpIgnoreWarning' id='wpIgnoreWarning' value='true' />
778 <label for='wpIgnoreWarning'>" . wfMsgHtml( 'ignorewarnings' ) . "</label>
786 <td align='left'><input tabindex='9' type='submit' name='wpUpload' value=\"{$ulb}\" /></td>
793 $wgOut->addWikiText( wfMsgForContent( 'edittools' ) );
802 /* -------------------------------------------------------------- */
805 * Split a file into a base name and all dot-delimited 'extensions'
806 * on the end. Some web server configurations will fall back to
807 * earlier pseudo-'extensions' to determine type and execute
808 * scripts, so the blacklist needs to check them all.
812 function splitExtensions( $filename ) {
813 $bits = explode( '.', $filename );
814 $basename = array_shift( $bits );
815 return array( $basename, $bits );
819 * Perform case-insensitive match against a list of file extensions.
820 * Returns true if the extension is in the list.
826 function checkFileExtension( $ext, $list ) {
827 return in_array( strtolower( $ext ), $list );
831 * Perform case-insensitive match against a list of file extensions.
832 * Returns true if any of the extensions are in the list.
838 function checkFileExtensionList( $ext, $list ) {
839 foreach( $ext as $e ) {
840 if( in_array( strtolower( $e ), $list ) ) {
848 * Verifies that it's ok to include the uploaded file
850 * @param string $tmpfile the full path of the temporary file to verify
851 * @param string $extension The filename extension that the file is to be served with
852 * @return mixed true of the file is verified, a WikiError object otherwise.
854 function verify( $tmpfile, $extension ) {
855 #magically determine mime type
856 $magic=& wfGetMimeMagic();
857 $mime= $magic->guessMimeType($tmpfile,false);
859 $fname= "SpecialUpload::verify";
861 #check mime type, if desired
862 global $wgVerifyMimeType;
863 if ($wgVerifyMimeType) {
865 #check mime type against file extension
866 if( !$this->verifyExtension( $mime, $extension ) ) {
867 return new WikiErrorMsg( 'uploadcorrupt' );
870 #check mime type blacklist
871 global $wgMimeTypeBlacklist;
872 if( isset($wgMimeTypeBlacklist) && !is_null($wgMimeTypeBlacklist)
873 && $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
874 return new WikiErrorMsg( 'badfiletype', htmlspecialchars( $mime ) );
878 #check for htmlish code and javascript
879 if( $this->detectScript ( $tmpfile, $mime, $extension ) ) {
880 return new WikiErrorMsg( 'uploadscripted' );
884 * Scan the uploaded file for viruses
886 $virus= $this->detectVirus($tmpfile);
888 return new WikiErrorMsg( 'uploadvirus', htmlspecialchars($virus) );
891 wfDebug( "$fname: all clear; passing.\n" );
896 * Checks if the mime type of the uploaded file matches the file extension.
898 * @param string $mime the mime type of the uploaded file
899 * @param string $extension The filename extension that the file is to be served with
902 function verifyExtension( $mime, $extension ) {
903 $fname = 'SpecialUpload::verifyExtension';
905 $magic =& wfGetMimeMagic();
907 if ( ! $mime ||
$mime == 'unknown' ||
$mime == 'unknown/unknown' )
908 if ( ! $magic->isRecognizableExtension( $extension ) ) {
909 wfDebug( "$fname: passing file with unknown detected mime type; unrecognized extension '$extension', can't verify\n" );
912 wfDebug( "$fname: rejecting file with unknown detected mime type; recognized extension '$extension', so probably invalid file\n" );
916 $match= $magic->isMatchingExtension($extension,$mime);
919 wfDebug( "$fname: no file extension known for mime type $mime, passing file\n" );
921 } elseif ($match===true) {
922 wfDebug( "$fname: mime type $mime matches extension $extension, passing file\n" );
924 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
928 wfDebug( "$fname: mime type $mime mismatches file extension $extension, rejecting file\n" );
933 /** Heuristig for detecting files that *could* contain JavaScript instructions or
934 * things that may look like HTML to a browser and are thus
935 * potentially harmful. The present implementation will produce false positives in some situations.
937 * @param string $file Pathname to the temporary upload file
938 * @param string $mime The mime type of the file
939 * @param string $extension The extension of the file
940 * @return bool true if the file contains something looking like embedded scripts
942 function detectScript($file, $mime, $extension) {
943 global $wgAllowTitlesInSVG;
945 #ugly hack: for text files, always look at the entire file.
946 #For binarie field, just check the first K.
948 if (strpos($mime,'text/')===0) $chunk = file_get_contents( $file );
950 $fp = fopen( $file, 'rb' );
951 $chunk = fread( $fp, 1024 );
955 $chunk= strtolower( $chunk );
957 if (!$chunk) return false;
959 #decode from UTF-16 if needed (could be used for obfuscation).
960 if (substr($chunk,0,2)=="\xfe\xff") $enc= "UTF-16BE";
961 elseif (substr($chunk,0,2)=="\xff\xfe") $enc= "UTF-16LE";
964 if ($enc) $chunk= iconv($enc,"ASCII//IGNORE",$chunk);
966 $chunk= trim($chunk);
968 #FIXME: convert from UTF-16 if necessarry!
970 wfDebug("SpecialUpload::detectScript: checking for embedded scripts and HTML stuff\n");
972 #check for HTML doctype
973 if (eregi("<!DOCTYPE *X?HTML",$chunk)) return true;
976 * Internet Explorer for Windows performs some really stupid file type
977 * autodetection which can cause it to interpret valid image files as HTML
978 * and potentially execute JavaScript, creating a cross-site scripting
981 * Apple's Safari browser also performs some unsafe file type autodetection
982 * which can cause legitimate files to be interpreted as HTML if the
983 * web server is not correctly configured to send the right content-type
984 * (or if you're really uploading plain text and octet streams!)
986 * Returns true if IE is likely to mistake the given file for HTML.
987 * Also returns true if Safari would mistake the given file for HTML
988 * when served with a generic content-type.
994 '<html', #also in safari
997 '<script', #also in safari
1000 if( ! $wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
1004 foreach( $tags as $tag ) {
1005 if( false !== strpos( $chunk, $tag ) ) {
1011 * look for javascript
1014 #resolve entity-refs to look at attributes. may be harsh on big files... cache result?
1015 $chunk = Sanitizer
::decodeCharReferences( $chunk );
1017 #look for script-types
1018 if (preg_match("!type\s*=\s*['\"]?\s*(\w*/)?(ecma|java)!sim",$chunk)) return true;
1020 #look for html-style script-urls
1021 if (preg_match("!(href|src|data)\s*=\s*['\"]?\s*(ecma|java)script:!sim",$chunk)) return true;
1023 #look for css-style script-urls
1024 if (preg_match("!url\s*\(\s*['\"]?\s*(ecma|java)script:!sim",$chunk)) return true;
1026 wfDebug("SpecialUpload::detectScript: no scripts found\n");
1030 /** Generic wrapper function for a virus scanner program.
1031 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
1032 * $wgAntivirusRequired may be used to deny upload if the scan fails.
1034 * @param string $file Pathname to the temporary upload file
1035 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
1036 * or a string containing feedback from the virus scanner if a virus was found.
1037 * If textual feedback is missing but a virus was found, this function returns true.
1039 function detectVirus($file) {
1040 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
1042 $fname= "SpecialUpload::detectVirus";
1044 if (!$wgAntivirus) { #disabled?
1045 wfDebug("$fname: virus scanner disabled\n");
1050 if (!$wgAntivirusSetup[$wgAntivirus]) {
1051 wfDebug("$fname: unknown virus scanner: $wgAntivirus\n");
1053 $wgOut->addHTML( "<div class='error'>Bad configuration: unknown virus scanner: <i>$wgAntivirus</i></div>\n" ); #LOCALIZE
1055 return "unknown antivirus: $wgAntivirus";
1058 #look up scanner configuration
1059 $virus_scanner= $wgAntivirusSetup[$wgAntivirus]["command"]; #command pattern
1060 $virus_scanner_codes= $wgAntivirusSetup[$wgAntivirus]["codemap"]; #exit-code map
1061 $msg_pattern= $wgAntivirusSetup[$wgAntivirus]["messagepattern"]; #message pattern
1063 $scanner= $virus_scanner; #copy, so we can resolve the pattern
1065 if (strpos($scanner,"%f")===false) $scanner.= " ".wfEscapeShellArg($file); #simple pattern: append file to scan
1066 else $scanner= str_replace("%f",wfEscapeShellArg($file),$scanner); #complex pattern: replace "%f" with file to scan
1068 wfDebug("$fname: running virus scan: $scanner \n");
1070 #execute virus scanner
1073 #NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
1074 # that does not seem to be worth the pain.
1075 # Ask me (Duesentrieb) about it if it's ever needed.
1076 if (wfIsWindows()) exec("$scanner",$output,$code);
1077 else exec("$scanner 2>&1",$output,$code);
1079 $exit_code= $code; #remeber for user feedback
1081 if ($virus_scanner_codes) { #map exit code to AV_xxx constants.
1082 if (isset($virus_scanner_codes[$code])) $code= $virus_scanner_codes[$code]; #explicite mapping
1083 else if (isset($virus_scanner_codes["*"])) $code= $virus_scanner_codes["*"]; #fallback mapping
1086 if ($code===AV_SCAN_FAILED
) { #scan failed (code was mapped to false by $virus_scanner_codes)
1087 wfDebug("$fname: failed to scan $file (code $exit_code).\n");
1089 if ($wgAntivirusRequired) return "scan failed (code $exit_code)";
1092 else if ($code===AV_SCAN_ABORTED
) { #scan failed because filetype is unknown (probably imune)
1093 wfDebug("$fname: unsupported file type $file (code $exit_code).\n");
1096 else if ($code===AV_NO_VIRUS
) {
1097 wfDebug("$fname: file passed virus scan.\n");
1098 return false; #no virus found
1101 $output= join("\n",$output);
1102 $output= trim($output);
1104 if (!$output) $output= true; #if ther's no output, return true
1105 else if ($msg_pattern) {
1107 if (preg_match($msg_pattern,$output,$groups)) {
1108 if ($groups[1]) $output= $groups[1];
1112 wfDebug("$fname: FOUND VIRUS! scanner feedback: $output");
1118 * Check if the temporary file is MacBinary-encoded, as some uploads
1119 * from Internet Explorer on Mac OS Classic and Mac OS X will be.
1120 * If so, the data fork will be extracted to a second temporary file,
1121 * which will then be checked for validity and either kept or discarded.
1125 function checkMacBinary() {
1126 $macbin = new MacBinary( $this->mUploadTempName
);
1127 if( $macbin->isValid() ) {
1128 $dataFile = tempnam( wfTempDir(), "WikiMacBinary" );
1129 $dataHandle = fopen( $dataFile, 'wb' );
1131 wfDebug( "SpecialUpload::checkMacBinary: Extracting MacBinary data fork to $dataFile\n" );
1132 $macbin->extractData( $dataHandle );
1134 $this->mUploadTempName
= $dataFile;
1135 $this->mUploadSize
= $macbin->dataForkLength();
1137 // We'll have to manually remove the new file if it's not kept.
1138 $this->mRemoveTempFile
= true;
1144 * If we've modified the upload file we need to manually remove it
1145 * on exit to clean up.
1148 function cleanupTempFile() {
1149 if( $this->mRemoveTempFile
&& file_exists( $this->mUploadTempName
) ) {
1150 wfDebug( "SpecialUpload::cleanupTempFile: Removing temporary file $this->mUploadTempName\n" );
1151 unlink( $this->mUploadTempName
);
1156 * Check if there's an overwrite conflict and, if so, if restrictions
1157 * forbid this user from performing the upload.
1159 * @return mixed true on success, WikiError on failure
1162 function checkOverwrite( $name ) {
1163 $img = Image
::newFromName( $name );
1164 if( is_null( $img ) ) {
1165 // Uh... this shouldn't happen ;)
1166 // But if it does, fall through to previous behavior
1171 if( $img->exists() ) {
1172 global $wgUser, $wgOut;
1173 if( $img->isLocal() ) {
1174 if( !$wgUser->isAllowed( 'reupload' ) ) {
1175 $error = 'fileexists-forbidden';
1178 if( !$wgUser->isAllowed( 'reupload' ) ||
1179 !$wgUser->isAllowed( 'reupload-shared' ) ) {
1180 $error = "fileexists-shared-forbidden";
1186 $errorText = wfMsg( $error, wfEscapeWikiText( $img->getName() ) );
1187 return new WikiError( $wgOut->parse( $errorText ) );
1190 // Rockin', go ahead and upload
1197 * Callback function for CURL-based web transfer
1198 * Apparently needs to be global
1201 function wfUploadCurlCallback ($ch, $data) {
1202 global $wgUploadTempFile, $wgMaxUploadSize, $wgUploadTempFileSize;
1203 $length = strlen($data);
1204 $wgUploadTempFileSize +
= $length;
1205 if( $wgUploadTempFileSize > $wgMaxUploadSize ) return 0;
1206 fwrite( $wgUploadTempFile , $data );