Update and fixes.
[lhc/web/wiklou.git] / includes / SpecialUpload.php
1 <?php
2 /**
3 *
4 * @addtogroup SpecialPage
5 */
6
7
8 /**
9 * Entry point
10 */
11 function wfSpecialUpload() {
12 global $wgRequest;
13 $form = new UploadForm( $wgRequest );
14 $form->execute();
15 }
16
17 /**
18 * implements Special:Upload
19 * @addtogroup SpecialPage
20 */
21 class UploadForm {
22 const SUCCESS = 0;
23 const BEFORE_PROCESSING = 1;
24 const LARGE_FILE_SERVER = 2;
25 const EMPTY_FILE = 3;
26 const MIN_LENGHT_PARTNAME = 4;
27 const ILLEGAL_FILENAME = 5;
28 const PROTECTED_PAGE = 6;
29 const OVERWRITE_EXISTING_FILE = 7;
30 const FILETYPE_MISSING = 8;
31 const FILETYPE_BADTYPE = 9;
32 const VERIFICATION_ERROR = 10;
33 const UPLOAD_VERIFICATION_ERROR = 11;
34 const UPLOAD_WARNING = 12;
35 const INTERNAL_ERROR = 13;
36
37 /**#@+
38 * @access private
39 */
40 var $mComment, $mLicense, $mIgnoreWarning, $mCurlError;
41 var $mDestName, $mTempPath, $mFileSize, $mFileProps;
42 var $mCopyrightStatus, $mCopyrightSource, $mReUpload, $mAction, $mUploadClicked;
43 var $mSrcName, $mSessionKey, $mStashed, $mDesiredDestName, $mRemoveTempFile, $mSourceType;
44 var $mDestWarningAck, $mCurlDestHandle;
45 var $mLocalFile;
46
47 # Placeholders for text injection by hooks (must be HTML)
48 # extensions should take care to _append_ to the present value
49 var $uploadFormTextTop;
50 var $uploadFormTextAfterSummary;
51
52 const SESSION_VERSION = 1;
53 /**#@-*/
54
55 /**
56 * Constructor : initialise object
57 * Get data POSTed through the form and assign them to the object
58 * @param $request Data posted.
59 */
60 function UploadForm( &$request ) {
61 global $wgAllowCopyUploads;
62 $this->mDesiredDestName = $request->getText( 'wpDestFile' );
63 $this->mIgnoreWarning = $request->getCheck( 'wpIgnoreWarning' );
64 $this->mComment = $request->getText( 'wpUploadDescription' );
65
66 if( !$request->wasPosted() ) {
67 # GET requests just give the main form; no data except destination
68 # filename and description
69 return;
70 }
71
72 # Placeholders for text injection by hooks (empty per default)
73 $this->uploadFormTextTop = "";
74 $this->uploadFormTextAfterSummary = "";
75
76 $this->mReUpload = $request->getCheck( 'wpReUpload' );
77 $this->mUploadClicked = $request->getCheck( 'wpUpload' );
78
79 $this->mLicense = $request->getText( 'wpLicense' );
80 $this->mCopyrightStatus = $request->getText( 'wpUploadCopyStatus' );
81 $this->mCopyrightSource = $request->getText( 'wpUploadSource' );
82 $this->mWatchthis = $request->getBool( 'wpWatchthis' );
83 $this->mSourceType = $request->getText( 'wpSourceType' );
84 $this->mDestWarningAck = $request->getText( 'wpDestFileWarningAck' );
85
86 $this->mAction = $request->getVal( 'action' );
87
88 $this->mSessionKey = $request->getInt( 'wpSessionKey' );
89 if( !empty( $this->mSessionKey ) &&
90 isset( $_SESSION['wsUploadData'][$this->mSessionKey]['version'] ) &&
91 $_SESSION['wsUploadData'][$this->mSessionKey]['version'] == self::SESSION_VERSION ) {
92 /**
93 * Confirming a temporarily stashed upload.
94 * We don't want path names to be forged, so we keep
95 * them in the session on the server and just give
96 * an opaque key to the user agent.
97 */
98 $data = $_SESSION['wsUploadData'][$this->mSessionKey];
99 $this->mTempPath = $data['mTempPath'];
100 $this->mFileSize = $data['mFileSize'];
101 $this->mSrcName = $data['mSrcName'];
102 $this->mFileProps = $data['mFileProps'];
103 $this->mCurlError = 0/*UPLOAD_ERR_OK*/;
104 $this->mStashed = true;
105 $this->mRemoveTempFile = false;
106 } else {
107 /**
108 *Check for a newly uploaded file.
109 */
110 if( $wgAllowCopyUploads && $this->mSourceType == 'web' ) {
111 $this->initializeFromUrl( $request );
112 } else {
113 $this->initializeFromUpload( $request );
114 }
115 }
116 }
117
118 /**
119 * Initialize the uploaded file from PHP data
120 * @access private
121 */
122 function initializeFromUpload( $request ) {
123 $this->mTempPath = $request->getFileTempName( 'wpUploadFile' );
124 $this->mFileSize = $request->getFileSize( 'wpUploadFile' );
125 $this->mSrcName = $request->getFileName( 'wpUploadFile' );
126 $this->mCurlError = $request->getUploadError( 'wpUploadFile' );
127 $this->mSessionKey = false;
128 $this->mStashed = false;
129 $this->mRemoveTempFile = false; // PHP will handle this
130 }
131
132 /**
133 * Copy a web file to a temporary file
134 * @access private
135 */
136 function initializeFromUrl( $request ) {
137 global $wgTmpDirectory;
138 $url = $request->getText( 'wpUploadFileURL' );
139 $local_file = tempnam( $wgTmpDirectory, 'WEBUPLOAD' );
140
141 $this->mTempPath = $local_file;
142 $this->mFileSize = 0; # Will be set by curlCopy
143 $this->mCurlError = $this->curlCopy( $url, $local_file );
144 $this->mSrcName = array_pop( explode( '/', $url ) );
145 $this->mSessionKey = false;
146 $this->mStashed = false;
147
148 // PHP won't auto-cleanup the file
149 $this->mRemoveTempFile = file_exists( $local_file );
150 }
151
152 /**
153 * Safe copy from URL
154 * Returns true if there was an error, false otherwise
155 */
156 private function curlCopy( $url, $dest ) {
157 global $wgUser, $wgOut;
158
159 if( !$wgUser->isAllowed( 'upload_by_url' ) ) {
160 $wgOut->permissionRequired( 'upload_by_url' );
161 return true;
162 }
163
164 # Maybe remove some pasting blanks :-)
165 $url = trim( $url );
166 if( stripos($url, 'http://') !== 0 && stripos($url, 'ftp://') !== 0 ) {
167 # Only HTTP or FTP URLs
168 $wgOut->errorPage( 'upload-proto-error', 'upload-proto-error-text' );
169 return true;
170 }
171
172 # Open temporary file
173 $this->mCurlDestHandle = @fopen( $this->mTempPath, "wb" );
174 if( $this->mCurlDestHandle === false ) {
175 # Could not open temporary file to write in
176 $wgOut->errorPage( 'upload-file-error', 'upload-file-error-text');
177 return true;
178 }
179
180 $ch = curl_init();
181 curl_setopt( $ch, CURLOPT_HTTP_VERSION, 1.0); # Probably not needed, but apparently can work around some bug
182 curl_setopt( $ch, CURLOPT_TIMEOUT, 10); # 10 seconds timeout
183 curl_setopt( $ch, CURLOPT_LOW_SPEED_LIMIT, 512); # 0.5KB per second minimum transfer speed
184 curl_setopt( $ch, CURLOPT_URL, $url);
185 curl_setopt( $ch, CURLOPT_WRITEFUNCTION, array( $this, 'uploadCurlCallback' ) );
186 curl_exec( $ch );
187 $error = curl_errno( $ch ) ? true : false;
188 $errornum = curl_errno( $ch );
189 // if ( $error ) print curl_error ( $ch ) ; # Debugging output
190 curl_close( $ch );
191
192 fclose( $this->mCurlDestHandle );
193 unset( $this->mCurlDestHandle );
194 if( $error ) {
195 unlink( $dest );
196 if( wfEmptyMsg( "upload-curl-error$errornum", wfMsg("upload-curl-error$errornum") ) )
197 $wgOut->errorPage( 'upload-misc-error', 'upload-misc-error-text' );
198 else
199 $wgOut->errorPage( "upload-curl-error$errornum", "upload-curl-error$errornum-text" );
200 }
201
202 return $error;
203 }
204
205 /**
206 * Callback function for CURL-based web transfer
207 * Write data to file unless we've passed the length limit;
208 * if so, abort immediately.
209 * @access private
210 */
211 function uploadCurlCallback( $ch, $data ) {
212 global $wgMaxUploadSize;
213 $length = strlen( $data );
214 $this->mFileSize += $length;
215 if( $this->mFileSize > $wgMaxUploadSize ) {
216 return 0;
217 }
218 fwrite( $this->mCurlDestHandle, $data );
219 return $length;
220 }
221
222 /**
223 * Start doing stuff
224 * @access public
225 */
226 function execute() {
227 global $wgUser, $wgOut;
228 global $wgEnableUploads;
229
230 # Check uploading enabled
231 if( !$wgEnableUploads ) {
232 $wgOut->showErrorPage( 'uploaddisabled', 'uploaddisabledtext', array( $this->mDesiredDestName ) );
233 return;
234 }
235
236 # Check permissions
237 if( !$wgUser->isAllowed( 'upload' ) ) {
238 if( !$wgUser->isLoggedIn() ) {
239 $wgOut->showErrorPage( 'uploadnologin', 'uploadnologintext' );
240 } else {
241 $wgOut->permissionRequired( 'upload' );
242 }
243 return;
244 }
245
246 # Check blocks
247 if( $wgUser->isBlocked() ) {
248 $wgOut->blockedPage();
249 return;
250 }
251
252 if( wfReadOnly() ) {
253 $wgOut->readOnlyPage();
254 return;
255 }
256
257 if( $this->mReUpload ) {
258 if( !$this->unsaveUploadedFile() ) {
259 return;
260 }
261 $this->mainUploadForm();
262 } else if( 'submit' == $this->mAction || $this->mUploadClicked ) {
263 $this->processUpload();
264 } else {
265 $this->mainUploadForm();
266 }
267
268 $this->cleanupTempFile();
269 }
270
271 /**
272 * Do the upload
273 * Checks are made in SpecialUpload::execute()
274 *
275 * @access private
276 */
277 function processUpload(){
278 global $wgUser, $wgOut, $wgFileExtensions;
279 $details = null;
280 $value = null;
281 $value = $this->internalProcessUpload( $details );
282
283 switch($value) {
284 case self::SUCCESS:
285 $wgOut->redirect( $this->mLocalFile->getTitle()->getFullURL() );
286 break;
287
288 case self::BEFORE_PROCESSING:
289 break;
290
291 case self::LARGE_FILE_SERVER:
292 $this->mainUploadForm( wfMsgHtml( 'largefileserver' ) );
293 break;
294
295 case self::EMPTY_FILE:
296 $this->mainUploadForm( wfMsgHtml( 'emptyfile' ) );
297 break;
298
299 case self::MIN_LENGHT_PARTNAME:
300 $this->mainUploadForm( wfMsgHtml( 'minlength1' ) );
301 break;
302
303 case self::ILLEGAL_FILENAME:
304 $filtered = $details['filtered'];
305 $this->uploadError( wfMsgWikiHtml( 'illegalfilename', htmlspecialchars( $filtered ) ) );
306 break;
307
308 case self::PROTECTED_PAGE:
309 $this->uploadError( wfMsgWikiHtml( 'protectedpage' ) );
310 break;
311
312 case self::OVERWRITE_EXISTING_FILE:
313 $errorText = $details['overwrite'];
314 $overwrite = new WikiError( $wgOut->parse( $errorText ) );
315 $this->uploadError( $overwrite->toString() );
316 break;
317
318 case self::FILETYPE_MISSING:
319 $this->uploadError( wfMsgExt( 'filetype-missing', array ( 'parseinline' ) ) );
320 break;
321
322 case self::FILETYPE_BADTYPE:
323 $finalExt = $details['finalExt'];
324 $this->uploadError( wfMsgExt( 'filetype-badtype', array ( 'parseinline' ), htmlspecialchars( $finalExt ), implode ( ', ', $wgFileExtensions ) ) );
325 break;
326
327 case self::VERIFICATION_ERROR:
328 $veri = $details['veri'];
329 $this->uploadError( $veri->toString() );
330 break;
331
332 case self::UPLOAD_VERIFICATION_ERROR:
333 $error = $details['error'];
334 $this->uploadError( $error );
335 break;
336
337 case self::UPLOAD_WARNING:
338 $warning = $details['warning'];
339 $this->uploadWarning( $warning );
340 break;
341
342 case self::INTERNAL_ERROR:
343 $internal = $details['internal'];
344 $this->showError( $internal );
345 break;
346
347 default:
348 throw new MWException( __METHOD__ . ": Unknown value `{$value}`" );
349 }
350 }
351
352 /**
353 * Really do the upload
354 * Checks are made in SpecialUpload::execute()
355 *
356 * @param array $resultDetails contains result-specific dict of additional values
357 *
358 * @access private
359 */
360 function internalProcessUpload( &$resultDetails ) {
361 global $wgUser;
362
363 if( !wfRunHooks( 'UploadForm:BeforeProcessing', array( &$this ) ) )
364 {
365 wfDebug( "Hook 'UploadForm:BeforeProcessing' broke processing the file." );
366 return self::BEFORE_PROCESSING;
367 }
368
369 /* Check for PHP error if any, requires php 4.2 or newer */
370 if( $this->mCurlError == 1/*UPLOAD_ERR_INI_SIZE*/ ) {
371 return self::LARGE_FILE_SERVER;
372 }
373
374 /**
375 * If there was no filename or a zero size given, give up quick.
376 */
377 if( trim( $this->mSrcName ) == '' || empty( $this->mFileSize ) ) {
378 return self::EMPTY_FILE;
379 }
380
381 # Chop off any directories in the given filename
382 if( $this->mDesiredDestName ) {
383 $basename = $this->mDesiredDestName;
384 } else {
385 $basename = $this->mSrcName;
386 }
387 $filtered = wfBaseName( $basename );
388
389 /**
390 * We'll want to blacklist against *any* 'extension', and use
391 * only the final one for the whitelist.
392 */
393 list( $partname, $ext ) = $this->splitExtensions( $filtered );
394
395 if( count( $ext ) ) {
396 $finalExt = $ext[count( $ext ) - 1];
397 } else {
398 $finalExt = '';
399 }
400
401 # If there was more than one "extension", reassemble the base
402 # filename to prevent bogus complaints about length
403 if( count( $ext ) > 1 ) {
404 for( $i = 0; $i < count( $ext ) - 1; $i++ )
405 $partname .= '.' . $ext[$i];
406 }
407
408 if( strlen( $partname ) < 1 ) {
409 return self::MIN_LENGHT_PARTNAME;
410 }
411
412 /**
413 * Filter out illegal characters, and try to make a legible name
414 * out of it. We'll strip some silently that Title would die on.
415 */
416 $filtered = preg_replace ( "/[^".Title::legalChars()."]|:/", '-', $filtered );
417 $nt = Title::makeTitleSafe( NS_IMAGE, $filtered );
418 if( is_null( $nt ) ) {
419 $resultDetails = array( 'filtered' => $filtered );
420 return self::ILLEGAL_FILENAME;
421 }
422 $this->mLocalFile = wfLocalFile( $nt );
423 $this->mDestName = $this->mLocalFile->getName();
424
425 /**
426 * If the image is protected, non-sysop users won't be able
427 * to modify it by uploading a new revision.
428 */
429 if( !$nt->userCan( 'edit' ) ) {
430 return self::PROTECTED_PAGE;
431 }
432
433 /**
434 * In some cases we may forbid overwriting of existing files.
435 */
436 $overwrite = $this->checkOverwrite( $this->mDestName );
437 if( $overwrite !== true ) {
438 $resultDetails = array( 'overwrite' => $overwrite );
439 return self::OVERWRITE_EXISTING_FILE;
440 }
441
442 /* Don't allow users to override the blacklist (check file extension) */
443 global $wgStrictFileExtensions;
444 global $wgFileExtensions, $wgFileBlacklist;
445 if ($finalExt == '') {
446 return self::FILETYPE_MISSING;
447 } elseif ( $this->checkFileExtensionList( $ext, $wgFileBlacklist ) ||
448 ($wgStrictFileExtensions && !$this->checkFileExtension( $finalExt, $wgFileExtensions ) ) ) {
449 $resultDetails = array( 'finalExt' => $finalExt );
450 return self::FILETYPE_BADTYPE;
451 }
452
453 /**
454 * Look at the contents of the file; if we can recognize the
455 * type but it's corrupt or data of the wrong type, we should
456 * probably not accept it.
457 */
458 if( !$this->mStashed ) {
459 $this->mFileProps = File::getPropsFromPath( $this->mTempPath, $finalExt );
460 $this->checkMacBinary();
461 $veri = $this->verify( $this->mTempPath, $finalExt );
462
463 if( $veri !== true ) { //it's a wiki error...
464 $resultDetails = array( 'veri' => $veri );
465 return self::VERIFICATION_ERROR;
466 }
467
468 /**
469 * Provide an opportunity for extensions to add further checks
470 */
471 $error = '';
472 if( !wfRunHooks( 'UploadVerification',
473 array( $this->mDestName, $this->mTempPath, &$error ) ) ) {
474 $resultDetails = array( 'error' => $error );
475 return self::UPLOAD_VERIFICATION_ERROR;
476 }
477 }
478
479
480 /**
481 * Check for non-fatal conditions
482 */
483 if ( ! $this->mIgnoreWarning ) {
484 $warning = '';
485
486 global $wgCapitalLinks;
487 if( $wgCapitalLinks ) {
488 $filtered = ucfirst( $filtered );
489 }
490 if( $basename != $filtered ) {
491 $warning .= '<li>'.wfMsgHtml( 'badfilename', htmlspecialchars( $this->mDestName ) ).'</li>';
492 }
493
494 global $wgCheckFileExtensions;
495 if ( $wgCheckFileExtensions ) {
496 if ( ! $this->checkFileExtension( $finalExt, $wgFileExtensions ) ) {
497 $warning .= '<li>'.wfMsgExt( 'filetype-badtype', array ( 'parseinline' ),
498 htmlspecialchars( $finalExt ), implode ( ', ', $wgFileExtensions ) ).'</li>';
499 }
500 }
501
502 global $wgUploadSizeWarning;
503 if ( $wgUploadSizeWarning && ( $this->mFileSize > $wgUploadSizeWarning ) ) {
504 $skin = $wgUser->getSkin();
505 $wsize = $skin->formatSize( $wgUploadSizeWarning );
506 $asize = $skin->formatSize( $this->mFileSize );
507 $warning .= '<li>' . wfMsgHtml( 'large-file', $wsize, $asize ) . '</li>';
508 }
509 if ( $this->mFileSize == 0 ) {
510 $warning .= '<li>'.wfMsgHtml( 'emptyfile' ).'</li>';
511 }
512
513 if ( !$this->mDestWarningAck ) {
514 $warning .= self::getExistsWarning( $this->mLocalFile );
515 }
516 if( $warning != '' ) {
517 /**
518 * Stash the file in a temporary location; the user can choose
519 * to let it through and we'll complete the upload then.
520 */
521 $resultDetails = array( 'warning' => $warning );
522 return self::UPLOAD_WARNING;
523 }
524 }
525
526 /**
527 * Try actually saving the thing...
528 * It will show an error form on failure.
529 */
530 $pageText = self::getInitialPageText( $this->mComment, $this->mLicense,
531 $this->mCopyrightStatus, $this->mCopyrightSource );
532
533 $status = $this->mLocalFile->upload( $this->mTempPath, $this->mComment, $pageText,
534 File::DELETE_SOURCE, $this->mFileProps );
535 if ( !$status->isGood() ) {
536 $resultDetails = array( 'internal' => $status->getWikiText() );
537 return self::INTERNAL_ERROR;
538 } else {
539 if ( $this->mWatchthis ) {
540 global $wgUser;
541 $wgUser->addWatch( $this->mLocalFile->getTitle() );
542 }
543 // Success, redirect to description page
544 $img = null; // @todo: added to avoid passing a ref to null - should this be defined somewhere?
545 wfRunHooks( 'UploadComplete', array( &$img ) );
546 return self::SUCCESS;
547 }
548 }
549
550 /**
551 * Do existence checks on a file and produce a warning
552 * This check is static and can be done pre-upload via AJAX
553 * Returns an HTML fragment consisting of one or more LI elements if there is a warning
554 * Returns an empty string if there is no warning
555 */
556 static function getExistsWarning( $file ) {
557 global $wgUser;
558 // Check for uppercase extension. We allow these filenames but check if an image
559 // with lowercase extension exists already
560 $warning = '';
561
562 if( strpos( $file->getName(), '.' ) == false ) {
563 $partname = $file->getName();
564 $rawExtension = '';
565 } else {
566 list( $partname, $rawExtension ) = explode( '.', $file->getName(), 2 );
567 }
568 $sk = $wgUser->getSkin();
569
570 if ( $rawExtension != $file->getExtension() ) {
571 // We're not using the normalized form of the extension.
572 // Normal form is lowercase, using most common of alternate
573 // extensions (eg 'jpg' rather than 'JPEG').
574 //
575 // Check for another file using the normalized form...
576 $nt_lc = Title::newFromText( $partname . '.' . $file->getExtension() );
577 $file_lc = wfLocalFile( $nt_lc );
578 } else {
579 $file_lc = false;
580 }
581
582 if( $file->exists() ) {
583 $dlink = $sk->makeKnownLinkObj( $file->getTitle() );
584 if ( $file->allowInlineDisplay() ) {
585 $dlink2 = $sk->makeImageLinkObj( $file->getTitle(), wfMsgExt( 'fileexists-thumb', 'parseinline', $dlink ),
586 $file->getName(), 'right', array(), false, true );
587 } elseif ( !$file->allowInlineDisplay() && $file->isSafeFile() ) {
588 $icon = $file->iconThumb();
589 $dlink2 = '<div style="float:right" id="mw-media-icon">' .
590 $icon->toHtml( array( 'desc-link' => true ) ) . '<br />' . $dlink . '</div>';
591 } else {
592 $dlink2 = '';
593 }
594
595 $warning .= '<li>' . wfMsgExt( 'fileexists', 'parseline', $dlink ) . '</li>' . $dlink2;
596
597 } elseif ( $file_lc && $file_lc->exists() ) {
598 # Check if image with lowercase extension exists.
599 # It's not forbidden but in 99% it makes no sense to upload the same filename with uppercase extension
600 $dlink = $sk->makeKnownLinkObj( $nt_lc );
601 if ( $file_lc->allowInlineDisplay() ) {
602 $dlink2 = $sk->makeImageLinkObj( $nt_lc, wfMsgExt( 'fileexists-thumb', 'parseinline', $dlink ),
603 $nt_lc->getText(), 'right', array(), false, true );
604 } elseif ( !$file_lc->allowInlineDisplay() && $file_lc->isSafeFile() ) {
605 $icon = $file_lc->iconThumb();
606 $dlink2 = '<div style="float:right" id="mw-media-icon">' .
607 $icon->toHtml( array( 'desc-link' => true ) ) . '<br />' . $dlink . '</div>';
608 } else {
609 $dlink2 = '';
610 }
611
612 $warning .= '<li>' . wfMsgExt( 'fileexists-extension', 'parsemag', $file->getName(), $dlink ) . '</li>' . $dlink2;
613
614 } elseif ( ( substr( $partname , 3, 3 ) == 'px-' || substr( $partname , 2, 3 ) == 'px-' )
615 && ereg( "[0-9]{2}" , substr( $partname , 0, 2) ) )
616 {
617 # Check for filenames like 50px- or 180px-, these are mostly thumbnails
618 $nt_thb = Title::newFromText( substr( $partname , strpos( $partname , '-' ) +1 ) . '.' . $rawExtension );
619 $file_thb = wfLocalFile( $nt_thb );
620 if ($file_thb->exists() ) {
621 # Check if an image without leading '180px-' (or similiar) exists
622 $dlink = $sk->makeKnownLinkObj( $nt_thb);
623 if ( $file_thb->allowInlineDisplay() ) {
624 $dlink2 = $sk->makeImageLinkObj( $nt_thb,
625 wfMsgExt( 'fileexists-thumb', 'parseinline', $dlink ),
626 $nt_thb->getText(), 'right', array(), false, true );
627 } elseif ( !$file_thb->allowInlineDisplay() && $file_thb->isSafeFile() ) {
628 $icon = $file_thb->iconThumb();
629 $dlink2 = '<div style="float:right" id="mw-media-icon">' .
630 $icon->toHtml( array( 'desc-link' => true ) ) . '<br />' .
631 $dlink . '</div>';
632 } else {
633 $dlink2 = '';
634 }
635
636 $warning .= '<li>' . wfMsgExt( 'fileexists-thumbnail-yes', 'parsemag', $dlink ) .
637 '</li>' . $dlink2;
638 } else {
639 # Image w/o '180px-' does not exists, but we do not like these filenames
640 $warning .= '<li>' . wfMsgExt( 'file-thumbnail-no', 'parseinline' ,
641 substr( $partname , 0, strpos( $partname , '-' ) +1 ) ) . '</li>';
642 }
643 }
644
645 $filenamePrefixBlacklist = self::getFilenamePrefixBlacklist();
646 # Do the match
647 foreach( $filenamePrefixBlacklist as $prefix ) {
648 if ( substr( $partname, 0, strlen( $prefix ) ) == $prefix ) {
649 $warning .= '<li>' . wfMsgExt( 'filename-bad-prefix', 'parseinline', $prefix ) . '</li>';
650 break;
651 }
652 }
653
654 if ( $file->wasDeleted() && !$file->exists() ) {
655 # If the file existed before and was deleted, warn the user of this
656 # Don't bother doing so if the file exists now, however
657 $ltitle = SpecialPage::getTitleFor( 'Log' );
658 $llink = $sk->makeKnownLinkObj( $ltitle, wfMsgHtml( 'deletionlog' ),
659 'type=delete&page=' . $file->getTitle()->getPrefixedUrl() );
660 $warning .= '<li>' . wfMsgWikiHtml( 'filewasdeleted', $llink ) . '</li>';
661 }
662 return $warning;
663 }
664
665 /**
666 * Get a list of warnings
667 *
668 * @param string local filename, e.g. 'file exists', 'non-descriptive filename'
669 * @return array list of warning messages
670 */
671 static function ajaxGetExistsWarning( $filename ) {
672 $file = wfFindFile( $filename );
673 if( !$file ) {
674 // Force local file so we have an object to do further checks against
675 // if there isn't an exact match...
676 $file = wfLocalFile( $filename );
677 }
678 $s = '&nbsp;';
679 if ( $file ) {
680 $warning = self::getExistsWarning( $file );
681 if ( $warning !== '' ) {
682 $s = "<ul>$warning</ul>";
683 }
684 }
685 return $s;
686 }
687
688 /**
689 * Render a preview of a given license for the AJAX preview on upload
690 *
691 * @param string $license
692 * @return string
693 */
694 public static function ajaxGetLicensePreview( $license ) {
695 global $wgParser, $wgUser;
696 $text = '{{' . $license . '}}';
697 $title = Title::makeTitle( NS_IMAGE, 'Sample.jpg' );
698 $options = ParserOptions::newFromUser( $wgUser );
699
700 // Expand subst: first, then live templates...
701 $text = $wgParser->preSaveTransform( $text, $title, $wgUser, $options );
702 $output = $wgParser->parse( $text, $title, $options );
703
704 return $output->getText();
705 }
706
707 /**
708 * Get a list of blacklisted filename prefixes from [[MediaWiki:filename-prefix-blacklist]]
709 *
710 * @return array list of prefixes
711 */
712 public static function getFilenamePrefixBlacklist() {
713 $blacklist = array();
714 $message = wfMsgForContent( 'filename-prefix-blacklist' );
715 if( $message && !( wfEmptyMsg( 'filename-prefix-blacklist', $message ) || $message == '-' ) ) {
716 $lines = explode( "\n", $message );
717 foreach( $lines as $line ) {
718 // Remove comment lines
719 $comment = substr( trim( $line ), 0, 1 );
720 if ( $comment == '#' || $comment == '' ) {
721 continue;
722 }
723 // Remove additional comments after a prefix
724 $comment = strpos( $line, '#' );
725 if ( $comment > 0 ) {
726 $line = substr( $line, 0, $comment-1 );
727 }
728 $blacklist[] = trim( $line );
729 }
730 }
731 return $blacklist;
732 }
733
734 /**
735 * Stash a file in a temporary directory for later processing
736 * after the user has confirmed it.
737 *
738 * If the user doesn't explicitly cancel or accept, these files
739 * can accumulate in the temp directory.
740 *
741 * @param string $saveName - the destination filename
742 * @param string $tempName - the source temporary file to save
743 * @return string - full path the stashed file, or false on failure
744 * @access private
745 */
746 function saveTempUploadedFile( $saveName, $tempName ) {
747 global $wgOut;
748 $repo = RepoGroup::singleton()->getLocalRepo();
749 $status = $repo->storeTemp( $saveName, $tempName );
750 if ( !$status->isGood() ) {
751 $this->showError( $status->getWikiText() );
752 return false;
753 } else {
754 return $status->value;
755 }
756 }
757
758 /**
759 * Stash a file in a temporary directory for later processing,
760 * and save the necessary descriptive info into the session.
761 * Returns a key value which will be passed through a form
762 * to pick up the path info on a later invocation.
763 *
764 * @return int
765 * @access private
766 */
767 function stashSession() {
768 $stash = $this->saveTempUploadedFile( $this->mDestName, $this->mTempPath );
769
770 if( !$stash ) {
771 # Couldn't save the file.
772 return false;
773 }
774
775 $key = mt_rand( 0, 0x7fffffff );
776 $_SESSION['wsUploadData'][$key] = array(
777 'mTempPath' => $stash,
778 'mFileSize' => $this->mFileSize,
779 'mSrcName' => $this->mSrcName,
780 'mFileProps' => $this->mFileProps,
781 'version' => self::SESSION_VERSION,
782 );
783 return $key;
784 }
785
786 /**
787 * Remove a temporarily kept file stashed by saveTempUploadedFile().
788 * @access private
789 * @return success
790 */
791 function unsaveUploadedFile() {
792 global $wgOut;
793 $repo = RepoGroup::singleton()->getLocalRepo();
794 $success = $repo->freeTemp( $this->mTempPath );
795 if ( ! $success ) {
796 $wgOut->showFileDeleteError( $this->mTempPath );
797 return false;
798 } else {
799 return true;
800 }
801 }
802
803 /* -------------------------------------------------------------- */
804
805 /**
806 * @param string $error as HTML
807 * @access private
808 */
809 function uploadError( $error ) {
810 global $wgOut;
811 $wgOut->addHTML( "<h2>" . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
812 $wgOut->addHTML( "<span class='error'>{$error}</span>\n" );
813 }
814
815 /**
816 * There's something wrong with this file, not enough to reject it
817 * totally but we require manual intervention to save it for real.
818 * Stash it away, then present a form asking to confirm or cancel.
819 *
820 * @param string $warning as HTML
821 * @access private
822 */
823 function uploadWarning( $warning ) {
824 global $wgOut, $wgContLang;
825 global $wgUseCopyrightUpload;
826
827 $this->mSessionKey = $this->stashSession();
828 if( !$this->mSessionKey ) {
829 # Couldn't save file; an error has been displayed so let's go.
830 return;
831 }
832
833 $wgOut->addHTML( "<h2>" . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
834 $wgOut->addHTML( "<ul class='warning'>{$warning}</ul><br />\n" );
835
836 $save = wfMsgHtml( 'savefile' );
837 $reupload = wfMsgHtml( 'reupload' );
838 $iw = wfMsgWikiHtml( 'ignorewarning' );
839 $reup = wfMsgWikiHtml( 'reuploaddesc' );
840 $titleObj = SpecialPage::getTitleFor( 'Upload' );
841 $action = $titleObj->escapeLocalURL( 'action=submit' );
842 $align1 = $wgContLang->isRTL() ? 'left' : 'right';
843 $align2 = $wgContLang->isRTL() ? 'right' : 'left';
844
845 if ( $wgUseCopyrightUpload )
846 {
847 $copyright = "
848 <input type='hidden' name='wpUploadCopyStatus' value=\"" . htmlspecialchars( $this->mCopyrightStatus ) . "\" />
849 <input type='hidden' name='wpUploadSource' value=\"" . htmlspecialchars( $this->mCopyrightSource ) . "\" />
850 ";
851 } else {
852 $copyright = "";
853 }
854
855 $wgOut->addHTML( "
856 <form id='uploadwarning' method='post' enctype='multipart/form-data' action='$action'>
857 <input type='hidden' name='wpIgnoreWarning' value='1' />
858 <input type='hidden' name='wpSessionKey' value=\"" . htmlspecialchars( $this->mSessionKey ) . "\" />
859 <input type='hidden' name='wpUploadDescription' value=\"" . htmlspecialchars( $this->mComment ) . "\" />
860 <input type='hidden' name='wpLicense' value=\"" . htmlspecialchars( $this->mLicense ) . "\" />
861 <input type='hidden' name='wpDestFile' value=\"" . htmlspecialchars( $this->mDesiredDestName ) . "\" />
862 <input type='hidden' name='wpWatchthis' value=\"" . htmlspecialchars( intval( $this->mWatchthis ) ) . "\" />
863 {$copyright}
864 <table border='0'>
865 <tr>
866 <tr>
867 <td align='$align1'>
868 <input tabindex='2' type='submit' name='wpUpload' value=\"$save\" />
869 </td>
870 <td align='$align2'>$iw</td>
871 </tr>
872 <tr>
873 <td align='$align1'>
874 <input tabindex='2' type='submit' name='wpReUpload' value=\"{$reupload}\" />
875 </td>
876 <td align='$align2'>$reup</td>
877 </tr>
878 </tr>
879 </table></form>\n" );
880 }
881
882 /**
883 * Displays the main upload form, optionally with a highlighted
884 * error message up at the top.
885 *
886 * @param string $msg as HTML
887 * @access private
888 */
889 function mainUploadForm( $msg='' ) {
890 global $wgOut, $wgUser, $wgContLang;
891 global $wgUseCopyrightUpload, $wgUseAjax, $wgAjaxUploadDestCheck, $wgAjaxLicensePreview;
892 global $wgRequest, $wgAllowCopyUploads;
893 global $wgStylePath, $wgStyleVersion;
894
895 $useAjaxDestCheck = $wgUseAjax && $wgAjaxUploadDestCheck;
896 $useAjaxLicensePreview = $wgUseAjax && $wgAjaxLicensePreview;
897
898 $adc = wfBoolToStr( $useAjaxDestCheck );
899 $alp = wfBoolToStr( $useAjaxLicensePreview );
900
901 $wgOut->addScript( "<script type=\"text/javascript\">
902 wgAjaxUploadDestCheck = {$adc};
903 wgAjaxLicensePreview = {$alp};
904 </script>
905 <script type=\"text/javascript\" src=\"{$wgStylePath}/common/upload.js?{$wgStyleVersion}\"></script>
906 " );
907
908 if( !wfRunHooks( 'UploadForm:initial', array( &$this ) ) )
909 {
910 wfDebug( "Hook 'UploadForm:initial' broke output of the upload form" );
911 return false;
912 }
913
914 if( $this->mDesiredDestName ) {
915 $title = Title::makeTitleSafe( NS_IMAGE, $this->mDesiredDestName );
916 // Show a subtitle link to deleted revisions (to sysops et al only)
917 if( $title instanceof Title && ( $count = $title->isDeleted() ) > 0 && $wgUser->isAllowed( 'deletedhistory' ) ) {
918 $link = wfMsgExt(
919 $wgUser->isAllowed( 'delete' ) ? 'thisisdeleted' : 'viewdeleted',
920 array( 'parse', 'replaceafter' ),
921 $wgUser->getSkin()->makeKnownLinkObj(
922 SpecialPage::getTitleFor( 'Undelete', $title->getPrefixedText() ),
923 wfMsgExt( 'restorelink', array( 'parsemag', 'escape' ), $count )
924 )
925 );
926 $wgOut->addHtml( "<div id=\"contentSub2\">{$link}</div>" );
927 }
928
929 // Show the relevant lines from deletion log (for still deleted files only)
930 if( $title instanceof Title && $title->isDeleted() > 0 && !$title->exists() ) {
931 $this->showDeletionLog( $wgOut, $title->getPrefixedText() );
932 }
933 }
934
935 $cols = intval($wgUser->getOption( 'cols' ));
936 $ew = $wgUser->getOption( 'editwidth' );
937 if ( $ew ) $ew = " style=\"width:100%\"";
938 else $ew = '';
939
940 if ( '' != $msg ) {
941 $sub = wfMsgHtml( 'uploaderror' );
942 $wgOut->addHTML( "<h2>{$sub}</h2>\n" .
943 "<span class='error'>{$msg}</span>\n" );
944 }
945 $wgOut->addHTML( '<div id="uploadtext">' );
946 $wgOut->addWikiText( wfMsgNoTrans( 'uploadtext', $this->mDesiredDestName ) );
947 $wgOut->addHTML( '</div>' );
948
949 $sourcefilename = wfMsgHtml( 'sourcefilename' );
950 $destfilename = wfMsgHtml( 'destfilename' );
951 $summary = wfMsgExt( 'fileuploadsummary', 'parseinline' );
952
953 $licenses = new Licenses();
954 $license = wfMsgExt( 'license', array( 'parseinline' ) );
955 $nolicense = wfMsgHtml( 'nolicense' );
956 $licenseshtml = $licenses->getHtml();
957
958 $ulb = wfMsgHtml( 'uploadbtn' );
959
960
961 $titleObj = SpecialPage::getTitleFor( 'Upload' );
962 $action = $titleObj->escapeLocalURL();
963
964 $encDestName = htmlspecialchars( $this->mDesiredDestName );
965
966 $watchChecked =
967 ( $wgUser->getOption( 'watchdefault' ) ||
968 ( $wgUser->getOption( 'watchcreations' ) && $this->mDesiredDestName == '' ) )
969 ? 'checked="checked"'
970 : '';
971 $warningChecked = $this->mIgnoreWarning ? 'checked' : '';
972
973 // Prepare form for upload or upload/copy
974 if( $wgAllowCopyUploads && $wgUser->isAllowed( 'upload_by_url' ) ) {
975 $filename_form =
976 "<input type='radio' id='wpSourceTypeFile' name='wpSourceType' value='file' " .
977 "onchange='toggle_element_activation(\"wpUploadFileURL\",\"wpUploadFile\")' checked />" .
978 "<input tabindex='1' type='file' name='wpUploadFile' id='wpUploadFile' " .
979 "onfocus='" .
980 "toggle_element_activation(\"wpUploadFileURL\",\"wpUploadFile\");" .
981 "toggle_element_check(\"wpSourceTypeFile\",\"wpSourceTypeURL\")'" .
982 ($this->mDesiredDestName?"":"onchange='fillDestFilename(\"wpUploadFile\")' ") . "size='40' />" .
983 wfMsgHTML( 'upload_source_file' ) . "<br/>" .
984 "<input type='radio' id='wpSourceTypeURL' name='wpSourceType' value='web' " .
985 "onchange='toggle_element_activation(\"wpUploadFile\",\"wpUploadFileURL\")' />" .
986 "<input tabindex='1' type='text' name='wpUploadFileURL' id='wpUploadFileURL' " .
987 "onfocus='" .
988 "toggle_element_activation(\"wpUploadFile\",\"wpUploadFileURL\");" .
989 "toggle_element_check(\"wpSourceTypeURL\",\"wpSourceTypeFile\")'" .
990 ($this->mDesiredDestName?"":"onchange='fillDestFilename(\"wpUploadFileURL\")' ") . "size='40' DISABLED />" .
991 wfMsgHtml( 'upload_source_url' ) ;
992 } else {
993 $filename_form =
994 "<input tabindex='1' type='file' name='wpUploadFile' id='wpUploadFile' " .
995 ($this->mDesiredDestName?"":"onchange='fillDestFilename(\"wpUploadFile\")' ") .
996 "size='40' />" .
997 "<input type='hidden' name='wpSourceType' value='file' />" ;
998 }
999 if ( $useAjaxDestCheck ) {
1000 $warningRow = "<tr><td colspan='2' id='wpDestFile-warning'>&nbsp;</td></tr>";
1001 $destOnkeyup = 'onkeyup="wgUploadWarningObj.keypress();"';
1002 } else {
1003 $warningRow = '';
1004 $destOnkeyup = '';
1005 }
1006
1007 $encComment = htmlspecialchars( $this->mComment );
1008 $align1 = $wgContLang->isRTL() ? 'left' : 'right';
1009 $align2 = $wgContLang->isRTL() ? 'right' : 'left';
1010
1011 $wgOut->addHTML( <<<EOT
1012 <form id='upload' method='post' enctype='multipart/form-data' action="$action">
1013 <table border='0'>
1014 <tr>
1015 {$this->uploadFormTextTop}
1016 <td align='$align1' valign='top'><label for='wpUploadFile'>{$sourcefilename}:</label></td>
1017 <td align='$align2'>
1018 {$filename_form}
1019 </td>
1020 </tr>
1021 <tr>
1022 <td align='$align1'><label for='wpDestFile'>{$destfilename}:</label></td>
1023 <td align='$align2'>
1024 <input tabindex='2' type='text' name='wpDestFile' id='wpDestFile' size='40'
1025 value="$encDestName" $destOnkeyup />
1026 </td>
1027 </tr>
1028 <tr>
1029 <td align='$align1'><label for='wpUploadDescription'>{$summary}</label></td>
1030 <td align='$align2'>
1031 <textarea tabindex='3' name='wpUploadDescription' id='wpUploadDescription' rows='6'
1032 cols='{$cols}'{$ew}>$encComment</textarea>
1033 {$this->uploadFormTextAfterSummary}
1034 </td>
1035 </tr>
1036 <tr>
1037 EOT
1038 );
1039
1040 if ( $licenseshtml != '' ) {
1041 global $wgStylePath;
1042 $wgOut->addHTML( "
1043 <td align='$align1'><label for='wpLicense'>$license:</label></td>
1044 <td align='$align2'>
1045 <select name='wpLicense' id='wpLicense' tabindex='4'
1046 onchange='licenseSelectorCheck()'>
1047 <option value=''>$nolicense</option>
1048 $licenseshtml
1049 </select>
1050 </td>
1051 </tr>
1052 <tr>" );
1053 if( $useAjaxLicensePreview ) {
1054 $wgOut->addHtml( "
1055 <td></td>
1056 <td id=\"mw-license-preview\"></td>
1057 </tr>
1058 <tr>" );
1059 }
1060 }
1061
1062 if ( $wgUseCopyrightUpload ) {
1063 $filestatus = wfMsgHtml ( 'filestatus' );
1064 $copystatus = htmlspecialchars( $this->mCopyrightStatus );
1065 $filesource = wfMsgHtml ( 'filesource' );
1066 $uploadsource = htmlspecialchars( $this->mCopyrightSource );
1067
1068 $wgOut->addHTML( "
1069 <td align='$align1' nowrap='nowrap'><label for='wpUploadCopyStatus'>$filestatus:</label></td>
1070 <td><input tabindex='5' type='text' name='wpUploadCopyStatus' id='wpUploadCopyStatus'
1071 value=\"$copystatus\" size='40' /></td>
1072 </tr>
1073 <tr>
1074 <td align='$align1'><label for='wpUploadCopyStatus'>$filesource:</label></td>
1075 <td><input tabindex='6' type='text' name='wpUploadSource' id='wpUploadCopyStatus'
1076 value=\"$uploadsource\" size='40' /></td>
1077 </tr>
1078 <tr>
1079 ");
1080 }
1081
1082 $wgOut->addHtml( "
1083 <td></td>
1084 <td>
1085 <input tabindex='7' type='checkbox' name='wpWatchthis' id='wpWatchthis' $watchChecked value='true' />
1086 <label for='wpWatchthis'>" . wfMsgHtml( 'watchthisupload' ) . "</label>
1087 <input tabindex='8' type='checkbox' name='wpIgnoreWarning' id='wpIgnoreWarning' value='true' $warningChecked/>
1088 <label for='wpIgnoreWarning'>" . wfMsgHtml( 'ignorewarnings' ) . "</label>
1089 </td>
1090 </tr>
1091 $warningRow
1092 <tr>
1093 <td></td>
1094 <td align='$align2'><input tabindex='9' type='submit' name='wpUpload' value=\"{$ulb}\"" . $wgUser->getSkin()->tooltipAndAccesskey( 'upload' ) . " /></td>
1095 </tr>
1096 <tr>
1097 <td></td>
1098 <td align='$align2'>
1099 " );
1100 $wgOut->addWikiText( wfMsgForContent( 'edittools' ) );
1101 $wgOut->addHTML( "
1102 </td>
1103 </tr>
1104
1105 </table>
1106 <input type='hidden' name='wpDestFileWarningAck' id='wpDestFileWarningAck' value=''/>
1107 </form>" );
1108 }
1109
1110 /* -------------------------------------------------------------- */
1111
1112 /**
1113 * Split a file into a base name and all dot-delimited 'extensions'
1114 * on the end. Some web server configurations will fall back to
1115 * earlier pseudo-'extensions' to determine type and execute
1116 * scripts, so the blacklist needs to check them all.
1117 *
1118 * @return array
1119 */
1120 function splitExtensions( $filename ) {
1121 $bits = explode( '.', $filename );
1122 $basename = array_shift( $bits );
1123 return array( $basename, $bits );
1124 }
1125
1126 /**
1127 * Perform case-insensitive match against a list of file extensions.
1128 * Returns true if the extension is in the list.
1129 *
1130 * @param string $ext
1131 * @param array $list
1132 * @return bool
1133 */
1134 function checkFileExtension( $ext, $list ) {
1135 return in_array( strtolower( $ext ), $list );
1136 }
1137
1138 /**
1139 * Perform case-insensitive match against a list of file extensions.
1140 * Returns true if any of the extensions are in the list.
1141 *
1142 * @param array $ext
1143 * @param array $list
1144 * @return bool
1145 */
1146 function checkFileExtensionList( $ext, $list ) {
1147 foreach( $ext as $e ) {
1148 if( in_array( strtolower( $e ), $list ) ) {
1149 return true;
1150 }
1151 }
1152 return false;
1153 }
1154
1155 /**
1156 * Verifies that it's ok to include the uploaded file
1157 *
1158 * @param string $tmpfile the full path of the temporary file to verify
1159 * @param string $extension The filename extension that the file is to be served with
1160 * @return mixed true of the file is verified, a WikiError object otherwise.
1161 */
1162 function verify( $tmpfile, $extension ) {
1163 #magically determine mime type
1164 $magic=& MimeMagic::singleton();
1165 $mime= $magic->guessMimeType($tmpfile,false);
1166
1167 #check mime type, if desired
1168 global $wgVerifyMimeType;
1169 if ($wgVerifyMimeType) {
1170
1171 wfDebug ( "\n\nmime: <$mime> extension: <$extension>\n\n");
1172 #check mime type against file extension
1173 if( !$this->verifyExtension( $mime, $extension ) ) {
1174 return new WikiErrorMsg( 'uploadcorrupt' );
1175 }
1176
1177 #check mime type blacklist
1178 global $wgMimeTypeBlacklist;
1179 if( isset($wgMimeTypeBlacklist) && !is_null($wgMimeTypeBlacklist)
1180 && $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
1181 return new WikiErrorMsg( 'filetype-badmime', htmlspecialchars( $mime ) );
1182 }
1183 }
1184
1185 #check for htmlish code and javascript
1186 if( $this->detectScript ( $tmpfile, $mime, $extension ) ) {
1187 return new WikiErrorMsg( 'uploadscripted' );
1188 }
1189
1190 /**
1191 * Scan the uploaded file for viruses
1192 */
1193 $virus= $this->detectVirus($tmpfile);
1194 if ( $virus ) {
1195 return new WikiErrorMsg( 'uploadvirus', htmlspecialchars($virus) );
1196 }
1197
1198 wfDebug( __METHOD__.": all clear; passing.\n" );
1199 return true;
1200 }
1201
1202 /**
1203 * Checks if the mime type of the uploaded file matches the file extension.
1204 *
1205 * @param string $mime the mime type of the uploaded file
1206 * @param string $extension The filename extension that the file is to be served with
1207 * @return bool
1208 */
1209 function verifyExtension( $mime, $extension ) {
1210 $magic =& MimeMagic::singleton();
1211
1212 if ( ! $mime || $mime == 'unknown' || $mime == 'unknown/unknown' )
1213 if ( ! $magic->isRecognizableExtension( $extension ) ) {
1214 wfDebug( __METHOD__.": passing file with unknown detected mime type; " .
1215 "unrecognized extension '$extension', can't verify\n" );
1216 return true;
1217 } else {
1218 wfDebug( __METHOD__.": rejecting file with unknown detected mime type; ".
1219 "recognized extension '$extension', so probably invalid file\n" );
1220 return false;
1221 }
1222
1223 $match= $magic->isMatchingExtension($extension,$mime);
1224
1225 if ($match===NULL) {
1226 wfDebug( __METHOD__.": no file extension known for mime type $mime, passing file\n" );
1227 return true;
1228 } elseif ($match===true) {
1229 wfDebug( __METHOD__.": mime type $mime matches extension $extension, passing file\n" );
1230
1231 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
1232 return true;
1233
1234 } else {
1235 wfDebug( __METHOD__.": mime type $mime mismatches file extension $extension, rejecting file\n" );
1236 return false;
1237 }
1238 }
1239
1240 /**
1241 * Heuristic for detecting files that *could* contain JavaScript instructions or
1242 * things that may look like HTML to a browser and are thus
1243 * potentially harmful. The present implementation will produce false positives in some situations.
1244 *
1245 * @param string $file Pathname to the temporary upload file
1246 * @param string $mime The mime type of the file
1247 * @param string $extension The extension of the file
1248 * @return bool true if the file contains something looking like embedded scripts
1249 */
1250 function detectScript($file, $mime, $extension) {
1251 global $wgAllowTitlesInSVG;
1252
1253 #ugly hack: for text files, always look at the entire file.
1254 #For binarie field, just check the first K.
1255
1256 if (strpos($mime,'text/')===0) $chunk = file_get_contents( $file );
1257 else {
1258 $fp = fopen( $file, 'rb' );
1259 $chunk = fread( $fp, 1024 );
1260 fclose( $fp );
1261 }
1262
1263 $chunk= strtolower( $chunk );
1264
1265 if (!$chunk) return false;
1266
1267 #decode from UTF-16 if needed (could be used for obfuscation).
1268 if (substr($chunk,0,2)=="\xfe\xff") $enc= "UTF-16BE";
1269 elseif (substr($chunk,0,2)=="\xff\xfe") $enc= "UTF-16LE";
1270 else $enc= NULL;
1271
1272 if ($enc) $chunk= iconv($enc,"ASCII//IGNORE",$chunk);
1273
1274 $chunk= trim($chunk);
1275
1276 #FIXME: convert from UTF-16 if necessarry!
1277
1278 wfDebug("SpecialUpload::detectScript: checking for embedded scripts and HTML stuff\n");
1279
1280 #check for HTML doctype
1281 if (eregi("<!DOCTYPE *X?HTML",$chunk)) return true;
1282
1283 /**
1284 * Internet Explorer for Windows performs some really stupid file type
1285 * autodetection which can cause it to interpret valid image files as HTML
1286 * and potentially execute JavaScript, creating a cross-site scripting
1287 * attack vectors.
1288 *
1289 * Apple's Safari browser also performs some unsafe file type autodetection
1290 * which can cause legitimate files to be interpreted as HTML if the
1291 * web server is not correctly configured to send the right content-type
1292 * (or if you're really uploading plain text and octet streams!)
1293 *
1294 * Returns true if IE is likely to mistake the given file for HTML.
1295 * Also returns true if Safari would mistake the given file for HTML
1296 * when served with a generic content-type.
1297 */
1298
1299 $tags = array(
1300 '<body',
1301 '<head',
1302 '<html', #also in safari
1303 '<img',
1304 '<pre',
1305 '<script', #also in safari
1306 '<table'
1307 );
1308 if( ! $wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
1309 $tags[] = '<title';
1310 }
1311
1312 foreach( $tags as $tag ) {
1313 if( false !== strpos( $chunk, $tag ) ) {
1314 return true;
1315 }
1316 }
1317
1318 /*
1319 * look for javascript
1320 */
1321
1322 #resolve entity-refs to look at attributes. may be harsh on big files... cache result?
1323 $chunk = Sanitizer::decodeCharReferences( $chunk );
1324
1325 #look for script-types
1326 if (preg_match('!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim',$chunk)) return true;
1327
1328 #look for html-style script-urls
1329 if (preg_match('!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim',$chunk)) return true;
1330
1331 #look for css-style script-urls
1332 if (preg_match('!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim',$chunk)) return true;
1333
1334 wfDebug("SpecialUpload::detectScript: no scripts found\n");
1335 return false;
1336 }
1337
1338 /**
1339 * Generic wrapper function for a virus scanner program.
1340 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
1341 * $wgAntivirusRequired may be used to deny upload if the scan fails.
1342 *
1343 * @param string $file Pathname to the temporary upload file
1344 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
1345 * or a string containing feedback from the virus scanner if a virus was found.
1346 * If textual feedback is missing but a virus was found, this function returns true.
1347 */
1348 function detectVirus($file) {
1349 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
1350
1351 if ( !$wgAntivirus ) {
1352 wfDebug( __METHOD__.": virus scanner disabled\n");
1353 return NULL;
1354 }
1355
1356 if ( !$wgAntivirusSetup[$wgAntivirus] ) {
1357 wfDebug( __METHOD__.": unknown virus scanner: $wgAntivirus\n" );
1358 # @TODO: localise
1359 $wgOut->addHTML( "<div class='error'>Bad configuration: unknown virus scanner: <i>$wgAntivirus</i></div>\n" );
1360 return "unknown antivirus: $wgAntivirus";
1361 }
1362
1363 # look up scanner configuration
1364 $command = $wgAntivirusSetup[$wgAntivirus]["command"];
1365 $exitCodeMap = $wgAntivirusSetup[$wgAntivirus]["codemap"];
1366 $msgPattern = isset( $wgAntivirusSetup[$wgAntivirus]["messagepattern"] ) ?
1367 $wgAntivirusSetup[$wgAntivirus]["messagepattern"] : null;
1368
1369 if ( strpos( $command,"%f" ) === false ) {
1370 # simple pattern: append file to scan
1371 $command .= " " . wfEscapeShellArg( $file );
1372 } else {
1373 # complex pattern: replace "%f" with file to scan
1374 $command = str_replace( "%f", wfEscapeShellArg( $file ), $command );
1375 }
1376
1377 wfDebug( __METHOD__.": running virus scan: $command \n" );
1378
1379 # execute virus scanner
1380 $exitCode = false;
1381
1382 #NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
1383 # that does not seem to be worth the pain.
1384 # Ask me (Duesentrieb) about it if it's ever needed.
1385 $output = array();
1386 if ( wfIsWindows() ) {
1387 exec( "$command", $output, $exitCode );
1388 } else {
1389 exec( "$command 2>&1", $output, $exitCode );
1390 }
1391
1392 # map exit code to AV_xxx constants.
1393 $mappedCode = $exitCode;
1394 if ( $exitCodeMap ) {
1395 if ( isset( $exitCodeMap[$exitCode] ) ) {
1396 $mappedCode = $exitCodeMap[$exitCode];
1397 } elseif ( isset( $exitCodeMap["*"] ) ) {
1398 $mappedCode = $exitCodeMap["*"];
1399 }
1400 }
1401
1402 if ( $mappedCode === AV_SCAN_FAILED ) {
1403 # scan failed (code was mapped to false by $exitCodeMap)
1404 wfDebug( __METHOD__.": failed to scan $file (code $exitCode).\n" );
1405
1406 if ( $wgAntivirusRequired ) {
1407 return "scan failed (code $exitCode)";
1408 } else {
1409 return NULL;
1410 }
1411 } else if ( $mappedCode === AV_SCAN_ABORTED ) {
1412 # scan failed because filetype is unknown (probably imune)
1413 wfDebug( __METHOD__.": unsupported file type $file (code $exitCode).\n" );
1414 return NULL;
1415 } else if ( $mappedCode === AV_NO_VIRUS ) {
1416 # no virus found
1417 wfDebug( __METHOD__.": file passed virus scan.\n" );
1418 return false;
1419 } else {
1420 $output = join( "\n", $output );
1421 $output = trim( $output );
1422
1423 if ( !$output ) {
1424 $output = true; #if there's no output, return true
1425 } elseif ( $msgPattern ) {
1426 $groups = array();
1427 if ( preg_match( $msgPattern, $output, $groups ) ) {
1428 if ( $groups[1] ) {
1429 $output = $groups[1];
1430 }
1431 }
1432 }
1433
1434 wfDebug( __METHOD__.": FOUND VIRUS! scanner feedback: $output" );
1435 return $output;
1436 }
1437 }
1438
1439 /**
1440 * Check if the temporary file is MacBinary-encoded, as some uploads
1441 * from Internet Explorer on Mac OS Classic and Mac OS X will be.
1442 * If so, the data fork will be extracted to a second temporary file,
1443 * which will then be checked for validity and either kept or discarded.
1444 *
1445 * @access private
1446 */
1447 function checkMacBinary() {
1448 $macbin = new MacBinary( $this->mTempPath );
1449 if( $macbin->isValid() ) {
1450 $dataFile = tempnam( wfTempDir(), "WikiMacBinary" );
1451 $dataHandle = fopen( $dataFile, 'wb' );
1452
1453 wfDebug( "SpecialUpload::checkMacBinary: Extracting MacBinary data fork to $dataFile\n" );
1454 $macbin->extractData( $dataHandle );
1455
1456 $this->mTempPath = $dataFile;
1457 $this->mFileSize = $macbin->dataForkLength();
1458
1459 // We'll have to manually remove the new file if it's not kept.
1460 $this->mRemoveTempFile = true;
1461 }
1462 $macbin->close();
1463 }
1464
1465 /**
1466 * If we've modified the upload file we need to manually remove it
1467 * on exit to clean up.
1468 * @access private
1469 */
1470 function cleanupTempFile() {
1471 if ( $this->mRemoveTempFile && file_exists( $this->mTempPath ) ) {
1472 wfDebug( "SpecialUpload::cleanupTempFile: Removing temporary file {$this->mTempPath}\n" );
1473 unlink( $this->mTempPath );
1474 }
1475 }
1476
1477 /**
1478 * Check if there's an overwrite conflict and, if so, if restrictions
1479 * forbid this user from performing the upload.
1480 *
1481 * @return mixed true on success, WikiError on failure
1482 * @access private
1483 */
1484 function checkOverwrite( $name ) {
1485 $img = wfFindFile( $name );
1486
1487 $error = '';
1488 if( $img ) {
1489 global $wgUser, $wgOut;
1490 if( $img->isLocal() ) {
1491 if( !self::userCanReUpload( $wgUser, $img->name ) ) {
1492 $error = 'fileexists-forbidden';
1493 }
1494 } else {
1495 if( !$wgUser->isAllowed( 'reupload' ) ||
1496 !$wgUser->isAllowed( 'reupload-shared' ) ) {
1497 $error = "fileexists-shared-forbidden";
1498 }
1499 }
1500 }
1501
1502 if( $error ) {
1503 $errorText = wfMsg( $error, wfEscapeWikiText( $img->getName() ) );
1504 return $errorText;
1505 }
1506
1507 // Rockin', go ahead and upload
1508 return true;
1509 }
1510
1511 /**
1512 * Check if a user is the last uploader
1513 *
1514 * @param User $user
1515 * @param string $img, image name
1516 * @return bool
1517 */
1518 public static function userCanReUpload( User $user, $img ) {
1519 if( $user->isAllowed( 'reupload' ) )
1520 return true; // non-conditional
1521 if( !$user->isAllowed( 'reupload-own' ) )
1522 return false;
1523
1524 $dbr = wfGetDB( DB_SLAVE );
1525 $row = $dbr->selectRow('image',
1526 /* SELECT */ 'img_user',
1527 /* WHERE */ array( 'img_name' => $img )
1528 );
1529 if ( !$row )
1530 return false;
1531
1532 return $user->getID() == $row->img_user;
1533 }
1534
1535 /**
1536 * Display an error with a wikitext description
1537 */
1538 function showError( $description ) {
1539 global $wgOut;
1540 $wgOut->setPageTitle( wfMsg( "internalerror" ) );
1541 $wgOut->setRobotpolicy( "noindex,nofollow" );
1542 $wgOut->setArticleRelated( false );
1543 $wgOut->enableClientCache( false );
1544 $wgOut->addWikiText( $description );
1545 }
1546
1547 /**
1548 * Get the initial image page text based on a comment and optional file status information
1549 */
1550 static function getInitialPageText( $comment, $license, $copyStatus, $source ) {
1551 global $wgUseCopyrightUpload;
1552 if ( $wgUseCopyrightUpload ) {
1553 if ( $license != '' ) {
1554 $licensetxt = '== ' . wfMsgForContent( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1555 }
1556 $pageText = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $comment . "\n" .
1557 '== ' . wfMsgForContent ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
1558 "$licensetxt" .
1559 '== ' . wfMsgForContent ( 'filesource' ) . " ==\n" . $source ;
1560 } else {
1561 if ( $license != '' ) {
1562 $filedesc = $comment == '' ? '' : '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $comment . "\n";
1563 $pageText = $filedesc .
1564 '== ' . wfMsgForContent ( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1565 } else {
1566 $pageText = $comment;
1567 }
1568 }
1569 return $pageText;
1570 }
1571
1572 /**
1573 * If there are rows in the deletion log for this file, show them,
1574 * along with a nice little note for the user
1575 *
1576 * @param OutputPage $out
1577 * @param string filename
1578 */
1579 private function showDeletionLog( $out, $filename ) {
1580 $reader = new LogReader(
1581 new FauxRequest(
1582 array(
1583 'page' => $filename,
1584 'type' => 'delete',
1585 )
1586 )
1587 );
1588 if( $reader->hasRows() ) {
1589 $out->addHtml( '<div id="mw-upload-deleted-warn">' );
1590 $out->addWikiText( wfMsg( 'upload-wasdeleted' ) );
1591 $viewer = new LogViewer( $reader );
1592 $viewer->showList( $out );
1593 $out->addHtml( '</div>' );
1594 }
1595 }
1596 }