Merge "Convert file delete to use OOUI"
[lhc/web/wiklou.git] / includes / actions / InfoAction.php
1 <?php
2 /**
3 * Displays information about a page.
4 *
5 * Copyright © 2011 Alexandre Emsenhuber
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
20 *
21 * @file
22 * @ingroup Actions
23 */
24
25 use MediaWiki\MediaWikiServices;
26 use Wikimedia\Rdbms\Database;
27
28 /**
29 * Displays information about a page.
30 *
31 * @ingroup Actions
32 */
33 class InfoAction extends FormlessAction {
34 const VERSION = 1;
35
36 /**
37 * Returns the name of the action this object responds to.
38 *
39 * @return string Lowercase name
40 */
41 public function getName() {
42 return 'info';
43 }
44
45 /**
46 * Whether this action can still be executed by a blocked user.
47 *
48 * @return bool
49 */
50 public function requiresUnblock() {
51 return false;
52 }
53
54 /**
55 * Whether this action requires the wiki not to be locked.
56 *
57 * @return bool
58 */
59 public function requiresWrite() {
60 return false;
61 }
62
63 /**
64 * Clear the info cache for a given Title.
65 *
66 * @since 1.22
67 * @param Title $title Title to clear cache for
68 * @param int|null $revid Revision id to clear
69 */
70 public static function invalidateCache( Title $title, $revid = null ) {
71 if ( !$revid ) {
72 $revision = Revision::newFromTitle( $title, 0, Revision::READ_LATEST );
73 $revid = $revision ? $revision->getId() : null;
74 }
75 if ( $revid !== null ) {
76 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
77 $key = self::getCacheKey( $cache, $title, $revid );
78 $cache->delete( $key );
79 }
80 }
81
82 /**
83 * Shows page information on GET request.
84 *
85 * @return string Page information that will be added to the output
86 */
87 public function onView() {
88 $content = '';
89
90 // Validate revision
91 $oldid = $this->page->getOldID();
92 if ( $oldid ) {
93 $revision = $this->page->getRevisionFetched();
94
95 // Revision is missing
96 if ( $revision === null ) {
97 return $this->msg( 'missing-revision', $oldid )->parse();
98 }
99
100 // Revision is not current
101 if ( !$revision->isCurrent() ) {
102 return $this->msg( 'pageinfo-not-current' )->plain();
103 }
104 }
105
106 // Page header
107 if ( !$this->msg( 'pageinfo-header' )->isDisabled() ) {
108 $content .= $this->msg( 'pageinfo-header' )->parse();
109 }
110
111 // Hide "This page is a member of # hidden categories" explanation
112 $content .= Html::element( 'style', [],
113 '.mw-hiddenCategoriesExplanation { display: none; }' ) . "\n";
114
115 // Hide "Templates used on this page" explanation
116 $content .= Html::element( 'style', [],
117 '.mw-templatesUsedExplanation { display: none; }' ) . "\n";
118
119 // Get page information
120 $pageInfo = $this->pageInfo();
121
122 // Allow extensions to add additional information
123 Hooks::run( 'InfoAction', [ $this->getContext(), &$pageInfo ] );
124
125 // Render page information
126 foreach ( $pageInfo as $header => $infoTable ) {
127 // Messages:
128 // pageinfo-header-basic, pageinfo-header-edits, pageinfo-header-restrictions,
129 // pageinfo-header-properties, pageinfo-category-info
130 $content .= $this->makeHeader(
131 $this->msg( "pageinfo-${header}" )->text(),
132 "mw-pageinfo-${header}"
133 ) . "\n";
134 $table = "\n";
135 foreach ( $infoTable as $infoRow ) {
136 $name = ( $infoRow[0] instanceof Message ) ? $infoRow[0]->escaped() : $infoRow[0];
137 $value = ( $infoRow[1] instanceof Message ) ? $infoRow[1]->escaped() : $infoRow[1];
138 $id = ( $infoRow[0] instanceof Message ) ? $infoRow[0]->getKey() : null;
139 $table = $this->addRow( $table, $name, $value, $id ) . "\n";
140 }
141 $content = $this->addTable( $content, $table ) . "\n";
142 }
143
144 // Page footer
145 if ( !$this->msg( 'pageinfo-footer' )->isDisabled() ) {
146 $content .= $this->msg( 'pageinfo-footer' )->parse();
147 }
148
149 return $content;
150 }
151
152 /**
153 * Creates a header that can be added to the output.
154 *
155 * @param string $header The header text.
156 * @param string $canonicalId
157 * @return string The HTML.
158 */
159 protected function makeHeader( $header, $canonicalId ) {
160 $spanAttribs = [ 'class' => 'mw-headline', 'id' => Sanitizer::escapeIdForAttribute( $header ) ];
161 $h2Attribs = [ 'id' => Sanitizer::escapeIdForAttribute( $canonicalId ) ];
162
163 return Html::rawElement( 'h2', $h2Attribs, Html::element( 'span', $spanAttribs, $header ) );
164 }
165
166 /**
167 * Adds a row to a table that will be added to the content.
168 *
169 * @param string $table The table that will be added to the content
170 * @param string $name The name of the row
171 * @param string $value The value of the row
172 * @param string $id The ID to use for the 'tr' element
173 * @return string The table with the row added
174 */
175 protected function addRow( $table, $name, $value, $id ) {
176 return $table .
177 Html::rawElement(
178 'tr',
179 $id === null ? [] : [ 'id' => 'mw-' . $id ],
180 Html::rawElement( 'td', [ 'style' => 'vertical-align: top;' ], $name ) .
181 Html::rawElement( 'td', [], $value )
182 );
183 }
184
185 /**
186 * Adds a table to the content that will be added to the output.
187 *
188 * @param string $content The content that will be added to the output
189 * @param string $table
190 * @return string The content with the table added
191 */
192 protected function addTable( $content, $table ) {
193 return $content . Html::rawElement( 'table', [ 'class' => 'wikitable mw-page-info' ],
194 $table );
195 }
196
197 /**
198 * Returns an array of info groups (will be rendered as tables), keyed by group ID.
199 * Group IDs are arbitrary and used so that extensions may add additional information in
200 * arbitrary positions (and as message keys for section headers for the tables, prefixed
201 * with 'pageinfo-').
202 * Each info group is a non-associative array of info items (rendered as table rows).
203 * Each info item is an array with two elements: the first describes the type of
204 * information, the second the value for the current page. Both can be strings (will be
205 * interpreted as raw HTML) or messages (will be interpreted as plain text and escaped).
206 *
207 * @return array
208 */
209 protected function pageInfo() {
210 global $wgContLang;
211
212 $services = MediaWikiServices::getInstance();
213
214 $user = $this->getUser();
215 $lang = $this->getLanguage();
216 $title = $this->getTitle();
217 $id = $title->getArticleID();
218 $config = $this->context->getConfig();
219 $linkRenderer = $services->getLinkRenderer();
220
221 $pageCounts = $this->pageCounts( $this->page );
222
223 $props = PageProps::getInstance()->getAllProperties( $title );
224 $pageProperties = $props[$id] ?? [];
225
226 // Basic information
227 $pageInfo = [];
228 $pageInfo['header-basic'] = [];
229
230 // Display title
231 $displayTitle = $pageProperties['displaytitle'] ?? $title->getPrefixedText();
232
233 $pageInfo['header-basic'][] = [
234 $this->msg( 'pageinfo-display-title' ), $displayTitle
235 ];
236
237 // Is it a redirect? If so, where to?
238 if ( $title->isRedirect() ) {
239 $pageInfo['header-basic'][] = [
240 $this->msg( 'pageinfo-redirectsto' ),
241 $linkRenderer->makeLink( $this->page->getRedirectTarget() ) .
242 $this->msg( 'word-separator' )->escaped() .
243 $this->msg( 'parentheses' )->rawParams( $linkRenderer->makeLink(
244 $this->page->getRedirectTarget(),
245 $this->msg( 'pageinfo-redirectsto-info' )->text(),
246 [],
247 [ 'action' => 'info' ]
248 ) )->escaped()
249 ];
250 }
251
252 // Default sort key
253 $sortKey = $pageProperties['defaultsort'] ?? $title->getCategorySortkey();
254
255 $sortKey = htmlspecialchars( $sortKey );
256 $pageInfo['header-basic'][] = [ $this->msg( 'pageinfo-default-sort' ), $sortKey ];
257
258 // Page length (in bytes)
259 $pageInfo['header-basic'][] = [
260 $this->msg( 'pageinfo-length' ), $lang->formatNum( $title->getLength() )
261 ];
262
263 // Page ID (number not localised, as it's a database ID)
264 $pageInfo['header-basic'][] = [ $this->msg( 'pageinfo-article-id' ), $id ];
265
266 // Language in which the page content is (supposed to be) written
267 $pageLang = $title->getPageLanguage()->getCode();
268
269 $pageLangHtml = $pageLang . ' - ' .
270 Language::fetchLanguageName( $pageLang, $lang->getCode() );
271 // Link to Special:PageLanguage with pre-filled page title if user has permissions
272 if ( $config->get( 'PageLanguageUseDB' )
273 && $title->userCan( 'pagelang', $user )
274 ) {
275 $pageLangHtml .= ' ' . $this->msg( 'parentheses' )->rawParams( $linkRenderer->makeLink(
276 SpecialPage::getTitleValueFor( 'PageLanguage', $title->getPrefixedText() ),
277 $this->msg( 'pageinfo-language-change' )->text()
278 ) )->escaped();
279 }
280
281 $pageInfo['header-basic'][] = [
282 $this->msg( 'pageinfo-language' )->escaped(),
283 $pageLangHtml
284 ];
285
286 // Content model of the page
287 $modelHtml = htmlspecialchars( ContentHandler::getLocalizedName( $title->getContentModel() ) );
288 // If the user can change it, add a link to Special:ChangeContentModel
289 if ( $config->get( 'ContentHandlerUseDB' )
290 && $title->userCan( 'editcontentmodel', $user )
291 ) {
292 $modelHtml .= ' ' . $this->msg( 'parentheses' )->rawParams( $linkRenderer->makeLink(
293 SpecialPage::getTitleValueFor( 'ChangeContentModel', $title->getPrefixedText() ),
294 $this->msg( 'pageinfo-content-model-change' )->text()
295 ) )->escaped();
296 }
297
298 $pageInfo['header-basic'][] = [
299 $this->msg( 'pageinfo-content-model' ),
300 $modelHtml
301 ];
302
303 if ( $title->inNamespace( NS_USER ) ) {
304 $pageUser = User::newFromName( $title->getRootText() );
305 if ( $pageUser && $pageUser->getId() && !$pageUser->isHidden() ) {
306 $pageInfo['header-basic'][] = [
307 $this->msg( 'pageinfo-user-id' ),
308 $pageUser->getId()
309 ];
310 }
311 }
312
313 // Search engine status
314 $pOutput = new ParserOutput();
315 if ( isset( $pageProperties['noindex'] ) ) {
316 $pOutput->setIndexPolicy( 'noindex' );
317 }
318 if ( isset( $pageProperties['index'] ) ) {
319 $pOutput->setIndexPolicy( 'index' );
320 }
321
322 // Use robot policy logic
323 $policy = $this->page->getRobotPolicy( 'view', $pOutput );
324 $pageInfo['header-basic'][] = [
325 // Messages: pageinfo-robot-index, pageinfo-robot-noindex
326 $this->msg( 'pageinfo-robot-policy' ),
327 $this->msg( "pageinfo-robot-${policy['index']}" )
328 ];
329
330 $unwatchedPageThreshold = $config->get( 'UnwatchedPageThreshold' );
331 if (
332 $user->isAllowed( 'unwatchedpages' ) ||
333 ( $unwatchedPageThreshold !== false &&
334 $pageCounts['watchers'] >= $unwatchedPageThreshold )
335 ) {
336 // Number of page watchers
337 $pageInfo['header-basic'][] = [
338 $this->msg( 'pageinfo-watchers' ),
339 $lang->formatNum( $pageCounts['watchers'] )
340 ];
341 if (
342 $config->get( 'ShowUpdatedMarker' ) &&
343 isset( $pageCounts['visitingWatchers'] )
344 ) {
345 $minToDisclose = $config->get( 'UnwatchedPageSecret' );
346 if ( $pageCounts['visitingWatchers'] > $minToDisclose ||
347 $user->isAllowed( 'unwatchedpages' ) ) {
348 $pageInfo['header-basic'][] = [
349 $this->msg( 'pageinfo-visiting-watchers' ),
350 $lang->formatNum( $pageCounts['visitingWatchers'] )
351 ];
352 } else {
353 $pageInfo['header-basic'][] = [
354 $this->msg( 'pageinfo-visiting-watchers' ),
355 $this->msg( 'pageinfo-few-visiting-watchers' )
356 ];
357 }
358 }
359 } elseif ( $unwatchedPageThreshold !== false ) {
360 $pageInfo['header-basic'][] = [
361 $this->msg( 'pageinfo-watchers' ),
362 $this->msg( 'pageinfo-few-watchers' )->numParams( $unwatchedPageThreshold )
363 ];
364 }
365
366 // Redirects to this page
367 $whatLinksHere = SpecialPage::getTitleFor( 'Whatlinkshere', $title->getPrefixedText() );
368 $pageInfo['header-basic'][] = [
369 $linkRenderer->makeLink(
370 $whatLinksHere,
371 $this->msg( 'pageinfo-redirects-name' )->text(),
372 [],
373 [
374 'hidelinks' => 1,
375 'hidetrans' => 1,
376 'hideimages' => $title->getNamespace() == NS_FILE
377 ]
378 ),
379 $this->msg( 'pageinfo-redirects-value' )
380 ->numParams( count( $title->getRedirectsHere() ) )
381 ];
382
383 // Is it counted as a content page?
384 if ( $this->page->isCountable() ) {
385 $pageInfo['header-basic'][] = [
386 $this->msg( 'pageinfo-contentpage' ),
387 $this->msg( 'pageinfo-contentpage-yes' )
388 ];
389 }
390
391 // Subpages of this page, if subpages are enabled for the current NS
392 if ( MWNamespace::hasSubpages( $title->getNamespace() ) ) {
393 $prefixIndex = SpecialPage::getTitleFor(
394 'Prefixindex', $title->getPrefixedText() . '/' );
395 $pageInfo['header-basic'][] = [
396 $linkRenderer->makeLink(
397 $prefixIndex,
398 $this->msg( 'pageinfo-subpages-name' )->text()
399 ),
400 $this->msg( 'pageinfo-subpages-value' )
401 ->numParams(
402 $pageCounts['subpages']['total'],
403 $pageCounts['subpages']['redirects'],
404 $pageCounts['subpages']['nonredirects'] )
405 ];
406 }
407
408 if ( $title->inNamespace( NS_CATEGORY ) ) {
409 $category = Category::newFromTitle( $title );
410
411 // $allCount is the total number of cat members,
412 // not the count of how many members are normal pages.
413 $allCount = (int)$category->getPageCount();
414 $subcatCount = (int)$category->getSubcatCount();
415 $fileCount = (int)$category->getFileCount();
416 $pagesCount = $allCount - $subcatCount - $fileCount;
417
418 $pageInfo['category-info'] = [
419 [
420 $this->msg( 'pageinfo-category-total' ),
421 $lang->formatNum( $allCount )
422 ],
423 [
424 $this->msg( 'pageinfo-category-pages' ),
425 $lang->formatNum( $pagesCount )
426 ],
427 [
428 $this->msg( 'pageinfo-category-subcats' ),
429 $lang->formatNum( $subcatCount )
430 ],
431 [
432 $this->msg( 'pageinfo-category-files' ),
433 $lang->formatNum( $fileCount )
434 ]
435 ];
436 }
437
438 // Display image SHA-1 value
439 if ( $title->inNamespace( NS_FILE ) ) {
440 $fileObj = wfFindFile( $title );
441 if ( $fileObj !== false ) {
442 // Convert the base-36 sha1 value obtained from database to base-16
443 $output = Wikimedia\base_convert( $fileObj->getSha1(), 36, 16, 40 );
444 $pageInfo['header-basic'][] = [
445 $this->msg( 'pageinfo-file-hash' ),
446 $output
447 ];
448 }
449 }
450
451 // Page protection
452 $pageInfo['header-restrictions'] = [];
453
454 // Is this page affected by the cascading protection of something which includes it?
455 if ( $title->isCascadeProtected() ) {
456 $cascadingFrom = '';
457 $sources = $title->getCascadeProtectionSources()[0];
458
459 foreach ( $sources as $sourceTitle ) {
460 $cascadingFrom .= Html::rawElement(
461 'li', [], $linkRenderer->makeKnownLink( $sourceTitle ) );
462 }
463
464 $cascadingFrom = Html::rawElement( 'ul', [], $cascadingFrom );
465 $pageInfo['header-restrictions'][] = [
466 $this->msg( 'pageinfo-protect-cascading-from' ),
467 $cascadingFrom
468 ];
469 }
470
471 // Is out protection set to cascade to other pages?
472 if ( $title->areRestrictionsCascading() ) {
473 $pageInfo['header-restrictions'][] = [
474 $this->msg( 'pageinfo-protect-cascading' ),
475 $this->msg( 'pageinfo-protect-cascading-yes' )
476 ];
477 }
478
479 // Page protection
480 foreach ( $title->getRestrictionTypes() as $restrictionType ) {
481 $protectionLevel = implode( ', ', $title->getRestrictions( $restrictionType ) );
482
483 if ( $protectionLevel == '' ) {
484 // Allow all users
485 $message = $this->msg( 'protect-default' )->escaped();
486 } else {
487 // Administrators only
488 // Messages: protect-level-autoconfirmed, protect-level-sysop
489 $message = $this->msg( "protect-level-$protectionLevel" );
490 if ( $message->isDisabled() ) {
491 // Require "$1" permission
492 $message = $this->msg( "protect-fallback", $protectionLevel )->parse();
493 } else {
494 $message = $message->escaped();
495 }
496 }
497 $expiry = $title->getRestrictionExpiry( $restrictionType );
498 $formattedexpiry = $this->msg( 'parentheses',
499 $lang->formatExpiry( $expiry ) )->escaped();
500 $message .= $this->msg( 'word-separator' )->escaped() . $formattedexpiry;
501
502 // Messages: restriction-edit, restriction-move, restriction-create,
503 // restriction-upload
504 $pageInfo['header-restrictions'][] = [
505 $this->msg( "restriction-$restrictionType" ), $message
506 ];
507 }
508
509 if ( !$this->page->exists() ) {
510 return $pageInfo;
511 }
512
513 // Edit history
514 $pageInfo['header-edits'] = [];
515
516 $firstRev = $this->page->getOldestRevision();
517 $lastRev = $this->page->getRevision();
518 $batch = new LinkBatch;
519
520 if ( $firstRev ) {
521 $firstRevUser = $firstRev->getUserText( Revision::FOR_THIS_USER );
522 if ( $firstRevUser !== '' ) {
523 $firstRevUserTitle = Title::makeTitle( NS_USER, $firstRevUser );
524 $batch->addObj( $firstRevUserTitle );
525 $batch->addObj( $firstRevUserTitle->getTalkPage() );
526 }
527 }
528
529 if ( $lastRev ) {
530 $lastRevUser = $lastRev->getUserText( Revision::FOR_THIS_USER );
531 if ( $lastRevUser !== '' ) {
532 $lastRevUserTitle = Title::makeTitle( NS_USER, $lastRevUser );
533 $batch->addObj( $lastRevUserTitle );
534 $batch->addObj( $lastRevUserTitle->getTalkPage() );
535 }
536 }
537
538 $batch->execute();
539
540 if ( $firstRev ) {
541 // Page creator
542 $pageInfo['header-edits'][] = [
543 $this->msg( 'pageinfo-firstuser' ),
544 Linker::revUserTools( $firstRev )
545 ];
546
547 // Date of page creation
548 $pageInfo['header-edits'][] = [
549 $this->msg( 'pageinfo-firsttime' ),
550 $linkRenderer->makeKnownLink(
551 $title,
552 $lang->userTimeAndDate( $firstRev->getTimestamp(), $user ),
553 [],
554 [ 'oldid' => $firstRev->getId() ]
555 )
556 ];
557 }
558
559 if ( $lastRev ) {
560 // Latest editor
561 $pageInfo['header-edits'][] = [
562 $this->msg( 'pageinfo-lastuser' ),
563 Linker::revUserTools( $lastRev )
564 ];
565
566 // Date of latest edit
567 $pageInfo['header-edits'][] = [
568 $this->msg( 'pageinfo-lasttime' ),
569 $linkRenderer->makeKnownLink(
570 $title,
571 $lang->userTimeAndDate( $this->page->getTimestamp(), $user ),
572 [],
573 [ 'oldid' => $this->page->getLatest() ]
574 )
575 ];
576 }
577
578 // Total number of edits
579 $pageInfo['header-edits'][] = [
580 $this->msg( 'pageinfo-edits' ), $lang->formatNum( $pageCounts['edits'] )
581 ];
582
583 // Total number of distinct authors
584 if ( $pageCounts['authors'] > 0 ) {
585 $pageInfo['header-edits'][] = [
586 $this->msg( 'pageinfo-authors' ), $lang->formatNum( $pageCounts['authors'] )
587 ];
588 }
589
590 // Recent number of edits (within past 30 days)
591 $pageInfo['header-edits'][] = [
592 $this->msg( 'pageinfo-recent-edits',
593 $lang->formatDuration( $config->get( 'RCMaxAge' ) ) ),
594 $lang->formatNum( $pageCounts['recent_edits'] )
595 ];
596
597 // Recent number of distinct authors
598 $pageInfo['header-edits'][] = [
599 $this->msg( 'pageinfo-recent-authors' ),
600 $lang->formatNum( $pageCounts['recent_authors'] )
601 ];
602
603 // Array of MagicWord objects
604 $magicWords = $services->getMagicWordFactory()->getDoubleUnderscoreArray();
605
606 // Array of magic word IDs
607 $wordIDs = $magicWords->names;
608
609 // Array of IDs => localized magic words
610 $localizedWords = $wgContLang->getMagicWords();
611
612 $listItems = [];
613 foreach ( $pageProperties as $property => $value ) {
614 if ( in_array( $property, $wordIDs ) ) {
615 $listItems[] = Html::element( 'li', [], $localizedWords[$property][1] );
616 }
617 }
618
619 $localizedList = Html::rawElement( 'ul', [], implode( '', $listItems ) );
620 $hiddenCategories = $this->page->getHiddenCategories();
621
622 if (
623 count( $listItems ) > 0 ||
624 count( $hiddenCategories ) > 0 ||
625 $pageCounts['transclusion']['from'] > 0 ||
626 $pageCounts['transclusion']['to'] > 0
627 ) {
628 $options = [ 'LIMIT' => $config->get( 'PageInfoTransclusionLimit' ) ];
629 $transcludedTemplates = $title->getTemplateLinksFrom( $options );
630 if ( $config->get( 'MiserMode' ) ) {
631 $transcludedTargets = [];
632 } else {
633 $transcludedTargets = $title->getTemplateLinksTo( $options );
634 }
635
636 // Page properties
637 $pageInfo['header-properties'] = [];
638
639 // Magic words
640 if ( count( $listItems ) > 0 ) {
641 $pageInfo['header-properties'][] = [
642 $this->msg( 'pageinfo-magic-words' )->numParams( count( $listItems ) ),
643 $localizedList
644 ];
645 }
646
647 // Hidden categories
648 if ( count( $hiddenCategories ) > 0 ) {
649 $pageInfo['header-properties'][] = [
650 $this->msg( 'pageinfo-hidden-categories' )
651 ->numParams( count( $hiddenCategories ) ),
652 Linker::formatHiddenCategories( $hiddenCategories )
653 ];
654 }
655
656 // Transcluded templates
657 if ( $pageCounts['transclusion']['from'] > 0 ) {
658 if ( $pageCounts['transclusion']['from'] > count( $transcludedTemplates ) ) {
659 $more = $this->msg( 'morenotlisted' )->escaped();
660 } else {
661 $more = null;
662 }
663
664 $templateListFormatter = new TemplatesOnThisPageFormatter(
665 $this->getContext(),
666 $linkRenderer
667 );
668
669 $pageInfo['header-properties'][] = [
670 $this->msg( 'pageinfo-templates' )
671 ->numParams( $pageCounts['transclusion']['from'] ),
672 $templateListFormatter->format( $transcludedTemplates, false, $more )
673 ];
674 }
675
676 if ( !$config->get( 'MiserMode' ) && $pageCounts['transclusion']['to'] > 0 ) {
677 if ( $pageCounts['transclusion']['to'] > count( $transcludedTargets ) ) {
678 $more = $linkRenderer->makeLink(
679 $whatLinksHere,
680 $this->msg( 'moredotdotdot' )->text(),
681 [],
682 [ 'hidelinks' => 1, 'hideredirs' => 1 ]
683 );
684 } else {
685 $more = null;
686 }
687
688 $templateListFormatter = new TemplatesOnThisPageFormatter(
689 $this->getContext(),
690 $linkRenderer
691 );
692
693 $pageInfo['header-properties'][] = [
694 $this->msg( 'pageinfo-transclusions' )
695 ->numParams( $pageCounts['transclusion']['to'] ),
696 $templateListFormatter->format( $transcludedTargets, false, $more )
697 ];
698 }
699 }
700
701 return $pageInfo;
702 }
703
704 /**
705 * Returns page counts that would be too "expensive" to retrieve by normal means.
706 *
707 * @param WikiPage|Article|Page $page
708 * @return array
709 */
710 protected function pageCounts( Page $page ) {
711 $fname = __METHOD__;
712 $config = $this->context->getConfig();
713 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
714
715 return $cache->getWithSetCallback(
716 self::getCacheKey( $cache, $page->getTitle(), $page->getLatest() ),
717 WANObjectCache::TTL_WEEK,
718 function ( $oldValue, &$ttl, &$setOpts ) use ( $page, $config, $fname ) {
719 global $wgActorTableSchemaMigrationStage;
720
721 $title = $page->getTitle();
722 $id = $title->getArticleID();
723
724 $dbr = wfGetDB( DB_REPLICA );
725 $dbrWatchlist = wfGetDB( DB_REPLICA, 'watchlist' );
726 $setOpts += Database::getCacheSetOptions( $dbr, $dbrWatchlist );
727
728 if ( $wgActorTableSchemaMigrationStage === MIGRATION_NEW ) {
729 $tables = [ 'revision_actor_temp' ];
730 $field = 'revactor_actor';
731 $pageField = 'revactor_page';
732 $tsField = 'revactor_timestamp';
733 $joins = [];
734 } elseif ( $wgActorTableSchemaMigrationStage === MIGRATION_OLD ) {
735 $tables = [ 'revision' ];
736 $field = 'rev_user_text';
737 $pageField = 'rev_page';
738 $tsField = 'rev_timestamp';
739 $joins = [];
740 } else {
741 $tables = [ 'revision', 'revision_actor_temp', 'actor' ];
742 $field = 'COALESCE( actor_name, rev_user_text)';
743 $pageField = 'rev_page';
744 $tsField = 'rev_timestamp';
745 $joins = [
746 'revision_actor_temp' => [ 'LEFT JOIN', 'revactor_rev = rev_id' ],
747 'actor' => [ 'LEFT JOIN', 'revactor_actor = actor_id' ],
748 ];
749 }
750
751 $watchedItemStore = MediaWikiServices::getInstance()->getWatchedItemStore();
752
753 $result = [];
754 $result['watchers'] = $watchedItemStore->countWatchers( $title );
755
756 if ( $config->get( 'ShowUpdatedMarker' ) ) {
757 $updated = wfTimestamp( TS_UNIX, $page->getTimestamp() );
758 $result['visitingWatchers'] = $watchedItemStore->countVisitingWatchers(
759 $title,
760 $updated - $config->get( 'WatchersMaxAge' )
761 );
762 }
763
764 // Total number of edits
765 $edits = (int)$dbr->selectField(
766 'revision',
767 'COUNT(*)',
768 [ 'rev_page' => $id ],
769 $fname
770 );
771 $result['edits'] = $edits;
772
773 // Total number of distinct authors
774 if ( $config->get( 'MiserMode' ) ) {
775 $result['authors'] = 0;
776 } else {
777 $result['authors'] = (int)$dbr->selectField(
778 $tables,
779 "COUNT(DISTINCT $field)",
780 [ $pageField => $id ],
781 $fname,
782 [],
783 $joins
784 );
785 }
786
787 // "Recent" threshold defined by RCMaxAge setting
788 $threshold = $dbr->timestamp( time() - $config->get( 'RCMaxAge' ) );
789
790 // Recent number of edits
791 $edits = (int)$dbr->selectField(
792 'revision',
793 'COUNT(rev_page)',
794 [
795 'rev_page' => $id,
796 "rev_timestamp >= " . $dbr->addQuotes( $threshold )
797 ],
798 $fname
799 );
800 $result['recent_edits'] = $edits;
801
802 // Recent number of distinct authors
803 $result['recent_authors'] = (int)$dbr->selectField(
804 $tables,
805 "COUNT(DISTINCT $field)",
806 [
807 $pageField => $id,
808 "$tsField >= " . $dbr->addQuotes( $threshold )
809 ],
810 $fname,
811 [],
812 $joins
813 );
814
815 // Subpages (if enabled)
816 if ( MWNamespace::hasSubpages( $title->getNamespace() ) ) {
817 $conds = [ 'page_namespace' => $title->getNamespace() ];
818 $conds[] = 'page_title ' .
819 $dbr->buildLike( $title->getDBkey() . '/', $dbr->anyString() );
820
821 // Subpages of this page (redirects)
822 $conds['page_is_redirect'] = 1;
823 $result['subpages']['redirects'] = (int)$dbr->selectField(
824 'page',
825 'COUNT(page_id)',
826 $conds,
827 $fname
828 );
829
830 // Subpages of this page (non-redirects)
831 $conds['page_is_redirect'] = 0;
832 $result['subpages']['nonredirects'] = (int)$dbr->selectField(
833 'page',
834 'COUNT(page_id)',
835 $conds,
836 $fname
837 );
838
839 // Subpages of this page (total)
840 $result['subpages']['total'] = $result['subpages']['redirects']
841 + $result['subpages']['nonredirects'];
842 }
843
844 // Counts for the number of transclusion links (to/from)
845 if ( $config->get( 'MiserMode' ) ) {
846 $result['transclusion']['to'] = 0;
847 } else {
848 $result['transclusion']['to'] = (int)$dbr->selectField(
849 'templatelinks',
850 'COUNT(tl_from)',
851 [
852 'tl_namespace' => $title->getNamespace(),
853 'tl_title' => $title->getDBkey()
854 ],
855 $fname
856 );
857 }
858
859 $result['transclusion']['from'] = (int)$dbr->selectField(
860 'templatelinks',
861 'COUNT(*)',
862 [ 'tl_from' => $title->getArticleID() ],
863 $fname
864 );
865
866 return $result;
867 }
868 );
869 }
870
871 /**
872 * Returns the name that goes in the "<h1>" page title.
873 *
874 * @return string
875 */
876 protected function getPageTitle() {
877 return $this->msg( 'pageinfo-title', $this->getTitle()->getPrefixedText() )->text();
878 }
879
880 /**
881 * Get a list of contributors of $article
882 * @return string Html
883 */
884 protected function getContributors() {
885 $contributors = $this->page->getContributors();
886 $real_names = [];
887 $user_names = [];
888 $anon_ips = [];
889 $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
890
891 # Sift for real versus user names
892 /** @var User $user */
893 foreach ( $contributors as $user ) {
894 $page = $user->isAnon()
895 ? SpecialPage::getTitleFor( 'Contributions', $user->getName() )
896 : $user->getUserPage();
897
898 $hiddenPrefs = $this->context->getConfig()->get( 'HiddenPrefs' );
899 if ( $user->getId() == 0 ) {
900 $anon_ips[] = $linkRenderer->makeLink( $page, $user->getName() );
901 } elseif ( !in_array( 'realname', $hiddenPrefs ) && $user->getRealName() ) {
902 $real_names[] = $linkRenderer->makeLink( $page, $user->getRealName() );
903 } else {
904 $user_names[] = $linkRenderer->makeLink( $page, $user->getName() );
905 }
906 }
907
908 $lang = $this->getLanguage();
909
910 $real = $lang->listToText( $real_names );
911
912 # "ThisSite user(s) A, B and C"
913 if ( count( $user_names ) ) {
914 $user = $this->msg( 'siteusers' )
915 ->rawParams( $lang->listToText( $user_names ) )
916 ->params( count( $user_names ) )->escaped();
917 } else {
918 $user = false;
919 }
920
921 if ( count( $anon_ips ) ) {
922 $anon = $this->msg( 'anonusers' )
923 ->rawParams( $lang->listToText( $anon_ips ) )
924 ->params( count( $anon_ips ) )->escaped();
925 } else {
926 $anon = false;
927 }
928
929 # This is the big list, all mooshed together. We sift for blank strings
930 $fulllist = [];
931 foreach ( [ $real, $user, $anon ] as $s ) {
932 if ( $s !== '' ) {
933 array_push( $fulllist, $s );
934 }
935 }
936
937 $count = count( $fulllist );
938
939 # "Based on work by ..."
940 return $count
941 ? $this->msg( 'othercontribs' )->rawParams(
942 $lang->listToText( $fulllist ) )->params( $count )->escaped()
943 : '';
944 }
945
946 /**
947 * Returns the description that goes below the "<h1>" tag.
948 *
949 * @return string
950 */
951 protected function getDescription() {
952 return '';
953 }
954
955 /**
956 * @param WANObjectCache $cache
957 * @param Title $title
958 * @param int $revId
959 * @return string
960 */
961 protected static function getCacheKey( WANObjectCache $cache, Title $title, $revId ) {
962 return $cache->makeKey( 'infoaction', md5( $title->getPrefixedText() ), $revId, self::VERSION );
963 }
964 }