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