(bug 5127) Auto edit summary when creating redirect page
[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
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->fileNotFoundError( $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->fileRenameError( $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->fileCopyError( $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->fileCopyError( $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 */
466 function unsaveUploadedFile() {
467 global $wgOut;
468 wfSuppressWarnings();
469 $success = unlink( $this->mUploadTempName );
470 wfRestoreWarnings();
471 if ( ! $success ) {
472 $wgOut->fileDeleteError( $this->mUploadTempName );
473 }
474 }
475
476 /* -------------------------------------------------------------- */
477
478 /**
479 * Show some text and linkage on successful upload.
480 * @access private
481 */
482 function showSuccess() {
483 global $wgUser, $wgOut, $wgContLang;
484
485 $sk = $wgUser->getSkin();
486 $ilink = $sk->makeMediaLink( $this->mUploadSaveName, Image::imageUrl( $this->mUploadSaveName ) );
487 $dname = $wgContLang->getNsText( NS_IMAGE ) . ':'.$this->mUploadSaveName;
488 $dlink = $sk->makeKnownLink( $dname, $dname );
489
490 $wgOut->addHTML( '<h2>' . wfMsgHtml( 'successfulupload' ) . "</h2>\n" );
491 $text = wfMsgWikiHtml( 'fileuploaded', $ilink, $dlink );
492 $wgOut->addHTML( $text );
493 $wgOut->returnToMain( false );
494 }
495
496 /**
497 * @param string $error as HTML
498 * @access private
499 */
500 function uploadError( $error ) {
501 global $wgOut;
502 $wgOut->addHTML( "<h2>" . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
503 $wgOut->addHTML( "<span class='error'>{$error}</span>\n" );
504 }
505
506 /**
507 * There's something wrong with this file, not enough to reject it
508 * totally but we require manual intervention to save it for real.
509 * Stash it away, then present a form asking to confirm or cancel.
510 *
511 * @param string $warning as HTML
512 * @access private
513 */
514 function uploadWarning( $warning ) {
515 global $wgOut;
516 global $wgUseCopyrightUpload;
517
518 $this->mSessionKey = $this->stashSession();
519 if( !$this->mSessionKey ) {
520 # Couldn't save file; an error has been displayed so let's go.
521 return;
522 }
523
524 $wgOut->addHTML( "<h2>" . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
525 $wgOut->addHTML( "<ul class='warning'>{$warning}</ul><br />\n" );
526
527 $save = wfMsgHtml( 'savefile' );
528 $reupload = wfMsgHtml( 'reupload' );
529 $iw = wfMsgWikiHtml( 'ignorewarning' );
530 $reup = wfMsgWikiHtml( 'reuploaddesc' );
531 $titleObj = Title::makeTitle( NS_SPECIAL, 'Upload' );
532 $action = $titleObj->escapeLocalURL( 'action=submit' );
533
534 if ( $wgUseCopyrightUpload )
535 {
536 $copyright = "
537 <input type='hidden' name='wpUploadCopyStatus' value=\"" . htmlspecialchars( $this->mUploadCopyStatus ) . "\" />
538 <input type='hidden' name='wpUploadSource' value=\"" . htmlspecialchars( $this->mUploadSource ) . "\" />
539 ";
540 } else {
541 $copyright = "";
542 }
543
544 $wgOut->addHTML( "
545 <form id='uploadwarning' method='post' enctype='multipart/form-data' action='$action'>
546 <input type='hidden' name='wpIgnoreWarning' value='1' />
547 <input type='hidden' name='wpSessionKey' value=\"" . htmlspecialchars( $this->mSessionKey ) . "\" />
548 <input type='hidden' name='wpUploadDescription' value=\"" . htmlspecialchars( $this->mUploadDescription ) . "\" />
549 <input type='hidden' name='wpLicense' value=\"" . htmlspecialchars( $this->mLicense ) . "\" />
550 <input type='hidden' name='wpDestFile' value=\"" . htmlspecialchars( $this->mDestFile ) . "\" />
551 <input type='hidden' name='wpWatchthis' value=\"" . htmlspecialchars( intval( $this->mWatchthis ) ) . "\" />
552 {$copyright}
553 <table border='0'>
554 <tr>
555 <tr>
556 <td align='right'>
557 <input tabindex='2' type='submit' name='wpUpload' value=\"$save\" />
558 </td>
559 <td align='left'>$iw</td>
560 </tr>
561 <tr>
562 <td align='right'>
563 <input tabindex='2' type='submit' name='wpReUpload' value=\"{$reupload}\" />
564 </td>
565 <td align='left'>$reup</td>
566 </tr>
567 </tr>
568 </table></form>\n" );
569 }
570
571 /**
572 * Displays the main upload form, optionally with a highlighted
573 * error message up at the top.
574 *
575 * @param string $msg as HTML
576 * @access private
577 */
578 function mainUploadForm( $msg='' ) {
579 global $wgOut, $wgUser;
580 global $wgUseCopyrightUpload;
581
582 $cols = intval($wgUser->getOption( 'cols' ));
583 $ew = $wgUser->getOption( 'editwidth' );
584 if ( $ew ) $ew = " style=\"width:100%\"";
585 else $ew = '';
586
587 if ( '' != $msg ) {
588 $sub = wfMsgHtml( 'uploaderror' );
589 $wgOut->addHTML( "<h2>{$sub}</h2>\n" .
590 "<span class='error'>{$msg}</span>\n" );
591 }
592 $wgOut->addHTML( '<div id="uploadtext">' );
593 $wgOut->addWikiText( wfMsg( 'uploadtext' ) );
594 $wgOut->addHTML( '</div>' );
595 $sk = $wgUser->getSkin();
596
597
598 $sourcefilename = wfMsgHtml( 'sourcefilename' );
599 $destfilename = wfMsgHtml( 'destfilename' );
600 $summary = wfMsgWikiHtml( 'fileuploadsummary' );
601
602 $licenses = new Licenses();
603 $license = wfMsgHtml( 'license' );
604 $nolicense = wfMsgHtml( 'nolicense' );
605 $licenseshtml = $licenses->getHtml();
606
607 $ulb = wfMsgHtml( 'uploadbtn' );
608
609
610 $titleObj = Title::makeTitle( NS_SPECIAL, 'Upload' );
611 $action = $titleObj->escapeLocalURL();
612
613 $encDestFile = htmlspecialchars( $this->mDestFile );
614
615 $watchChecked = $wgUser->getOption( 'watchdefault' )
616 ? 'checked="checked"'
617 : '';
618
619 $wgOut->addHTML( "
620 <form id='upload' method='post' enctype='multipart/form-data' action=\"$action\">
621 <table border='0'>
622 <tr>
623 <td align='right'><label for='wpUploadFile'>{$sourcefilename}:</label></td>
624 <td align='left'>
625 <input tabindex='1' type='file' name='wpUploadFile' id='wpUploadFile' " . ($this->mDestFile?"":"onchange='fillDestFilename()' ") . "size='40' />
626 </td>
627 </tr>
628 <tr>
629 <td align='right'><label for='wpDestFile'>{$destfilename}:</label></td>
630 <td align='left'>
631 <input tabindex='2' type='text' name='wpDestFile' id='wpDestFile' size='40' value=\"$encDestFile\" />
632 </td>
633 </tr>
634 <tr>
635 <td align='right'><label for='wpUploadDescription'>{$summary}</label></td>
636 <td align='left'>
637 <textarea tabindex='3' name='wpUploadDescription' id='wpUploadDescription' rows='6' cols='{$cols}'{$ew}>" . htmlspecialchars( $this->mUploadDescription ) . "</textarea>
638 </td>
639 </tr>
640 <tr>" );
641
642 if ( $licenseshtml != '' ) {
643 global $wgStylePath;
644 $wgOut->addHTML( "
645 <td align='right'><label for='wpLicense'>$license:</label></td>
646 <td align='left'>
647 <script type='text/javascript' src=\"$wgStylePath/common/upload.js\"></script>
648 <select name='wpLicense' id='wpLicense' tabindex='4'
649 onchange='licenseSelectorCheck()'>
650 <option value=''>$nolicense</option>
651 $licenseshtml
652 </select>
653 </td>
654 </tr>
655 <tr>
656 ");
657 }
658
659 if ( $wgUseCopyrightUpload ) {
660 $filestatus = wfMsgHtml ( 'filestatus' );
661 $copystatus = htmlspecialchars( $this->mUploadCopyStatus );
662 $filesource = wfMsgHtml ( 'filesource' );
663 $uploadsource = htmlspecialchars( $this->mUploadSource );
664
665 $wgOut->addHTML( "
666 <td align='right' nowrap='nowrap'><label for='wpUploadCopyStatus'>$filestatus:</label></td>
667 <td><input tabindex='5' type='text' name='wpUploadCopyStatus' id='wpUploadCopyStatus' value=\"$copystatus\" size='40' /></td>
668 </tr>
669 <tr>
670 <td align='right'><label for='wpUploadCopyStatus'>$filesource:</label></td>
671 <td><input tabindex='6' type='text' name='wpUploadSource' id='wpUploadCopyStatus' value=\"$uploadsource\" size='40' /></td>
672 </tr>
673 <tr>
674 ");
675 }
676
677
678 $wgOut->addHtml( "
679 <td></td>
680 <td>
681 <input tabindex='7' type='checkbox' name='wpWatchthis' id='wpWatchthis' $watchChecked value='true' />
682 <label for='wpWatchthis'>" . wfMsgHtml( 'watchthis' ) . "</label>
683 <input tabindex='8' type='checkbox' name='wpIgnoreWarning' id='wpIgnoreWarning' value='true' />
684 <label for='wpIgnoreWarning'>" . wfMsgHtml( 'ignorewarnings' ) . "</label>
685 </td>
686 </tr>
687 <tr>
688
689 </tr>
690 <tr>
691 <td></td>
692 <td align='left'><input tabindex='9' type='submit' name='wpUpload' value=\"{$ulb}\" /></td>
693 </tr>
694
695 <tr>
696 <td></td>
697 <td align='left'>
698 " );
699 $wgOut->addWikiText( wfMsgForContent( 'edittools' ) );
700 $wgOut->addHTML( "
701 </td>
702 </tr>
703
704 </table>
705 </form>" );
706 }
707
708 /* -------------------------------------------------------------- */
709
710 /**
711 * Split a file into a base name and all dot-delimited 'extensions'
712 * on the end. Some web server configurations will fall back to
713 * earlier pseudo-'extensions' to determine type and execute
714 * scripts, so the blacklist needs to check them all.
715 *
716 * @return array
717 */
718 function splitExtensions( $filename ) {
719 $bits = explode( '.', $filename );
720 $basename = array_shift( $bits );
721 return array( $basename, $bits );
722 }
723
724 /**
725 * Perform case-insensitive match against a list of file extensions.
726 * Returns true if the extension is in the list.
727 *
728 * @param string $ext
729 * @param array $list
730 * @return bool
731 */
732 function checkFileExtension( $ext, $list ) {
733 return in_array( strtolower( $ext ), $list );
734 }
735
736 /**
737 * Perform case-insensitive match against a list of file extensions.
738 * Returns true if any of the extensions are in the list.
739 *
740 * @param array $ext
741 * @param array $list
742 * @return bool
743 */
744 function checkFileExtensionList( $ext, $list ) {
745 foreach( $ext as $e ) {
746 if( in_array( strtolower( $e ), $list ) ) {
747 return true;
748 }
749 }
750 return false;
751 }
752
753 /**
754 * Verifies that it's ok to include the uploaded file
755 *
756 * @param string $tmpfile the full path of the temporary file to verify
757 * @param string $extension The filename extension that the file is to be served with
758 * @return mixed true of the file is verified, a WikiError object otherwise.
759 */
760 function verify( $tmpfile, $extension ) {
761 #magically determine mime type
762 $magic=& wfGetMimeMagic();
763 $mime= $magic->guessMimeType($tmpfile,false);
764
765 $fname= "SpecialUpload::verify";
766
767 #check mime type, if desired
768 global $wgVerifyMimeType;
769 if ($wgVerifyMimeType) {
770
771 #check mime type against file extension
772 if( !$this->verifyExtension( $mime, $extension ) ) {
773 return new WikiErrorMsg( 'uploadcorrupt' );
774 }
775
776 #check mime type blacklist
777 global $wgMimeTypeBlacklist;
778 if( isset($wgMimeTypeBlacklist) && !is_null($wgMimeTypeBlacklist)
779 && $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
780 return new WikiErrorMsg( 'badfiletype', htmlspecialchars( $mime ) );
781 }
782 }
783
784 #check for htmlish code and javascript
785 if( $this->detectScript ( $tmpfile, $mime, $extension ) ) {
786 return new WikiErrorMsg( 'uploadscripted' );
787 }
788
789 /**
790 * Scan the uploaded file for viruses
791 */
792 $virus= $this->detectVirus($tmpfile);
793 if ( $virus ) {
794 return new WikiErrorMsg( 'uploadvirus', htmlspecialchars($virus) );
795 }
796
797 wfDebug( "$fname: all clear; passing.\n" );
798 return true;
799 }
800
801 /**
802 * Checks if the mime type of the uploaded file matches the file extension.
803 *
804 * @param string $mime the mime type of the uploaded file
805 * @param string $extension The filename extension that the file is to be served with
806 * @return bool
807 */
808 function verifyExtension( $mime, $extension ) {
809 $fname = 'SpecialUpload::verifyExtension';
810
811 $magic =& wfGetMimeMagic();
812
813 if ( ! $mime || $mime == 'unknown' || $mime == 'unknown/unknown' )
814 if ( ! $magic->isRecognizableExtension( $extension ) ) {
815 wfDebug( "$fname: passing file with unknown detected mime type; unrecognized extension '$extension', can't verify\n" );
816 return true;
817 } else {
818 wfDebug( "$fname: rejecting file with unknown detected mime type; recognized extension '$extension', so probably invalid file\n" );
819 return false;
820 }
821
822 $match= $magic->isMatchingExtension($extension,$mime);
823
824 if ($match===NULL) {
825 wfDebug( "$fname: no file extension known for mime type $mime, passing file\n" );
826 return true;
827 } elseif ($match===true) {
828 wfDebug( "$fname: mime type $mime matches extension $extension, passing file\n" );
829
830 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
831 return true;
832
833 } else {
834 wfDebug( "$fname: mime type $mime mismatches file extension $extension, rejecting file\n" );
835 return false;
836 }
837 }
838
839 /** Heuristig for detecting files that *could* contain JavaScript instructions or
840 * things that may look like HTML to a browser and are thus
841 * potentially harmful. The present implementation will produce false positives in some situations.
842 *
843 * @param string $file Pathname to the temporary upload file
844 * @param string $mime The mime type of the file
845 * @param string $extension The extension of the file
846 * @return bool true if the file contains something looking like embedded scripts
847 */
848 function detectScript($file, $mime, $extension) {
849 global $wgAllowTitlesInSVG;
850
851 #ugly hack: for text files, always look at the entire file.
852 #For binarie field, just check the first K.
853
854 if (strpos($mime,'text/')===0) $chunk = file_get_contents( $file );
855 else {
856 $fp = fopen( $file, 'rb' );
857 $chunk = fread( $fp, 1024 );
858 fclose( $fp );
859 }
860
861 $chunk= strtolower( $chunk );
862
863 if (!$chunk) return false;
864
865 #decode from UTF-16 if needed (could be used for obfuscation).
866 if (substr($chunk,0,2)=="\xfe\xff") $enc= "UTF-16BE";
867 elseif (substr($chunk,0,2)=="\xff\xfe") $enc= "UTF-16LE";
868 else $enc= NULL;
869
870 if ($enc) $chunk= iconv($enc,"ASCII//IGNORE",$chunk);
871
872 $chunk= trim($chunk);
873
874 #FIXME: convert from UTF-16 if necessarry!
875
876 wfDebug("SpecialUpload::detectScript: checking for embedded scripts and HTML stuff\n");
877
878 #check for HTML doctype
879 if (eregi("<!DOCTYPE *X?HTML",$chunk)) return true;
880
881 /**
882 * Internet Explorer for Windows performs some really stupid file type
883 * autodetection which can cause it to interpret valid image files as HTML
884 * and potentially execute JavaScript, creating a cross-site scripting
885 * attack vectors.
886 *
887 * Apple's Safari browser also performs some unsafe file type autodetection
888 * which can cause legitimate files to be interpreted as HTML if the
889 * web server is not correctly configured to send the right content-type
890 * (or if you're really uploading plain text and octet streams!)
891 *
892 * Returns true if IE is likely to mistake the given file for HTML.
893 * Also returns true if Safari would mistake the given file for HTML
894 * when served with a generic content-type.
895 */
896
897 $tags = array(
898 '<body',
899 '<head',
900 '<html', #also in safari
901 '<img',
902 '<pre',
903 '<script', #also in safari
904 '<table'
905 );
906 if( ! $wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
907 $tags[] = '<title';
908 }
909
910 foreach( $tags as $tag ) {
911 if( false !== strpos( $chunk, $tag ) ) {
912 return true;
913 }
914 }
915
916 /*
917 * look for javascript
918 */
919
920 #resolve entity-refs to look at attributes. may be harsh on big files... cache result?
921 $chunk = Sanitizer::decodeCharReferences( $chunk );
922
923 #look for script-types
924 if (preg_match("!type\s*=\s*['\"]?\s*(\w*/)?(ecma|java)!sim",$chunk)) return true;
925
926 #look for html-style script-urls
927 if (preg_match("!(href|src|data)\s*=\s*['\"]?\s*(ecma|java)script:!sim",$chunk)) return true;
928
929 #look for css-style script-urls
930 if (preg_match("!url\s*\(\s*['\"]?\s*(ecma|java)script:!sim",$chunk)) return true;
931
932 wfDebug("SpecialUpload::detectScript: no scripts found\n");
933 return false;
934 }
935
936 /** Generic wrapper function for a virus scanner program.
937 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
938 * $wgAntivirusRequired may be used to deny upload if the scan fails.
939 *
940 * @param string $file Pathname to the temporary upload file
941 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
942 * or a string containing feedback from the virus scanner if a virus was found.
943 * If textual feedback is missing but a virus was found, this function returns true.
944 */
945 function detectVirus($file) {
946 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
947
948 $fname= "SpecialUpload::detectVirus";
949
950 if (!$wgAntivirus) { #disabled?
951 wfDebug("$fname: virus scanner disabled\n");
952
953 return NULL;
954 }
955
956 if (!$wgAntivirusSetup[$wgAntivirus]) {
957 wfDebug("$fname: unknown virus scanner: $wgAntivirus\n");
958
959 $wgOut->addHTML( "<div class='error'>Bad configuration: unknown virus scanner: <i>$wgAntivirus</i></div>\n" ); #LOCALIZE
960
961 return "unknown antivirus: $wgAntivirus";
962 }
963
964 #look up scanner configuration
965 $virus_scanner= $wgAntivirusSetup[$wgAntivirus]["command"]; #command pattern
966 $virus_scanner_codes= $wgAntivirusSetup[$wgAntivirus]["codemap"]; #exit-code map
967 $msg_pattern= $wgAntivirusSetup[$wgAntivirus]["messagepattern"]; #message pattern
968
969 $scanner= $virus_scanner; #copy, so we can resolve the pattern
970
971 if (strpos($scanner,"%f")===false) $scanner.= " ".wfEscapeShellArg($file); #simple pattern: append file to scan
972 else $scanner= str_replace("%f",wfEscapeShellArg($file),$scanner); #complex pattern: replace "%f" with file to scan
973
974 wfDebug("$fname: running virus scan: $scanner \n");
975
976 #execute virus scanner
977 $code= false;
978
979 #NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
980 # that does not seem to be worth the pain.
981 # Ask me (Duesentrieb) about it if it's ever needed.
982 if (wfIsWindows()) exec("$scanner",$output,$code);
983 else exec("$scanner 2>&1",$output,$code);
984
985 $exit_code= $code; #remeber for user feedback
986
987 if ($virus_scanner_codes) { #map exit code to AV_xxx constants.
988 if (isset($virus_scanner_codes[$code])) $code= $virus_scanner_codes[$code]; #explicite mapping
989 else if (isset($virus_scanner_codes["*"])) $code= $virus_scanner_codes["*"]; #fallback mapping
990 }
991
992 if ($code===AV_SCAN_FAILED) { #scan failed (code was mapped to false by $virus_scanner_codes)
993 wfDebug("$fname: failed to scan $file (code $exit_code).\n");
994
995 if ($wgAntivirusRequired) return "scan failed (code $exit_code)";
996 else return NULL;
997 }
998 else if ($code===AV_SCAN_ABORTED) { #scan failed because filetype is unknown (probably imune)
999 wfDebug("$fname: unsupported file type $file (code $exit_code).\n");
1000 return NULL;
1001 }
1002 else if ($code===AV_NO_VIRUS) {
1003 wfDebug("$fname: file passed virus scan.\n");
1004 return false; #no virus found
1005 }
1006 else {
1007 $output= join("\n",$output);
1008 $output= trim($output);
1009
1010 if (!$output) $output= true; #if ther's no output, return true
1011 else if ($msg_pattern) {
1012 $groups= array();
1013 if (preg_match($msg_pattern,$output,$groups)) {
1014 if ($groups[1]) $output= $groups[1];
1015 }
1016 }
1017
1018 wfDebug("$fname: FOUND VIRUS! scanner feedback: $output");
1019 return $output;
1020 }
1021 }
1022
1023 /**
1024 * Check if the temporary file is MacBinary-encoded, as some uploads
1025 * from Internet Explorer on Mac OS Classic and Mac OS X will be.
1026 * If so, the data fork will be extracted to a second temporary file,
1027 * which will then be checked for validity and either kept or discarded.
1028 *
1029 * @access private
1030 */
1031 function checkMacBinary() {
1032 $macbin = new MacBinary( $this->mUploadTempName );
1033 if( $macbin->isValid() ) {
1034 $dataFile = tempnam( wfTempDir(), "WikiMacBinary" );
1035 $dataHandle = fopen( $dataFile, 'wb' );
1036
1037 wfDebug( "SpecialUpload::checkMacBinary: Extracting MacBinary data fork to $dataFile\n" );
1038 $macbin->extractData( $dataHandle );
1039
1040 $this->mUploadTempName = $dataFile;
1041 $this->mUploadSize = $macbin->dataForkLength();
1042
1043 // We'll have to manually remove the new file if it's not kept.
1044 $this->mRemoveTempFile = true;
1045 }
1046 $macbin->close();
1047 }
1048
1049 /**
1050 * If we've modified the upload file we need to manually remove it
1051 * on exit to clean up.
1052 * @access private
1053 */
1054 function cleanupTempFile() {
1055 if( $this->mRemoveTempFile && file_exists( $this->mUploadTempName ) ) {
1056 wfDebug( "SpecialUpload::cleanupTempFile: Removing temporary file $this->mUploadTempName\n" );
1057 unlink( $this->mUploadTempName );
1058 }
1059 }
1060
1061 /**
1062 * Check if there's an overwrite conflict and, if so, if restrictions
1063 * forbid this user from performing the upload.
1064 *
1065 * @return mixed true on success, WikiError on failure
1066 * @access private
1067 */
1068 function checkOverwrite( $name ) {
1069 $img = Image::newFromName( $name );
1070 if( is_null( $img ) ) {
1071 // Uh... this shouldn't happen ;)
1072 // But if it does, fall through to previous behavior
1073 return false;
1074 }
1075
1076 $error = '';
1077 if( $img->exists() ) {
1078 global $wgUser, $wgOut;
1079 if( $img->isLocal() ) {
1080 if( !$wgUser->isAllowed( 'reupload' ) ) {
1081 $error = 'fileexists-forbidden';
1082 }
1083 } else {
1084 if( !$wgUser->isAllowed( 'reupload' ) ||
1085 !$wgUser->isAllowed( 'reupload-shared' ) ) {
1086 $error = "fileexists-shared-forbidden";
1087 }
1088 }
1089 }
1090
1091 if( $error ) {
1092 $errorText = wfMsg( $error, wfEscapeWikiText( $img->getName() ) );
1093 return new WikiError( $wgOut->parse( $errorText ) );
1094 }
1095
1096 // Rockin', go ahead and upload
1097 return true;
1098 }
1099
1100 }
1101 ?>