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