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