Localisation updates from https://translatewiki.net.
[mediawiki.git] / includes / actions / InfoAction.php
blob00622f84ccd6d0f8ee281d21155278976ea9f135
1 <?php
2 /**
3 * Displays information about a page.
5 * Copyright © 2011 Alexandre Emsenhuber
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.
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.
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
21 * @file
22 * @ingroup Actions
25 use MediaWiki\Cache\LinkBatchFactory;
26 use MediaWiki\Category\Category;
27 use MediaWiki\Content\ContentHandler;
28 use MediaWiki\Context\IContextSource;
29 use MediaWiki\EditPage\TemplatesOnThisPageFormatter;
30 use MediaWiki\Html\Html;
31 use MediaWiki\Language\Language;
32 use MediaWiki\Languages\LanguageNameUtils;
33 use MediaWiki\Linker\Linker;
34 use MediaWiki\Linker\LinkRenderer;
35 use MediaWiki\Linker\LinksMigration;
36 use MediaWiki\MainConfigNames;
37 use MediaWiki\MediaWikiServices;
38 use MediaWiki\Message\Message;
39 use MediaWiki\Page\PageIdentity;
40 use MediaWiki\Page\PageProps;
41 use MediaWiki\Page\RedirectLookup;
42 use MediaWiki\Parser\MagicWordFactory;
43 use MediaWiki\Parser\ParserOutput;
44 use MediaWiki\Parser\Sanitizer;
45 use MediaWiki\Permissions\RestrictionStore;
46 use MediaWiki\Revision\RevisionLookup;
47 use MediaWiki\Revision\RevisionRecord;
48 use MediaWiki\SpecialPage\SpecialPage;
49 use MediaWiki\Title\NamespaceInfo;
50 use MediaWiki\Title\Title;
51 use MediaWiki\User\UserFactory;
52 use MediaWiki\Watchlist\WatchedItemStoreInterface;
53 use Wikimedia\ObjectCache\WANObjectCache;
54 use Wikimedia\Rdbms\Database;
55 use Wikimedia\Rdbms\IConnectionProvider;
56 use Wikimedia\Rdbms\IDBAccessObject;
57 use Wikimedia\Rdbms\IExpression;
58 use Wikimedia\Rdbms\LikeValue;
60 /**
61 * Displays information about a page.
63 * @ingroup Actions
65 class InfoAction extends FormlessAction {
66 private const VERSION = 1;
68 private Language $contentLanguage;
69 private LanguageNameUtils $languageNameUtils;
70 private LinkBatchFactory $linkBatchFactory;
71 private LinkRenderer $linkRenderer;
72 private IConnectionProvider $dbProvider;
73 private MagicWordFactory $magicWordFactory;
74 private NamespaceInfo $namespaceInfo;
75 private PageProps $pageProps;
76 private RepoGroup $repoGroup;
77 private RevisionLookup $revisionLookup;
78 private WANObjectCache $wanObjectCache;
79 private WatchedItemStoreInterface $watchedItemStore;
80 private RedirectLookup $redirectLookup;
81 private RestrictionStore $restrictionStore;
82 private LinksMigration $linksMigration;
83 private UserFactory $userFactory;
85 public function __construct(
86 Article $article,
87 IContextSource $context,
88 Language $contentLanguage,
89 LanguageNameUtils $languageNameUtils,
90 LinkBatchFactory $linkBatchFactory,
91 LinkRenderer $linkRenderer,
92 IConnectionProvider $dbProvider,
93 MagicWordFactory $magicWordFactory,
94 NamespaceInfo $namespaceInfo,
95 PageProps $pageProps,
96 RepoGroup $repoGroup,
97 RevisionLookup $revisionLookup,
98 WANObjectCache $wanObjectCache,
99 WatchedItemStoreInterface $watchedItemStore,
100 RedirectLookup $redirectLookup,
101 RestrictionStore $restrictionStore,
102 LinksMigration $linksMigration,
103 UserFactory $userFactory
105 parent::__construct( $article, $context );
106 $this->contentLanguage = $contentLanguage;
107 $this->languageNameUtils = $languageNameUtils;
108 $this->linkBatchFactory = $linkBatchFactory;
109 $this->linkRenderer = $linkRenderer;
110 $this->dbProvider = $dbProvider;
111 $this->magicWordFactory = $magicWordFactory;
112 $this->namespaceInfo = $namespaceInfo;
113 $this->pageProps = $pageProps;
114 $this->repoGroup = $repoGroup;
115 $this->revisionLookup = $revisionLookup;
116 $this->wanObjectCache = $wanObjectCache;
117 $this->watchedItemStore = $watchedItemStore;
118 $this->redirectLookup = $redirectLookup;
119 $this->restrictionStore = $restrictionStore;
120 $this->linksMigration = $linksMigration;
121 $this->userFactory = $userFactory;
124 /** @inheritDoc */
125 public function getName() {
126 return 'info';
129 /** @inheritDoc */
130 public function requiresUnblock() {
131 return false;
134 /** @inheritDoc */
135 public function requiresWrite() {
136 return false;
140 * Clear the info cache for a given Title.
142 * @since 1.22
143 * @param PageIdentity $page Title to clear cache for
144 * @param int|null $revid Revision id to clear
146 public static function invalidateCache( PageIdentity $page, $revid = null ) {
147 $services = MediaWikiServices::getInstance();
148 if ( $revid === null ) {
149 $revision = $services->getRevisionLookup()
150 ->getRevisionByTitle( $page, 0, IDBAccessObject::READ_LATEST );
151 $revid = $revision ? $revision->getId() : 0;
153 $cache = $services->getMainWANObjectCache();
154 $key = self::getCacheKey( $cache, $page, $revid ?? 0 );
155 $cache->delete( $key );
159 * Shows page information on GET request.
161 * @return string Page information that will be added to the output
163 public function onView() {
164 $this->getOutput()->addModuleStyles( [
165 'mediawiki.interface.helpers.styles',
166 'mediawiki.action.styles',
167 ] );
169 // "Help" button
170 $this->addHelpLink( 'Page information' );
172 // Validate revision
173 $oldid = $this->getArticle()->getOldID();
174 if ( $oldid ) {
175 $revRecord = $this->getArticle()->fetchRevisionRecord();
177 if ( !$revRecord ) {
178 return $this->msg( 'missing-revision', $oldid )->parse();
179 } elseif ( !$revRecord->isCurrent() ) {
180 return $this->msg( 'pageinfo-not-current' )->plain();
184 // Page header
185 $msg = $this->msg( 'pageinfo-header' );
186 $content = $msg->isDisabled() ? '' : $msg->parse();
188 // Get page information
189 $pageInfo = $this->pageInfo();
191 // Allow extensions to add additional information
192 $this->getHookRunner()->onInfoAction( $this->getContext(), $pageInfo );
194 // Render page information
195 foreach ( $pageInfo as $header => $infoTable ) {
196 // Messages:
197 // pageinfo-header-basic, pageinfo-header-edits, pageinfo-header-restrictions,
198 // pageinfo-header-properties, pageinfo-category-info
199 $content .= $this->makeHeader(
200 $this->msg( "pageinfo-$header" )->text(),
201 "mw-pageinfo-$header"
202 ) . "\n";
203 $rows = '';
204 $below = "";
205 foreach ( $infoTable as $infoRow ) {
206 if ( $infoRow[0] == "below" ) {
207 $below = $infoRow[1] . "\n";
208 continue;
210 $name = ( $infoRow[0] instanceof Message ) ? $infoRow[0]->escaped() : $infoRow[0];
211 $value = ( $infoRow[1] instanceof Message ) ? $infoRow[1]->escaped() : $infoRow[1];
212 $id = ( $infoRow[0] instanceof Message ) ? $infoRow[0]->getKey() : null;
213 $rows .= $this->getRow( $name, $value, $id ) . "\n";
215 if ( $rows !== '' ) {
216 $content .= Html::rawElement( 'table', [ 'class' => 'wikitable mw-page-info' ],
217 "\n" . $rows );
219 $content .= "\n" . $below;
222 // Page footer
223 if ( !$this->msg( 'pageinfo-footer' )->isDisabled() ) {
224 $content .= $this->msg( 'pageinfo-footer' )->parse();
227 return $content;
231 * Creates a header that can be added to the output.
233 * @param string $header The header text.
234 * @param string $canonicalId
235 * @return string The HTML.
237 private function makeHeader( $header, $canonicalId ) {
238 return Html::rawElement(
239 'h2',
240 [ 'id' => Sanitizer::escapeIdForAttribute( $header ) ],
241 Html::element(
242 'span',
243 [ 'id' => Sanitizer::escapeIdForAttribute( $canonicalId ) ],
246 htmlspecialchars( $header )
251 * @param string $name The name of the row
252 * @param string $value The value of the row
253 * @param string|null $id The ID to use for the 'tr' element
254 * @param-taint $id none
255 * @return string HTML
257 private function getRow( $name, $value, $id ) {
258 return Html::rawElement(
259 'tr',
261 'id' => $id === null ? null : 'mw-' . $id,
262 'style' => 'vertical-align: top;',
264 Html::rawElement( 'td', [], $name ) .
265 Html::rawElement( 'td', [], $value )
270 * Returns an array of info groups (will be rendered as tables), keyed by group ID.
271 * Group IDs are arbitrary and used so that extensions may add additional information in
272 * arbitrary positions (and as message keys for section headers for the tables, prefixed
273 * with 'pageinfo-').
274 * Each info group is a non-associative array of info items (rendered as table rows).
275 * Each info item is an array with two elements: the first describes the type of
276 * information, the second the value for the current page. Both can be strings (will be
277 * interpreted as raw HTML) or messages (will be interpreted as plain text and escaped).
279 * @return array
280 * @phan-return array<string, list<array{0:string|Message, 1:string|Message}>>
282 private function pageInfo() {
283 $user = $this->getUser();
284 $lang = $this->getLanguage();
285 $title = $this->getTitle();
286 $id = $title->getArticleID();
287 $config = $this->context->getConfig();
288 $linkRenderer = $this->linkRenderer;
290 $pageCounts = $this->pageCounts();
292 $pageProperties = $this->pageProps->getAllProperties( $title )[$id] ?? [];
294 // Basic information
295 $pageInfo = [];
296 $pageInfo['header-basic'] = [];
298 // Display title
299 $displayTitle = $pageProperties['displaytitle'] ??
300 htmlspecialchars( $title->getPrefixedText(), ENT_NOQUOTES );
302 $pageInfo['header-basic'][] = [
303 $this->msg( 'pageinfo-display-title' ),
304 $displayTitle
307 // Is it a redirect? If so, where to?
308 $redirectTarget = $this->redirectLookup->getRedirectTarget( $this->getWikiPage() );
309 if ( $redirectTarget !== null ) {
310 $pageInfo['header-basic'][] = [
311 $this->msg( 'pageinfo-redirectsto' ),
312 $linkRenderer->makeLink( $redirectTarget ) .
313 $this->msg( 'word-separator' )->escaped() .
314 $this->msg( 'parentheses' )->rawParams( $linkRenderer->makeLink(
315 $redirectTarget,
316 $this->msg( 'pageinfo-redirectsto-info' )->text(),
318 [ 'action' => 'info' ]
319 ) )->escaped()
323 // Default sort key
324 $sortKey = $pageProperties['defaultsort'] ?? $title->getCategorySortkey();
325 $pageInfo['header-basic'][] = [
326 $this->msg( 'pageinfo-default-sort' ),
327 htmlspecialchars( $sortKey )
330 // Page length (in bytes)
331 $pageInfo['header-basic'][] = [
332 $this->msg( 'pageinfo-length' ),
333 $lang->formatNum( $title->getLength() )
336 // Page namespace
337 $pageInfo['header-basic'][] = [ $this->msg( 'pageinfo-namespace-id' ), $title->getNamespace() ];
338 $pageNamespace = $title->getNsText();
339 if ( $pageNamespace ) {
340 $pageInfo['header-basic'][] = [ $this->msg( 'pageinfo-namespace' ), $pageNamespace ];
343 // Page ID (number not localised, as it's a database ID)
344 $pageInfo['header-basic'][] = [ $this->msg( 'pageinfo-article-id' ), $id ];
346 // Language in which the page content is (supposed to be) written
347 $pageLang = $title->getPageLanguage()->getCode();
349 $pageLangHtml = $pageLang . ' - ' .
350 $this->languageNameUtils->getLanguageName( $pageLang, $lang->getCode() );
351 // Link to Special:PageLanguage with pre-filled page title if user has permissions
352 if ( $config->get( MainConfigNames::PageLanguageUseDB )
353 && $this->getAuthority()->probablyCan( 'pagelang', $title )
355 $pageLangHtml .= $this->msg( 'word-separator' )->escaped();
356 $pageLangHtml .= $this->msg( 'parentheses' )->rawParams( $linkRenderer->makeLink(
357 SpecialPage::getTitleValueFor( 'PageLanguage', $title->getPrefixedText() ),
358 $this->msg( 'pageinfo-language-change' )->text()
359 ) )->escaped();
362 $pageInfo['header-basic'][] = [
363 $this->msg( 'pageinfo-language' )->escaped(),
364 $pageLangHtml
367 // Content model of the page
368 $modelHtml = htmlspecialchars( ContentHandler::getLocalizedName( $title->getContentModel() ) );
369 // If the user can change it, add a link to Special:ChangeContentModel
370 if ( $this->getAuthority()->probablyCan( 'editcontentmodel', $title ) ) {
371 $modelHtml .= $this->msg( 'word-separator' )->escaped();
372 $modelHtml .= $this->msg( 'parentheses' )->rawParams( $linkRenderer->makeLink(
373 SpecialPage::getTitleValueFor( 'ChangeContentModel', $title->getPrefixedText() ),
374 $this->msg( 'pageinfo-content-model-change' )->text()
375 ) )->escaped();
378 $pageInfo['header-basic'][] = [
379 $this->msg( 'pageinfo-content-model' ),
380 $modelHtml
383 if ( $title->inNamespace( NS_USER ) ) {
384 $pageUser = $this->userFactory->newFromName( $title->getRootText() );
385 if ( $pageUser && $pageUser->getId() && !$pageUser->isHidden() ) {
386 $pageInfo['header-basic'][] = [
387 $this->msg( 'pageinfo-user-id' ),
388 $pageUser->getId()
393 // Search engine status
394 $parserOutput = new ParserOutput();
395 if ( isset( $pageProperties['noindex'] ) ) {
396 $parserOutput->setIndexPolicy( 'noindex' );
398 if ( isset( $pageProperties['index'] ) ) {
399 $parserOutput->setIndexPolicy( 'index' );
402 // Use robot policy logic
403 $policy = $this->getArticle()->getRobotPolicy( 'view', $parserOutput );
404 $pageInfo['header-basic'][] = [
405 // Messages: pageinfo-robot-index, pageinfo-robot-noindex
406 $this->msg( 'pageinfo-robot-policy' ),
407 $this->msg( "pageinfo-robot-{$policy['index']}" )
410 $unwatchedPageThreshold = $config->get( MainConfigNames::UnwatchedPageThreshold );
411 if ( $this->getAuthority()->isAllowed( 'unwatchedpages' ) ||
412 ( $unwatchedPageThreshold !== false &&
413 $pageCounts['watchers'] >= $unwatchedPageThreshold )
415 // Number of page watchers
416 $pageInfo['header-basic'][] = [
417 $this->msg( 'pageinfo-watchers' ),
418 $lang->formatNum( $pageCounts['watchers'] )
421 $visiting = $pageCounts['visitingWatchers'] ?? null;
422 if ( $visiting !== null && $config->get( MainConfigNames::ShowUpdatedMarker ) ) {
423 if ( $visiting > $config->get( MainConfigNames::UnwatchedPageSecret ) ||
424 $this->getAuthority()->isAllowed( 'unwatchedpages' )
426 $value = $lang->formatNum( $visiting );
427 } else {
428 $value = $this->msg( 'pageinfo-few-visiting-watchers' );
430 $pageInfo['header-basic'][] = [
431 $this->msg( 'pageinfo-visiting-watchers' )
432 ->numParams( ceil( $config->get( MainConfigNames::WatchersMaxAge ) / 86400 ) ),
433 $value
436 } elseif ( $unwatchedPageThreshold !== false ) {
437 $pageInfo['header-basic'][] = [
438 $this->msg( 'pageinfo-watchers' ),
439 $this->msg( 'pageinfo-few-watchers' )->numParams( $unwatchedPageThreshold )
443 // Redirects to this page
444 $whatLinksHere = SpecialPage::getTitleFor( 'Whatlinkshere', $title->getPrefixedText() );
445 $pageInfo['header-basic'][] = [
446 $linkRenderer->makeLink(
447 $whatLinksHere,
448 $this->msg( 'pageinfo-redirects-name' )->text(),
451 'hidelinks' => 1,
452 'hidetrans' => 1,
453 'hideimages' => $title->getNamespace() === NS_FILE
456 $this->msg( 'pageinfo-redirects-value' )
457 ->numParams( count( $title->getRedirectsHere() ) )
460 // Is it counted as a content page?
461 if ( $this->getWikiPage()->isCountable() ) {
462 $pageInfo['header-basic'][] = [
463 $this->msg( 'pageinfo-contentpage' ),
464 $this->msg( 'pageinfo-contentpage-yes' )
468 // Subpages of this page, if subpages are enabled for the current NS
469 if ( $this->namespaceInfo->hasSubpages( $title->getNamespace() ) ) {
470 $prefixIndex = SpecialPage::getTitleFor(
471 'Prefixindex',
472 $title->getPrefixedText() . '/'
474 $pageInfo['header-basic'][] = [
475 $linkRenderer->makeLink(
476 $prefixIndex,
477 $this->msg( 'pageinfo-subpages-name' )->text()
479 // $wgNamespacesWithSubpages can be changed and this can be unset (T340749)
480 isset( $pageCounts['subpages'] )
481 ? $this->msg( 'pageinfo-subpages-value' )->numParams(
482 $pageCounts['subpages']['total'],
483 $pageCounts['subpages']['redirects'],
484 $pageCounts['subpages']['nonredirects']
485 ) : $this->msg( 'pageinfo-subpages-value-unknown' )->rawParams(
486 $linkRenderer->makeKnownLink(
487 $title, $this->msg( 'purge' )->text(), [], [ 'action' => 'purge' ] )
492 if ( $title->inNamespace( NS_CATEGORY ) ) {
493 $category = Category::newFromTitle( $title );
495 $allCount = $category->getMemberCount();
496 $subcatCount = $category->getSubcatCount();
497 $fileCount = $category->getFileCount();
498 $pageCount = $category->getPageCount( Category::COUNT_CONTENT_PAGES );
500 $pageInfo['category-info'] = [
502 $this->msg( 'pageinfo-category-total' ),
503 $lang->formatNum( $allCount )
506 $this->msg( 'pageinfo-category-pages' ),
507 $lang->formatNum( $pageCount )
510 $this->msg( 'pageinfo-category-subcats' ),
511 $lang->formatNum( $subcatCount )
514 $this->msg( 'pageinfo-category-files' ),
515 $lang->formatNum( $fileCount )
520 // Display image SHA-1 value
521 if ( $title->inNamespace( NS_FILE ) ) {
522 $fileObj = $this->repoGroup->findFile( $title );
523 if ( $fileObj !== false ) {
524 // Convert the base-36 sha1 value obtained from database to base-16
525 $output = Wikimedia\base_convert( $fileObj->getSha1(), 36, 16, 40 );
526 $pageInfo['header-basic'][] = [
527 $this->msg( 'pageinfo-file-hash' ),
528 $output
533 // Page protection
534 $pageInfo['header-restrictions'] = [];
536 // Is this page affected by the cascading protection of something which includes it?
537 if ( $this->restrictionStore->isCascadeProtected( $title ) ) {
538 $cascadingFrom = '';
539 $sources = $this->restrictionStore->getCascadeProtectionSources( $title )[0];
541 foreach ( $sources as $sourcePageIdentity ) {
542 $cascadingFrom .= Html::rawElement(
543 'li',
545 $linkRenderer->makeKnownLink( $sourcePageIdentity )
549 $cascadingFrom = Html::rawElement( 'ul', [], $cascadingFrom );
550 $pageInfo['header-restrictions'][] = [
551 $this->msg( 'pageinfo-protect-cascading-from' ),
552 $cascadingFrom
556 // Is out protection set to cascade to other pages?
557 if ( $this->restrictionStore->areRestrictionsCascading( $title ) ) {
558 $pageInfo['header-restrictions'][] = [
559 $this->msg( 'pageinfo-protect-cascading' ),
560 $this->msg( 'pageinfo-protect-cascading-yes' )
564 // Page protection
565 foreach ( $this->restrictionStore->listApplicableRestrictionTypes( $title ) as $restrictionType ) {
566 $protections = $this->restrictionStore->getRestrictions( $title, $restrictionType );
568 switch ( count( $protections ) ) {
569 case 0:
570 $message = $this->getNamespaceProtectionMessage( $title ) ??
571 // Allow all users by default
572 $this->msg( 'protect-default' )->escaped();
573 break;
575 case 1:
576 // Messages: protect-level-autoconfirmed, protect-level-sysop
577 $message = $this->msg( 'protect-level-' . $protections[0] );
578 if ( !$message->isDisabled() ) {
579 $message = $message->escaped();
580 break;
582 // Intentional fall-through if message is disabled (or non-existent)
584 default:
585 // Require "$1" permission
586 $message = $this->msg( "protect-fallback", $lang->commaList( $protections ) )->parse();
587 break;
589 $expiry = $this->restrictionStore->getRestrictionExpiry( $title, $restrictionType );
590 $formattedexpiry = $expiry === null ? '' : $this->msg(
591 'parentheses',
592 $lang->formatExpiry( $expiry, true, 'infinity', $user )
593 )->escaped();
594 $message .= $this->msg( 'word-separator' )->escaped() . $formattedexpiry;
596 // Messages: restriction-edit, restriction-move, restriction-create,
597 // restriction-upload
598 $pageInfo['header-restrictions'][] = [
599 $this->msg( "restriction-$restrictionType" ), $message
602 $protectLog = SpecialPage::getTitleFor( 'Log' );
603 $pageInfo['header-restrictions'][] = [
604 'below',
605 $linkRenderer->makeKnownLink(
606 $protectLog,
607 $this->msg( 'pageinfo-view-protect-log' )->text(),
609 [ 'type' => 'protect', 'page' => $title->getPrefixedText() ]
613 if ( !$this->getWikiPage()->exists() ) {
614 return $pageInfo;
617 // Edit history
618 $pageInfo['header-edits'] = [];
620 $firstRev = $this->revisionLookup->getFirstRevision( $this->getTitle() );
621 $lastRev = $this->getWikiPage()->getRevisionRecord();
622 $batch = $this->linkBatchFactory->newLinkBatch();
623 if ( $firstRev ) {
624 $firstRevUser = $firstRev->getUser( RevisionRecord::FOR_THIS_USER, $user );
625 if ( $firstRevUser ) {
626 $batch->add( NS_USER, $firstRevUser->getName() );
627 $batch->add( NS_USER_TALK, $firstRevUser->getName() );
631 if ( $lastRev ) {
632 $lastRevUser = $lastRev->getUser( RevisionRecord::FOR_THIS_USER, $user );
633 if ( $lastRevUser ) {
634 $batch->add( NS_USER, $lastRevUser->getName() );
635 $batch->add( NS_USER_TALK, $lastRevUser->getName() );
639 $batch->execute();
641 if ( $firstRev ) {
642 // Page creator
643 $firstRevUser = $firstRev->getUser( RevisionRecord::FOR_THIS_USER, $user );
644 // Check if the username is available – it may have been suppressed, in
645 // which case use the invalid user name '[HIDDEN]' to get the wiki's
646 // default user gender.
647 $firstRevUserName = $firstRevUser ? $firstRevUser->getName() : '[HIDDEN]';
648 $pageInfo['header-edits'][] = [
649 $this->msg( 'pageinfo-firstuser', $firstRevUserName ),
650 Linker::revUserTools( $firstRev )
653 // Date of page creation
654 $pageInfo['header-edits'][] = [
655 $this->msg( 'pageinfo-firsttime' ),
656 $linkRenderer->makeKnownLink(
657 $title,
658 $lang->userTimeAndDate( $firstRev->getTimestamp(), $user ),
660 [ 'oldid' => $firstRev->getId() ]
665 if ( $lastRev ) {
666 // Latest editor
667 $lastRevUser = $lastRev->getUser( RevisionRecord::FOR_THIS_USER, $user );
668 // Check if the username is available – it may have been suppressed, in
669 // which case use the invalid user name '[HIDDEN]' to get the wiki's
670 // default user gender.
671 $lastRevUserName = $lastRevUser ? $lastRevUser->getName() : '[HIDDEN]';
672 $pageInfo['header-edits'][] = [
673 $this->msg( 'pageinfo-lastuser', $lastRevUserName ),
674 Linker::revUserTools( $lastRev )
677 // Date of latest edit
678 $pageInfo['header-edits'][] = [
679 $this->msg( 'pageinfo-lasttime' ),
680 $linkRenderer->makeKnownLink(
681 $title,
682 $lang->userTimeAndDate( $this->getWikiPage()->getTimestamp(), $user ),
684 [ 'oldid' => $this->getWikiPage()->getLatest() ]
689 // Total number of edits
690 $pageInfo['header-edits'][] = [
691 $this->msg( 'pageinfo-edits' ),
692 $lang->formatNum( $pageCounts['edits'] )
695 // Total number of distinct authors
696 if ( $pageCounts['authors'] > 0 ) {
697 $pageInfo['header-edits'][] = [
698 $this->msg( 'pageinfo-authors' ),
699 $lang->formatNum( $pageCounts['authors'] )
703 // Recent number of edits (within past 30 days)
704 $pageInfo['header-edits'][] = [
705 $this->msg(
706 'pageinfo-recent-edits',
707 $lang->formatDuration( $config->get( MainConfigNames::RCMaxAge ) )
709 $lang->formatNum( $pageCounts['recent_edits'] )
712 // Recent number of distinct authors
713 $pageInfo['header-edits'][] = [
714 $this->msg( 'pageinfo-recent-authors' ),
715 $lang->formatNum( $pageCounts['recent_authors'] )
718 // Array of magic word IDs
719 $wordIDs = $this->magicWordFactory->getDoubleUnderscoreArray()->getNames();
721 // Array of IDs => localized magic words
722 $localizedWords = $this->contentLanguage->getMagicWords();
724 $listItems = [];
725 foreach ( $pageProperties as $property => $value ) {
726 if ( in_array( $property, $wordIDs ) ) {
727 $listItems[] = Html::element( 'li', [], $localizedWords[$property][1] );
731 $localizedList = Html::rawElement( 'ul', [], implode( '', $listItems ) );
732 $hiddenCategories = $this->getWikiPage()->getHiddenCategories();
734 if (
735 count( $listItems ) > 0 ||
736 count( $hiddenCategories ) > 0 ||
737 $pageCounts['transclusion']['from'] > 0 ||
738 $pageCounts['transclusion']['to'] > 0
740 $options = [ 'LIMIT' => $config->get( MainConfigNames::PageInfoTransclusionLimit ) ];
741 $transcludedTemplates = $title->getTemplateLinksFrom( $options );
742 if ( $config->get( MainConfigNames::MiserMode ) ) {
743 $transcludedTargets = [];
744 } else {
745 $transcludedTargets = $title->getTemplateLinksTo( $options );
748 // Page properties
749 $pageInfo['header-properties'] = [];
751 // Magic words
752 if ( count( $listItems ) > 0 ) {
753 $pageInfo['header-properties'][] = [
754 $this->msg( 'pageinfo-magic-words' )->numParams( count( $listItems ) ),
755 $localizedList
759 // Hidden categories
760 if ( count( $hiddenCategories ) > 0 ) {
761 $pageInfo['header-properties'][] = [
762 $this->msg( 'pageinfo-hidden-categories' )
763 ->numParams( count( $hiddenCategories ) ),
764 Linker::formatHiddenCategories( $hiddenCategories )
768 // Transcluded templates
769 if ( $pageCounts['transclusion']['from'] > 0 ) {
770 if ( $pageCounts['transclusion']['from'] > count( $transcludedTemplates ) ) {
771 $more = $this->msg( 'morenotlisted' )->escaped();
772 } else {
773 $more = null;
776 $templateListFormatter = new TemplatesOnThisPageFormatter(
777 $this->getContext(),
778 $linkRenderer,
779 $this->linkBatchFactory,
780 $this->restrictionStore
783 $pageInfo['header-properties'][] = [
784 $this->msg( 'pageinfo-templates' )
785 ->numParams( $pageCounts['transclusion']['from'] ),
786 $templateListFormatter->format( $transcludedTemplates, false, $more )
790 if ( !$config->get( MainConfigNames::MiserMode ) && $pageCounts['transclusion']['to'] > 0 ) {
791 if ( $pageCounts['transclusion']['to'] > count( $transcludedTargets ) ) {
792 $more = $linkRenderer->makeLink(
793 $whatLinksHere,
794 $this->msg( 'moredotdotdot' )->text(),
796 [ 'hidelinks' => 1, 'hideredirs' => 1 ]
798 } else {
799 $more = null;
802 $templateListFormatter = new TemplatesOnThisPageFormatter(
803 $this->getContext(),
804 $linkRenderer,
805 $this->linkBatchFactory,
806 $this->restrictionStore
809 $pageInfo['header-properties'][] = [
810 $this->msg( 'pageinfo-transclusions' )
811 ->numParams( $pageCounts['transclusion']['to'] ),
812 $templateListFormatter->format( $transcludedTargets, false, $more )
817 return $pageInfo;
821 * Get namespace protection message for title or null if no namespace protection
822 * has been applied
824 * @param Title $title
825 * @return ?string HTML
827 private function getNamespaceProtectionMessage( Title $title ): ?string {
828 $rights = [];
829 if ( $title->isRawHtmlMessage() ) {
830 $rights[] = 'editsitecss';
831 $rights[] = 'editsitejs';
832 } elseif ( $title->isSiteCssConfigPage() ) {
833 $rights[] = 'editsitecss';
834 } elseif ( $title->isSiteJsConfigPage() ) {
835 $rights[] = 'editsitejs';
836 } elseif ( $title->isSiteJsonConfigPage() ) {
837 $rights[] = 'editsitejson';
838 } elseif ( $title->isUserCssConfigPage() ) {
839 $rights[] = 'editusercss';
840 } elseif ( $title->isUserJsConfigPage() ) {
841 $rights[] = 'edituserjs';
842 } elseif ( $title->isUserJsonConfigPage() ) {
843 $rights[] = 'edituserjson';
844 } else {
845 $namespaceProtection = $this->context->getConfig()->get( MainConfigNames::NamespaceProtection );
846 $right = $namespaceProtection[$title->getNamespace()] ?? null;
847 if ( $right ) {
848 // a single string as the value is allowed as well as an array
849 $rights = (array)$right;
852 if ( $rights ) {
853 return $this->msg( 'protect-fallback', $this->getLanguage()->commaList( $rights ) )->parse();
854 } else {
855 return null;
860 * Returns page counts that would be too "expensive" to retrieve by normal means.
862 * @return array
864 private function pageCounts() {
865 $page = $this->getWikiPage();
866 $fname = __METHOD__;
867 $config = $this->context->getConfig();
868 $cache = $this->wanObjectCache;
870 return $cache->getWithSetCallback(
871 self::getCacheKey( $cache, $page->getTitle(), $page->getLatest() ),
872 WANObjectCache::TTL_WEEK,
873 function ( $oldValue, &$ttl, &$setOpts ) use ( $page, $config, $fname ) {
874 $title = $page->getTitle();
875 $id = $title->getArticleID();
877 $dbr = $this->dbProvider->getReplicaDatabase();
878 $setOpts += Database::getCacheSetOptions( $dbr );
880 $field = 'rev_actor';
881 $pageField = 'rev_page';
883 $watchedItemStore = $this->watchedItemStore;
885 $result = [];
886 $result['watchers'] = $watchedItemStore->countWatchers( $title );
888 if ( $config->get( MainConfigNames::ShowUpdatedMarker ) ) {
889 $updated = (int)wfTimestamp( TS_UNIX, $page->getTimestamp() );
890 $result['visitingWatchers'] = $watchedItemStore->countVisitingWatchers(
891 $title,
892 $updated - $config->get( MainConfigNames::WatchersMaxAge )
896 // Total number of edits
897 $edits = (int)$dbr->newSelectQueryBuilder()
898 ->select( 'COUNT(*)' )
899 ->from( 'revision' )
900 ->where( [ 'rev_page' => $id ] )
901 ->caller( $fname )
902 ->fetchField();
903 $result['edits'] = $edits;
905 // Total number of distinct authors
906 if ( $config->get( MainConfigNames::MiserMode ) ) {
907 $result['authors'] = 0;
908 } else {
909 $result['authors'] = (int)$dbr->newSelectQueryBuilder()
910 ->select( "COUNT(DISTINCT $field)" )
911 ->from( 'revision' )
912 ->where( [ $pageField => $id ] )
913 ->caller( $fname )
914 ->fetchField();
917 // "Recent" threshold defined by RCMaxAge setting
918 $threshold = $dbr->timestamp( time() - $config->get( MainConfigNames::RCMaxAge ) );
920 // Recent number of edits
921 $edits = (int)$dbr->newSelectQueryBuilder()
922 ->select( 'COUNT(rev_page)' )
923 ->from( 'revision' )
924 ->where( [ 'rev_page' => $id ] )
925 ->andWhere( $dbr->expr( 'rev_timestamp', '>=', $threshold ) )
926 ->caller( $fname )
927 ->fetchField();
928 $result['recent_edits'] = $edits;
930 // Recent number of distinct authors
931 $result['recent_authors'] = (int)$dbr->newSelectQueryBuilder()
932 ->select( "COUNT(DISTINCT $field)" )
933 ->from( 'revision' )
934 ->where( [ $pageField => $id ] )
935 ->andWhere( [ $dbr->expr( 'rev_timestamp', '>=', $threshold ) ] )
936 ->caller( $fname )
937 ->fetchField();
939 // Subpages (if enabled)
940 if ( $this->namespaceInfo->hasSubpages( $title->getNamespace() ) ) {
941 $conds = [ 'page_namespace' => $title->getNamespace() ];
942 $conds[] = $dbr->expr(
943 'page_title',
944 IExpression::LIKE,
945 new LikeValue( $title->getDBkey() . '/', $dbr->anyString() )
948 // Subpages of this page (redirects)
949 $conds['page_is_redirect'] = 1;
950 $result['subpages']['redirects'] = (int)$dbr->newSelectQueryBuilder()
951 ->select( 'COUNT(page_id)' )
952 ->from( 'page' )
953 ->where( $conds )
954 ->caller( $fname )
955 ->fetchField();
956 // Subpages of this page (non-redirects)
957 $conds['page_is_redirect'] = 0;
958 $result['subpages']['nonredirects'] = (int)$dbr->newSelectQueryBuilder()
959 ->select( 'COUNT(page_id)' )
960 ->from( 'page' )
961 ->where( $conds )
962 ->caller( $fname )
963 ->fetchField();
965 // Subpages of this page (total)
966 $result['subpages']['total'] = $result['subpages']['redirects']
967 + $result['subpages']['nonredirects'];
970 // Counts for the number of transclusion links (to/from)
971 if ( $config->get( MainConfigNames::MiserMode ) ) {
972 $result['transclusion']['to'] = 0;
973 } else {
974 $result['transclusion']['to'] = (int)$dbr->newSelectQueryBuilder()
975 ->select( 'COUNT(tl_from)' )
976 ->from( 'templatelinks' )
977 ->where( $this->linksMigration->getLinksConditions( 'templatelinks', $title ) )
978 ->caller( $fname )
979 ->fetchField();
982 $result['transclusion']['from'] = (int)$dbr->newSelectQueryBuilder()
983 ->select( 'COUNT(*)' )
984 ->from( 'templatelinks' )
985 ->where( [ 'tl_from' => $title->getArticleID() ] )
986 ->caller( $fname )
987 ->fetchField();
989 return $result;
995 * Returns the name that goes in the "<h1>" page title.
997 * @return string
999 protected function getPageTitle() {
1000 return $this->msg( 'pageinfo-title' )->plaintextParams( $this->getTitle()->getPrefixedText() );
1004 * Returns the description that goes below the "<h1>" tag.
1006 * @return string
1008 protected function getDescription() {
1009 return '';
1013 * @param WANObjectCache $cache
1014 * @param PageIdentity $page
1015 * @param int $revId
1016 * @return string
1018 protected static function getCacheKey( WANObjectCache $cache, PageIdentity $page, $revId ) {
1019 return $cache->makeKey( 'infoaction', md5( (string)$page ), $revId, self::VERSION );