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