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