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