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