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