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;
112 $url = $request->getText( 'wpUploadFile' );
113 $local_file = tempnam( $wgTmpDirectory, 'WEBUPLOAD' );
115 # Maybe check for filesize($url) first?
116 $error = !@copy
( $url, $local_file );
118 $this->mUploadTempName
= $local_file;
119 $this->mUploadSize
= filesize( $local_file );
120 $this->mOname
= array_pop( explode( '/', $url ) );
121 $this->mUploadError
= $error;
122 $this->mSessionKey
= false;
123 $this->mStashed
= false;
124 $this->mRemoveTempFile
= false; // PHP will *not* handle this
132 global $wgUser, $wgOut;
133 global $wgEnableUploads, $wgUploadDirectory;
135 # Check uploading enabled
136 if( !$wgEnableUploads ) {
137 $wgOut->showErrorPage( 'uploaddisabled', 'uploaddisabledtext' );
142 if( $wgUser->isLoggedIn() ) {
143 if( !$wgUser->isAllowed( 'upload' ) ) {
144 $wgOut->permissionRequired( 'upload' );
148 $wgOut->showErrorPage( 'uploadnologin', 'uploadnologintext' );
153 if( $wgUser->isBlocked() ) {
154 $wgOut->blockedPage();
159 $wgOut->readOnlyPage();
163 /** Check if the image directory is writeable, this is a common mistake */
164 if( !is_writeable( $wgUploadDirectory ) ) {
165 $wgOut->addWikiText( wfMsg( 'upload_directory_read_only', $wgUploadDirectory ) );
169 if( $this->mReUpload
) {
170 if( !$this->unsaveUploadedFile() ) {
173 $this->mainUploadForm();
174 } else if( 'submit' == $this->mAction ||
$this->mUpload
) {
175 $this->processUpload();
177 $this->mainUploadForm();
180 $this->cleanupTempFile();
183 /* -------------------------------------------------------------- */
186 * Really do the upload
187 * Checks are made in SpecialUpload::execute()
190 function processUpload() {
191 global $wgUser, $wgOut;
193 /* Check for PHP error if any, requires php 4.2 or newer */
194 if( $this->mUploadError
== 1/*UPLOAD_ERR_INI_SIZE*/ ) {
195 $this->mainUploadForm( wfMsgHtml( 'largefileserver' ) );
200 * If there was no filename or a zero size given, give up quick.
202 if( trim( $this->mOname
) == '' ||
empty( $this->mUploadSize
) ) {
203 $this->mainUploadForm( wfMsgHtml( 'emptyfile' ) );
207 # Chop off any directories in the given filename
208 if( $this->mDestFile
) {
209 $basename = wfBaseName( $this->mDestFile
);
211 $basename = wfBaseName( $this->mOname
);
215 * We'll want to blacklist against *any* 'extension', and use
216 * only the final one for the whitelist.
218 list( $partname, $ext ) = $this->splitExtensions( $basename );
220 if( count( $ext ) ) {
221 $finalExt = $ext[count( $ext ) - 1];
225 $fullExt = implode( '.', $ext );
227 # If there was more than one "extension", reassemble the base
228 # filename to prevent bogus complaints about length
229 if( count( $ext ) > 1 ) {
230 for( $i = 0; $i < count( $ext ) - 1; $i++
)
231 $partname .= '.' . $ext[$i];
234 if( strlen( $partname ) < 3 ) {
235 $this->mainUploadForm( wfMsgHtml( 'minlength' ) );
240 * Filter out illegal characters, and try to make a legible name
241 * out of it. We'll strip some silently that Title would die on.
243 $filtered = preg_replace ( "/[^".Title
::legalChars()."]|:/", '-', $basename );
244 $nt = Title
::newFromText( $filtered );
245 if( is_null( $nt ) ) {
246 $this->uploadError( wfMsgWikiHtml( 'illegalfilename', htmlspecialchars( $filtered ) ) );
249 $nt =& Title
::makeTitle( NS_IMAGE
, $nt->getDBkey() );
250 $this->mUploadSaveName
= $nt->getDBkey();
253 * If the image is protected, non-sysop users won't be able
254 * to modify it by uploading a new revision.
256 if( !$nt->userCanEdit() ) {
257 return $this->uploadError( wfMsgWikiHtml( 'protectedpage' ) );
261 * In some cases we may forbid overwriting of existing files.
263 $overwrite = $this->checkOverwrite( $this->mUploadSaveName
);
264 if( WikiError
::isError( $overwrite ) ) {
265 return $this->uploadError( $overwrite->toString() );
268 /* Don't allow users to override the blacklist (check file extension) */
269 global $wgStrictFileExtensions;
270 global $wgFileExtensions, $wgFileBlacklist;
271 if( $this->checkFileExtensionList( $ext, $wgFileBlacklist ) ||
272 ($wgStrictFileExtensions &&
273 !$this->checkFileExtension( $finalExt, $wgFileExtensions ) ) ) {
274 return $this->uploadError( wfMsgHtml( 'badfiletype', htmlspecialchars( $fullExt ) ) );
278 * Look at the contents of the file; if we can recognize the
279 * type but it's corrupt or data of the wrong type, we should
280 * probably not accept it.
282 if( !$this->mStashed
) {
283 $this->checkMacBinary();
284 $veri = $this->verify( $this->mUploadTempName
, $finalExt );
286 if( $veri !== true ) { //it's a wiki error...
287 return $this->uploadError( $veri->toString() );
292 * Provide an opportunity for extensions to add futher checks
295 if( !wfRunHooks( 'UploadVerification',
296 array( $this->mUploadSaveName
, $this->mUploadTempName
, &$error ) ) ) {
297 return $this->uploadError( $error );
301 * Check for non-fatal conditions
303 if ( ! $this->mIgnoreWarning
) {
306 global $wgCapitalLinks;
307 if( $wgCapitalLinks ) {
308 $filtered = ucfirst( $filtered );
310 if( $this->mUploadSaveName
!= $filtered ) {
311 $warning .= '<li>'.wfMsgHtml( 'badfilename', htmlspecialchars( $this->mUploadSaveName
) ).'</li>';
314 global $wgCheckFileExtensions;
315 if ( $wgCheckFileExtensions ) {
316 if ( ! $this->checkFileExtension( $finalExt, $wgFileExtensions ) ) {
317 $warning .= '<li>'.wfMsgHtml( 'badfiletype', htmlspecialchars( $fullExt ) ).'</li>';
321 global $wgUploadSizeWarning;
322 if ( $wgUploadSizeWarning && ( $this->mUploadSize
> $wgUploadSizeWarning ) ) {
323 # TODO: Format $wgUploadSizeWarning to something that looks better than the raw byte
324 # value, perhaps add GB,MB and KB suffixes?
325 $warning .= '<li>'.wfMsgHtml( 'largefile', $wgUploadSizeWarning, $this->mUploadSize
).'</li>';
327 if ( $this->mUploadSize
== 0 ) {
328 $warning .= '<li>'.wfMsgHtml( 'emptyfile' ).'</li>';
331 if( $nt->getArticleID() ) {
333 $sk = $wgUser->getSkin();
334 $dlink = $sk->makeKnownLinkObj( $nt );
335 $warning .= '<li>'.wfMsgHtml( 'fileexists', $dlink ).'</li>';
337 # If the file existed before and was deleted, warn the user of this
338 # Don't bother doing so if the image exists now, however
339 $image = new Image( $nt );
340 if( $image->wasDeleted() ) {
341 $skin = $wgUser->getSkin();
342 $ltitle = Title
::makeTitle( NS_SPECIAL
, 'Log' );
343 $llink = $skin->makeKnownLinkObj( $ltitle, wfMsgHtml( 'deletionlog' ), 'type=delete&page=' . $nt->getPrefixedUrl() );
344 $warning .= wfOpenElement( 'li' ) . wfMsgWikiHtml( 'filewasdeleted', $llink ) . wfCloseElement( 'li' );
348 if( $warning != '' ) {
350 * Stash the file in a temporary location; the user can choose
351 * to let it through and we'll complete the upload then.
353 return $this->uploadWarning( $warning );
358 * Try actually saving the thing...
359 * It will show an error form on failure.
361 $hasBeenMunged = !empty( $this->mSessionKey
) ||
$this->mRemoveTempFile
;
362 if( $this->saveUploadedFile( $this->mUploadSaveName
,
363 $this->mUploadTempName
,
366 * Update the upload log and create the description page
367 * if it's a new file.
369 $img = Image
::newFromName( $this->mUploadSaveName
);
370 $success = $img->recordUpload( $this->mUploadOldVersion
,
371 $this->mUploadDescription
,
373 $this->mUploadCopyStatus
,
374 $this->mUploadSource
,
378 $this->showSuccess();
379 wfRunHooks( 'UploadComplete', array( &$img ) );
381 // Image::recordUpload() fails if the image went missing, which is
382 // unlikely, hence the lack of a specialised message
383 $wgOut->showFileNotFoundError( $this->mUploadSaveName
);
389 * Move the uploaded file from its temporary location to the final
390 * destination. If a previous version of the file exists, move
391 * it into the archive subdirectory.
393 * @todo If the later save fails, we may have disappeared the original file.
395 * @param string $saveName
396 * @param string $tempName full path to the temporary file
397 * @param bool $useRename if true, doesn't check that the source file
398 * is a PHP-managed upload temporary
400 function saveUploadedFile( $saveName, $tempName, $useRename = false ) {
401 global $wgOut, $wgAllowCopyUploads;
403 if ( !$useRename AND $wgAllowCopyUploads AND $this->mSourceType
== 'web' ) $useRename = true;
405 $fname= "SpecialUpload::saveUploadedFile";
407 $dest = wfImageDir( $saveName );
408 $archive = wfImageArchiveDir( $saveName );
409 if ( !is_dir( $dest ) ) wfMkdirParents( $dest );
410 if ( !is_dir( $archive ) ) wfMkdirParents( $archive );
412 $this->mSavedFile
= "{$dest}/{$saveName}";
414 if( is_file( $this->mSavedFile
) ) {
415 $this->mUploadOldVersion
= gmdate( 'YmdHis' ) . "!{$saveName}";
416 wfSuppressWarnings();
417 $success = rename( $this->mSavedFile
, "${archive}/{$this->mUploadOldVersion}" );
421 $wgOut->showFileRenameError( $this->mSavedFile
,
422 "${archive}/{$this->mUploadOldVersion}" );
425 else wfDebug("$fname: moved file ".$this->mSavedFile
." to ${archive}/{$this->mUploadOldVersion}\n");
428 $this->mUploadOldVersion
= '';
431 wfSuppressWarnings();
432 $success = $useRename
433 ?
rename( $tempName, $this->mSavedFile
)
434 : move_uploaded_file( $tempName, $this->mSavedFile
);
438 $wgOut->showFileCopyError( $tempName, $this->mSavedFile
);
441 wfDebug("$fname: wrote tempfile $tempName to ".$this->mSavedFile
."\n");
444 chmod( $this->mSavedFile
, 0644 );
449 * Stash a file in a temporary directory for later processing
450 * after the user has confirmed it.
452 * If the user doesn't explicitly cancel or accept, these files
453 * can accumulate in the temp directory.
455 * @param string $saveName - the destination filename
456 * @param string $tempName - the source temporary file to save
457 * @return string - full path the stashed file, or false on failure
460 function saveTempUploadedFile( $saveName, $tempName ) {
462 $archive = wfImageArchiveDir( $saveName, 'temp' );
463 if ( !is_dir ( $archive ) ) wfMkdirParents( $archive );
464 $stash = $archive . '/' . gmdate( "YmdHis" ) . '!' . $saveName;
466 $success = $this->mRemoveTempFile
467 ?
rename( $tempName, $stash )
468 : move_uploaded_file( $tempName, $stash );
470 $wgOut->showFileCopyError( $tempName, $stash );
478 * Stash a file in a temporary directory for later processing,
479 * and save the necessary descriptive info into the session.
480 * Returns a key value which will be passed through a form
481 * to pick up the path info on a later invocation.
486 function stashSession() {
487 $stash = $this->saveTempUploadedFile(
488 $this->mUploadSaveName
, $this->mUploadTempName
);
491 # Couldn't save the file.
495 $key = mt_rand( 0, 0x7fffffff );
496 $_SESSION['wsUploadData'][$key] = array(
497 'mUploadTempName' => $stash,
498 'mUploadSize' => $this->mUploadSize
,
499 'mOname' => $this->mOname
);
504 * Remove a temporarily kept file stashed by saveTempUploadedFile().
508 function unsaveUploadedFile() {
510 wfSuppressWarnings();
511 $success = unlink( $this->mUploadTempName
);
514 $wgOut->showFileDeleteError( $this->mUploadTempName
);
521 /* -------------------------------------------------------------- */
524 * Show some text and linkage on successful upload.
527 function showSuccess() {
528 global $wgUser, $wgOut, $wgContLang;
530 $sk = $wgUser->getSkin();
531 $ilink = $sk->makeMediaLink( $this->mUploadSaveName
, Image
::imageUrl( $this->mUploadSaveName
) );
532 $dname = $wgContLang->getNsText( NS_IMAGE
) . ':'.$this->mUploadSaveName
;
533 $dlink = $sk->makeKnownLink( $dname, $dname );
535 $wgOut->addHTML( '<h2>' . wfMsgHtml( 'successfulupload' ) . "</h2>\n" );
536 $text = wfMsgWikiHtml( 'fileuploaded', $ilink, $dlink );
537 $wgOut->addHTML( $text );
538 $wgOut->returnToMain( false );
542 * @param string $error as HTML
545 function uploadError( $error ) {
547 $wgOut->addHTML( "<h2>" . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
548 $wgOut->addHTML( "<span class='error'>{$error}</span>\n" );
552 * There's something wrong with this file, not enough to reject it
553 * totally but we require manual intervention to save it for real.
554 * Stash it away, then present a form asking to confirm or cancel.
556 * @param string $warning as HTML
559 function uploadWarning( $warning ) {
561 global $wgUseCopyrightUpload;
563 $this->mSessionKey
= $this->stashSession();
564 if( !$this->mSessionKey
) {
565 # Couldn't save file; an error has been displayed so let's go.
569 $wgOut->addHTML( "<h2>" . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
570 $wgOut->addHTML( "<ul class='warning'>{$warning}</ul><br />\n" );
572 $save = wfMsgHtml( 'savefile' );
573 $reupload = wfMsgHtml( 'reupload' );
574 $iw = wfMsgWikiHtml( 'ignorewarning' );
575 $reup = wfMsgWikiHtml( 'reuploaddesc' );
576 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Upload' );
577 $action = $titleObj->escapeLocalURL( 'action=submit' );
579 if ( $wgUseCopyrightUpload )
582 <input type='hidden' name='wpUploadCopyStatus' value=\"" . htmlspecialchars( $this->mUploadCopyStatus
) . "\" />
583 <input type='hidden' name='wpUploadSource' value=\"" . htmlspecialchars( $this->mUploadSource
) . "\" />
590 <form id='uploadwarning' method='post' enctype='multipart/form-data' action='$action'>
591 <input type='hidden' name='wpIgnoreWarning' value='1' />
592 <input type='hidden' name='wpSessionKey' value=\"" . htmlspecialchars( $this->mSessionKey
) . "\" />
593 <input type='hidden' name='wpUploadDescription' value=\"" . htmlspecialchars( $this->mUploadDescription
) . "\" />
594 <input type='hidden' name='wpLicense' value=\"" . htmlspecialchars( $this->mLicense
) . "\" />
595 <input type='hidden' name='wpDestFile' value=\"" . htmlspecialchars( $this->mDestFile
) . "\" />
596 <input type='hidden' name='wpWatchthis' value=\"" . htmlspecialchars( intval( $this->mWatchthis
) ) . "\" />
602 <input tabindex='2' type='submit' name='wpUpload' value=\"$save\" />
604 <td align='left'>$iw</td>
608 <input tabindex='2' type='submit' name='wpReUpload' value=\"{$reupload}\" />
610 <td align='left'>$reup</td>
613 </table></form>\n" );
617 * Displays the main upload form, optionally with a highlighted
618 * error message up at the top.
620 * @param string $msg as HTML
623 function mainUploadForm( $msg='' ) {
624 global $wgOut, $wgUser;
625 global $wgUseCopyrightUpload;
626 global $wgRequest, $wgAllowCopyUploads;
628 $cols = intval($wgUser->getOption( 'cols' ));
629 $ew = $wgUser->getOption( 'editwidth' );
630 if ( $ew ) $ew = " style=\"width:100%\"";
634 $sub = wfMsgHtml( 'uploaderror' );
635 $wgOut->addHTML( "<h2>{$sub}</h2>\n" .
636 "<span class='error'>{$msg}</span>\n" );
638 $wgOut->addHTML( '<div id="uploadtext">' );
639 $wgOut->addWikiText( wfMsg( 'uploadtext' ) );
640 $wgOut->addHTML( '</div>' );
641 $sk = $wgUser->getSkin();
644 $sourcefilename = wfMsgHtml( 'sourcefilename' );
645 $destfilename = wfMsgHtml( 'destfilename' );
646 $summary = wfMsgWikiHtml( 'fileuploadsummary' );
648 $licenses = new Licenses();
649 $license = wfMsgHtml( 'license' );
650 $nolicense = wfMsgHtml( 'nolicense' );
651 $licenseshtml = $licenses->getHtml();
653 $ulb = wfMsgHtml( 'uploadbtn' );
656 $titleObj = Title
::makeTitle( NS_SPECIAL
, 'Upload' );
657 $action = $titleObj->escapeLocalURL();
659 $encDestFile = htmlspecialchars( $this->mDestFile
);
661 $watchChecked = $wgUser->getOption( 'watchdefault' )
662 ?
'checked="checked"'
665 if ( $wgAllowCopyUploads AND $wgRequest->getText('source') == 'web' ) {
666 $sourcetype = 'text';
667 $source_comment = '<input type="hidden" name="wpSourceType" value="web"/>' . wfMsgHtml( 'upload_source_url' );
669 $sourcetype = 'file';
670 $source_comment = '';
674 <form id='upload' method='post' enctype='multipart/form-data' action=\"$action\">
677 <td align='right'><label for='wpUploadFile'>{$sourcefilename}:</label></td>
679 <input tabindex='1' type='{$sourcetype}' name='wpUploadFile' id='wpUploadFile' " . ($this->mDestFile?
"":"onchange='fillDestFilename()' ") . "size='40' />{$source_comment}
683 <td align='right'><label for='wpDestFile'>{$destfilename}:</label></td>
685 <input tabindex='2' type='text' name='wpDestFile' id='wpDestFile' size='40' value=\"$encDestFile\" />
689 <td align='right'><label for='wpUploadDescription'>{$summary}</label></td>
691 <textarea tabindex='3' name='wpUploadDescription' id='wpUploadDescription' rows='6' cols='{$cols}'{$ew}>" . htmlspecialchars( $this->mUploadDescription
) . "</textarea>
696 if ( $licenseshtml != '' ) {
699 <td align='right'><label for='wpLicense'>$license:</label></td>
701 <script type='text/javascript' src=\"$wgStylePath/common/upload.js\"></script>
702 <select name='wpLicense' id='wpLicense' tabindex='4'
703 onchange='licenseSelectorCheck()'>
704 <option value=''>$nolicense</option>
713 if ( $wgUseCopyrightUpload ) {
714 $filestatus = wfMsgHtml ( 'filestatus' );
715 $copystatus = htmlspecialchars( $this->mUploadCopyStatus
);
716 $filesource = wfMsgHtml ( 'filesource' );
717 $uploadsource = htmlspecialchars( $this->mUploadSource
);
720 <td align='right' nowrap='nowrap'><label for='wpUploadCopyStatus'>$filestatus:</label></td>
721 <td><input tabindex='5' type='text' name='wpUploadCopyStatus' id='wpUploadCopyStatus' value=\"$copystatus\" size='40' /></td>
724 <td align='right'><label for='wpUploadCopyStatus'>$filesource:</label></td>
725 <td><input tabindex='6' type='text' name='wpUploadSource' id='wpUploadCopyStatus' value=\"$uploadsource\" size='40' /></td>
735 <input tabindex='7' type='checkbox' name='wpWatchthis' id='wpWatchthis' $watchChecked value='true' />
736 <label for='wpWatchthis'>" . wfMsgHtml( 'watchthis' ) . "</label>
737 <input tabindex='8' type='checkbox' name='wpIgnoreWarning' id='wpIgnoreWarning' value='true' />
738 <label for='wpIgnoreWarning'>" . wfMsgHtml( 'ignorewarnings' ) . "</label>
746 <td align='left'><input tabindex='9' type='submit' name='wpUpload' value=\"{$ulb}\" /></td>
753 $wgOut->addWikiText( wfMsgForContent( 'edittools' ) );
762 /* -------------------------------------------------------------- */
765 * Split a file into a base name and all dot-delimited 'extensions'
766 * on the end. Some web server configurations will fall back to
767 * earlier pseudo-'extensions' to determine type and execute
768 * scripts, so the blacklist needs to check them all.
772 function splitExtensions( $filename ) {
773 $bits = explode( '.', $filename );
774 $basename = array_shift( $bits );
775 return array( $basename, $bits );
779 * Perform case-insensitive match against a list of file extensions.
780 * Returns true if the extension is in the list.
786 function checkFileExtension( $ext, $list ) {
787 return in_array( strtolower( $ext ), $list );
791 * Perform case-insensitive match against a list of file extensions.
792 * Returns true if any of the extensions are in the list.
798 function checkFileExtensionList( $ext, $list ) {
799 foreach( $ext as $e ) {
800 if( in_array( strtolower( $e ), $list ) ) {
808 * Verifies that it's ok to include the uploaded file
810 * @param string $tmpfile the full path of the temporary file to verify
811 * @param string $extension The filename extension that the file is to be served with
812 * @return mixed true of the file is verified, a WikiError object otherwise.
814 function verify( $tmpfile, $extension ) {
815 #magically determine mime type
816 $magic=& wfGetMimeMagic();
817 $mime= $magic->guessMimeType($tmpfile,false);
819 $fname= "SpecialUpload::verify";
821 #check mime type, if desired
822 global $wgVerifyMimeType;
823 if ($wgVerifyMimeType) {
825 #check mime type against file extension
826 if( !$this->verifyExtension( $mime, $extension ) ) {
827 return new WikiErrorMsg( 'uploadcorrupt' );
830 #check mime type blacklist
831 global $wgMimeTypeBlacklist;
832 if( isset($wgMimeTypeBlacklist) && !is_null($wgMimeTypeBlacklist)
833 && $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
834 return new WikiErrorMsg( 'badfiletype', htmlspecialchars( $mime ) );
838 #check for htmlish code and javascript
839 if( $this->detectScript ( $tmpfile, $mime, $extension ) ) {
840 return new WikiErrorMsg( 'uploadscripted' );
844 * Scan the uploaded file for viruses
846 $virus= $this->detectVirus($tmpfile);
848 return new WikiErrorMsg( 'uploadvirus', htmlspecialchars($virus) );
851 wfDebug( "$fname: all clear; passing.\n" );
856 * Checks if the mime type of the uploaded file matches the file extension.
858 * @param string $mime the mime type of the uploaded file
859 * @param string $extension The filename extension that the file is to be served with
862 function verifyExtension( $mime, $extension ) {
863 $fname = 'SpecialUpload::verifyExtension';
865 $magic =& wfGetMimeMagic();
867 if ( ! $mime ||
$mime == 'unknown' ||
$mime == 'unknown/unknown' )
868 if ( ! $magic->isRecognizableExtension( $extension ) ) {
869 wfDebug( "$fname: passing file with unknown detected mime type; unrecognized extension '$extension', can't verify\n" );
872 wfDebug( "$fname: rejecting file with unknown detected mime type; recognized extension '$extension', so probably invalid file\n" );
876 $match= $magic->isMatchingExtension($extension,$mime);
879 wfDebug( "$fname: no file extension known for mime type $mime, passing file\n" );
881 } elseif ($match===true) {
882 wfDebug( "$fname: mime type $mime matches extension $extension, passing file\n" );
884 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
888 wfDebug( "$fname: mime type $mime mismatches file extension $extension, rejecting file\n" );
893 /** Heuristig for detecting files that *could* contain JavaScript instructions or
894 * things that may look like HTML to a browser and are thus
895 * potentially harmful. The present implementation will produce false positives in some situations.
897 * @param string $file Pathname to the temporary upload file
898 * @param string $mime The mime type of the file
899 * @param string $extension The extension of the file
900 * @return bool true if the file contains something looking like embedded scripts
902 function detectScript($file, $mime, $extension) {
903 global $wgAllowTitlesInSVG;
905 #ugly hack: for text files, always look at the entire file.
906 #For binarie field, just check the first K.
908 if (strpos($mime,'text/')===0) $chunk = file_get_contents( $file );
910 $fp = fopen( $file, 'rb' );
911 $chunk = fread( $fp, 1024 );
915 $chunk= strtolower( $chunk );
917 if (!$chunk) return false;
919 #decode from UTF-16 if needed (could be used for obfuscation).
920 if (substr($chunk,0,2)=="\xfe\xff") $enc= "UTF-16BE";
921 elseif (substr($chunk,0,2)=="\xff\xfe") $enc= "UTF-16LE";
924 if ($enc) $chunk= iconv($enc,"ASCII//IGNORE",$chunk);
926 $chunk= trim($chunk);
928 #FIXME: convert from UTF-16 if necessarry!
930 wfDebug("SpecialUpload::detectScript: checking for embedded scripts and HTML stuff\n");
932 #check for HTML doctype
933 if (eregi("<!DOCTYPE *X?HTML",$chunk)) return true;
936 * Internet Explorer for Windows performs some really stupid file type
937 * autodetection which can cause it to interpret valid image files as HTML
938 * and potentially execute JavaScript, creating a cross-site scripting
941 * Apple's Safari browser also performs some unsafe file type autodetection
942 * which can cause legitimate files to be interpreted as HTML if the
943 * web server is not correctly configured to send the right content-type
944 * (or if you're really uploading plain text and octet streams!)
946 * Returns true if IE is likely to mistake the given file for HTML.
947 * Also returns true if Safari would mistake the given file for HTML
948 * when served with a generic content-type.
954 '<html', #also in safari
957 '<script', #also in safari
960 if( ! $wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
964 foreach( $tags as $tag ) {
965 if( false !== strpos( $chunk, $tag ) ) {
971 * look for javascript
974 #resolve entity-refs to look at attributes. may be harsh on big files... cache result?
975 $chunk = Sanitizer
::decodeCharReferences( $chunk );
977 #look for script-types
978 if (preg_match("!type\s*=\s*['\"]?\s*(\w*/)?(ecma|java)!sim",$chunk)) return true;
980 #look for html-style script-urls
981 if (preg_match("!(href|src|data)\s*=\s*['\"]?\s*(ecma|java)script:!sim",$chunk)) return true;
983 #look for css-style script-urls
984 if (preg_match("!url\s*\(\s*['\"]?\s*(ecma|java)script:!sim",$chunk)) return true;
986 wfDebug("SpecialUpload::detectScript: no scripts found\n");
990 /** Generic wrapper function for a virus scanner program.
991 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
992 * $wgAntivirusRequired may be used to deny upload if the scan fails.
994 * @param string $file Pathname to the temporary upload file
995 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
996 * or a string containing feedback from the virus scanner if a virus was found.
997 * If textual feedback is missing but a virus was found, this function returns true.
999 function detectVirus($file) {
1000 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
1002 $fname= "SpecialUpload::detectVirus";
1004 if (!$wgAntivirus) { #disabled?
1005 wfDebug("$fname: virus scanner disabled\n");
1010 if (!$wgAntivirusSetup[$wgAntivirus]) {
1011 wfDebug("$fname: unknown virus scanner: $wgAntivirus\n");
1013 $wgOut->addHTML( "<div class='error'>Bad configuration: unknown virus scanner: <i>$wgAntivirus</i></div>\n" ); #LOCALIZE
1015 return "unknown antivirus: $wgAntivirus";
1018 #look up scanner configuration
1019 $virus_scanner= $wgAntivirusSetup[$wgAntivirus]["command"]; #command pattern
1020 $virus_scanner_codes= $wgAntivirusSetup[$wgAntivirus]["codemap"]; #exit-code map
1021 $msg_pattern= $wgAntivirusSetup[$wgAntivirus]["messagepattern"]; #message pattern
1023 $scanner= $virus_scanner; #copy, so we can resolve the pattern
1025 if (strpos($scanner,"%f")===false) $scanner.= " ".wfEscapeShellArg($file); #simple pattern: append file to scan
1026 else $scanner= str_replace("%f",wfEscapeShellArg($file),$scanner); #complex pattern: replace "%f" with file to scan
1028 wfDebug("$fname: running virus scan: $scanner \n");
1030 #execute virus scanner
1033 #NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
1034 # that does not seem to be worth the pain.
1035 # Ask me (Duesentrieb) about it if it's ever needed.
1036 if (wfIsWindows()) exec("$scanner",$output,$code);
1037 else exec("$scanner 2>&1",$output,$code);
1039 $exit_code= $code; #remeber for user feedback
1041 if ($virus_scanner_codes) { #map exit code to AV_xxx constants.
1042 if (isset($virus_scanner_codes[$code])) $code= $virus_scanner_codes[$code]; #explicite mapping
1043 else if (isset($virus_scanner_codes["*"])) $code= $virus_scanner_codes["*"]; #fallback mapping
1046 if ($code===AV_SCAN_FAILED
) { #scan failed (code was mapped to false by $virus_scanner_codes)
1047 wfDebug("$fname: failed to scan $file (code $exit_code).\n");
1049 if ($wgAntivirusRequired) return "scan failed (code $exit_code)";
1052 else if ($code===AV_SCAN_ABORTED
) { #scan failed because filetype is unknown (probably imune)
1053 wfDebug("$fname: unsupported file type $file (code $exit_code).\n");
1056 else if ($code===AV_NO_VIRUS
) {
1057 wfDebug("$fname: file passed virus scan.\n");
1058 return false; #no virus found
1061 $output= join("\n",$output);
1062 $output= trim($output);
1064 if (!$output) $output= true; #if ther's no output, return true
1065 else if ($msg_pattern) {
1067 if (preg_match($msg_pattern,$output,$groups)) {
1068 if ($groups[1]) $output= $groups[1];
1072 wfDebug("$fname: FOUND VIRUS! scanner feedback: $output");
1078 * Check if the temporary file is MacBinary-encoded, as some uploads
1079 * from Internet Explorer on Mac OS Classic and Mac OS X will be.
1080 * If so, the data fork will be extracted to a second temporary file,
1081 * which will then be checked for validity and either kept or discarded.
1085 function checkMacBinary() {
1086 $macbin = new MacBinary( $this->mUploadTempName
);
1087 if( $macbin->isValid() ) {
1088 $dataFile = tempnam( wfTempDir(), "WikiMacBinary" );
1089 $dataHandle = fopen( $dataFile, 'wb' );
1091 wfDebug( "SpecialUpload::checkMacBinary: Extracting MacBinary data fork to $dataFile\n" );
1092 $macbin->extractData( $dataHandle );
1094 $this->mUploadTempName
= $dataFile;
1095 $this->mUploadSize
= $macbin->dataForkLength();
1097 // We'll have to manually remove the new file if it's not kept.
1098 $this->mRemoveTempFile
= true;
1104 * If we've modified the upload file we need to manually remove it
1105 * on exit to clean up.
1108 function cleanupTempFile() {
1109 if( $this->mRemoveTempFile
&& file_exists( $this->mUploadTempName
) ) {
1110 wfDebug( "SpecialUpload::cleanupTempFile: Removing temporary file $this->mUploadTempName\n" );
1111 unlink( $this->mUploadTempName
);
1116 * Check if there's an overwrite conflict and, if so, if restrictions
1117 * forbid this user from performing the upload.
1119 * @return mixed true on success, WikiError on failure
1122 function checkOverwrite( $name ) {
1123 $img = Image
::newFromName( $name );
1124 if( is_null( $img ) ) {
1125 // Uh... this shouldn't happen ;)
1126 // But if it does, fall through to previous behavior
1131 if( $img->exists() ) {
1132 global $wgUser, $wgOut;
1133 if( $img->isLocal() ) {
1134 if( !$wgUser->isAllowed( 'reupload' ) ) {
1135 $error = 'fileexists-forbidden';
1138 if( !$wgUser->isAllowed( 'reupload' ) ||
1139 !$wgUser->isAllowed( 'reupload-shared' ) ) {
1140 $error = "fileexists-shared-forbidden";
1146 $errorText = wfMsg( $error, wfEscapeWikiText( $img->getName() ) );
1147 return new WikiError( $wgOut->parse( $errorText ) );
1150 // Rockin', go ahead and upload