In Special:RevisionDelete:
[lhc/web/wiklou.git] / includes / specials / SpecialUpload.php
1 <?php
2 /**
3 * @file
4 * @ingroup 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 * @ingroup 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_LENGTH_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 $this->mForReUpload = $request->getBool( 'wpForReUpload' );
66 $this->mReUpload = $request->getCheck( 'wpReUpload' );
67
68 if( !$request->wasPosted() ) {
69 # GET requests just give the main form; no data except destination
70 # filename and description
71 return;
72 }
73
74 # Placeholders for text injection by hooks (empty per default)
75 $this->uploadFormTextTop = "";
76 $this->uploadFormTextAfterSummary = "";
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 $pathParts = explode( '/', $url );
145 $this->mSrcName = array_pop( $pathParts );
146 $this->mSessionKey = false;
147 $this->mStashed = false;
148
149 // PHP won't auto-cleanup the file
150 $this->mRemoveTempFile = file_exists( $local_file );
151 }
152
153 /**
154 * Safe copy from URL
155 * Returns true if there was an error, false otherwise
156 */
157 private function curlCopy( $url, $dest ) {
158 global $wgUser, $wgOut, $wgHTTPProxy, $wgCopyUploadTimeout;
159
160 if( !$wgUser->isAllowed( 'upload_by_url' ) ) {
161 $wgOut->permissionRequired( 'upload_by_url' );
162 return true;
163 }
164
165 # Maybe remove some pasting blanks :-)
166 $url = trim( $url );
167 if( stripos($url, 'http://') !== 0 && stripos($url, 'ftp://') !== 0 ) {
168 # Only HTTP or FTP URLs
169 $wgOut->showErrorPage( 'upload-proto-error', 'upload-proto-error-text' );
170 return true;
171 }
172
173 # Open temporary file
174 $this->mCurlDestHandle = @fopen( $this->mTempPath, "wb" );
175 if( $this->mCurlDestHandle === false ) {
176 # Could not open temporary file to write in
177 $wgOut->showErrorPage( 'upload-file-error', 'upload-file-error-text');
178 return true;
179 }
180
181 $ch = curl_init();
182 curl_setopt( $ch, CURLOPT_HTTP_VERSION, 1.0); # Probably not needed, but apparently can work around some bug
183 curl_setopt( $ch, CURLOPT_TIMEOUT, $wgCopyUploadTimeout); # Default 30 seconds timeout
184 curl_setopt( $ch, CURLOPT_LOW_SPEED_LIMIT, 512); # 0.5KB per second minimum transfer speed
185 curl_setopt( $ch, CURLOPT_URL, $url);
186 if( $wgHTTPProxy ) {
187 curl_setopt( $ch, CURLOPT_PROXY, $wgHTTPProxy );
188 }
189 curl_setopt( $ch, CURLOPT_WRITEFUNCTION, array( $this, 'uploadCurlCallback' ) );
190 curl_exec( $ch );
191 $error = curl_errno( $ch ) ? true : false;
192 $errornum = curl_errno( $ch );
193 // if ( $error ) print curl_error ( $ch ) ; # Debugging output
194 curl_close( $ch );
195
196 fclose( $this->mCurlDestHandle );
197 unset( $this->mCurlDestHandle );
198 if( $error ) {
199 unlink( $dest );
200 if( wfEmptyMsg( "upload-curl-error$errornum", wfMsg("upload-curl-error$errornum") ) )
201 $wgOut->showErrorPage( 'upload-misc-error', 'upload-misc-error-text' );
202 else
203 $wgOut->showErrorPage( "upload-curl-error$errornum", "upload-curl-error$errornum-text" );
204 }
205
206 return $error;
207 }
208
209 /**
210 * Callback function for CURL-based web transfer
211 * Write data to file unless we've passed the length limit;
212 * if so, abort immediately.
213 * @access private
214 */
215 function uploadCurlCallback( $ch, $data ) {
216 global $wgMaxUploadSize;
217 $length = strlen( $data );
218 $this->mFileSize += $length;
219 if( $this->mFileSize > $wgMaxUploadSize ) {
220 return 0;
221 }
222 fwrite( $this->mCurlDestHandle, $data );
223 return $length;
224 }
225
226 /**
227 * Start doing stuff
228 * @access public
229 */
230 function execute() {
231 global $wgUser, $wgOut;
232 global $wgEnableUploads;
233
234 # Check php's file_uploads setting
235 if( !wfIniGetBool( 'file_uploads' ) ) {
236 $wgOut->showErrorPage( 'uploaddisabled', 'php-uploaddisabledtext', array( $this->mDesiredDestName ) );
237 return;
238 }
239
240 # Check uploading enabled
241 if( !$wgEnableUploads ) {
242 $wgOut->showErrorPage( 'uploaddisabled', 'uploaddisabledtext', array( $this->mDesiredDestName ) );
243 return;
244 }
245
246 # Check permissions
247 global $wgGroupPermissions;
248 if( !$wgUser->isAllowed( 'upload' ) ) {
249 if( !$wgUser->isLoggedIn() && ( $wgGroupPermissions['user']['upload']
250 || $wgGroupPermissions['autoconfirmed']['upload'] ) ) {
251 // Custom message if logged-in users without any special rights can upload
252 $wgOut->showErrorPage( 'uploadnologin', 'uploadnologintext' );
253 } else {
254 $wgOut->permissionRequired( 'upload' );
255 }
256 return;
257 }
258
259 # Check blocks
260 if( $wgUser->isBlocked() ) {
261 $wgOut->blockedPage();
262 return;
263 }
264
265 if( wfReadOnly() ) {
266 $wgOut->readOnlyPage();
267 return;
268 }
269
270 if( $this->mReUpload ) {
271 if( !$this->unsaveUploadedFile() ) {
272 return;
273 }
274 # Because it is probably checked and shouldn't be
275 $this->mIgnoreWarning = false;
276
277 $this->mainUploadForm();
278 } else if( 'submit' == $this->mAction || $this->mUploadClicked ) {
279 $this->processUpload();
280 } else {
281 $this->mainUploadForm();
282 }
283
284 $this->cleanupTempFile();
285 }
286
287 /**
288 * Do the upload
289 * Checks are made in SpecialUpload::execute()
290 *
291 * @access private
292 */
293 function processUpload(){
294 global $wgOut, $wgFileExtensions, $wgLang;
295 $details = null;
296 $value = null;
297 $value = $this->internalProcessUpload( $details );
298
299 switch($value) {
300 case self::SUCCESS:
301 $wgOut->redirect( $this->mLocalFile->getTitle()->getFullURL() );
302 break;
303
304 case self::BEFORE_PROCESSING:
305 break;
306
307 case self::LARGE_FILE_SERVER:
308 $this->mainUploadForm( wfMsgHtml( 'largefileserver' ) );
309 break;
310
311 case self::EMPTY_FILE:
312 $this->mainUploadForm( wfMsgHtml( 'emptyfile' ) );
313 break;
314
315 case self::MIN_LENGTH_PARTNAME:
316 $this->mainUploadForm( wfMsgHtml( 'minlength1' ) );
317 break;
318
319 case self::ILLEGAL_FILENAME:
320 $filtered = $details['filtered'];
321 $this->uploadError( wfMsgWikiHtml( 'illegalfilename', htmlspecialchars( $filtered ) ) );
322 break;
323
324 case self::PROTECTED_PAGE:
325 $wgOut->showPermissionsErrorPage( $details['permissionserrors'] );
326 break;
327
328 case self::OVERWRITE_EXISTING_FILE:
329 $errorText = $details['overwrite'];
330 $this->uploadError( $wgOut->parse( $errorText ) );
331 break;
332
333 case self::FILETYPE_MISSING:
334 $this->uploadError( wfMsgExt( 'filetype-missing', array ( 'parseinline' ) ) );
335 break;
336
337 case self::FILETYPE_BADTYPE:
338 $finalExt = $details['finalExt'];
339 $this->uploadError(
340 wfMsgExt( 'filetype-banned-type',
341 array( 'parseinline' ),
342 htmlspecialchars( $finalExt ),
343 $wgLang->commaList( $wgFileExtensions ),
344 $wgLang->formatNum( count($wgFileExtensions) )
345 )
346 );
347 break;
348
349 case self::VERIFICATION_ERROR:
350 $veri = $details['veri'];
351 $this->uploadError( $veri->toString() );
352 break;
353
354 case self::UPLOAD_VERIFICATION_ERROR:
355 $error = $details['error'];
356 $this->uploadError( $error );
357 break;
358
359 case self::UPLOAD_WARNING:
360 $warning = $details['warning'];
361 $this->uploadWarning( $warning );
362 break;
363
364 case self::INTERNAL_ERROR:
365 $internal = $details['internal'];
366 $this->showError( $internal );
367 break;
368
369 default:
370 throw new MWException( __METHOD__ . ": Unknown value `{$value}`" );
371 }
372 }
373
374 /**
375 * Really do the upload
376 * Checks are made in SpecialUpload::execute()
377 *
378 * @param array $resultDetails contains result-specific dict of additional values
379 *
380 * @access private
381 */
382 function internalProcessUpload( &$resultDetails ) {
383 global $wgUser;
384
385 if( !wfRunHooks( 'UploadForm:BeforeProcessing', array( &$this ) ) )
386 {
387 wfDebug( "Hook 'UploadForm:BeforeProcessing' broke processing the file.\n" );
388 return self::BEFORE_PROCESSING;
389 }
390
391 /**
392 * If there was no filename or a zero size given, give up quick.
393 */
394 if( trim( $this->mSrcName ) == '' || empty( $this->mFileSize ) ) {
395 return self::EMPTY_FILE;
396 }
397
398 /* Check for curl error */
399 if( $this->mCurlError ) {
400 return self::BEFORE_PROCESSING;
401 }
402
403 /**
404 * Chop off any directories in the given filename. Then
405 * filter out illegal characters, and try to make a legible name
406 * out of it. We'll strip some silently that Title would die on.
407 */
408 if( $this->mDesiredDestName ) {
409 $basename = $this->mDesiredDestName;
410 } else {
411 $basename = $this->mSrcName;
412 }
413 $filtered = wfStripIllegalFilenameChars( $basename );
414
415 /* Normalize to title form before we do any further processing */
416 $nt = Title::makeTitleSafe( NS_FILE, $filtered );
417 if( is_null( $nt ) ) {
418 $resultDetails = array( 'filtered' => $filtered );
419 return self::ILLEGAL_FILENAME;
420 }
421 $filtered = $nt->getDBkey();
422
423 /**
424 * We'll want to blacklist against *any* 'extension', and use
425 * only the final one for the whitelist.
426 */
427 list( $partname, $ext ) = $this->splitExtensions( $filtered );
428
429 if( count( $ext ) ) {
430 $finalExt = $ext[count( $ext ) - 1];
431 } else {
432 $finalExt = '';
433 }
434
435 # If there was more than one "extension", reassemble the base
436 # filename to prevent bogus complaints about length
437 if( count( $ext ) > 1 ) {
438 for( $i = 0; $i < count( $ext ) - 1; $i++ )
439 $partname .= '.' . $ext[$i];
440 }
441
442 if( strlen( $partname ) < 1 ) {
443 return self::MIN_LENGTH_PARTNAME;
444 }
445
446 $this->mLocalFile = wfLocalFile( $nt );
447 $this->mDestName = $this->mLocalFile->getName();
448
449 /**
450 * If the image is protected, non-sysop users won't be able
451 * to modify it by uploading a new revision.
452 */
453 $permErrors = $nt->getUserPermissionsErrors( 'edit', $wgUser );
454 $permErrorsUpload = $nt->getUserPermissionsErrors( 'upload', $wgUser );
455 $permErrorsCreate = ( $nt->exists() ? array() : $nt->getUserPermissionsErrors( 'create', $wgUser ) );
456
457 if( $permErrors || $permErrorsUpload || $permErrorsCreate ) {
458 // merge all the problems into one list, avoiding duplicates
459 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsUpload, $permErrors ) );
460 $permErrors = array_merge( $permErrors, wfArrayDiff2( $permErrorsCreate, $permErrors ) );
461 $resultDetails = array( 'permissionserrors' => $permErrors );
462 return self::PROTECTED_PAGE;
463 }
464
465 /**
466 * In some cases we may forbid overwriting of existing files.
467 */
468 $overwrite = $this->checkOverwrite( $this->mDestName );
469 if( $overwrite !== true ) {
470 $resultDetails = array( 'overwrite' => $overwrite );
471 return self::OVERWRITE_EXISTING_FILE;
472 }
473
474 /* Don't allow users to override the blacklist (check file extension) */
475 global $wgCheckFileExtensions, $wgStrictFileExtensions;
476 global $wgFileExtensions, $wgFileBlacklist;
477 if ($finalExt == '') {
478 return self::FILETYPE_MISSING;
479 } elseif ( $this->checkFileExtensionList( $ext, $wgFileBlacklist ) ||
480 ($wgCheckFileExtensions && $wgStrictFileExtensions &&
481 !$this->checkFileExtension( $finalExt, $wgFileExtensions ) ) ) {
482 $resultDetails = array( 'finalExt' => $finalExt );
483 return self::FILETYPE_BADTYPE;
484 }
485
486 /**
487 * Look at the contents of the file; if we can recognize the
488 * type but it's corrupt or data of the wrong type, we should
489 * probably not accept it.
490 */
491 if( !$this->mStashed ) {
492 $this->mFileProps = File::getPropsFromPath( $this->mTempPath, $finalExt );
493 $this->checkMacBinary();
494 $veri = $this->verify( $this->mTempPath, $finalExt );
495
496 if( $veri !== true ) { //it's a wiki error...
497 $resultDetails = array( 'veri' => $veri );
498 return self::VERIFICATION_ERROR;
499 }
500
501 /**
502 * Provide an opportunity for extensions to add further checks
503 */
504 $error = '';
505 if( !wfRunHooks( 'UploadVerification',
506 array( $this->mDestName, $this->mTempPath, &$error ) ) ) {
507 $resultDetails = array( 'error' => $error );
508 return self::UPLOAD_VERIFICATION_ERROR;
509 }
510 }
511
512
513 /**
514 * Check for non-fatal conditions
515 */
516 if ( ! $this->mIgnoreWarning ) {
517 $warning = '';
518
519 $comparableName = str_replace( ' ', '_', $basename );
520 global $wgCapitalLinks, $wgContLang;
521 if ( $wgCapitalLinks ) {
522 $comparableName = $wgContLang->ucfirst( $comparableName );
523 }
524
525 if( $comparableName !== $filtered ) {
526 $warning .= '<li>'.wfMsgHtml( 'badfilename', htmlspecialchars( $this->mDestName ) ).'</li>';
527 }
528
529 global $wgCheckFileExtensions;
530 if ( $wgCheckFileExtensions ) {
531 if ( !$this->checkFileExtension( $finalExt, $wgFileExtensions ) ) {
532 global $wgLang;
533 $warning .= '<li>' .
534 wfMsgExt( 'filetype-unwanted-type',
535 array( 'parseinline' ),
536 htmlspecialchars( $finalExt ),
537 $wgLang->commaList( $wgFileExtensions ),
538 $wgLang->formatNum( count($wgFileExtensions) )
539 ) . '</li>';
540 }
541 }
542
543 global $wgUploadSizeWarning;
544 if ( $wgUploadSizeWarning && ( $this->mFileSize > $wgUploadSizeWarning ) ) {
545 $skin = $wgUser->getSkin();
546 $wsize = $skin->formatSize( $wgUploadSizeWarning );
547 $asize = $skin->formatSize( $this->mFileSize );
548 $warning .= '<li>' . wfMsgHtml( 'large-file', $wsize, $asize ) . '</li>';
549 }
550 if ( $this->mFileSize == 0 ) {
551 $warning .= '<li>'.wfMsgHtml( 'emptyfile' ).'</li>';
552 }
553
554 if ( !$this->mDestWarningAck ) {
555 $warning .= self::getExistsWarning( $this->mLocalFile );
556 }
557
558 $warning .= $this->getDupeWarning( $this->mTempPath, $finalExt, $nt );
559
560 if( $warning != '' ) {
561 /**
562 * Stash the file in a temporary location; the user can choose
563 * to let it through and we'll complete the upload then.
564 */
565 $resultDetails = array( 'warning' => $warning );
566 return self::UPLOAD_WARNING;
567 }
568 }
569
570 /**
571 * Try actually saving the thing...
572 * It will show an error form on failure.
573 */
574 if( !$this->mForReUpload ) {
575 $pageText = self::getInitialPageText( $this->mComment, $this->mLicense,
576 $this->mCopyrightStatus, $this->mCopyrightSource );
577 } else {
578 $pageText = false;
579 }
580
581 $status = $this->mLocalFile->upload( $this->mTempPath, $this->mComment, $pageText,
582 File::DELETE_SOURCE, $this->mFileProps );
583 if ( !$status->isGood() ) {
584 $resultDetails = array( 'internal' => $status->getWikiText() );
585 return self::INTERNAL_ERROR;
586 } else {
587 if ( $this->mWatchthis ) {
588 global $wgUser;
589 $wgUser->addWatch( $this->mLocalFile->getTitle() );
590 }
591 // Success, redirect to description page
592 $img = null; // @todo: added to avoid passing a ref to null - should this be defined somewhere?
593 wfRunHooks( 'UploadComplete', array( &$this ) );
594 return self::SUCCESS;
595 }
596 }
597
598 /**
599 * Do existence checks on a file and produce a warning
600 * This check is static and can be done pre-upload via AJAX
601 * Returns an HTML fragment consisting of one or more LI elements if there is a warning
602 * Returns an empty string if there is no warning
603 */
604 static function getExistsWarning( $file ) {
605 global $wgUser, $wgContLang;
606 // Check for uppercase extension. We allow these filenames but check if an image
607 // with lowercase extension exists already
608 $warning = '';
609 $align = $wgContLang->isRtl() ? 'left' : 'right';
610
611 if( strpos( $file->getName(), '.' ) == false ) {
612 $partname = $file->getName();
613 $rawExtension = '';
614 } else {
615 $n = strrpos( $file->getName(), '.' );
616 $rawExtension = substr( $file->getName(), $n + 1 );
617 $partname = substr( $file->getName(), 0, $n );
618 }
619
620 $sk = $wgUser->getSkin();
621
622 if ( $rawExtension != $file->getExtension() ) {
623 // We're not using the normalized form of the extension.
624 // Normal form is lowercase, using most common of alternate
625 // extensions (eg 'jpg' rather than 'JPEG').
626 //
627 // Check for another file using the normalized form...
628 $nt_lc = Title::makeTitle( NS_FILE, $partname . '.' . $file->getExtension() );
629 $file_lc = wfLocalFile( $nt_lc );
630 } else {
631 $file_lc = false;
632 }
633
634 if( $file->exists() ) {
635 $dlink = $sk->makeKnownLinkObj( $file->getTitle() );
636 if ( $file->allowInlineDisplay() ) {
637 $dlink2 = $sk->makeImageLinkObj( $file->getTitle(), wfMsgExt( 'fileexists-thumb', 'parseinline' ),
638 $file->getName(), $align, array(), false, true );
639 } elseif ( !$file->allowInlineDisplay() && $file->isSafeFile() ) {
640 $icon = $file->iconThumb();
641 $dlink2 = '<div style="float:' . $align . '" id="mw-media-icon">' .
642 $icon->toHtml( array( 'desc-link' => true ) ) . '<br />' . $dlink . '</div>';
643 } else {
644 $dlink2 = '';
645 }
646
647 $warning .= '<li>' . wfMsgExt( 'fileexists', array('parseinline','replaceafter'), $dlink ) . '</li>' . $dlink2;
648
649 } elseif( $file->getTitle()->getArticleID() ) {
650 $lnk = $sk->makeKnownLinkObj( $file->getTitle(), '', 'redirect=no' );
651 $warning .= '<li>' . wfMsgExt( 'filepageexists', array( 'parseinline', 'replaceafter' ), $lnk ) . '</li>';
652 } elseif ( $file_lc && $file_lc->exists() ) {
653 # Check if image with lowercase extension exists.
654 # It's not forbidden but in 99% it makes no sense to upload the same filename with uppercase extension
655 $dlink = $sk->makeKnownLinkObj( $nt_lc );
656 if ( $file_lc->allowInlineDisplay() ) {
657 $dlink2 = $sk->makeImageLinkObj( $nt_lc, wfMsgExt( 'fileexists-thumb', 'parseinline' ),
658 $nt_lc->getText(), $align, array(), false, true );
659 } elseif ( !$file_lc->allowInlineDisplay() && $file_lc->isSafeFile() ) {
660 $icon = $file_lc->iconThumb();
661 $dlink2 = '<div style="float:' . $align . '" id="mw-media-icon">' .
662 $icon->toHtml( array( 'desc-link' => true ) ) . '<br />' . $dlink . '</div>';
663 } else {
664 $dlink2 = '';
665 }
666
667 $warning .= '<li>' .
668 wfMsgExt( 'fileexists-extension', 'parsemag',
669 $file->getTitle()->getPrefixedText(), $dlink ) .
670 '</li>' . $dlink2;
671
672 } elseif ( ( substr( $partname , 3, 3 ) == 'px-' || substr( $partname , 2, 3 ) == 'px-' )
673 && preg_match( "/[0-9]{2}/" , substr( $partname , 0, 2 ) ) )
674 {
675 # Check for filenames like 50px- or 180px-, these are mostly thumbnails
676 $nt_thb = Title::newFromText( substr( $partname , strpos( $partname , '-' ) +1 ) . '.' . $rawExtension );
677 $file_thb = wfLocalFile( $nt_thb );
678 if ($file_thb->exists() ) {
679 # Check if an image without leading '180px-' (or similiar) exists
680 $dlink = $sk->makeKnownLinkObj( $nt_thb);
681 if ( $file_thb->allowInlineDisplay() ) {
682 $dlink2 = $sk->makeImageLinkObj( $nt_thb,
683 wfMsgExt( 'fileexists-thumb', 'parseinline' ),
684 $nt_thb->getText(), $align, array(), false, true );
685 } elseif ( !$file_thb->allowInlineDisplay() && $file_thb->isSafeFile() ) {
686 $icon = $file_thb->iconThumb();
687 $dlink2 = '<div style="float:' . $align . '" id="mw-media-icon">' .
688 $icon->toHtml( array( 'desc-link' => true ) ) . '<br />' .
689 $dlink . '</div>';
690 } else {
691 $dlink2 = '';
692 }
693
694 $warning .= '<li>' . wfMsgExt( 'fileexists-thumbnail-yes', 'parsemag', $dlink ) .
695 '</li>' . $dlink2;
696 } else {
697 # Image w/o '180px-' does not exists, but we do not like these filenames
698 $warning .= '<li>' . wfMsgExt( 'file-thumbnail-no', 'parseinline' ,
699 substr( $partname , 0, strpos( $partname , '-' ) +1 ) ) . '</li>';
700 }
701 }
702
703 $filenamePrefixBlacklist = self::getFilenamePrefixBlacklist();
704 # Do the match
705 foreach( $filenamePrefixBlacklist as $prefix ) {
706 if ( substr( $partname, 0, strlen( $prefix ) ) == $prefix ) {
707 $warning .= '<li>' . wfMsgExt( 'filename-bad-prefix', 'parseinline', $prefix ) . '</li>';
708 break;
709 }
710 }
711
712 if ( $file->wasDeleted() && !$file->exists() ) {
713 # If the file existed before and was deleted, warn the user of this
714 # Don't bother doing so if the file exists now, however
715 $ltitle = SpecialPage::getTitleFor( 'Log' );
716 $llink = $sk->makeKnownLinkObj( $ltitle, wfMsgHtml( 'deletionlog' ),
717 'type=delete&page=' . $file->getTitle()->getPrefixedUrl() );
718 $warning .= '<li>' . wfMsgWikiHtml( 'filewasdeleted', $llink ) . '</li>';
719 }
720 return $warning;
721 }
722
723 /**
724 * Get a list of warnings
725 *
726 * @param string local filename, e.g. 'file exists', 'non-descriptive filename'
727 * @return array list of warning messages
728 */
729 static function ajaxGetExistsWarning( $filename ) {
730 $file = wfFindFile( $filename );
731 if( !$file ) {
732 // Force local file so we have an object to do further checks against
733 // if there isn't an exact match...
734 $file = wfLocalFile( $filename );
735 }
736 $s = '&nbsp;';
737 if ( $file ) {
738 $warning = self::getExistsWarning( $file );
739 if ( $warning !== '' ) {
740 $s = "<ul>$warning</ul>";
741 }
742 }
743 return $s;
744 }
745
746 /**
747 * Render a preview of a given license for the AJAX preview on upload
748 *
749 * @param string $license
750 * @return string
751 */
752 public static function ajaxGetLicensePreview( $license ) {
753 global $wgParser, $wgUser;
754 $text = '{{' . $license . '}}';
755 $title = Title::makeTitle( NS_FILE, 'Sample.jpg' );
756 $options = ParserOptions::newFromUser( $wgUser );
757
758 // Expand subst: first, then live templates...
759 $text = $wgParser->preSaveTransform( $text, $title, $wgUser, $options );
760 $output = $wgParser->parse( $text, $title, $options );
761
762 return $output->getText();
763 }
764
765 /**
766 * Check for duplicate files and throw up a warning before the upload
767 * completes.
768 */
769 function getDupeWarning( $tempfile, $extension, $destinationTitle ) {
770 $hash = File::sha1Base36( $tempfile );
771 $dupes = RepoGroup::singleton()->findBySha1( $hash );
772 $archivedImage = new ArchivedFile( null, 0, $hash.".$extension" );
773 if( $dupes ) {
774 global $wgOut;
775 $msg = "<gallery>";
776 foreach( $dupes as $file ) {
777 $title = $file->getTitle();
778 # Don't throw the warning when the titles are the same, it's a reupload
779 # and highly redundant.
780 if ( !$title->equals( $destinationTitle ) || !$this->mForReUpload ) {
781 $msg .= $title->getPrefixedText() .
782 "|" . $title->getText() . "\n";
783 }
784 }
785 $msg .= "</gallery>";
786 return "<li>" .
787 wfMsgExt( "file-exists-duplicate", array( "parse" ), count( $dupes ) ) .
788 $wgOut->parse( $msg ) .
789 "</li>\n";
790 } elseif ( $archivedImage->getID() > 0 ) {
791 global $wgOut;
792 $name = Title::makeTitle( NS_FILE, $archivedImage->getName() )->getPrefixedText();
793 return Xml::tags( 'li', null, wfMsgExt( 'file-deleted-duplicate', array( 'parseinline' ), array( $name ) ) );
794 } else {
795 return '';
796 }
797 }
798
799 /**
800 * Get a list of blacklisted filename prefixes from [[MediaWiki:filename-prefix-blacklist]]
801 *
802 * @return array list of prefixes
803 */
804 public static function getFilenamePrefixBlacklist() {
805 $blacklist = array();
806 $message = wfMsgForContent( 'filename-prefix-blacklist' );
807 if( $message && !( wfEmptyMsg( 'filename-prefix-blacklist', $message ) || $message == '-' ) ) {
808 $lines = explode( "\n", $message );
809 foreach( $lines as $line ) {
810 // Remove comment lines
811 $comment = substr( trim( $line ), 0, 1 );
812 if ( $comment == '#' || $comment == '' ) {
813 continue;
814 }
815 // Remove additional comments after a prefix
816 $comment = strpos( $line, '#' );
817 if ( $comment > 0 ) {
818 $line = substr( $line, 0, $comment-1 );
819 }
820 $blacklist[] = trim( $line );
821 }
822 }
823 return $blacklist;
824 }
825
826 /**
827 * Stash a file in a temporary directory for later processing
828 * after the user has confirmed it.
829 *
830 * If the user doesn't explicitly cancel or accept, these files
831 * can accumulate in the temp directory.
832 *
833 * @param string $saveName - the destination filename
834 * @param string $tempName - the source temporary file to save
835 * @return string - full path the stashed file, or false on failure
836 * @access private
837 */
838 function saveTempUploadedFile( $saveName, $tempName ) {
839 global $wgOut;
840 $repo = RepoGroup::singleton()->getLocalRepo();
841 $status = $repo->storeTemp( $saveName, $tempName );
842 if ( !$status->isGood() ) {
843 $this->showError( $status->getWikiText() );
844 return false;
845 } else {
846 return $status->value;
847 }
848 }
849
850 /**
851 * Stash a file in a temporary directory for later processing,
852 * and save the necessary descriptive info into the session.
853 * Returns a key value which will be passed through a form
854 * to pick up the path info on a later invocation.
855 *
856 * @return int
857 * @access private
858 */
859 function stashSession() {
860 $stash = $this->saveTempUploadedFile( $this->mDestName, $this->mTempPath );
861
862 if( !$stash ) {
863 # Couldn't save the file.
864 return false;
865 }
866
867 $key = mt_rand( 0, 0x7fffffff );
868 $_SESSION['wsUploadData'][$key] = array(
869 'mTempPath' => $stash,
870 'mFileSize' => $this->mFileSize,
871 'mSrcName' => $this->mSrcName,
872 'mFileProps' => $this->mFileProps,
873 'version' => self::SESSION_VERSION,
874 );
875 return $key;
876 }
877
878 /**
879 * Remove a temporarily kept file stashed by saveTempUploadedFile().
880 * @access private
881 * @return success
882 */
883 function unsaveUploadedFile() {
884 global $wgOut;
885 if( !$this->mTempPath ) return true; // nothing to delete
886 $repo = RepoGroup::singleton()->getLocalRepo();
887 $success = $repo->freeTemp( $this->mTempPath );
888 if ( ! $success ) {
889 $wgOut->showFileDeleteError( $this->mTempPath );
890 return false;
891 } else {
892 return true;
893 }
894 }
895
896 /* -------------------------------------------------------------- */
897
898 /**
899 * @param string $error as HTML
900 * @access private
901 */
902 function uploadError( $error ) {
903 global $wgOut;
904 $wgOut->addHTML( '<h2>' . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
905 $wgOut->addHTML( '<span class="error">' . $error . '</span>' );
906 }
907
908 /**
909 * There's something wrong with this file, not enough to reject it
910 * totally but we require manual intervention to save it for real.
911 * Stash it away, then present a form asking to confirm or cancel.
912 *
913 * @param string $warning as HTML
914 * @access private
915 */
916 function uploadWarning( $warning ) {
917 global $wgOut;
918 global $wgUseCopyrightUpload;
919
920 $this->mSessionKey = $this->stashSession();
921 if( !$this->mSessionKey ) {
922 # Couldn't save file; an error has been displayed so let's go.
923 return;
924 }
925
926 $wgOut->addHTML( '<h2>' . wfMsgHtml( 'uploadwarning' ) . "</h2>\n" );
927 $wgOut->addHTML( '<ul class="warning">' . $warning . "</ul>\n" );
928
929 $titleObj = SpecialPage::getTitleFor( 'Upload' );
930
931 if ( $wgUseCopyrightUpload ) {
932 $copyright = Xml::hidden( 'wpUploadCopyStatus', $this->mCopyrightStatus ) . "\n" .
933 Xml::hidden( 'wpUploadSource', $this->mCopyrightSource ) . "\n";
934 } else {
935 $copyright = '';
936 }
937
938 $wgOut->addHTML(
939 Xml::openElement( 'form', array( 'method' => 'post', 'action' => $titleObj->getLocalURL( 'action=submit' ),
940 'enctype' => 'multipart/form-data', 'id' => 'uploadwarning' ) ) . "\n" .
941 Xml::hidden( 'wpIgnoreWarning', '1' ) . "\n" .
942 Xml::hidden( 'wpSessionKey', $this->mSessionKey ) . "\n" .
943 Xml::hidden( 'wpUploadDescription', $this->mComment ) . "\n" .
944 Xml::hidden( 'wpLicense', $this->mLicense ) . "\n" .
945 Xml::hidden( 'wpDestFile', $this->mDesiredDestName ) . "\n" .
946 Xml::hidden( 'wpWatchthis', $this->mWatchthis ) . "\n" .
947 "{$copyright}<br />" .
948 Xml::submitButton( wfMsg( 'ignorewarning' ), array ( 'name' => 'wpUpload', 'id' => 'wpUpload', 'checked' => 'checked' ) ) . ' ' .
949 Xml::submitButton( wfMsg( 'reuploaddesc' ), array ( 'name' => 'wpReUpload', 'id' => 'wpReUpload' ) ) .
950 Xml::closeElement( 'form' ) . "\n"
951 );
952 }
953
954 /**
955 * Displays the main upload form, optionally with a highlighted
956 * error message up at the top.
957 *
958 * @param string $msg as HTML
959 * @access private
960 */
961 function mainUploadForm( $msg='' ) {
962 global $wgOut, $wgUser, $wgLang, $wgMaxUploadSize;
963 global $wgUseCopyrightUpload, $wgUseAjax, $wgAjaxUploadDestCheck, $wgAjaxLicensePreview;
964 global $wgRequest, $wgAllowCopyUploads;
965 global $wgStylePath, $wgStyleVersion;
966
967 $useAjaxDestCheck = $wgUseAjax && $wgAjaxUploadDestCheck;
968 $useAjaxLicensePreview = $wgUseAjax && $wgAjaxLicensePreview;
969
970 $adc = wfBoolToStr( $useAjaxDestCheck );
971 $alp = wfBoolToStr( $useAjaxLicensePreview );
972 $autofill = wfBoolToStr( $this->mDesiredDestName == '' );
973
974 $wgOut->addScript( "<script type=\"text/javascript\">
975 wgAjaxUploadDestCheck = {$adc};
976 wgAjaxLicensePreview = {$alp};
977 wgUploadAutoFill = {$autofill};
978 </script>" );
979 $wgOut->addScriptFile( 'upload.js' );
980 $wgOut->addScriptFile( 'edit.js' ); // For <charinsert> support
981
982 if( !wfRunHooks( 'UploadForm:initial', array( &$this ) ) )
983 {
984 wfDebug( "Hook 'UploadForm:initial' broke output of the upload form\n" );
985 return false;
986 }
987
988 if( $this->mDesiredDestName ) {
989 $title = Title::makeTitleSafe( NS_FILE, $this->mDesiredDestName );
990 // Show a subtitle link to deleted revisions (to sysops et al only)
991 if( $title instanceof Title && ( $count = $title->isDeleted() ) > 0 && $wgUser->isAllowed( 'deletedhistory' ) ) {
992 $link = wfMsgExt(
993 $wgUser->isAllowed( 'delete' ) ? 'thisisdeleted' : 'viewdeleted',
994 array( 'parse', 'replaceafter' ),
995 $wgUser->getSkin()->makeKnownLinkObj(
996 SpecialPage::getTitleFor( 'Undelete', $title->getPrefixedText() ),
997 wfMsgExt( 'restorelink', array( 'parsemag', 'escape' ), $count )
998 )
999 );
1000 $wgOut->addHTML( "<div id=\"contentSub2\">{$link}</div>" );
1001 }
1002
1003 // Show the relevant lines from deletion log (for still deleted files only)
1004 if( $title instanceof Title && $title->isDeletedQuick() && !$title->exists() ) {
1005 $this->showDeletionLog( $wgOut, $title->getPrefixedText() );
1006 }
1007 }
1008
1009 $cols = intval($wgUser->getOption( 'cols' ));
1010
1011 if( $wgUser->getOption( 'editwidth' ) ) {
1012 $width = " style=\"width:100%\"";
1013 } else {
1014 $width = '';
1015 }
1016
1017 if ( '' != $msg ) {
1018 $sub = wfMsgHtml( 'uploaderror' );
1019 $wgOut->addHTML( "<h2>{$sub}</h2>\n" .
1020 "<span class='error'>{$msg}</span>\n" );
1021 }
1022 $wgOut->addHTML( '<div id="uploadtext">' );
1023 $wgOut->addWikiMsg( 'uploadtext', $this->mDesiredDestName );
1024 $wgOut->addHTML( "</div>\n" );
1025
1026 # Print a list of allowed file extensions, if so configured. We ignore
1027 # MIME type here, it's incomprehensible to most people and too long.
1028 global $wgCheckFileExtensions, $wgStrictFileExtensions,
1029 $wgFileExtensions, $wgFileBlacklist;
1030
1031 $allowedExtensions = '';
1032 if( $wgCheckFileExtensions ) {
1033 if( $wgStrictFileExtensions ) {
1034 # Everything not permitted is banned
1035 $extensionsList =
1036 '<div id="mw-upload-permitted">' .
1037 wfMsgWikiHtml( 'upload-permitted', $wgLang->commaList( $wgFileExtensions ) ) .
1038 "</div>\n";
1039 } else {
1040 # We have to list both preferred and prohibited
1041 $extensionsList =
1042 '<div id="mw-upload-preferred">' .
1043 wfMsgWikiHtml( 'upload-preferred', $wgLang->commaList( $wgFileExtensions ) ) .
1044 "</div>\n" .
1045 '<div id="mw-upload-prohibited">' .
1046 wfMsgWikiHtml( 'upload-prohibited', $wgLang->commaList( $wgFileBlacklist ) ) .
1047 "</div>\n";
1048 }
1049 } else {
1050 # Everything is permitted.
1051 $extensionsList = '';
1052 }
1053
1054 # Get the maximum file size from php.ini as $wgMaxUploadSize works for uploads from URL via CURL only
1055 # See http://www.php.net/manual/en/faq.using.php#faq.using.shorthandbytes for possible values of upload_max_filesize and post_max_filesize
1056 $max_sizes = array();
1057 $max_sizes[] = trim( ini_get( 'upload_max_filesize' ) );
1058 $max_sizes[] = trim( ini_get( 'post_max_size' ) );
1059 foreach( $max_sizes as &$size) {
1060 $last = strtoupper( substr( $size, -1 ) );
1061 switch( $last ) {
1062 case 'G':
1063 $size = substr( $size, 0, -1 ) * 1024 * 1024 * 1024;
1064 break;
1065 case 'M':
1066 $size = substr( $size, 0, -1 ) * 1024 * 1024;
1067 break;
1068 case 'K':
1069 $size = substr( $size, 0, -1 ) * 1024;
1070 break;
1071 }
1072 }
1073 $val = min( $max_sizes[0], $max_sizes[1] );
1074 $val = $wgAllowCopyUploads ? min( $wgMaxUploadSize, $val ) : $val;
1075 $maxUploadSize = '<div id="mw-upload-maxfilesize">' .
1076 wfMsgExt( 'upload-maxfilesize', array( 'parseinline', 'escapenoentities' ),
1077 $wgLang->formatSize( $val ) ) .
1078 "</div>\n";
1079
1080 $sourcefilename = wfMsgExt( 'sourcefilename', array( 'parseinline', 'escapenoentities' ) );
1081 $destfilename = wfMsgExt( 'destfilename', array( 'parseinline', 'escapenoentities' ) );
1082
1083 $msg = $this->mForReUpload ? 'filereuploadsummary' : 'fileuploadsummary';
1084 $summary = wfMsgExt( $msg, 'parseinline' );
1085
1086 $licenses = new Licenses();
1087 $license = wfMsgExt( 'license', array( 'parseinline' ) );
1088 $nolicense = wfMsgHtml( 'nolicense' );
1089 $licenseshtml = $licenses->getHtml();
1090
1091 $ulb = wfMsgHtml( 'uploadbtn' );
1092
1093
1094 $titleObj = SpecialPage::getTitleFor( 'Upload' );
1095
1096 $encDestName = htmlspecialchars( $this->mDesiredDestName );
1097
1098 $watchChecked = $this->watchCheck() ? 'checked="checked"' : '';
1099 # Re-uploads should not need "file exist already" warnings
1100 $warningChecked = ($this->mIgnoreWarning || $this->mForReUpload) ? 'checked="checked"' : '';
1101
1102 // Prepare form for upload or upload/copy
1103 if( $wgAllowCopyUploads && $wgUser->isAllowed( 'upload_by_url' ) ) {
1104 $filename_form =
1105 "<input type='radio' id='wpSourceTypeFile' name='wpSourceType' value='file' " .
1106 "onchange='toggle_element_activation(\"wpUploadFileURL\",\"wpUploadFile\")' checked='checked' />" .
1107 "<input tabindex='1' type='file' name='wpUploadFile' id='wpUploadFile' " .
1108 "onfocus='" .
1109 "toggle_element_activation(\"wpUploadFileURL\",\"wpUploadFile\");" .
1110 "toggle_element_check(\"wpSourceTypeFile\",\"wpSourceTypeURL\")' " .
1111 "onchange='fillDestFilename(\"wpUploadFile\")' size='60' />" .
1112 wfMsgHTML( 'upload_source_file' ) . "<br/>" .
1113 "<input type='radio' id='wpSourceTypeURL' name='wpSourceType' value='web' " .
1114 "onchange='toggle_element_activation(\"wpUploadFile\",\"wpUploadFileURL\")' />" .
1115 "<input tabindex='1' type='text' name='wpUploadFileURL' id='wpUploadFileURL' " .
1116 "onfocus='" .
1117 "toggle_element_activation(\"wpUploadFile\",\"wpUploadFileURL\");" .
1118 "toggle_element_check(\"wpSourceTypeURL\",\"wpSourceTypeFile\")' " .
1119 "onchange='fillDestFilename(\"wpUploadFileURL\")' size='60' disabled='disabled' />" .
1120 wfMsgHtml( 'upload_source_url' ) ;
1121 } else {
1122 $filename_form =
1123 "<input tabindex='1' type='file' name='wpUploadFile' id='wpUploadFile' " .
1124 ($this->mDesiredDestName?"":"onchange='fillDestFilename(\"wpUploadFile\")' ") .
1125 "size='60' />" .
1126 "<input type='hidden' name='wpSourceType' value='file' />" ;
1127 }
1128 if ( $useAjaxDestCheck ) {
1129 $warningRow = "<tr><td colspan='2' id='wpDestFile-warning'>&nbsp;</td></tr>";
1130 $destOnkeyup = 'onkeyup="wgUploadWarningObj.keypress();"';
1131 } else {
1132 $warningRow = '';
1133 $destOnkeyup = '';
1134 }
1135 $encComment = htmlspecialchars( $this->mComment );
1136
1137
1138 $wgOut->addHTML(
1139 Xml::openElement( 'form', array( 'method' => 'post', 'action' => $titleObj->getLocalURL(),
1140 'enctype' => 'multipart/form-data', 'id' => 'mw-upload-form' ) ) .
1141 Xml::openElement( 'fieldset' ) .
1142 Xml::element( 'legend', null, wfMsg( 'upload' ) ) .
1143 Xml::openElement( 'table', array( 'border' => '0', 'id' => 'mw-upload-table' ) ) .
1144 "<tr>
1145 {$this->uploadFormTextTop}
1146 <td class='mw-label'>
1147 <label for='wpUploadFile'>{$sourcefilename}</label>
1148 </td>
1149 <td class='mw-input'>
1150 {$filename_form}
1151 </td>
1152 </tr>
1153 <tr>
1154 <td></td>
1155 <td>
1156 {$maxUploadSize}
1157 {$extensionsList}
1158 </td>
1159 </tr>
1160 <tr>
1161 <td class='mw-label'>
1162 <label for='wpDestFile'>{$destfilename}</label>
1163 </td>
1164 <td class='mw-input'>"
1165 );
1166 if( $this->mForReUpload ) {
1167 $wgOut->addHTML(
1168 Xml::hidden( 'wpDestFile', $this->mDesiredDestName, array('id'=>'wpDestFile','tabindex'=>2) ) .
1169 "<tt>" .
1170 $encDestName .
1171 "</tt>"
1172 );
1173 }
1174 else {
1175 $wgOut->addHTML(
1176 "<input tabindex='2' type='text' name='wpDestFile' id='wpDestFile' size='60'
1177 value=\"{$encDestName}\" onchange='toggleFilenameFiller()' $destOnkeyup />"
1178 );
1179 }
1180
1181
1182 $wgOut->addHTML(
1183 "</td>
1184 </tr>
1185 <tr>
1186 <td class='mw-label'>
1187 <label for='wpUploadDescription'>{$summary}</label>
1188 </td>
1189 <td class='mw-input'>
1190 <textarea tabindex='3' name='wpUploadDescription' id='wpUploadDescription' rows='6'
1191 cols='{$cols}'{$width}>$encComment</textarea>
1192 {$this->uploadFormTextAfterSummary}
1193 </td>
1194 </tr>
1195 <tr>"
1196 );
1197 # Re-uploads should not need license info
1198 if ( !$this->mForReUpload && $licenseshtml != '' ) {
1199 global $wgStylePath;
1200 $wgOut->addHTML( "
1201 <td class='mw-label'>
1202 <label for='wpLicense'>$license</label>
1203 </td>
1204 <td class='mw-input'>
1205 <select name='wpLicense' id='wpLicense' tabindex='4'
1206 onchange='licenseSelectorCheck()'>
1207 <option value=''>$nolicense</option>
1208 $licenseshtml
1209 </select>
1210 </td>
1211 </tr>
1212 <tr>"
1213 );
1214 if( $useAjaxLicensePreview ) {
1215 $wgOut->addHTML( "
1216 <td></td>
1217 <td id=\"mw-license-preview\"></td>
1218 </tr>
1219 <tr>"
1220 );
1221 }
1222 }
1223
1224 if ( !$this->mForReUpload && $wgUseCopyrightUpload ) {
1225 $filestatus = wfMsgExt( 'filestatus', 'escapenoentities' );
1226 $copystatus = htmlspecialchars( $this->mCopyrightStatus );
1227 $filesource = wfMsgExt( 'filesource', 'escapenoentities' );
1228 $uploadsource = htmlspecialchars( $this->mCopyrightSource );
1229
1230 $wgOut->addHTML( "
1231 <td class='mw-label' style='white-space: nowrap;'>
1232 <label for='wpUploadCopyStatus'>$filestatus</label></td>
1233 <td class='mw-input'>
1234 <input tabindex='5' type='text' name='wpUploadCopyStatus' id='wpUploadCopyStatus'
1235 value=\"$copystatus\" size='60' />
1236 </td>
1237 </tr>
1238 <tr>
1239 <td class='mw-label'>
1240 <label for='wpUploadCopyStatus'>$filesource</label>
1241 </td>
1242 <td class='mw-input'>
1243 <input tabindex='6' type='text' name='wpUploadSource' id='wpUploadCopyStatus'
1244 value=\"$uploadsource\" size='60' />
1245 </td>
1246 </tr>
1247 <tr>"
1248 );
1249 }
1250
1251 $wgOut->addHTML( "
1252 <td></td>
1253 <td>
1254 <input tabindex='7' type='checkbox' name='wpWatchthis' id='wpWatchthis' $watchChecked value='true' />
1255 <label for='wpWatchthis'>" . wfMsgHtml( 'watchthisupload' ) . "</label>
1256 <input tabindex='8' type='checkbox' name='wpIgnoreWarning' id='wpIgnoreWarning' value='true' $warningChecked />
1257 <label for='wpIgnoreWarning'>" . wfMsgHtml( 'ignorewarnings' ) . "</label>
1258 </td>
1259 </tr>
1260 $warningRow
1261 <tr>
1262 <td></td>
1263 <td class='mw-input'>
1264 <input tabindex='9' type='submit' name='wpUpload' value=\"{$ulb}\"" .
1265 $wgUser->getSkin()->tooltipAndAccesskey( 'upload' ) . " />
1266 </td>
1267 </tr>
1268 <tr>
1269 <td></td>
1270 <td class='mw-input'>"
1271 );
1272 $wgOut->addHTML( '<div class="mw-editTools">' );
1273 $wgOut->addWikiMsgArray( 'edittools', array(), array( 'content' ) );
1274 $wgOut->addHTML( '</div>' );
1275 $wgOut->addHTML( "
1276 </td>
1277 </tr>" .
1278 Xml::closeElement( 'table' ) .
1279 Xml::hidden( 'wpDestFileWarningAck', '', array( 'id' => 'wpDestFileWarningAck' ) ) .
1280 Xml::hidden( 'wpForReUpload', $this->mForReUpload, array( 'id' => 'wpForReUpload' ) ) .
1281 Xml::closeElement( 'fieldset' ) .
1282 Xml::closeElement( 'form' )
1283 );
1284 $uploadfooter = wfMsgNoTrans( 'uploadfooter' );
1285 if( $uploadfooter != '-' && !wfEmptyMsg( 'uploadfooter', $uploadfooter ) ){
1286 $wgOut->addWikiText( '<div id="mw-upload-footer-message">' . $uploadfooter . '</div>' );
1287 }
1288 }
1289
1290 /* -------------------------------------------------------------- */
1291
1292 /**
1293 * See if we should check the 'watch this page' checkbox on the form
1294 * based on the user's preferences and whether we're being asked
1295 * to create a new file or update an existing one.
1296 *
1297 * In the case where 'watch edits' is off but 'watch creations' is on,
1298 * we'll leave the box unchecked.
1299 *
1300 * Note that the page target can be changed *on the form*, so our check
1301 * state can get out of sync.
1302 */
1303 function watchCheck() {
1304 global $wgUser;
1305 if( $wgUser->getOption( 'watchdefault' ) ) {
1306 // Watch all edits!
1307 return true;
1308 }
1309
1310 $local = wfLocalFile( $this->mDesiredDestName );
1311 if( $local && $local->exists() ) {
1312 // We're uploading a new version of an existing file.
1313 // No creation, so don't watch it if we're not already.
1314 return $local->getTitle()->userIsWatching();
1315 } else {
1316 // New page should get watched if that's our option.
1317 return $wgUser->getOption( 'watchcreations' );
1318 }
1319 }
1320
1321 /**
1322 * Split a file into a base name and all dot-delimited 'extensions'
1323 * on the end. Some web server configurations will fall back to
1324 * earlier pseudo-'extensions' to determine type and execute
1325 * scripts, so the blacklist needs to check them all.
1326 *
1327 * @return array
1328 */
1329 public function splitExtensions( $filename ) {
1330 $bits = explode( '.', $filename );
1331 $basename = array_shift( $bits );
1332 return array( $basename, $bits );
1333 }
1334
1335 /**
1336 * Perform case-insensitive match against a list of file extensions.
1337 * Returns true if the extension is in the list.
1338 *
1339 * @param string $ext
1340 * @param array $list
1341 * @return bool
1342 */
1343 function checkFileExtension( $ext, $list ) {
1344 return in_array( strtolower( $ext ), $list );
1345 }
1346
1347 /**
1348 * Perform case-insensitive match against a list of file extensions.
1349 * Returns true if any of the extensions are in the list.
1350 *
1351 * @param array $ext
1352 * @param array $list
1353 * @return bool
1354 */
1355 public function checkFileExtensionList( $ext, $list ) {
1356 foreach( $ext as $e ) {
1357 if( in_array( strtolower( $e ), $list ) ) {
1358 return true;
1359 }
1360 }
1361 return false;
1362 }
1363
1364 /**
1365 * Verifies that it's ok to include the uploaded file
1366 *
1367 * @param string $tmpfile the full path of the temporary file to verify
1368 * @param string $extension The filename extension that the file is to be served with
1369 * @return mixed true of the file is verified, a WikiError object otherwise.
1370 */
1371 function verify( $tmpfile, $extension ) {
1372 #magically determine mime type
1373 $magic = MimeMagic::singleton();
1374 $mime = $magic->guessMimeType($tmpfile,false);
1375
1376
1377 #check mime type, if desired
1378 global $wgVerifyMimeType;
1379 if ($wgVerifyMimeType) {
1380 wfDebug ( "\n\nmime: <$mime> extension: <$extension>\n\n");
1381 #check mime type against file extension
1382 if( !self::verifyExtension( $mime, $extension ) ) {
1383 return new WikiErrorMsg( 'uploadcorrupt' );
1384 }
1385
1386 #check mime type blacklist
1387 global $wgMimeTypeBlacklist;
1388 if( isset($wgMimeTypeBlacklist) && !is_null($wgMimeTypeBlacklist) ) {
1389 if ( $this->checkFileExtension( $mime, $wgMimeTypeBlacklist ) ) {
1390 return new WikiErrorMsg( 'filetype-badmime', htmlspecialchars( $mime ) );
1391 }
1392
1393 # Check IE type
1394 $fp = fopen( $tmpfile, 'rb' );
1395 $chunk = fread( $fp, 256 );
1396 fclose( $fp );
1397 $extMime = $magic->guessTypesForExtension( $extension );
1398 $ieTypes = $magic->getIEMimeTypes( $tmpfile, $chunk, $extMime );
1399 foreach ( $ieTypes as $ieType ) {
1400 if ( $this->checkFileExtension( $ieType, $wgMimeTypeBlacklist ) ) {
1401 return new WikiErrorMsg( 'filetype-bad-ie-mime', $ieType );
1402 }
1403 }
1404 }
1405 }
1406
1407 #check for htmlish code and javascript
1408 if( $this->detectScript ( $tmpfile, $mime, $extension ) ) {
1409 return new WikiErrorMsg( 'uploadscripted' );
1410 }
1411 if( $extension == 'svg' || $mime == 'image/svg+xml' ) {
1412 if( $this->detectScriptInSvg( $tmpfile ) ) {
1413 return new WikiErrorMsg( 'uploadscripted' );
1414 }
1415 }
1416
1417 /**
1418 * Scan the uploaded file for viruses
1419 */
1420 $virus= $this->detectVirus($tmpfile);
1421 if ( $virus ) {
1422 return new WikiErrorMsg( 'uploadvirus', htmlspecialchars($virus) );
1423 }
1424
1425 wfDebug( __METHOD__.": all clear; passing.\n" );
1426 return true;
1427 }
1428
1429 /**
1430 * Checks if the mime type of the uploaded file matches the file extension.
1431 *
1432 * @param string $mime the mime type of the uploaded file
1433 * @param string $extension The filename extension that the file is to be served with
1434 * @return bool
1435 */
1436 static function verifyExtension( $mime, $extension ) {
1437 $magic = MimeMagic::singleton();
1438
1439 if ( ! $mime || $mime == 'unknown' || $mime == 'unknown/unknown' )
1440 if ( ! $magic->isRecognizableExtension( $extension ) ) {
1441 wfDebug( __METHOD__.": passing file with unknown detected mime type; " .
1442 "unrecognized extension '$extension', can't verify\n" );
1443 return true;
1444 } else {
1445 wfDebug( __METHOD__.": rejecting file with unknown detected mime type; ".
1446 "recognized extension '$extension', so probably invalid file\n" );
1447 return false;
1448 }
1449
1450 $match= $magic->isMatchingExtension($extension,$mime);
1451
1452 if ($match===NULL) {
1453 wfDebug( __METHOD__.": no file extension known for mime type $mime, passing file\n" );
1454 return true;
1455 } elseif ($match===true) {
1456 wfDebug( __METHOD__.": mime type $mime matches extension $extension, passing file\n" );
1457
1458 #TODO: if it's a bitmap, make sure PHP or ImageMagic resp. can handle it!
1459 return true;
1460
1461 } else {
1462 wfDebug( __METHOD__.": mime type $mime mismatches file extension $extension, rejecting file\n" );
1463 return false;
1464 }
1465 }
1466
1467
1468 /**
1469 * Heuristic for detecting files that *could* contain JavaScript instructions or
1470 * things that may look like HTML to a browser and are thus
1471 * potentially harmful. The present implementation will produce false positives in some situations.
1472 *
1473 * @param string $file Pathname to the temporary upload file
1474 * @param string $mime The mime type of the file
1475 * @param string $extension The extension of the file
1476 * @return bool true if the file contains something looking like embedded scripts
1477 */
1478 function detectScript($file, $mime, $extension) {
1479 global $wgAllowTitlesInSVG;
1480
1481 #ugly hack: for text files, always look at the entire file.
1482 #For binarie field, just check the first K.
1483
1484 if (strpos($mime,'text/')===0) $chunk = file_get_contents( $file );
1485 else {
1486 $fp = fopen( $file, 'rb' );
1487 $chunk = fread( $fp, 1024 );
1488 fclose( $fp );
1489 }
1490
1491 $chunk= strtolower( $chunk );
1492
1493 if (!$chunk) return false;
1494
1495 #decode from UTF-16 if needed (could be used for obfuscation).
1496 if (substr($chunk,0,2)=="\xfe\xff") $enc= "UTF-16BE";
1497 elseif (substr($chunk,0,2)=="\xff\xfe") $enc= "UTF-16LE";
1498 else $enc= NULL;
1499
1500 if ($enc) $chunk= iconv($enc,"ASCII//IGNORE",$chunk);
1501
1502 $chunk= trim($chunk);
1503
1504 #FIXME: convert from UTF-16 if necessarry!
1505
1506 wfDebug("SpecialUpload::detectScript: checking for embedded scripts and HTML stuff\n");
1507
1508 #check for HTML doctype
1509 if ( preg_match( "/<!DOCTYPE *X?HTML/i", $chunk ) ) return true;
1510
1511 /**
1512 * Internet Explorer for Windows performs some really stupid file type
1513 * autodetection which can cause it to interpret valid image files as HTML
1514 * and potentially execute JavaScript, creating a cross-site scripting
1515 * attack vectors.
1516 *
1517 * Apple's Safari browser also performs some unsafe file type autodetection
1518 * which can cause legitimate files to be interpreted as HTML if the
1519 * web server is not correctly configured to send the right content-type
1520 * (or if you're really uploading plain text and octet streams!)
1521 *
1522 * Returns true if IE is likely to mistake the given file for HTML.
1523 * Also returns true if Safari would mistake the given file for HTML
1524 * when served with a generic content-type.
1525 */
1526
1527 $tags = array(
1528 '<a href',
1529 '<body',
1530 '<head',
1531 '<html', #also in safari
1532 '<img',
1533 '<pre',
1534 '<script', #also in safari
1535 '<table'
1536 );
1537 if( ! $wgAllowTitlesInSVG && $extension !== 'svg' && $mime !== 'image/svg' ) {
1538 $tags[] = '<title';
1539 }
1540
1541 foreach( $tags as $tag ) {
1542 if( false !== strpos( $chunk, $tag ) ) {
1543 return true;
1544 }
1545 }
1546
1547 /*
1548 * look for javascript
1549 */
1550
1551 #resolve entity-refs to look at attributes. may be harsh on big files... cache result?
1552 $chunk = Sanitizer::decodeCharReferences( $chunk );
1553
1554 #look for script-types
1555 if (preg_match('!type\s*=\s*[\'"]?\s*(?:\w*/)?(?:ecma|java)!sim',$chunk)) return true;
1556
1557 #look for html-style script-urls
1558 if (preg_match('!(?:href|src|data)\s*=\s*[\'"]?\s*(?:ecma|java)script:!sim',$chunk)) return true;
1559
1560 #look for css-style script-urls
1561 if (preg_match('!url\s*\(\s*[\'"]?\s*(?:ecma|java)script:!sim',$chunk)) return true;
1562
1563 wfDebug("SpecialUpload::detectScript: no scripts found\n");
1564 return false;
1565 }
1566
1567 function detectScriptInSvg( $filename ) {
1568 $check = new XmlTypeCheck( $filename, array( $this, 'checkSvgScriptCallback' ) );
1569 return $check->filterMatch;
1570 }
1571
1572 /**
1573 * @todo Replace this with a whitelist filter!
1574 */
1575 function checkSvgScriptCallback( $element, $attribs ) {
1576 $stripped = $this->stripXmlNamespace( $element );
1577
1578 if( $stripped == 'script' ) {
1579 wfDebug( __METHOD__ . ": Found script element '$element' in uploaded file.\n" );
1580 return true;
1581 }
1582
1583 foreach( $attribs as $attrib => $value ) {
1584 $stripped = $this->stripXmlNamespace( $attrib );
1585 if( substr( $stripped, 0, 2 ) == 'on' ) {
1586 wfDebug( __METHOD__ . ": Found script attribute '$attrib'='value' in uploaded file.\n" );
1587 return true;
1588 }
1589 if( $stripped == 'href' && strpos( strtolower( $value ), 'javascript:' ) !== false ) {
1590 wfDebug( __METHOD__ . ": Found script href attribute '$attrib'='$value' in uploaded file.\n" );
1591 return true;
1592 }
1593 }
1594 }
1595
1596 private function stripXmlNamespace( $name ) {
1597 // 'http://www.w3.org/2000/svg:script' -> 'script'
1598 $parts = explode( ':', strtolower( $name ) );
1599 return array_pop( $parts );
1600 }
1601
1602 /**
1603 * Generic wrapper function for a virus scanner program.
1604 * This relies on the $wgAntivirus and $wgAntivirusSetup variables.
1605 * $wgAntivirusRequired may be used to deny upload if the scan fails.
1606 *
1607 * @param string $file Pathname to the temporary upload file
1608 * @return mixed false if not virus is found, NULL if the scan fails or is disabled,
1609 * or a string containing feedback from the virus scanner if a virus was found.
1610 * If textual feedback is missing but a virus was found, this function returns true.
1611 */
1612 function detectVirus($file) {
1613 global $wgAntivirus, $wgAntivirusSetup, $wgAntivirusRequired, $wgOut;
1614
1615 if ( !$wgAntivirus ) {
1616 wfDebug( __METHOD__.": virus scanner disabled\n");
1617 return NULL;
1618 }
1619
1620 if ( !$wgAntivirusSetup[$wgAntivirus] ) {
1621 wfDebug( __METHOD__.": unknown virus scanner: $wgAntivirus\n" );
1622 $wgOut->wrapWikiMsg( '<div class="error">$1</div>', array( 'virus-badscanner', $wgAntivirus ) );
1623 return wfMsg('virus-unknownscanner') . " $wgAntivirus";
1624 }
1625
1626 # look up scanner configuration
1627 $command = $wgAntivirusSetup[$wgAntivirus]["command"];
1628 $exitCodeMap = $wgAntivirusSetup[$wgAntivirus]["codemap"];
1629 $msgPattern = isset( $wgAntivirusSetup[$wgAntivirus]["messagepattern"] ) ?
1630 $wgAntivirusSetup[$wgAntivirus]["messagepattern"] : null;
1631
1632 if ( strpos( $command,"%f" ) === false ) {
1633 # simple pattern: append file to scan
1634 $command .= " " . wfEscapeShellArg( $file );
1635 } else {
1636 # complex pattern: replace "%f" with file to scan
1637 $command = str_replace( "%f", wfEscapeShellArg( $file ), $command );
1638 }
1639
1640 wfDebug( __METHOD__.": running virus scan: $command \n" );
1641
1642 # execute virus scanner
1643 $exitCode = false;
1644
1645 #NOTE: there's a 50 line workaround to make stderr redirection work on windows, too.
1646 # that does not seem to be worth the pain.
1647 # Ask me (Duesentrieb) about it if it's ever needed.
1648 $output = array();
1649 if ( wfIsWindows() ) {
1650 exec( "$command", $output, $exitCode );
1651 } else {
1652 exec( "$command 2>&1", $output, $exitCode );
1653 }
1654
1655 # map exit code to AV_xxx constants.
1656 $mappedCode = $exitCode;
1657 if ( $exitCodeMap ) {
1658 if ( isset( $exitCodeMap[$exitCode] ) ) {
1659 $mappedCode = $exitCodeMap[$exitCode];
1660 } elseif ( isset( $exitCodeMap["*"] ) ) {
1661 $mappedCode = $exitCodeMap["*"];
1662 }
1663 }
1664
1665 if ( $mappedCode === AV_SCAN_FAILED ) {
1666 # scan failed (code was mapped to false by $exitCodeMap)
1667 wfDebug( __METHOD__.": failed to scan $file (code $exitCode).\n" );
1668
1669 if ( $wgAntivirusRequired ) {
1670 return wfMsg('virus-scanfailed', array( $exitCode ) );
1671 } else {
1672 return NULL;
1673 }
1674 } else if ( $mappedCode === AV_SCAN_ABORTED ) {
1675 # scan failed because filetype is unknown (probably imune)
1676 wfDebug( __METHOD__.": unsupported file type $file (code $exitCode).\n" );
1677 return NULL;
1678 } else if ( $mappedCode === AV_NO_VIRUS ) {
1679 # no virus found
1680 wfDebug( __METHOD__.": file passed virus scan.\n" );
1681 return false;
1682 } else {
1683 $output = join( "\n", $output );
1684 $output = trim( $output );
1685
1686 if ( !$output ) {
1687 $output = true; #if there's no output, return true
1688 } elseif ( $msgPattern ) {
1689 $groups = array();
1690 if ( preg_match( $msgPattern, $output, $groups ) ) {
1691 if ( $groups[1] ) {
1692 $output = $groups[1];
1693 }
1694 }
1695 }
1696
1697 wfDebug( __METHOD__.": FOUND VIRUS! scanner feedback: $output \n" );
1698 return $output;
1699 }
1700 }
1701
1702 /**
1703 * Check if the temporary file is MacBinary-encoded, as some uploads
1704 * from Internet Explorer on Mac OS Classic and Mac OS X will be.
1705 * If so, the data fork will be extracted to a second temporary file,
1706 * which will then be checked for validity and either kept or discarded.
1707 *
1708 * @access private
1709 */
1710 function checkMacBinary() {
1711 $macbin = new MacBinary( $this->mTempPath );
1712 if( $macbin->isValid() ) {
1713 $dataFile = tempnam( wfTempDir(), "WikiMacBinary" );
1714 $dataHandle = fopen( $dataFile, 'wb' );
1715
1716 wfDebug( "SpecialUpload::checkMacBinary: Extracting MacBinary data fork to $dataFile\n" );
1717 $macbin->extractData( $dataHandle );
1718
1719 $this->mTempPath = $dataFile;
1720 $this->mFileSize = $macbin->dataForkLength();
1721
1722 // We'll have to manually remove the new file if it's not kept.
1723 $this->mRemoveTempFile = true;
1724 }
1725 $macbin->close();
1726 }
1727
1728 /**
1729 * If we've modified the upload file we need to manually remove it
1730 * on exit to clean up.
1731 * @access private
1732 */
1733 function cleanupTempFile() {
1734 if ( $this->mRemoveTempFile && $this->mTempPath && file_exists( $this->mTempPath ) ) {
1735 wfDebug( "SpecialUpload::cleanupTempFile: Removing temporary file {$this->mTempPath}\n" );
1736 unlink( $this->mTempPath );
1737 }
1738 }
1739
1740 /**
1741 * Check if there's an overwrite conflict and, if so, if restrictions
1742 * forbid this user from performing the upload.
1743 *
1744 * @return mixed true on success, WikiError on failure
1745 * @access private
1746 */
1747 function checkOverwrite( $name ) {
1748 $img = wfFindFile( $name );
1749
1750 $error = '';
1751 if( $img ) {
1752 global $wgUser, $wgOut;
1753 if( $img->isLocal() ) {
1754 if( !self::userCanReUpload( $wgUser, $img->name ) ) {
1755 $error = 'fileexists-forbidden';
1756 }
1757 } else {
1758 if( !$wgUser->isAllowed( 'reupload' ) ||
1759 !$wgUser->isAllowed( 'reupload-shared' ) ) {
1760 $error = "fileexists-shared-forbidden";
1761 }
1762 }
1763 }
1764
1765 if( $error ) {
1766 $errorText = wfMsg( $error, wfEscapeWikiText( $img->getName() ) );
1767 return $errorText;
1768 }
1769
1770 // Rockin', go ahead and upload
1771 return true;
1772 }
1773
1774 /**
1775 * Check if a user is the last uploader
1776 *
1777 * @param User $user
1778 * @param string $img, image name
1779 * @return bool
1780 */
1781 public static function userCanReUpload( User $user, $img ) {
1782 if( $user->isAllowed( 'reupload' ) )
1783 return true; // non-conditional
1784 if( !$user->isAllowed( 'reupload-own' ) )
1785 return false;
1786
1787 $dbr = wfGetDB( DB_SLAVE );
1788 $row = $dbr->selectRow('image',
1789 /* SELECT */ 'img_user',
1790 /* WHERE */ array( 'img_name' => $img )
1791 );
1792 if ( !$row )
1793 return false;
1794
1795 return $user->getId() == $row->img_user;
1796 }
1797
1798 /**
1799 * Display an error with a wikitext description
1800 */
1801 function showError( $description ) {
1802 global $wgOut;
1803 $wgOut->setPageTitle( wfMsg( "internalerror" ) );
1804 $wgOut->setRobotPolicy( "noindex,nofollow" );
1805 $wgOut->setArticleRelated( false );
1806 $wgOut->enableClientCache( false );
1807 $wgOut->addWikiText( $description );
1808 }
1809
1810 /**
1811 * Get the initial image page text based on a comment and optional file status information
1812 */
1813 static function getInitialPageText( $comment, $license, $copyStatus, $source ) {
1814 global $wgUseCopyrightUpload;
1815 if ( $wgUseCopyrightUpload ) {
1816 if ( $license != '' ) {
1817 $licensetxt = '== ' . wfMsgForContent( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1818 }
1819 $pageText = '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $comment . "\n" .
1820 '== ' . wfMsgForContent ( 'filestatus' ) . " ==\n" . $copyStatus . "\n" .
1821 "$licensetxt" .
1822 '== ' . wfMsgForContent ( 'filesource' ) . " ==\n" . $source ;
1823 } else {
1824 if ( $license != '' ) {
1825 $filedesc = $comment == '' ? '' : '== ' . wfMsg ( 'filedesc' ) . " ==\n" . $comment . "\n";
1826 $pageText = $filedesc .
1827 '== ' . wfMsgForContent ( 'license' ) . " ==\n" . '{{' . $license . '}}' . "\n";
1828 } else {
1829 $pageText = $comment;
1830 }
1831 }
1832 return $pageText;
1833 }
1834
1835 /**
1836 * If there are rows in the deletion log for this file, show them,
1837 * along with a nice little note for the user
1838 *
1839 * @param OutputPage $out
1840 * @param string filename
1841 */
1842 private function showDeletionLog( $out, $filename ) {
1843 global $wgUser;
1844 $loglist = new LogEventsList( $wgUser->getSkin(), $out );
1845 $pager = new LogPager( $loglist, 'delete', false, $filename );
1846 if( $pager->getNumRows() > 0 ) {
1847 $out->addHTML( '<div class="mw-warning-with-logexcerpt">' );
1848 $out->addWikiMsg( 'upload-wasdeleted' );
1849 $out->addHTML(
1850 $loglist->beginLogEventsList() .
1851 $pager->getBody() .
1852 $loglist->endLogEventsList()
1853 );
1854 $out->addHTML( '</div>' );
1855 }
1856 }
1857 }