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