Fix bogus "filename too short" error when uploading files with a period in the base...
[lhc/web/wiklou.git] / includes / SpecialUpload.php
1 <?php
2 /**
3 *
4 * @package MediaWiki
5 * @subpackage SpecialPage
6 */
7
8 /**
9 *
10 */
11 require_once 'Image.php';
12 require_once 'MacBinary.php';
13 require_once 'Licenses.php';
14 /**
15 * Entry point
16 */
17 function wfSpecialUpload() {
18 global $wgRequest;
19 $form = new UploadForm( $wgRequest );
20 $form->execute();
21 }
22
23 /**
24 *
25 * @package MediaWiki
26 * @subpackage SpecialPage
27 */
28 class UploadForm {
29 /**#@+
30 * @access private
31 */
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 /**#@-*/
37
38 /**
39 * Constructor : initialise object
40 * Get data POSTed through the form and assign them to the object
41 * @param $request Data posted.
42 */
43 function UploadForm( &$request ) {
44 $this->mDestFile = $request->getText( 'wpDestFile' );
45
46 if( !$request->wasPosted() ) {
47 # GET requests just give the main form; no data except wpDestfile.
48 return;
49 }
50
51 $this->mIgnoreWarning = $request->getCheck( 'wpIgnoreWarning');
52 $this->mReUpload = $request->getCheck( 'wpReUpload' );
53 $this->mUpload = $request->getCheck( 'wpUpload' );
54
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" );
61
62 $this->mAction = $request->getVal( 'action' );
63
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.
72 */
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.
83 */
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
91 }
92 }
93
94 /**
95 * Start doing stuff
96 * @access public
97 */
98 function execute() {
99 global $wgUser, $wgOut;
100 global $wgEnableUploads, $wgUploadDirectory;
101
102 # Check uploading enabled
103 if( !$wgEnableUploads ) {
104 $wgOut->errorPage( 'uploaddisabled', 'uploaddisabledtext' );
105 return;
106 }
107
108 # Check permissions
109 if( $wgUser->isLoggedIn() ) {
110 if( !$wgUser->isAllowed( 'upload' ) ) {
111 $wgOut->permissionRequired( 'upload' );
112 return;
113 }
114 } else {
115 $wgOut->errorPage( 'uploadnologin', 'uploadnologintext' );
116 return;
117 }
118
119 # Check blocks
120 if( $wgUser->isBlocked() ) {
121 $wgOut->blockedPage();
122 return;
123 }
124
125 if( wfReadOnly() ) {
126 $wgOut->readOnlyPage();
127 return;
128 }
129
130 /** Check if the image directory is writeable, this is a common mistake */
131 if ( !is_writeable( $wgUploadDirectory ) ) {
132 $wgOut->addWikiText( wfMsg( 'upload_directory_read_only', $wgUploadDirectory ) );
133 return;
134 }
135
136 if( $this->mReUpload ) {
137 $this->unsaveUploadedFile();
138 $this->mainUploadForm();
139 } else if ( 'submit' == $this->mAction || $this->mUpload ) {
140 $this->processUpload();
141 } else {
142 $this->mainUploadForm();
143 }
144
145 $this->cleanupTempFile();
146 }
147
148 /* -------------------------------------------------------------- */
149
150 /**
151 * Really do the upload
152 * Checks are made in SpecialUpload::execute()
153 * @access private
154 */
155 function processUpload() {
156 global $wgUser, $wgOut;
157
158 /* Check for PHP error if any, requires php 4.2 or newer */
159 if ( $this->mUploadError == 1/*UPLOAD_ERR_INI_SIZE*/ ) {
160 $this->mainUploadForm( wfMsgHtml( 'largefileserver' ) );
161 return;
162 }
163
164 /**
165 * If there was no filename or a zero size given, give up quick.
166 */
167 if( trim( $this->mOname ) == '' || empty( $this->mUploadSize ) ) {
168 $this->mainUploadForm( wfMsgHtml( 'emptyfile' ) );
169 return;
170 }
171
172 # Chop off any directories in the given filename
173 if ( $this->mDestFile ) {
174 $basename = wfBaseName( $this->mDestFile );
175 } else {
176 $basename = wfBaseName( $this->mOname );
177 }
178
179 /**
180 * We'll want to blacklist against *any* 'extension', and use
181 * only the final one for the whitelist.
182 */
183 list( $partname, $ext ) = $this->splitExtensions( $basename );
184
185 if( count( $ext ) ) {
186 $finalExt = $ext[count( $ext ) - 1];
187 } else {
188 $finalExt = '';
189 }
190 $fullExt = implode( '.', $ext );
191
192 # If there was more than one "extension", reassemble the base
193 # filename to prevent bogus complaints about length
194 if( count( $ext ) > 1 ) {
195 for( $i = 0; $i < count( $ext ) - 1; $i++ )
196 $partname .= '.' . $ext[$i];
197 }
198
199 if ( strlen( $partname ) < 3 ) {
200 $this->mainUploadForm( wfMsgHtml( 'minlength' ) );
201 return;
202 }
203
204 /**
205 * Filter out illegal characters, and try to make a legible name
206 * out of it. We'll strip some silently that Title would die on.
207 */
208 $filtered = preg_replace ( "/[^".Title::legalChars()."]|:/", '-', $basename );
209 $nt = Title::newFromText( $filtered );
210 if( is_null( $nt ) ) {
211 $this->uploadError( wfMsgWikiHtml( 'illegalfilename', htmlspecialchars( $filtered ) ) );
212 return;
213 }
214 $nt =& Title::makeTitle( NS_IMAGE, $nt->getDBkey() );
215 $this->mUploadSaveName = $nt->getDBkey();
216
217 /**
218 * If the image is protected, non-sysop users won't be able
219 * to modify it by uploading a new revision.
220 */
221 if( !$nt->userCanEdit() ) {
222 return $this->uploadError( wfMsgWikiHtml( 'protectedpage' ) );
223 }
224
225 /**
226 * In some cases we may forbid overwriting of existing files.
227 */
228 $overwrite = $this->checkOverwrite( $this->mUploadSaveName );
229 if( WikiError::isError( $overwrite ) ) {
230 return $this->uploadError( $overwrite->toString() );
231 }
232
233 /* Don't allow users to override the blacklist (check file extension) */
234 global $wgStrictFileExtensions;
235 global $wgFileExtensions, $wgFileBlacklist;
236 if( $this->checkFileExtensionList( $ext, $wgFileBlacklist ) ||
237 ($wgStrictFileExtensions &&
238 !$this->checkFileExtension( $finalExt, $wgFileExtensions ) ) ) {
239 return $this->uploadError( wfMsgHtml( 'badfiletype', htmlspecialchars( $fullExt ) ) );
240 }
241
242 /**
243 * Look at the contents of the file; if we can recognize the
244 * type but it's corrupt or data of the wrong type, we should
245 * probably not accept it.
246 */
247 if( !$this->mStashed ) {
248 $this->checkMacBinary();
249 $veri = $this->verify( $this->mUploadTempName, $finalExt );
250
251 if( $veri !== true ) { //it's a wiki error...
252 return $this->uploadError( $veri->toString() );
253 }
254 }
255
256 /**
257 * Provide an opportunity for extensions to add futher checks
258 */
259 $error = '';
260 if( !wfRunHooks( 'UploadVerification',
261 array( $this->mUploadSaveName, $this->mUploadTempName, &$error ) ) ) {
262 return $this->uploadError( $error );
263 }
264
265 /**
266 * Check for non-fatal conditions
267 */
268 if ( ! $this->mIgnoreWarning ) {
269 $warning = '';
270
271 global $wgCapitalLinks;
272 if( $wgCapitalLinks ) {
273 $filtered = ucfirst( $filtered );
274 }
275 if( $this->mUploadSaveName != $filtered ) {
276 $warning .= '<li>'.wfMsgHtml( 'badfilename', htmlspecialchars( $this->mUploadSaveName ) ).'</li>';
277 }
278
279 global $wgCheckFileExtensions;
280 if ( $wgCheckFileExtensions ) {
281 if ( ! $this->checkFileExtension( $finalExt, $wgFileExtensions ) ) {
282 $warning .= '<li>'.wfMsgHtml( 'badfiletype', htmlspecialchars( $fullExt ) ).'</li>';
283 }
284 }
285
286 global $wgUploadSizeWarning;
287 if ( $wgUploadSizeWarning && ( $this->mUploadSize > $wgUploadSizeWarning ) ) {
288 # TODO: Format $wgUploadSizeWarning to something that looks better than the raw byte
289 # value, perhaps add GB,MB and KB suffixes?
290 $warning .= '<li>'.wfMsgHtml( 'largefile', $wgUploadSizeWarning, $this->mUploadSize ).'</li>';
291 }
292 if ( $this->mUploadSize == 0 ) {
293 $warning .= '<li>'.wfMsgHtml( 'emptyfile' ).'</li>';
294 }
295
296 if( $nt->getArticleID() ) {
297 global $wgUser;
298 $sk = $wgUser->getSkin();
299 $dlink = $sk->makeKnownLinkObj( $nt );
300 $warning .= '<li>'.wfMsgHtml( 'fileexists', $dlink ).'</li>';
301 }
302
303 if( $warning != '' ) {
304 /**
305 * Stash the file in a temporary location; the user can choose
306 * to let it through and we'll complete the upload then.
307 */
308 return $this->uploadWarning( $warning );
309 }
310 }
311
312 /**
313 * Try actually saving the thing...
314 * It will show an error form on failure.
315 */
316 $hasBeenMunged = !empty( $this->mSessionKey ) || $this->mRemoveTempFile;
317 if( $this->saveUploadedFile( $this->mUploadSaveName,
318 $this->mUploadTempName,
319 $hasBeenMunged ) ) {
320 /**
321 * Update the upload log and create the description page
322 * if it's a new file.
323 */
324 $img = Image::newFromName( $this->mUploadSaveName );
325 $success = $img->recordUpload( $this->mUploadOldVersion,
326 $this->mUploadDescription,
327 $this->mLicense,
328 $this->mUploadCopyStatus,
329 $this->mUploadSource,
330 $this->mWatchthis );
331
332 if ( $success ) {
333 $this->showSuccess();
334 } else {
335 // Image::recordUpload() fails if the image went missing, which is
336 // unlikely, hence the lack of a specialised message
337 $wgOut->fileNotFoundError( $this->mUploadSaveName );
338 }
339 }
340 }
341
342 /**
343 * Move the uploaded file from its temporary location to the final
344 * destination. If a previous version of the file exists, move
345 * it into the archive subdirectory.
346 *
347 * @todo If the later save fails, we may have disappeared the original file.
348 *
349 * @param string $saveName
350 * @param string $tempName full path to the temporary file
351 * @param bool $useRename if true, doesn't check that the source file
352 * is a PHP-managed upload temporary
353 */
354 function saveUploadedFile( $saveName, $tempName, $useRename = false ) {
355 global $wgOut;
356
357 $fname= "SpecialUpload::saveUploadedFile";
358
359 $dest = wfImageDir( $saveName );
360 $archive = wfImageArchiveDir( $saveName );
361 $this->mSavedFile = "{$dest}/{$saveName}";
362
363 if( is_file( $this->mSavedFile ) ) {
364 $this->mUploadOldVersion = gmdate( 'YmdHis' ) . "!{$saveName}";
365 wfSuppressWarnings();
366 $success = rename( $this->mSavedFile, "${archive}/{$this->mUploadOldVersion}" );
367 wfRestoreWarnings();
368
369 if( ! $success ) {
370 $wgOut->fileRenameError( $this->mSavedFile,
371 "${archive}/{$this->mUploadOldVersion}" );
372 return false;
373 }
374 else wfDebug("$fname: moved file ".$this->mSavedFile." to ${archive}/{$this->mUploadOldVersion}\n");
375 }
376 else {
377 $this->mUploadOldVersion = '';
378 }
379
380 wfSuppressWarnings();
381 $success = $useRename
382 ? rename( $tempName, $this->mSavedFile )
383 : move_uploaded_file( $tempName, $this->mSavedFile );
384 wfRestoreWarnings();
385
386 if( ! $success ) {
387 $wgOut->fileCopyError( $tempName, $this->mSavedFile );
388 return false;
389 } else {
390 wfDebug("$fname: wrote tempfile $tempName to ".$this->mSavedFile."\n");
391 }
392
393 chmod( $this->mSavedFile, 0644 );
394 return true;
395 }
396
397 /**
398 * Stash a file in a temporary directory for later processing
399 * after the user has confirmed it.
400 *
401 * If the user doesn't explicitly cancel or accept, these files
402 * can accumulate in the temp directory.
403 *
404 * @param string $saveName - the destination filename
405 * @param string $tempName - the source temporary file to save
406 * @return string - full path the stashed file, or false on failure
407 * @access private
408 */
409 function saveTempUploadedFile( $saveName, $tempName ) {
410 global $wgOut;
411 $archive = wfImageArchiveDir( $saveName, 'temp' );
412 $stash = $archive . '/' . gmdate( "YmdHis" ) . '!' . $saveName;
413
414 $success = $this->mRemoveTempFile
415 ? rename( $tempName, $stash )
416 : move_uploaded_file( $tempName, $stash );
417 if ( !$success ) {
418 $wgOut->fileCopyError( $tempName, $stash );
419 return false;
420 }
421
422 return $stash;
423 }
424
425 /**
426 * Stash a file in a temporary directory for later processing,
427 * and save the necessary descriptive info into the session.
428 * Returns a key value which will be passed through a form
429 * to pick up the path info on a later invocation.
430 *
431 * @return int
432 * @access private
433 */
434 function stashSession() {
435 $stash = $this->saveTempUploadedFile(
436 $this->mUploadSaveName, $this->mUploadTempName );
437
438 if( !$stash ) {
439 # Couldn't save the file.
440 return false;
441 }
442
443 $key = mt_rand( 0, 0x7fffffff );
444 $_SESSION['wsUploadData'][$key] = array(
445 'mUploadTempName' => $stash,
446 'mUploadSize' => $this->mUploadSize,
447 'mOname' => $this->mOname );
448 return $key;
449 }
450
451 /**
452 * Remove a temporarily kept file stashed by saveTempUploadedFile().
453 * @access private
454 */
455 function unsaveUploadedFile() {
456 global $wgOut;
457 wfSuppressWarnings();
458 $success = unlink( $this->mUploadTempName );
459 wfRestoreWarnings();
460 if ( ! $success ) {
461 $wgOut->fileDeleteError( $this->mUploadTempName );
462 }
463 }
464
465 /* -------------------------------------------------------------- */
466
467 /**
468 * Show some text and linkage on successful upload.
469 * @access private
470 */
471 function showSuccess() {
472 global $wgUser, $wgOut, $wgContLang;
473
474 $sk = $wgUser->getSkin();
475 $ilink = $sk->makeMediaLink( $this->mUploadSaveName, Image::imageUrl( $this->mUploadSaveName ) );
476 $dname = $wgContLang->getNsText( NS_IMAGE ) . ':'.$this->mUploadSaveName;
477 $dlink = $sk->makeKnownLink( $dname, $dname );
478
479 $wgOut->addHTML( '<h2>' . wfMsgHtml( 'successfulupload' ) . "</h2>\n" );
480 $text = wfMsgWikiHtml( 'fileuploaded', $ilink, $dlink );
481 $wgOut->addHTML( $text );
482 $wgOut->returnToMain( false );
483 }
484
485 /**
486 * @param string $error as HTML
487 * @access private
488 */
489 function uploadError( $error ) {
490 global $wgOut;
491 $wgOut->addHTML( "<h2>" . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
492 $wgOut->addHTML( "<span class='error'>{$error}</span>\n" );
493 }
494
495 /**
496 * There's something wrong with this file, not enough to reject it
497 * totally but we require manual intervention to save it for real.
498 * Stash it away, then present a form asking to confirm or cancel.
499 *
500 * @param string $warning as HTML
501 * @access private
502 */
503 function uploadWarning( $warning ) {
504 global $wgOut;
505 global $wgUseCopyrightUpload;
506
507 $this->mSessionKey = $this->stashSession();
508 if( !$this->mSessionKey ) {
509 # Couldn't save file; an error has been displayed so let's go.
510 return;
511 }
512
513 $wgOut->addHTML( "<h2>" . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
514 $wgOut->addHTML( "<ul class='warning'>{$warning}</ul><br />\n" );
515
516 $save = wfMsgHtml( 'savefile' );
517 $reupload = wfMsgHtml( 'reupload' );
518 $iw = wfMsgWikiHtml( 'ignorewarning' );
519 $reup = wfMsgWikiHtml( 'reuploaddesc' );
520 $titleObj = Title::makeTitle( NS_SPECIAL, 'Upload' );
521 $action = $titleObj->escapeLocalURL( 'action=submit' );
522
523 if ( $wgUseCopyrightUpload )
524 {
525 $copyright = "
526 <input type='hidden' name='wpUploadCopyStatus' value=\"" . htmlspecialchars( $this->mUploadCopyStatus ) . "\" />
527 <input type='hidden' name='wpUploadSource' value=\"" . htmlspecialchars( $this->mUploadSource ) . "\" />
528 ";
529 } else {
530 $copyright = "";
531 }
532
533 $wgOut->addHTML( "
534 <form id='uploadwarning' method='post' enctype='multipart/form-data' action='$action'>
535 <input type='hidden' name='wpIgnoreWarning' value='1' />
536 <input type='hidden' name='wpSessionKey' value=\"" . htmlspecialchars( $this->mSessionKey ) . "\" />
537 <input type='hidden' name='wpUploadDescription' value=\"" . htmlspecialchars( $this->mUploadDescription ) . "\" />
538 <input type='hidden' name='wpLicense' value=\"" . htmlspecialchars( $this->mLicense ) . "\" />
539 <input type='hidden' name='wpDestFile' value=\"" . htmlspecialchars( $this->mDestFile ) . "\" />
540 <input type='hidden' name='wpWatchthis' value=\"" . htmlspecialchars( intval( $this->mWatchthis ) ) . "\" />
541 {$copyright}
542 <table border='0'>
543 <tr>
544 <tr>
545 <td align='right'>
546 <input tabindex='2' type='submit' name='wpUpload' value='$save' />
547 </td>
548 <td align='left'>$iw</td>
549 </tr>
550 <tr>
551 <td align='right'>
552 <input tabindex='2' type='submit' name='wpReUpload' value='{$reupload}' />
553 </td>
554 <td align='left'>$reup</td>
555 </tr>
556 </tr>
557 </table></form>\n" );
558 }
559
560 /**
561 * Displays the main upload form, optionally with a highlighted
562 * error message up at the top.
563 *
564 * @param string $msg as HTML
565 * @access private
566 */
567 function mainUploadForm( $msg='' ) {
568 global $wgOut, $wgUser;
569 global $wgUseCopyrightUpload;
570
571 $cols = intval($wgUser->getOption( 'cols' ));
572 $ew = $wgUser->getOption( 'editwidth' );
573 if ( $ew ) $ew = " style=\"width:100%\"";
574 else $ew = '';
575
576 if ( '' != $msg ) {
577 $sub = wfMsgHtml( 'uploaderror' );
578 $wgOut->addHTML( "<h2>{$sub}</h2>\n" .
579 "<span class='error'>{$msg}</span>\n" );
580 }
581 $wgOut->addHTML( '<div id="uploadtext">' );
582 $wgOut->addWikiText( wfMsg( 'uploadtext' ) );
583 $wgOut->addHTML( '</div>' );
584 $sk = $wgUser->getSkin();
585
586
587 $sourcefilename = wfMsgHtml( 'sourcefilename' );
588 $destfilename = wfMsgHtml( 'destfilename' );
589 $summary = wfMsgWikiHtml( 'fileuploadsummary' );
590
591 $licenses = new Licenses();
592 $license = wfMsgHtml( 'license' );
593 $nolicense = wfMsgHtml( 'nolicense' );
594 $licenseshtml = $licenses->getHtml();
595
596 $ulb = wfMsgHtml( 'uploadbtn' );
597
598
599 $titleObj = Title::makeTitle( NS_SPECIAL, 'Upload' );
600 $action = $titleObj->escapeLocalURL();
601
602 $encDestFile = htmlspecialchars( $this->mDestFile );
603
604 $watchChecked = $wgUser->getOption( 'watchdefault' )
605 ? 'checked="checked"'
606 : '';
607
608 $wgOut->addHTML( "
609 <form id='upload' method='post' enctype='multipart/form-data' action=\"$action\">
610 <table border='0'>
611 <tr>
612 <td align='right'><label for='wpUploadFile'>{$sourcefilename}:</label></td>
613 <td align='left'>
614 <input tabindex='1' type='file' name='wpUploadFile' id='wpUploadFile' " . ($this->mDestFile?"":"onchange='fillDestFilename()' ") . "size='40' />
615 </td>
616 </tr>
617 <tr>
618 <td align='right'><label for='wpDestFile'>{$destfilename}:</label></td>
619 <td align='left'>
620 <input tabindex='2' type='text' name='wpDestFile' id='wpDestFile' size='40' value=\"$encDestFile\" />
621 </td>
622 </tr>
623 <tr>
624 <td align='right'><label for='wpUploadDescription'>{$summary}</label></td>
625 <td align='left'>
626 <textarea tabindex='3' name='wpUploadDescription' id='wpUploadDescription' rows='6' cols='{$cols}'{$ew}>" . htmlspecialchars( $this->mUploadDescription ) . "</textarea>
627 </td>
628 </tr>
629 <tr>" );
630
631 if ( $licenseshtml != '' ) {
632 global $wgStylePath;
633 $wgOut->addHTML( "
634 <td align='right'><label for='wpLicense'>$license:</label></td>
635 <td align='left'>
636 <script type='text/javascript' src=\"$wgStylePath/common/upload.js\"></script>
637 <select name='wpLicense' id='wpLicense' tabindex='4'
638 onchange='licenseSelectorCheck()'>
639 <option value=''>$nolicense</option>
640 $licenseshtml
641 </select>
642 </td>
643 </tr>
644 <tr>
645 ");
646 }
647
648 if ( $wgUseCopyrightUpload ) {
649 $filestatus = wfMsgHtml ( 'filestatus' );
650 $copystatus = htmlspecialchars( $this->mUploadCopyStatus );
651 $filesource = wfMsgHtml ( 'filesource' );
652 $uploadsource = htmlspecialchars( $this->mUploadSource );
653
654 $wgOut->addHTML( "
655 <td align='right' nowrap='nowrap'><label for='wpUploadCopyStatus'>$filestatus:</label></td>
656 <td><input tabindex='5' type='text' name='wpUploadCopyStatus' id='wpUploadCopyStatus' value=\"$copystatus\" size='40' /></td>
657 </tr>
658 <tr>
659 <td align='right'><label for='wpUploadCopyStatus'>$filesource:</label></td>
660 <td><input tabindex='6' type='text' name='wpUploadSource' id='wpUploadCopyStatus' value=\"$uploadsource\" size='40' /></td>
661 </tr>
662 <tr>
663 ");
664 }
665
666
667 $wgOut->addHtml( "
668 <td></td>
669 <td>
670 <input tabindex='7' type='checkbox' name='wpWatchthis' id='wpWatchthis' $watchChecked value='true' />
671 <label for='wpWatchthis'>" . wfMsgHtml( 'watchthis' ) . "</label>
672 <input tabindex='8' type='checkbox' name='wpIgnoreWarning' id='wpIgnoreWarning' value='true' />
673 <label for='wpIgnoreWarning'>" . wfMsgHtml( 'ignorewarnings' ) . "</label>
674 </td>
675 </tr>
676 <tr>
677
678 </tr>
679 <tr>
680 <td></td>
681 <td align='left'><input tabindex='9' type='submit' name='wpUpload' value=\"{$ulb}\" /></td>
682 </tr>
683
684 <tr>
685 <td></td>
686 <td align='left'>
687 " );
688 $wgOut->addWikiText( wfMsgForContent( 'edittools' ) );
689 $wgOut->addHTML( "
690 </td>
691 </tr>
692
693 </table>
694 </form>" );
695 }
696
697 /* -------------------------------------------------------------- */
698
699 /**
700 * Split a file into a base name and all dot-delimited 'extensions'
701 * on the end. Some web server configurations will fall back to
702 * earlier pseudo-'extensions' to determine type and execute
703 * scripts, so the blacklist needs to check them all.
704 *
705 * @return array
706 */
707 function splitExtensions( $filename ) {
708 $bits = explode( '.', $filename );
709 $basename = array_shift( $bits );
710 return array( $basename, $bits );
711 }
712
713 /**
714 * Perform case-insensitive match against a list of file extensions.
715 * Returns true if the extension is in the list.
716 *
717 * @param string $ext
718 * @param array $list
719 * @return bool
720 */
721 function checkFileExtension( $ext, $list ) {
722 return in_array( strtolower( $ext ), $list );
723 }
724
725 /**
726 * Perform case-insensitive match against a list of file extensions.
727 * Returns true if any of the extensions are in the list.
728 *
729 * @param array $ext
730 * @param array $list
731 * @return bool
732 */
733 function checkFileExtensionList( $ext, $list ) {
734 foreach( $ext as $e ) {
735 if( in_array( strtolower( $e ), $list ) ) {
736 return true;
737 }
738 }
739 return false;
740 }
741
742 /**
743 * Verifies that it's ok to include the uploaded file
744 *
745 * @param string $tmpfile the full path of the temporary file to verify
746 * @param string $extension The filename extension that the file is to be served with
747 * @return mixed true of the file is verified, a WikiError object otherwise.
748 */
749 function verify( $tmpfile, $extension ) {
750 #magically determine mime type
751 $magic=& wfGetMimeMagic();
752 $mime= $magic->guessMimeType($tmpfile,false);
753
754 $fname= "SpecialUpload::verify";
755
756 #check mime type, if desired
757 global $wgVerifyMimeType;
758 if ($wgVerifyMimeType) {
759
760 #check mime type against file extension
761 if( !$this->verifyExtension( $mime, $extension ) ) {
762 return new WikiErrorMsg( 'uploadcorrupt' );
763 }
764
765 #check mime type blacklist
766 global $wgMimeTypeBlacklist;
767 if( isset($wgMimeTypeBlacklist) && !is_null($wgMimeTypeBlacklist)
768 && $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
769 return new WikiErrorMsg( 'badfiletype', htmlspecialchars( $mime ) );
770 }
771 }
772
773 #check for htmlish code and javascript
774 if( $this->detectScript ( $tmpfile, $mime ) ) {
775 return new WikiErrorMsg( 'uploadscripted' );
776 }
777
778 /**
779 * Scan the uploaded file for viruses
780 */
781 $virus= $this->detectVirus($tmpfile);
782 if ( $virus ) {
783 return new WikiErrorMsg( 'uploadvirus', htmlspecialchars($virus) );
784 }
785
786 wfDebug( "$fname: all clear; passing.\n" );
787 return true;
788 }
789
790 /**
791 * Checks if the mime type of the uploaded file matches the file extension.
792 *
793 * @param string $mime the mime type of the uploaded file
794 * @param string $extension The filename extension that the file is to be served with
795 * @return bool
796 */
797 function verifyExtension( $mime, $extension ) {
798 $fname = 'SpecialUpload::verifyExtension';
799
800 $magic =& wfGetMimeMagic();
801
802 if ( ! $mime || $mime == 'unknown' || $mime == 'unknown/unknown' )
803 if ( ! $magic->isRecognizableExtension( $extension ) ) {
804 wfDebug( "$fname: passing file with unknown detected mime type; unrecognized extension '$extension', can't verify\n" );
805 return true;
806 } else {
807 wfDebug( "$fname: rejecting file with unknown detected mime type; recognized extension '$extension', so probably invalid file\n" );
808 return false;
809 }
810
811 $match= $magic->isMatchingExtension($extension,$mime);
812
813 if ($match===NULL) {
814 wfDebug( "$fname: no file extension known for mime type $mime, passing file\n" );
815 return true;
816 } elseif ($match===true) {
817 wfDebug( "$fname: mime type $mime matches extension $extension, passing file\n" );
818
819 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
820 return true;
821
822 } else {
823 wfDebug( "$fname: mime type $mime mismatches file extension $extension, rejecting file\n" );
824 return false;
825 }
826 }
827
828 /** Heuristig for detecting files that *could* contain JavaScript instructions or
829 * things that may look like HTML to a browser and are thus
830 * potentially harmful. The present implementation will produce false positives in some situations.
831 *
832 * @param string $file Pathname to the temporary upload file
833 * @param string $mime The mime type of the file
834 * @return bool true if the file contains something looking like embedded scripts
835 */
836 function detectScript($file,$mime) {
837
838 #ugly hack: for text files, always look at the entire file.
839 #For binarie field, just check the first K.
840
841 if (strpos($mime,'text/')===0) $chunk = file_get_contents( $file );
842 else {
843 $fp = fopen( $file, 'rb' );
844 $chunk = fread( $fp, 1024 );
845 fclose( $fp );
846 }
847
848 $chunk= strtolower( $chunk );
849
850 if (!$chunk) return false;
851
852 #decode from UTF-16 if needed (could be used for obfuscation).
853 if (substr($chunk,0,2)=="\xfe\xff") $enc= "UTF-16BE";
854 elseif (substr($chunk,0,2)=="\xff\xfe") $enc= "UTF-16LE";
855 else $enc= NULL;
856
857 if ($enc) $chunk= iconv($enc,"ASCII//IGNORE",$chunk);
858
859 $chunk= trim($chunk);
860
861 #FIXME: convert from UTF-16 if necessarry!
862
863 wfDebug("SpecialUpload::detectScript: checking for embedded scripts and HTML stuff\n");
864
865 #check for HTML doctype
866 if (eregi("<!DOCTYPE *X?HTML",$chunk)) return true;
867
868 /**
869 * Internet Explorer for Windows performs some really stupid file type
870 * autodetection which can cause it to interpret valid image files as HTML
871 * and potentially execute JavaScript, creating a cross-site scripting
872 * attack vectors.
873 *
874 * Apple's Safari browser also performs some unsafe file type autodetection
875 * which can cause legitimate files to be interpreted as HTML if the
876 * web server is not correctly configured to send the right content-type
877 * (or if you're really uploading plain text and octet streams!)
878 *
879 * Returns true if IE is likely to mistake the given file for HTML.
880 * Also returns true if Safari would mistake the given file for HTML
881 * when served with a generic content-type.
882 */
883
884 $tags = array(
885 '<body',
886 '<head',
887 '<html', #also in safari
888 '<img',
889 '<pre',
890 '<script', #also in safari
891 '<table',
892 '<title' #also in safari
893 );
894
895 foreach( $tags as $tag ) {
896 if( false !== strpos( $chunk, $tag ) ) {
897 return true;
898 }
899 }
900
901 /*
902 * look for javascript
903 */
904
905 #resolve entity-refs to look at attributes. may be harsh on big files... cache result?
906 $chunk = Sanitizer::decodeCharReferences( $chunk );
907
908 #look for script-types
909 if (preg_match("!type\s*=\s*['\"]?\s*(\w*/)?(ecma|java)!sim",$chunk)) return true;
910
911 #look for html-style script-urls
912 if (preg_match("!(href|src|data)\s*=\s*['\"]?\s*(ecma|java)script:!sim",$chunk)) return true;
913
914 #look for css-style script-urls
915 if (preg_match("!url\s*\(\s*['\"]?\s*(ecma|java)script:!sim",$chunk)) return true;
916
917 wfDebug("SpecialUpload::detectScript: no scripts found\n");
918 return false;
919 }
920
921 /** Generic wrapper function for a virus scanner program.
922 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
923 * $wgAntivirusRequired may be used to deny upload if the scan fails.
924 *
925 * @param string $file Pathname to the temporary upload file
926 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
927 * or a string containing feedback from the virus scanner if a virus was found.
928 * If textual feedback is missing but a virus was found, this function returns true.
929 */
930 function detectVirus($file) {
931 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
932
933 $fname= "SpecialUpload::detectVirus";
934
935 if (!$wgAntivirus) { #disabled?
936 wfDebug("$fname: virus scanner disabled\n");
937
938 return NULL;
939 }
940
941 if (!$wgAntivirusSetup[$wgAntivirus]) {
942 wfDebug("$fname: unknown virus scanner: $wgAntivirus\n");
943
944 $wgOut->addHTML( "<div class='error'>Bad configuration: unknown virus scanner: <i>$wgAntivirus</i></div>\n" ); #LOCALIZE
945
946 return "unknown antivirus: $wgAntivirus";
947 }
948
949 #look up scanner configuration
950 $virus_scanner= $wgAntivirusSetup[$wgAntivirus]["command"]; #command pattern
951 $virus_scanner_codes= $wgAntivirusSetup[$wgAntivirus]["codemap"]; #exit-code map
952 $msg_pattern= $wgAntivirusSetup[$wgAntivirus]["messagepattern"]; #message pattern
953
954 $scanner= $virus_scanner; #copy, so we can resolve the pattern
955
956 if (strpos($scanner,"%f")===false) $scanner.= " ".wfEscapeShellArg($file); #simple pattern: append file to scan
957 else $scanner= str_replace("%f",wfEscapeShellArg($file),$scanner); #complex pattern: replace "%f" with file to scan
958
959 wfDebug("$fname: running virus scan: $scanner \n");
960
961 #execute virus scanner
962 $code= false;
963
964 #NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
965 # that does not seem to be worth the pain.
966 # Ask me (Duesentrieb) about it if it's ever needed.
967 if (wfIsWindows()) exec("$scanner",$output,$code);
968 else exec("$scanner 2>&1",$output,$code);
969
970 $exit_code= $code; #remeber for user feedback
971
972 if ($virus_scanner_codes) { #map exit code to AV_xxx constants.
973 if (isset($virus_scanner_codes[$code])) $code= $virus_scanner_codes[$code]; #explicite mapping
974 else if (isset($virus_scanner_codes["*"])) $code= $virus_scanner_codes["*"]; #fallback mapping
975 }
976
977 if ($code===AV_SCAN_FAILED) { #scan failed (code was mapped to false by $virus_scanner_codes)
978 wfDebug("$fname: failed to scan $file (code $exit_code).\n");
979
980 if ($wgAntivirusRequired) return "scan failed (code $exit_code)";
981 else return NULL;
982 }
983 else if ($code===AV_SCAN_ABORTED) { #scan failed because filetype is unknown (probably imune)
984 wfDebug("$fname: unsupported file type $file (code $exit_code).\n");
985 return NULL;
986 }
987 else if ($code===AV_NO_VIRUS) {
988 wfDebug("$fname: file passed virus scan.\n");
989 return false; #no virus found
990 }
991 else {
992 $output= join("\n",$output);
993 $output= trim($output);
994
995 if (!$output) $output= true; #if ther's no output, return true
996 else if ($msg_pattern) {
997 $groups= array();
998 if (preg_match($msg_pattern,$output,$groups)) {
999 if ($groups[1]) $output= $groups[1];
1000 }
1001 }
1002
1003 wfDebug("$fname: FOUND VIRUS! scanner feedback: $output");
1004 return $output;
1005 }
1006 }
1007
1008 /**
1009 * Check if the temporary file is MacBinary-encoded, as some uploads
1010 * from Internet Explorer on Mac OS Classic and Mac OS X will be.
1011 * If so, the data fork will be extracted to a second temporary file,
1012 * which will then be checked for validity and either kept or discarded.
1013 *
1014 * @access private
1015 */
1016 function checkMacBinary() {
1017 $macbin = new MacBinary( $this->mUploadTempName );
1018 if( $macbin->isValid() ) {
1019 $dataFile = tempnam( wfTempDir(), "WikiMacBinary" );
1020 $dataHandle = fopen( $dataFile, 'wb' );
1021
1022 wfDebug( "SpecialUpload::checkMacBinary: Extracting MacBinary data fork to $dataFile\n" );
1023 $macbin->extractData( $dataHandle );
1024
1025 $this->mUploadTempName = $dataFile;
1026 $this->mUploadSize = $macbin->dataForkLength();
1027
1028 // We'll have to manually remove the new file if it's not kept.
1029 $this->mRemoveTempFile = true;
1030 }
1031 $macbin->close();
1032 }
1033
1034 /**
1035 * If we've modified the upload file we need to manually remove it
1036 * on exit to clean up.
1037 * @access private
1038 */
1039 function cleanupTempFile() {
1040 if( $this->mRemoveTempFile && file_exists( $this->mUploadTempName ) ) {
1041 wfDebug( "SpecialUpload::cleanupTempFile: Removing temporary file $this->mUploadTempName\n" );
1042 unlink( $this->mUploadTempName );
1043 }
1044 }
1045
1046 /**
1047 * Check if there's an overwrite conflict and, if so, if restrictions
1048 * forbid this user from performing the upload.
1049 *
1050 * @return mixed true on success, WikiError on failure
1051 * @access private
1052 */
1053 function checkOverwrite( $name ) {
1054 $img = Image::newFromName( $name );
1055 if( is_null( $img ) ) {
1056 // Uh... this shouldn't happen ;)
1057 // But if it does, fall through to previous behavior
1058 return false;
1059 }
1060
1061 $error = '';
1062 if( $img->exists() ) {
1063 global $wgUser, $wgOut;
1064 if( $img->isLocal() ) {
1065 if( !$wgUser->isAllowed( 'reupload' ) ) {
1066 $error = 'fileexists-forbidden';
1067 }
1068 } else {
1069 if( !$wgUser->isAllowed( 'reupload' ) ||
1070 !$wgUser->isAllowed( 'reupload-shared' ) ) {
1071 $error = "fileexists-shared-forbidden";
1072 }
1073 }
1074 }
1075
1076 if( $error ) {
1077 $errorText = wfMsg( $error, wfEscapeWikiText( $img->getName() ) );
1078 return new WikiError( $wgOut->parse( $errorText ) );
1079 }
1080
1081 // Rockin', go ahead and upload
1082 return true;
1083 }
1084
1085 }
1086 ?>