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