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