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