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