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