Code housekeeping stuff (and barring any stuff-ups on my behalf, there should be...
[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;
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 $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
708 $sourcefilename = wfMsgHtml( 'sourcefilename' );
709 $destfilename = wfMsgHtml( 'destfilename' );
710 $summary = wfMsgWikiHtml( 'fileuploadsummary' );
711
712 $licenses = new Licenses();
713 $license = wfMsgHtml( 'license' );
714 $nolicense = wfMsgHtml( 'nolicense' );
715 $licenseshtml = $licenses->getHtml();
716
717 $ulb = wfMsgHtml( 'uploadbtn' );
718
719
720 $titleObj = SpecialPage::getTitleFor( 'Upload' );
721 $action = $titleObj->escapeLocalURL();
722
723 $encDestFile = htmlspecialchars( $this->mDestFile );
724
725 $watchChecked =
726 ( $wgUser->getOption( 'watchdefault' ) ||
727 ( $wgUser->getOption( 'watchcreations' ) && $this->mDestFile == '' ) )
728 ? 'checked="checked"'
729 : '';
730
731 // Prepare form for upload or upload/copy
732 if( $wgAllowCopyUploads && $wgUser->isAllowed( 'upload_by_url' ) ) {
733 $filename_form =
734 "<input type='radio' id='wpSourceTypeFile' name='wpSourceType' value='file' onchange='toggle_element_activation(\"wpUploadFileURL\",\"wpUploadFile\")' checked />" .
735 "<input tabindex='1' type='file' name='wpUploadFile' id='wpUploadFile' onfocus='toggle_element_activation(\"wpUploadFileURL\",\"wpUploadFile\");toggle_element_check(\"wpSourceTypeFile\",\"wpSourceTypeURL\")'" .
736 ($this->mDestFile?"":"onchange='fillDestFilename(\"wpUploadFile\")' ") . "size='40' />" .
737 wfMsgHTML( 'upload_source_file' ) . "<br/>" .
738 "<input type='radio' id='wpSourceTypeURL' name='wpSourceType' value='web' onchange='toggle_element_activation(\"wpUploadFile\",\"wpUploadFileURL\")' />" .
739 "<input tabindex='1' type='text' name='wpUploadFileURL' id='wpUploadFileURL' onfocus='toggle_element_activation(\"wpUploadFile\",\"wpUploadFileURL\");toggle_element_check(\"wpSourceTypeURL\",\"wpSourceTypeFile\")'" .
740 ($this->mDestFile?"":"onchange='fillDestFilename(\"wpUploadFileURL\")' ") . "size='40' DISABLED />" .
741 wfMsgHtml( 'upload_source_url' ) ;
742 } else {
743 $filename_form =
744 "<input tabindex='1' type='file' name='wpUploadFile' id='wpUploadFile' " .
745 ($this->mDestFile?"":"onchange='fillDestFilename(\"wpUploadFile\")' ") .
746 "size='40' />" .
747 "<input type='hidden' name='wpSourceType' value='file' />" ;
748 }
749
750 $wgOut->addHTML( "
751 <form id='upload' method='post' enctype='multipart/form-data' action=\"$action\">
752 <table border='0'>
753 <tr>
754 <td align='right' valign='top'><label for='wpUploadFile'>{$sourcefilename}:</label></td>
755 <td align='left'>
756 {$filename_form}
757 </td>
758 </tr>
759 <tr>
760 <td align='right'><label for='wpDestFile'>{$destfilename}:</label></td>
761 <td align='left'>
762 <input tabindex='2' type='text' name='wpDestFile' id='wpDestFile' size='40' value=\"$encDestFile\" />
763 </td>
764 </tr>
765 <tr>
766 <td align='right'><label for='wpUploadDescription'>{$summary}</label></td>
767 <td align='left'>
768 <textarea tabindex='3' name='wpUploadDescription' id='wpUploadDescription' rows='6' cols='{$cols}'{$ew}>" . htmlspecialchars( $this->mUploadDescription ) . "</textarea>
769 </td>
770 </tr>
771 <tr>" );
772
773 if ( $licenseshtml != '' ) {
774 global $wgStylePath;
775 $wgOut->addHTML( "
776 <td align='right'><label for='wpLicense'>$license:</label></td>
777 <td align='left'>
778 <script type='text/javascript' src=\"$wgStylePath/common/upload.js\"></script>
779 <select name='wpLicense' id='wpLicense' tabindex='4'
780 onchange='licenseSelectorCheck()'>
781 <option value=''>$nolicense</option>
782 $licenseshtml
783 </select>
784 </td>
785 </tr>
786 <tr>
787 ");
788 }
789
790 if ( $wgUseCopyrightUpload ) {
791 $filestatus = wfMsgHtml ( 'filestatus' );
792 $copystatus = htmlspecialchars( $this->mUploadCopyStatus );
793 $filesource = wfMsgHtml ( 'filesource' );
794 $uploadsource = htmlspecialchars( $this->mUploadSource );
795
796 $wgOut->addHTML( "
797 <td align='right' nowrap='nowrap'><label for='wpUploadCopyStatus'>$filestatus:</label></td>
798 <td><input tabindex='5' type='text' name='wpUploadCopyStatus' id='wpUploadCopyStatus' value=\"$copystatus\" size='40' /></td>
799 </tr>
800 <tr>
801 <td align='right'><label for='wpUploadCopyStatus'>$filesource:</label></td>
802 <td><input tabindex='6' type='text' name='wpUploadSource' id='wpUploadCopyStatus' value=\"$uploadsource\" size='40' /></td>
803 </tr>
804 <tr>
805 ");
806 }
807
808
809 $wgOut->addHtml( "
810 <td></td>
811 <td>
812 <input tabindex='7' type='checkbox' name='wpWatchthis' id='wpWatchthis' $watchChecked value='true' />
813 <label for='wpWatchthis'>" . wfMsgHtml( 'watchthisupload' ) . "</label>
814 <input tabindex='8' type='checkbox' name='wpIgnoreWarning' id='wpIgnoreWarning' value='true' />
815 <label for='wpIgnoreWarning'>" . wfMsgHtml( 'ignorewarnings' ) . "</label>
816 </td>
817 </tr>
818 <tr>
819
820 </tr>
821 <tr>
822 <td></td>
823 <td align='left'><input tabindex='9' type='submit' name='wpUpload' value=\"{$ulb}\" /></td>
824 </tr>
825
826 <tr>
827 <td></td>
828 <td align='left'>
829 " );
830 $wgOut->addWikiText( wfMsgForContent( 'edittools' ) );
831 $wgOut->addHTML( "
832 </td>
833 </tr>
834
835 </table>
836 </form>" );
837 }
838
839 /* -------------------------------------------------------------- */
840
841 /**
842 * Split a file into a base name and all dot-delimited 'extensions'
843 * on the end. Some web server configurations will fall back to
844 * earlier pseudo-'extensions' to determine type and execute
845 * scripts, so the blacklist needs to check them all.
846 *
847 * @return array
848 */
849 function splitExtensions( $filename ) {
850 $bits = explode( '.', $filename );
851 $basename = array_shift( $bits );
852 return array( $basename, $bits );
853 }
854
855 /**
856 * Perform case-insensitive match against a list of file extensions.
857 * Returns true if the extension is in the list.
858 *
859 * @param string $ext
860 * @param array $list
861 * @return bool
862 */
863 function checkFileExtension( $ext, $list ) {
864 return in_array( strtolower( $ext ), $list );
865 }
866
867 /**
868 * Perform case-insensitive match against a list of file extensions.
869 * Returns true if any of the extensions are in the list.
870 *
871 * @param array $ext
872 * @param array $list
873 * @return bool
874 */
875 function checkFileExtensionList( $ext, $list ) {
876 foreach( $ext as $e ) {
877 if( in_array( strtolower( $e ), $list ) ) {
878 return true;
879 }
880 }
881 return false;
882 }
883
884 /**
885 * Verifies that it's ok to include the uploaded file
886 *
887 * @param string $tmpfile the full path of the temporary file to verify
888 * @param string $extension The filename extension that the file is to be served with
889 * @return mixed true of the file is verified, a WikiError object otherwise.
890 */
891 function verify( $tmpfile, $extension ) {
892 #magically determine mime type
893 $magic=& MimeMagic::singleton();
894 $mime= $magic->guessMimeType($tmpfile,false);
895
896 $fname= "SpecialUpload::verify";
897
898 #check mime type, if desired
899 global $wgVerifyMimeType;
900 if ($wgVerifyMimeType) {
901
902 #check mime type against file extension
903 if( !$this->verifyExtension( $mime, $extension ) ) {
904 return new WikiErrorMsg( 'uploadcorrupt' );
905 }
906
907 #check mime type blacklist
908 global $wgMimeTypeBlacklist;
909 if( isset($wgMimeTypeBlacklist) && !is_null($wgMimeTypeBlacklist)
910 && $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
911 return new WikiErrorMsg( 'badfiletype', htmlspecialchars( $mime ) );
912 }
913 }
914
915 #check for htmlish code and javascript
916 if( $this->detectScript ( $tmpfile, $mime, $extension ) ) {
917 return new WikiErrorMsg( 'uploadscripted' );
918 }
919
920 /**
921 * Scan the uploaded file for viruses
922 */
923 $virus= $this->detectVirus($tmpfile);
924 if ( $virus ) {
925 return new WikiErrorMsg( 'uploadvirus', htmlspecialchars($virus) );
926 }
927
928 wfDebug( "$fname: all clear; passing.\n" );
929 return true;
930 }
931
932 /**
933 * Checks if the mime type of the uploaded file matches the file extension.
934 *
935 * @param string $mime the mime type of the uploaded file
936 * @param string $extension The filename extension that the file is to be served with
937 * @return bool
938 */
939 function verifyExtension( $mime, $extension ) {
940 $fname = 'SpecialUpload::verifyExtension';
941
942 $magic =& MimeMagic::singleton();
943
944 if ( ! $mime || $mime == 'unknown' || $mime == 'unknown/unknown' )
945 if ( ! $magic->isRecognizableExtension( $extension ) ) {
946 wfDebug( "$fname: passing file with unknown detected mime type; unrecognized extension '$extension', can't verify\n" );
947 return true;
948 } else {
949 wfDebug( "$fname: rejecting file with unknown detected mime type; recognized extension '$extension', so probably invalid file\n" );
950 return false;
951 }
952
953 $match= $magic->isMatchingExtension($extension,$mime);
954
955 if ($match===NULL) {
956 wfDebug( "$fname: no file extension known for mime type $mime, passing file\n" );
957 return true;
958 } elseif ($match===true) {
959 wfDebug( "$fname: mime type $mime matches extension $extension, passing file\n" );
960
961 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
962 return true;
963
964 } else {
965 wfDebug( "$fname: mime type $mime mismatches file extension $extension, rejecting file\n" );
966 return false;
967 }
968 }
969
970 /** Heuristig for detecting files that *could* contain JavaScript instructions or
971 * things that may look like HTML to a browser and are thus
972 * potentially harmful. The present implementation will produce false positives in some situations.
973 *
974 * @param string $file Pathname to the temporary upload file
975 * @param string $mime The mime type of the file
976 * @param string $extension The extension of the file
977 * @return bool true if the file contains something looking like embedded scripts
978 */
979 function detectScript($file, $mime, $extension) {
980 global $wgAllowTitlesInSVG;
981
982 #ugly hack: for text files, always look at the entire file.
983 #For binarie field, just check the first K.
984
985 if (strpos($mime,'text/')===0) $chunk = file_get_contents( $file );
986 else {
987 $fp = fopen( $file, 'rb' );
988 $chunk = fread( $fp, 1024 );
989 fclose( $fp );
990 }
991
992 $chunk= strtolower( $chunk );
993
994 if (!$chunk) return false;
995
996 #decode from UTF-16 if needed (could be used for obfuscation).
997 if (substr($chunk,0,2)=="\xfe\xff") $enc= "UTF-16BE";
998 elseif (substr($chunk,0,2)=="\xff\xfe") $enc= "UTF-16LE";
999 else $enc= NULL;
1000
1001 if ($enc) $chunk= iconv($enc,"ASCII//IGNORE",$chunk);
1002
1003 $chunk= trim($chunk);
1004
1005 #FIXME: convert from UTF-16 if necessarry!
1006
1007 wfDebug("SpecialUpload::detectScript: checking for embedded scripts and HTML stuff\n");
1008
1009 #check for HTML doctype
1010 if (eregi("<!DOCTYPE *X?HTML",$chunk)) return true;
1011
1012 /**
1013 * Internet Explorer for Windows performs some really stupid file type
1014 * autodetection which can cause it to interpret valid image files as HTML
1015 * and potentially execute JavaScript, creating a cross-site scripting
1016 * attack vectors.
1017 *
1018 * Apple's Safari browser also performs some unsafe file type autodetection
1019 * which can cause legitimate files to be interpreted as HTML if the
1020 * web server is not correctly configured to send the right content-type
1021 * (or if you're really uploading plain text and octet streams!)
1022 *
1023 * Returns true if IE is likely to mistake the given file for HTML.
1024 * Also returns true if Safari would mistake the given file for HTML
1025 * when served with a generic content-type.
1026 */
1027
1028 $tags = array(
1029 '<body',
1030 '<head',
1031 '<html', #also in safari
1032 '<img',
1033 '<pre',
1034 '<script', #also in safari
1035 '<table'
1036 );
1037 if( ! $wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
1038 $tags[] = '<title';
1039 }
1040
1041 foreach( $tags as $tag ) {
1042 if( false !== strpos( $chunk, $tag ) ) {
1043 return true;
1044 }
1045 }
1046
1047 /*
1048 * look for javascript
1049 */
1050
1051 #resolve entity-refs to look at attributes. may be harsh on big files... cache result?
1052 $chunk = Sanitizer::decodeCharReferences( $chunk );
1053
1054 #look for script-types
1055 if (preg_match('!type\s*=\s*[\'"]?\s*(\w*/)?(ecma|java)!sim',$chunk)) return true;
1056
1057 #look for html-style script-urls
1058 if (preg_match('!(href|src|data)\s*=\s*[\'"]?\s*(ecma|java)script:!sim',$chunk)) return true;
1059
1060 #look for css-style script-urls
1061 if (preg_match('!url\s*\(\s*[\'"]?\s*(ecma|java)script:!sim',$chunk)) return true;
1062
1063 wfDebug("SpecialUpload::detectScript: no scripts found\n");
1064 return false;
1065 }
1066
1067 /** Generic wrapper function for a virus scanner program.
1068 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
1069 * $wgAntivirusRequired may be used to deny upload if the scan fails.
1070 *
1071 * @param string $file Pathname to the temporary upload file
1072 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
1073 * or a string containing feedback from the virus scanner if a virus was found.
1074 * If textual feedback is missing but a virus was found, this function returns true.
1075 */
1076 function detectVirus($file) {
1077 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
1078
1079 $fname= "SpecialUpload::detectVirus";
1080
1081 if (!$wgAntivirus) { #disabled?
1082 wfDebug("$fname: virus scanner disabled\n");
1083
1084 return NULL;
1085 }
1086
1087 if (!$wgAntivirusSetup[$wgAntivirus]) {
1088 wfDebug("$fname: unknown virus scanner: $wgAntivirus\n");
1089
1090 $wgOut->addHTML( "<div class='error'>Bad configuration: unknown virus scanner: <i>$wgAntivirus</i></div>\n" ); #LOCALIZE
1091
1092 return "unknown antivirus: $wgAntivirus";
1093 }
1094
1095 #look up scanner configuration
1096 $virus_scanner= $wgAntivirusSetup[$wgAntivirus]["command"]; #command pattern
1097 $virus_scanner_codes= $wgAntivirusSetup[$wgAntivirus]["codemap"]; #exit-code map
1098 $msg_pattern= $wgAntivirusSetup[$wgAntivirus]["messagepattern"]; #message pattern
1099
1100 $scanner= $virus_scanner; #copy, so we can resolve the pattern
1101
1102 if (strpos($scanner,"%f")===false) $scanner.= " ".wfEscapeShellArg($file); #simple pattern: append file to scan
1103 else $scanner= str_replace("%f",wfEscapeShellArg($file),$scanner); #complex pattern: replace "%f" with file to scan
1104
1105 wfDebug("$fname: running virus scan: $scanner \n");
1106
1107 #execute virus scanner
1108 $code= false;
1109
1110 #NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
1111 # that does not seem to be worth the pain.
1112 # Ask me (Duesentrieb) about it if it's ever needed.
1113 $output = array();
1114 if (wfIsWindows()) exec("$scanner",$output,$code);
1115 else exec("$scanner 2>&1",$output,$code);
1116
1117 $exit_code= $code; #remember for user feedback
1118
1119 if ($virus_scanner_codes) { #map exit code to AV_xxx constants.
1120 if (isset($virus_scanner_codes[$code])) {
1121 $code= $virus_scanner_codes[$code]; # explicit mapping
1122 } else if (isset($virus_scanner_codes["*"])) {
1123 $code= $virus_scanner_codes["*"]; # fallback mapping
1124 }
1125 }
1126
1127 if ($code===AV_SCAN_FAILED) { #scan failed (code was mapped to false by $virus_scanner_codes)
1128 wfDebug("$fname: failed to scan $file (code $exit_code).\n");
1129
1130 if ($wgAntivirusRequired) { return "scan failed (code $exit_code)"; }
1131 else { return NULL; }
1132 }
1133 else if ($code===AV_SCAN_ABORTED) { #scan failed because filetype is unknown (probably imune)
1134 wfDebug("$fname: unsupported file type $file (code $exit_code).\n");
1135 return NULL;
1136 }
1137 else if ($code===AV_NO_VIRUS) {
1138 wfDebug("$fname: file passed virus scan.\n");
1139 return false; #no virus found
1140 }
1141 else {
1142 $output= join("\n",$output);
1143 $output= trim($output);
1144
1145 if (!$output) $output= true; #if there's no output, return true
1146 else if ($msg_pattern) {
1147 $groups= array();
1148 if (preg_match($msg_pattern,$output,$groups)) {
1149 if ($groups[1]) $output= $groups[1];
1150 }
1151 }
1152
1153 wfDebug("$fname: FOUND VIRUS! scanner feedback: $output");
1154 return $output;
1155 }
1156 }
1157
1158 /**
1159 * Check if the temporary file is MacBinary-encoded, as some uploads
1160 * from Internet Explorer on Mac OS Classic and Mac OS X will be.
1161 * If so, the data fork will be extracted to a second temporary file,
1162 * which will then be checked for validity and either kept or discarded.
1163 *
1164 * @access private
1165 */
1166 function checkMacBinary() {
1167 $macbin = new MacBinary( $this->mUploadTempName );
1168 if( $macbin->isValid() ) {
1169 $dataFile = tempnam( wfTempDir(), "WikiMacBinary" );
1170 $dataHandle = fopen( $dataFile, 'wb' );
1171
1172 wfDebug( "SpecialUpload::checkMacBinary: Extracting MacBinary data fork to $dataFile\n" );
1173 $macbin->extractData( $dataHandle );
1174
1175 $this->mUploadTempName = $dataFile;
1176 $this->mUploadSize = $macbin->dataForkLength();
1177
1178 // We'll have to manually remove the new file if it's not kept.
1179 $this->mRemoveTempFile = true;
1180 }
1181 $macbin->close();
1182 }
1183
1184 /**
1185 * If we've modified the upload file we need to manually remove it
1186 * on exit to clean up.
1187 * @access private
1188 */
1189 function cleanupTempFile() {
1190 if( $this->mRemoveTempFile && file_exists( $this->mUploadTempName ) ) {
1191 wfDebug( "SpecialUpload::cleanupTempFile: Removing temporary file $this->mUploadTempName\n" );
1192 unlink( $this->mUploadTempName );
1193 }
1194 }
1195
1196 /**
1197 * Check if there's an overwrite conflict and, if so, if restrictions
1198 * forbid this user from performing the upload.
1199 *
1200 * @return mixed true on success, WikiError on failure
1201 * @access private
1202 */
1203 function checkOverwrite( $name ) {
1204 $img = Image::newFromName( $name );
1205 if( is_null( $img ) ) {
1206 // Uh... this shouldn't happen ;)
1207 // But if it does, fall through to previous behavior
1208 return false;
1209 }
1210
1211 $error = '';
1212 if( $img->exists() ) {
1213 global $wgUser, $wgOut;
1214 if( $img->isLocal() ) {
1215 if( !$wgUser->isAllowed( 'reupload' ) ) {
1216 $error = 'fileexists-forbidden';
1217 }
1218 } else {
1219 if( !$wgUser->isAllowed( 'reupload' ) ||
1220 !$wgUser->isAllowed( 'reupload-shared' ) ) {
1221 $error = "fileexists-shared-forbidden";
1222 }
1223 }
1224 }
1225
1226 if( $error ) {
1227 $errorText = wfMsg( $error, wfEscapeWikiText( $img->getName() ) );
1228 return new WikiError( $wgOut->parse( $errorText ) );
1229 }
1230
1231 // Rockin', go ahead and upload
1232 return true;
1233 }
1234
1235 }
1236
1237
1238 ?>