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