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