* Don't show useless empty preview on new page creation
[mediawiki.git] / includes / SpecialUpload.php
blob9f8b63f120ba2177a5e30bd68b8ffbf07575e68d
1 <?php
2 /**
4 * @package MediaWiki
5 * @subpackage SpecialPage
6 */
8 /**
11 require_once 'Image.php';
12 require_once 'MacBinary.php';
13 require_once 'Licenses.php';
14 /**
15 * Entry point
17 function wfSpecialUpload() {
18 global $wgRequest;
19 $form = new UploadForm( $wgRequest );
20 $form->execute();
23 /**
25 * @package MediaWiki
26 * @subpackage SpecialPage
28 class UploadForm {
29 /**#@+
30 * @access private
32 var $mUploadFile, $mUploadDescription, $mLicense ,$mIgnoreWarning, $mUploadError;
33 var $mUploadSaveName, $mUploadTempName, $mUploadSize, $mUploadOldVersion;
34 var $mUploadCopyStatus, $mUploadSource, $mReUpload, $mAction, $mUpload;
35 var $mOname, $mSessionKey, $mStashed, $mDestFile, $mRemoveTempFile;
36 /**#@-*/
38 /**
39 * Constructor : initialise object
40 * Get data POSTed through the form and assign them to the object
41 * @param $request Data posted.
43 function UploadForm( &$request ) {
44 $this->mDestFile = $request->getText( 'wpDestFile' );
46 if( !$request->wasPosted() ) {
47 # GET requests just give the main form; no data except wpDestfile.
48 return;
51 $this->mIgnoreWarning = $request->getCheck( 'wpIgnoreWarning');
52 $this->mReUpload = $request->getCheck( 'wpReUpload' );
53 $this->mUpload = $request->getCheck( 'wpUpload' );
55 $this->mUploadDescription = $request->getText( 'wpUploadDescription' );
56 $this->mLicense = $request->getText( 'wpLicense' );
57 $this->mUploadCopyStatus = $request->getText( 'wpUploadCopyStatus' );
58 $this->mUploadSource = $request->getText( 'wpUploadSource' );
59 $this->mWatchthis = $request->getBool( 'wpWatchthis' );
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] ) ) {
67 /**
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;
80 } else {
81 /**
82 *Check for a newly uploaded file.
84 $this->mUploadTempName = $request->getFileTempName( 'wpUploadFile' );
85 $this->mUploadSize = $request->getFileSize( 'wpUploadFile' );
86 $this->mOname = $request->getFileName( 'wpUploadFile' );
87 $this->mUploadError = $request->getUploadError( 'wpUploadFile' );
88 $this->mSessionKey = false;
89 $this->mStashed = false;
90 $this->mRemoveTempFile = false; // PHP will handle this
94 /**
95 * Start doing stuff
96 * @access public
98 function execute() {
99 global $wgUser, $wgOut;
100 global $wgEnableUploads, $wgUploadDirectory;
102 /** Show an error message if file upload is disabled */
103 if( ! $wgEnableUploads ) {
104 $wgOut->addWikiText( wfMsg( 'uploaddisabled' ) );
105 return;
108 /** Various rights checks */
109 if( !$wgUser->isAllowed( 'upload' ) || $wgUser->isBlocked() ) {
110 $wgOut->errorpage( 'uploadnologin', 'uploadnologintext' );
111 return;
113 if( wfReadOnly() ) {
114 $wgOut->readOnlyPage();
115 return;
118 /** Check if the image directory is writeable, this is a common mistake */
119 if ( !is_writeable( $wgUploadDirectory ) ) {
120 $wgOut->addWikiText( wfMsg( 'upload_directory_read_only', $wgUploadDirectory ) );
121 return;
124 if( $this->mReUpload ) {
125 $this->unsaveUploadedFile();
126 $this->mainUploadForm();
127 } else if ( 'submit' == $this->mAction || $this->mUpload ) {
128 $this->processUpload();
129 } else {
130 $this->mainUploadForm();
133 $this->cleanupTempFile();
136 /* -------------------------------------------------------------- */
139 * Really do the upload
140 * Checks are made in SpecialUpload::execute()
141 * @access private
143 function processUpload() {
144 global $wgUser, $wgOut, $wgUploadDirectory;
146 /* Check for PHP error if any, requires php 4.2 or newer */
147 if ( $this->mUploadError == 1/*UPLOAD_ERR_INI_SIZE*/ ) {
148 $this->mainUploadForm( wfMsgHtml( 'largefileserver' ) );
149 return;
153 * If there was no filename or a zero size given, give up quick.
155 if( trim( $this->mOname ) == '' || empty( $this->mUploadSize ) ) {
156 $this->mainUploadForm( wfMsgHtml( 'emptyfile' ) );
157 return;
160 # Chop off any directories in the given filename
161 if ( $this->mDestFile ) {
162 $basename = basename( $this->mDestFile );
163 } else {
164 $basename = basename( $this->mOname );
168 * We'll want to blacklist against *any* 'extension', and use
169 * only the final one for the whitelist.
171 list( $partname, $ext ) = $this->splitExtensions( $basename );
172 if( count( $ext ) ) {
173 $finalExt = $ext[count( $ext ) - 1];
174 } else {
175 $finalExt = '';
177 $fullExt = implode( '.', $ext );
179 if ( strlen( $partname ) < 3 ) {
180 $this->mainUploadForm( wfMsgHtml( 'minlength' ) );
181 return;
185 * Filter out illegal characters, and try to make a legible name
186 * out of it. We'll strip some silently that Title would die on.
188 $filtered = preg_replace ( "/[^".Title::legalChars()."]|:/", '-', $basename );
189 $nt = Title::newFromText( $filtered );
190 if( is_null( $nt ) ) {
191 $this->uploadError( wfMsgWikiHtml( 'illegalfilename', htmlspecialchars( $filtered ) ) );
192 return;
194 $nt =& Title::makeTitle( NS_IMAGE, $nt->getDBkey() );
195 $this->mUploadSaveName = $nt->getDBkey();
198 * If the image is protected, non-sysop users won't be able
199 * to modify it by uploading a new revision.
201 if( !$nt->userCanEdit() ) {
202 return $this->uploadError( wfMsgWikiHtml( 'protectedpage' ) );
206 * In some cases we may forbid overwriting of existing files.
208 $overwrite = $this->checkOverwrite( $this->mUploadSaveName );
209 if( WikiError::isError( $overwrite ) ) {
210 return $this->uploadError( $overwrite->toString() );
213 /* Don't allow users to override the blacklist (check file extension) */
214 global $wgStrictFileExtensions;
215 global $wgFileExtensions, $wgFileBlacklist;
216 if( $this->checkFileExtensionList( $ext, $wgFileBlacklist ) ||
217 ($wgStrictFileExtensions &&
218 !$this->checkFileExtension( $finalExt, $wgFileExtensions ) ) ) {
219 return $this->uploadError( wfMsgHtml( 'badfiletype', htmlspecialchars( $fullExt ) ) );
223 * Look at the contents of the file; if we can recognize the
224 * type but it's corrupt or data of the wrong type, we should
225 * probably not accept it.
227 if( !$this->mStashed ) {
228 $this->checkMacBinary();
229 $veri = $this->verify( $this->mUploadTempName, $finalExt );
231 if( $veri !== true ) { //it's a wiki error...
232 return $this->uploadError( $veri->toString() );
237 * Provide an opportunity for extensions to add futher checks
239 $error = '';
240 if( !wfRunHooks( 'UploadVerification',
241 array( $this->mUploadSaveName, $this->mUploadTempName, &$error ) ) ) {
242 return $this->uploadError( $error );
246 * Check for non-fatal conditions
248 if ( ! $this->mIgnoreWarning ) {
249 $warning = '';
251 global $wgCapitalLinks;
252 if( $wgCapitalLinks ) {
253 $filtered = ucfirst( $filtered );
255 if( $this->mUploadSaveName != $filtered ) {
256 $warning .= '<li>'.wfMsgHtml( 'badfilename', htmlspecialchars( $this->mUploadSaveName ) ).'</li>';
259 global $wgCheckFileExtensions;
260 if ( $wgCheckFileExtensions ) {
261 if ( ! $this->checkFileExtension( $finalExt, $wgFileExtensions ) ) {
262 $warning .= '<li>'.wfMsgHtml( 'badfiletype', htmlspecialchars( $fullExt ) ).'</li>';
266 global $wgUploadSizeWarning;
267 if ( $wgUploadSizeWarning && ( $this->mUploadSize > $wgUploadSizeWarning ) ) {
268 # TODO: Format $wgUploadSizeWarning to something that looks better than the raw byte
269 # value, perhaps add GB,MB and KB suffixes?
270 $warning .= '<li>'.wfMsgHtml( 'largefile', $wgUploadSizeWarning, $this->mUploadSize ).'</li>';
272 if ( $this->mUploadSize == 0 ) {
273 $warning .= '<li>'.wfMsgHtml( 'emptyfile' ).'</li>';
276 if( $nt->getArticleID() ) {
277 global $wgUser;
278 $sk = $wgUser->getSkin();
279 $dlink = $sk->makeKnownLinkObj( $nt );
280 $warning .= '<li>'.wfMsgHtml( 'fileexists', $dlink ).'</li>';
283 if( $warning != '' ) {
285 * Stash the file in a temporary location; the user can choose
286 * to let it through and we'll complete the upload then.
288 return $this->uploadWarning( $warning );
293 * Try actually saving the thing...
294 * It will show an error form on failure.
296 $hasBeenMunged = !empty( $this->mSessionKey ) || $this->mRemoveTempFile;
297 if( $this->saveUploadedFile( $this->mUploadSaveName,
298 $this->mUploadTempName,
299 $hasBeenMunged ) ) {
301 * Update the upload log and create the description page
302 * if it's a new file.
304 $img = Image::newFromName( $this->mUploadSaveName );
305 $success = $img->recordUpload( $this->mUploadOldVersion,
306 $this->mUploadDescription,
307 $this->mLicense,
308 $this->mUploadCopyStatus,
309 $this->mUploadSource,
310 $this->mWatchthis );
312 if ( $success ) {
313 $this->showSuccess();
314 } else {
315 // Image::recordUpload() fails if the image went missing, which is
316 // unlikely, hence the lack of a specialised message
317 $wgOut->fileNotFoundError( $this->mUploadSaveName );
323 * Move the uploaded file from its temporary location to the final
324 * destination. If a previous version of the file exists, move
325 * it into the archive subdirectory.
327 * @todo If the later save fails, we may have disappeared the original file.
329 * @param string $saveName
330 * @param string $tempName full path to the temporary file
331 * @param bool $useRename if true, doesn't check that the source file
332 * is a PHP-managed upload temporary
334 function saveUploadedFile( $saveName, $tempName, $useRename = false ) {
335 global $wgUploadDirectory, $wgOut;
337 $fname= "SpecialUpload::saveUploadedFile";
339 $dest = wfImageDir( $saveName );
340 $archive = wfImageArchiveDir( $saveName );
341 $this->mSavedFile = "{$dest}/{$saveName}";
343 if( is_file( $this->mSavedFile ) ) {
344 $this->mUploadOldVersion = gmdate( 'YmdHis' ) . "!{$saveName}";
345 wfSuppressWarnings();
346 $success = rename( $this->mSavedFile, "${archive}/{$this->mUploadOldVersion}" );
347 wfRestoreWarnings();
349 if( ! $success ) {
350 $wgOut->fileRenameError( $this->mSavedFile,
351 "${archive}/{$this->mUploadOldVersion}" );
352 return false;
354 else wfDebug("$fname: moved file ".$this->mSavedFile." to ${archive}/{$this->mUploadOldVersion}\n");
356 else {
357 $this->mUploadOldVersion = '';
360 wfSuppressWarnings();
361 $success = $useRename
362 ? rename( $tempName, $this->mSavedFile )
363 : move_uploaded_file( $tempName, $this->mSavedFile );
364 wfRestoreWarnings();
366 if( ! $success ) {
367 $wgOut->fileCopyError( $tempName, $this->mSavedFile );
368 return false;
369 } else {
370 wfDebug("$fname: wrote tempfile $tempName to ".$this->mSavedFile."\n");
373 chmod( $this->mSavedFile, 0644 );
374 return true;
378 * Stash a file in a temporary directory for later processing
379 * after the user has confirmed it.
381 * If the user doesn't explicitly cancel or accept, these files
382 * can accumulate in the temp directory.
384 * @param string $saveName - the destination filename
385 * @param string $tempName - the source temporary file to save
386 * @return string - full path the stashed file, or false on failure
387 * @access private
389 function saveTempUploadedFile( $saveName, $tempName ) {
390 global $wgOut;
391 $archive = wfImageArchiveDir( $saveName, 'temp' );
392 $stash = $archive . '/' . gmdate( "YmdHis" ) . '!' . $saveName;
394 $success = $this->mRemoveTempFile
395 ? rename( $tempName, $stash )
396 : move_uploaded_file( $tempName, $stash );
397 if ( !$success ) {
398 $wgOut->fileCopyError( $tempName, $stash );
399 return false;
402 return $stash;
406 * Stash a file in a temporary directory for later processing,
407 * and save the necessary descriptive info into the session.
408 * Returns a key value which will be passed through a form
409 * to pick up the path info on a later invocation.
411 * @return int
412 * @access private
414 function stashSession() {
415 $stash = $this->saveTempUploadedFile(
416 $this->mUploadSaveName, $this->mUploadTempName );
418 if( !$stash ) {
419 # Couldn't save the file.
420 return false;
423 $key = mt_rand( 0, 0x7fffffff );
424 $_SESSION['wsUploadData'][$key] = array(
425 'mUploadTempName' => $stash,
426 'mUploadSize' => $this->mUploadSize,
427 'mOname' => $this->mOname );
428 return $key;
432 * Remove a temporarily kept file stashed by saveTempUploadedFile().
433 * @access private
435 function unsaveUploadedFile() {
436 global $wgOut;
437 wfSuppressWarnings();
438 $success = unlink( $this->mUploadTempName );
439 wfRestoreWarnings();
440 if ( ! $success ) {
441 $wgOut->fileDeleteError( $this->mUploadTempName );
445 /* -------------------------------------------------------------- */
448 * Show some text and linkage on successful upload.
449 * @access private
451 function showSuccess() {
452 global $wgUser, $wgOut, $wgContLang;
454 $sk = $wgUser->getSkin();
455 $ilink = $sk->makeMediaLink( $this->mUploadSaveName, Image::imageUrl( $this->mUploadSaveName ) );
456 $dname = $wgContLang->getNsText( NS_IMAGE ) . ':'.$this->mUploadSaveName;
457 $dlink = $sk->makeKnownLink( $dname, $dname );
459 $wgOut->addHTML( '<h2>' . wfMsgHtml( 'successfulupload' ) . "</h2>\n" );
460 $text = wfMsgWikiHtml( 'fileuploaded', $ilink, $dlink );
461 $wgOut->addHTML( $text );
462 $wgOut->returnToMain( false );
466 * @param string $error as HTML
467 * @access private
469 function uploadError( $error ) {
470 global $wgOut;
471 $wgOut->addHTML( "<h2>" . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
472 $wgOut->addHTML( "<span class='error'>{$error}</span>\n" );
476 * There's something wrong with this file, not enough to reject it
477 * totally but we require manual intervention to save it for real.
478 * Stash it away, then present a form asking to confirm or cancel.
480 * @param string $warning as HTML
481 * @access private
483 function uploadWarning( $warning ) {
484 global $wgOut, $wgUser, $wgUploadDirectory, $wgRequest;
485 global $wgUseCopyrightUpload;
487 $this->mSessionKey = $this->stashSession();
488 if( !$this->mSessionKey ) {
489 # Couldn't save file; an error has been displayed so let's go.
490 return;
493 $wgOut->addHTML( "<h2>" . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
494 $wgOut->addHTML( "<ul class='warning'>{$warning}</ul><br />\n" );
496 $save = wfMsgHtml( 'savefile' );
497 $reupload = wfMsgHtml( 'reupload' );
498 $iw = wfMsgWikiHtml( 'ignorewarning' );
499 $reup = wfMsgWikiHtml( 'reuploaddesc' );
500 $titleObj = Title::makeTitle( NS_SPECIAL, 'Upload' );
501 $action = $titleObj->escapeLocalURL( 'action=submit' );
503 if ( $wgUseCopyrightUpload )
505 $copyright = "
506 <input type='hidden' name='wpUploadCopyStatus' value=\"" . htmlspecialchars( $this->mUploadCopyStatus ) . "\" />
507 <input type='hidden' name='wpUploadSource' value=\"" . htmlspecialchars( $this->mUploadSource ) . "\" />
509 } else {
510 $copyright = "";
513 $wgOut->addHTML( "
514 <form id='uploadwarning' method='post' enctype='multipart/form-data' action='$action'>
515 <input type='hidden' name='wpIgnoreWarning' value='1' />
516 <input type='hidden' name='wpSessionKey' value=\"" . htmlspecialchars( $this->mSessionKey ) . "\" />
517 <input type='hidden' name='wpUploadDescription' value=\"" . htmlspecialchars( $this->mUploadDescription ) . "\" />
518 <input type='hidden' name='wpLicense' value=\"" . htmlspecialchars( $this->mLicense ) . "\" />
519 <input type='hidden' name='wpDestFile' value=\"" . htmlspecialchars( $this->mDestFile ) . "\" />
520 <input type='hidden' name='wpWatchthis' value=\"" . htmlspecialchars( intval( $this->mWatchthis ) ) . "\" />
521 {$copyright}
522 <table border='0'>
523 <tr>
524 <tr>
525 <td align='right'>
526 <input tabindex='2' type='submit' name='wpUpload' value='$save' />
527 </td>
528 <td align='left'>$iw</td>
529 </tr>
530 <tr>
531 <td align='right'>
532 <input tabindex='2' type='submit' name='wpReUpload' value='{$reupload}' />
533 </td>
534 <td align='left'>$reup</td>
535 </tr>
536 </tr>
537 </table></form>\n" );
541 * Displays the main upload form, optionally with a highlighted
542 * error message up at the top.
544 * @param string $msg as HTML
545 * @access private
547 function mainUploadForm( $msg='' ) {
548 global $wgOut, $wgUser, $wgUploadDirectory, $wgRequest;
549 global $wgUseCopyrightUpload;
551 $cols = intval($wgUser->getOption( 'cols' ));
552 $ew = $wgUser->getOption( 'editwidth' );
553 if ( $ew ) $ew = " style=\"width:100%\"";
554 else $ew = '';
556 if ( '' != $msg ) {
557 $sub = wfMsgHtml( 'uploaderror' );
558 $wgOut->addHTML( "<h2>{$sub}</h2>\n" .
559 "<span class='error'>{$msg}</span>\n" );
561 $wgOut->addHTML( '<div id="uploadtext">' );
562 $wgOut->addWikiText( wfMsg( 'uploadtext' ) );
563 $wgOut->addHTML( '</div>' );
564 $sk = $wgUser->getSkin();
567 $sourcefilename = wfMsgHtml( 'sourcefilename' );
568 $destfilename = wfMsgHtml( 'destfilename' );
569 $summary = wfMsgWikiHtml( 'fileuploadsummary' );
571 $licenses = new Licenses();
572 $license = wfMsgHtml( 'license' );
573 $nolicense = wfMsgHtml( 'nolicense' );
574 $licenseshtml = $licenses->getHtml();
576 $ulb = wfMsgHtml( 'uploadbtn' );
579 $titleObj = Title::makeTitle( NS_SPECIAL, 'Upload' );
580 $action = $titleObj->escapeLocalURL();
582 $encDestFile = htmlspecialchars( $this->mDestFile );
584 $watchChecked = $wgUser->getOption( 'watchdefault' )
585 ? 'checked="checked"'
586 : '';
588 $wgOut->addHTML( "
589 <form id='upload' method='post' enctype='multipart/form-data' action=\"$action\">
590 <table border='0'>
591 <tr>
592 <td align='right'><label for='wpUploadFile'>{$sourcefilename}:</label></td>
593 <td align='left'>
594 <input tabindex='1' type='file' name='wpUploadFile' id='wpUploadFile' " . ($this->mDestFile?"":"onchange='fillDestFilename()' ") . "size='40' />
595 </td>
596 </tr>
597 <tr>
598 <td align='right'><label for='wpDestFile'>{$destfilename}:</label></td>
599 <td align='left'>
600 <input tabindex='2' type='text' name='wpDestFile' id='wpDestFile' size='40' value=\"$encDestFile\" />
601 </td>
602 </tr>
603 <tr>
604 <td align='right'><label for='wpUploadDescription'>{$summary}</label></td>
605 <td align='left'>
606 <textarea tabindex='3' name='wpUploadDescription' id='wpUploadDescription' rows='6' cols='{$cols}'{$ew}>" . htmlspecialchars( $this->mUploadDescription ) . "</textarea>
607 </td>
608 </tr>
609 <tr>" );
611 if ( $licenseshtml != '' ) {
612 $wgOut->addHTML( "
613 <td align='right'><label for='wpLicense'>$license:</label></td>
614 <td align='left'>
615 <select name='wpLicense' id='wpLicense' tabindex='4'>
616 <option value=''>$nolicense</option>
617 $licenseshtml
618 </select>
619 </td>
620 </tr>
621 <tr>
625 if ( $wgUseCopyrightUpload ) {
626 $filestatus = wfMsgHtml ( 'filestatus' );
627 $copystatus = htmlspecialchars( $this->mUploadCopyStatus );
628 $filesource = wfMsgHtml ( 'filesource' );
629 $uploadsource = htmlspecialchars( $this->mUploadSource );
631 $wgOut->addHTML( "
632 <td align='right' nowrap='nowrap'><label for='wpUploadCopyStatus'>$filestatus:</label></td>
633 <td><input tabindex='5' type='text' name='wpUploadCopyStatus' id='wpUploadCopyStatus' value=\"$copystatus\" size='40' /></td>
634 </tr>
635 <tr>
636 <td align='right'><label for='wpUploadCopyStatus'>$filesource:</label></td>
637 <td><input tabindex='6' type='text' name='wpUploadSource' id='wpUploadCopyStatus' value=\"$uploadsource\" size='40' /></td>
638 </tr>
639 <tr>
644 $wgOut->addHtml( "
645 <td></td>
646 <td>
647 <input tabindex='7' type='checkbox' name='wpWatchthis' id='wpWatchthis' $watchChecked value='true' />
648 <label for='wpWatchthis'>" . wfMsgHtml( 'watchthis' ) . "</label>
649 <input tabindex='8' type='checkbox' name='wpIgnoreWarning' id='wpIgnoreWarning' value='true' />
650 <label for='wpIgnoreWarning'>" . wfMsgHtml( 'ignorewarnings' ) . "</label>
651 </td>
652 </tr>
653 <tr>
655 </tr>
656 <tr>
657 <td></td>
658 <td align='left'><input tabindex='9' type='submit' name='wpUpload' value=\"{$ulb}\" /></td>
659 </tr>
661 <tr>
662 <td></td>
663 <td align='left'>
664 " );
665 $wgOut->addWikiText( wfMsgForContent( 'edittools' ) );
666 $wgOut->addHTML( "
667 </td>
668 </tr>
670 </table>
671 </form>" );
674 /* -------------------------------------------------------------- */
677 * Split a file into a base name and all dot-delimited 'extensions'
678 * on the end. Some web server configurations will fall back to
679 * earlier pseudo-'extensions' to determine type and execute
680 * scripts, so the blacklist needs to check them all.
682 * @return array
684 function splitExtensions( $filename ) {
685 $bits = explode( '.', $filename );
686 $basename = array_shift( $bits );
687 return array( $basename, $bits );
691 * Perform case-insensitive match against a list of file extensions.
692 * Returns true if the extension is in the list.
694 * @param string $ext
695 * @param array $list
696 * @return bool
698 function checkFileExtension( $ext, $list ) {
699 return in_array( strtolower( $ext ), $list );
703 * Perform case-insensitive match against a list of file extensions.
704 * Returns true if any of the extensions are in the list.
706 * @param array $ext
707 * @param array $list
708 * @return bool
710 function checkFileExtensionList( $ext, $list ) {
711 foreach( $ext as $e ) {
712 if( in_array( strtolower( $e ), $list ) ) {
713 return true;
716 return false;
720 * Verifies that it's ok to include the uploaded file
722 * @param string $tmpfile the full path of the temporary file to verify
723 * @param string $extension The filename extension that the file is to be served with
724 * @return mixed true of the file is verified, a WikiError object otherwise.
726 function verify( $tmpfile, $extension ) {
727 #magically determine mime type
728 $magic=& wfGetMimeMagic();
729 $mime= $magic->guessMimeType($tmpfile,false);
731 $fname= "SpecialUpload::verify";
733 #check mime type, if desired
734 global $wgVerifyMimeType;
735 if ($wgVerifyMimeType) {
737 #check mime type against file extension
738 if( !$this->verifyExtension( $mime, $extension ) ) {
739 return new WikiErrorMsg( 'uploadcorrupt' );
742 #check mime type blacklist
743 global $wgMimeTypeBlacklist;
744 if( isset($wgMimeTypeBlacklist) && !is_null($wgMimeTypeBlacklist)
745 && $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
746 return new WikiErrorMsg( 'badfiletype', htmlspecialchars( $mime ) );
750 #check for htmlish code and javascript
751 if( $this->detectScript ( $tmpfile, $mime ) ) {
752 return new WikiErrorMsg( 'uploadscripted' );
756 * Scan the uploaded file for viruses
758 $virus= $this->detectVirus($tmpfile);
759 if ( $virus ) {
760 return new WikiErrorMsg( 'uploadvirus', htmlspecialchars($virus) );
763 wfDebug( "$fname: all clear; passing.\n" );
764 return true;
768 * Checks if the mime type of the uploaded file matches the file extension.
770 * @param string $mime the mime type of the uploaded file
771 * @param string $extension The filename extension that the file is to be served with
772 * @return bool
774 function verifyExtension( $mime, $extension ) {
775 $fname = 'SpecialUpload::verifyExtension';
777 $magic =& wfGetMimeMagic();
779 if ( ! $mime || $mime == 'unknown' || $mime == 'unknown/unknown' )
780 if ( ! $magic->isRecognizableExtension( $extension ) ) {
781 wfDebug( "$fname: passing file with unknown detected mime type; unrecognized extension '$extension', can't verify\n" );
782 return true;
783 } else {
784 wfDebug( "$fname: rejecting file with unknown detected mime type; recognized extension '$extension', so probably invalid file\n" );
785 return false;
788 $match= $magic->isMatchingExtension($extension,$mime);
790 if ($match===NULL) {
791 wfDebug( "$fname: no file extension known for mime type $mime, passing file\n" );
792 return true;
793 } elseif ($match===true) {
794 wfDebug( "$fname: mime type $mime matches extension $extension, passing file\n" );
796 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
797 return true;
799 } else {
800 wfDebug( "$fname: mime type $mime mismatches file extension $extension, rejecting file\n" );
801 return false;
805 /** Heuristig for detecting files that *could* contain JavaScript instructions or
806 * things that may look like HTML to a browser and are thus
807 * potentially harmful. The present implementation will produce false positives in some situations.
809 * @param string $file Pathname to the temporary upload file
810 * @param string $mime The mime type of the file
811 * @return bool true if the file contains something looking like embedded scripts
813 function detectScript($file,$mime) {
815 #ugly hack: for text files, always look at the entire file.
816 #For binarie field, just check the first K.
818 if (strpos($mime,'text/')===0) $chunk = file_get_contents( $file );
819 else {
820 $fp = fopen( $file, 'rb' );
821 $chunk = fread( $fp, 1024 );
822 fclose( $fp );
825 $chunk= strtolower( $chunk );
827 if (!$chunk) return false;
829 #decode from UTF-16 if needed (could be used for obfuscation).
830 if (substr($chunk,0,2)=="\xfe\xff") $enc= "UTF-16BE";
831 elseif (substr($chunk,0,2)=="\xff\xfe") $enc= "UTF-16LE";
832 else $enc= NULL;
834 if ($enc) $chunk= iconv($enc,"ASCII//IGNORE",$chunk);
836 $chunk= trim($chunk);
838 #FIXME: convert from UTF-16 if necessarry!
840 wfDebug("SpecialUpload::detectScript: checking for embedded scripts and HTML stuff\n");
842 #check for HTML doctype
843 if (eregi("<!DOCTYPE *X?HTML",$chunk)) return true;
846 * Internet Explorer for Windows performs some really stupid file type
847 * autodetection which can cause it to interpret valid image files as HTML
848 * and potentially execute JavaScript, creating a cross-site scripting
849 * attack vectors.
851 * Apple's Safari browser also performs some unsafe file type autodetection
852 * which can cause legitimate files to be interpreted as HTML if the
853 * web server is not correctly configured to send the right content-type
854 * (or if you're really uploading plain text and octet streams!)
856 * Returns true if IE is likely to mistake the given file for HTML.
857 * Also returns true if Safari would mistake the given file for HTML
858 * when served with a generic content-type.
861 $tags = array(
862 '<body',
863 '<head',
864 '<html', #also in safari
865 '<img',
866 '<pre',
867 '<script', #also in safari
868 '<table',
869 '<title' #also in safari
872 foreach( $tags as $tag ) {
873 if( false !== strpos( $chunk, $tag ) ) {
874 return true;
879 * look for javascript
882 #resolve entity-refs to look at attributes. may be harsh on big files... cache result?
883 $chunk = Sanitizer::decodeCharReferences( $chunk );
885 #look for script-types
886 if (preg_match("!type\s*=\s*['\"]?\s*(\w*/)?(ecma|java)!sim",$chunk)) return true;
888 #look for html-style script-urls
889 if (preg_match("!(href|src|data)\s*=\s*['\"]?\s*(ecma|java)script:!sim",$chunk)) return true;
891 #look for css-style script-urls
892 if (preg_match("!url\s*\(\s*['\"]?\s*(ecma|java)script:!sim",$chunk)) return true;
894 wfDebug("SpecialUpload::detectScript: no scripts found\n");
895 return false;
898 /** Generic wrapper function for a virus scanner program.
899 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
900 * $wgAntivirusRequired may be used to deny upload if the scan fails.
902 * @param string $file Pathname to the temporary upload file
903 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
904 * or a string containing feedback from the virus scanner if a virus was found.
905 * If textual feedback is missing but a virus was found, this function returns true.
907 function detectVirus($file) {
908 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired;
910 $fname= "SpecialUpload::detectVirus";
912 if (!$wgAntivirus) { #disabled?
913 wfDebug("$fname: virus scanner disabled\n");
915 return NULL;
918 if (!$wgAntivirusSetup[$wgAntivirus]) {
919 wfDebug("$fname: unknown virus scanner: $wgAntivirus\n");
921 $wgOut->addHTML( "<div class='error'>Bad configuration: unknown virus scanner: <i>$wgAntivirus</i></div>\n" ); #LOCALIZE
923 return "unknown antivirus: $wgAntivirus";
926 #look up scanner configuration
927 $virus_scanner= $wgAntivirusSetup[$wgAntivirus]["command"]; #command pattern
928 $virus_scanner_codes= $wgAntivirusSetup[$wgAntivirus]["codemap"]; #exit-code map
929 $msg_pattern= $wgAntivirusSetup[$wgAntivirus]["messagepattern"]; #message pattern
931 $scanner= $virus_scanner; #copy, so we can resolve the pattern
933 if (strpos($scanner,"%f")===false) $scanner.= " ".wfEscapeShellArg($file); #simple pattern: append file to scan
934 else $scanner= str_replace("%f",wfEscapeShellArg($file),$scanner); #complex pattern: replace "%f" with file to scan
936 wfDebug("$fname: running virus scan: $scanner \n");
938 #execute virus scanner
939 $code= false;
941 #NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
942 # that does not seem to be worth the pain.
943 # Ask me (Duesentrieb) about it if it's ever needed.
944 if (wfIsWindows()) exec("$scanner",$output,$code);
945 else exec("$scanner 2>&1",$output,$code);
947 $exit_code= $code; #remeber for user feedback
949 if ($virus_scanner_codes) { #map exit code to AV_xxx constants.
950 if (isset($virus_scanner_codes[$code])) $code= $virus_scanner_codes[$code]; #explicite mapping
951 else if (isset($virus_scanner_codes["*"])) $code= $virus_scanner_codes["*"]; #fallback mapping
954 if ($code===AV_SCAN_FAILED) { #scan failed (code was mapped to false by $virus_scanner_codes)
955 wfDebug("$fname: failed to scan $file (code $exit_code).\n");
957 if ($wgAntivirusRequired) return "scan failed (code $exit_code)";
958 else return NULL;
960 else if ($code===AV_SCAN_ABORTED) { #scan failed because filetype is unknown (probably imune)
961 wfDebug("$fname: unsupported file type $file (code $exit_code).\n");
962 return NULL;
964 else if ($code===AV_NO_VIRUS) {
965 wfDebug("$fname: file passed virus scan.\n");
966 return false; #no virus found
968 else {
969 $output= join("\n",$output);
970 $output= trim($output);
972 if (!$output) $output= true; #if ther's no output, return true
973 else if ($msg_pattern) {
974 $groups= array();
975 if (preg_match($msg_pattern,$output,$groups)) {
976 if ($groups[1]) $output= $groups[1];
980 wfDebug("$fname: FOUND VIRUS! scanner feedback: $output");
981 return $output;
986 * Check if the temporary file is MacBinary-encoded, as some uploads
987 * from Internet Explorer on Mac OS Classic and Mac OS X will be.
988 * If so, the data fork will be extracted to a second temporary file,
989 * which will then be checked for validity and either kept or discarded.
991 * @access private
993 function checkMacBinary() {
994 $macbin = new MacBinary( $this->mUploadTempName );
995 if( $macbin->isValid() ) {
996 $dataFile = tempnam( wfTempDir(), "WikiMacBinary" );
997 $dataHandle = fopen( $dataFile, 'wb' );
999 wfDebug( "SpecialUpload::checkMacBinary: Extracting MacBinary data fork to $dataFile\n" );
1000 $macbin->extractData( $dataHandle );
1002 $this->mUploadTempName = $dataFile;
1003 $this->mUploadSize = $macbin->dataForkLength();
1005 // We'll have to manually remove the new file if it's not kept.
1006 $this->mRemoveTempFile = true;
1008 $macbin->close();
1012 * If we've modified the upload file we need to manually remove it
1013 * on exit to clean up.
1014 * @access private
1016 function cleanupTempFile() {
1017 if( $this->mRemoveTempFile && file_exists( $this->mUploadTempName ) ) {
1018 wfDebug( "SpecialUpload::cleanupTempFile: Removing temporary file $this->mUploadTempName\n" );
1019 unlink( $this->mUploadTempName );
1024 * Check if there's an overwrite conflict and, if so, if restrictions
1025 * forbid this user from performing the upload.
1027 * @return mixed true on success, WikiError on failure
1028 * @access private
1030 function checkOverwrite( $name ) {
1031 $img = Image::newFromName( $name );
1032 if( is_null( $img ) ) {
1033 // Uh... this shouldn't happen ;)
1034 // But if it does, fall through to previous behavior
1035 return false;
1038 $error = '';
1039 if( $img->exists() ) {
1040 global $wgUser, $wgOut;
1041 if( $img->isLocal() ) {
1042 if( !$wgUser->isAllowed( 'reupload' ) ) {
1043 $error = 'fileexists-forbidden';
1045 } else {
1046 if( !$wgUser->isAllowed( 'reupload' ) ||
1047 !$wgUser->isAllowed( 'reupload-shared' ) ) {
1048 $error = "fileexists-shared-forbidden";
1053 if( $error ) {
1054 $errorText = wfMsg( $error, wfEscapeWikiText( $img->getName() ) );
1055 return new WikiError( $wgOut->parse( $errorText ) );
1058 // Rockin', go ahead and upload
1059 return true;