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