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