Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 573
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 / 573
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 / 368
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\Content\ContentHandler;
28use MediaWiki\Context\IContextSource;
29use MediaWiki\EditPage\TemplatesOnThisPageFormatter;
30use MediaWiki\Html\Html;
31use MediaWiki\Language\Language;
32use MediaWiki\Languages\LanguageNameUtils;
33use MediaWiki\Linker\Linker;
34use MediaWiki\Linker\LinkRenderer;
35use MediaWiki\Linker\LinksMigration;
36use MediaWiki\MainConfigNames;
37use MediaWiki\MediaWikiServices;
38use MediaWiki\Message\Message;
39use MediaWiki\Page\PageIdentity;
40use MediaWiki\Page\PageProps;
41use MediaWiki\Page\RedirectLookup;
42use MediaWiki\Parser\MagicWordFactory;
43use MediaWiki\Parser\ParserOutput;
44use MediaWiki\Parser\Sanitizer;
45use MediaWiki\Permissions\RestrictionStore;
46use MediaWiki\Revision\RevisionLookup;
47use MediaWiki\Revision\RevisionRecord;
48use MediaWiki\SpecialPage\SpecialPage;
49use MediaWiki\Title\NamespaceInfo;
50use MediaWiki\Title\Title;
51use MediaWiki\User\UserFactory;
52use MediaWiki\Watchlist\WatchedItemStoreInterface;
53use Wikimedia\ObjectCache\WANObjectCache;
54use Wikimedia\Rdbms\Database;
55use Wikimedia\Rdbms\IConnectionProvider;
56use Wikimedia\Rdbms\IDBAccessObject;
57use Wikimedia\Rdbms\IExpression;
58use Wikimedia\Rdbms\LikeValue;
59
60/**
61 * Displays information about a page.
62 *
63 * @ingroup Actions
64 */
65class InfoAction extends FormlessAction {
66    private const VERSION = 1;
67
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;
84
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
104    ) {
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;
122    }
123
124    /** @inheritDoc */
125    public function getName() {
126        return 'info';
127    }
128
129    /** @inheritDoc */
130    public function requiresUnblock() {
131        return false;
132    }
133
134    /** @inheritDoc */
135    public function requiresWrite() {
136        return false;
137    }
138
139    /**
140     * Clear the info cache for a given Title.
141     *
142     * @since 1.22
143     * @param PageIdentity $page Title to clear cache for
144     * @param int|null $revid Revision id to clear
145     */
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;
152        }
153        $cache = $services->getMainWANObjectCache();
154        $key = self::getCacheKey( $cache, $page, $revid ?? 0 );
155        $cache->delete( $key );
156    }
157
158    /**
159     * Shows page information on GET request.
160     *
161     * @return string Page information that will be added to the output
162     */
163    public function onView() {
164        $this->getOutput()->addModuleStyles( [
165            'mediawiki.interface.helpers.styles',
166            'mediawiki.action.styles',
167        ] );
168
169        // "Help" button
170        $this->addHelpLink( 'Page information' );
171
172        // Validate revision
173        $oldid = $this->getArticle()->getOldID();
174        if ( $oldid ) {
175            $revRecord = $this->getArticle()->fetchRevisionRecord();
176
177            if ( !$revRecord ) {
178                return $this->msg( 'missing-revision', $oldid )->parse();
179            } elseif ( !$revRecord->isCurrent() ) {
180                return $this->msg( 'pageinfo-not-current' )->plain();
181            }
182        }
183
184        // Page header
185        $msg = $this->msg( 'pageinfo-header' );
186        $content = $msg->isDisabled() ? '' : $msg->parse();
187
188        // Get page information
189        $pageInfo = $this->pageInfo();
190
191        // Allow extensions to add additional information
192        $this->getHookRunner()->onInfoAction( $this->getContext(), $pageInfo );
193
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;
209                }
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";
214            }
215            if ( $rows !== '' ) {
216                $content .= Html::rawElement( 'table', [ 'class' => 'wikitable mw-page-info' ],
217                    "\n" . $rows );
218            }
219            $content .= "\n" . $below;
220        }
221
222        // Page footer
223        if ( !$this->msg( 'pageinfo-footer' )->isDisabled() ) {
224            $content .= $this->msg( 'pageinfo-footer' )->parse();
225        }
226
227        return $content;
228    }
229
230    /**
231     * Creates a header that can be added to the output.
232     *
233     * @param string $header The header text.
234     * @param string $canonicalId
235     * @return string The HTML.
236     */
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 ) ],
244                ''
245            ) .
246            htmlspecialchars( $header )
247        );
248    }
249
250    /**
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
256     */
257    private function getRow( $name, $value, $id ) {
258        return Html::rawElement(
259                'tr',
260                [
261                    'id' => $id === null ? null : 'mw-' . $id,
262                    'style' => 'vertical-align: top;',
263                ],
264                Html::rawElement( 'td', [], $name ) .
265                    Html::rawElement( 'td', [], $value )
266            );
267    }
268
269    /**
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).
278     *
279     * @return array
280     * @phan-return array<string, list<array{0:string|Message, 1:string|Message}>>
281     */
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;
289
290        $pageCounts = $this->pageCounts();
291
292        $pageProperties = $this->pageProps->getAllProperties( $title )[$id] ?? [];
293
294        // Basic information
295        $pageInfo = [];
296        $pageInfo['header-basic'] = [];
297
298        // Display title
299        $displayTitle = $pageProperties['displaytitle'] ??
300            htmlspecialchars( $title->getPrefixedText(), ENT_NOQUOTES );
301
302        $pageInfo['header-basic'][] = [
303            $this->msg( 'pageinfo-display-title' ),
304            $displayTitle
305        ];
306
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(),
317                    [],
318                    [ 'action' => 'info' ]
319                ) )->escaped()
320            ];
321        }
322
323        // Default sort key
324        $sortKey = $pageProperties['defaultsort'] ?? $title->getCategorySortkey();
325        $pageInfo['header-basic'][] = [
326            $this->msg( 'pageinfo-default-sort' ),
327            htmlspecialchars( $sortKey )
328        ];
329
330        // Page length (in bytes)
331        $pageInfo['header-basic'][] = [
332            $this->msg( 'pageinfo-length' ),
333            $lang->formatNum( $title->getLength() )
334        ];
335
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 ];
341        }
342
343        // Page ID (number not localised, as it's a database ID)
344        $pageInfo['header-basic'][] = [ $this->msg( 'pageinfo-article-id' ), $id ];
345
346        // Language in which the page content is (supposed to be) written
347        $pageLang = $title->getPageLanguage()->getCode();
348
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 )
354        ) {
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();
360        }
361
362        $pageInfo['header-basic'][] = [
363            $this->msg( 'pageinfo-language' )->escaped(),
364            $pageLangHtml
365        ];
366
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();
376        }
377
378        $pageInfo['header-basic'][] = [
379            $this->msg( 'pageinfo-content-model' ),
380            $modelHtml
381        ];
382
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()
389                ];
390            }
391        }
392
393        // Search engine status
394        $parserOutput = new ParserOutput();
395        if ( isset( $pageProperties['noindex'] ) ) {
396            $parserOutput->setIndexPolicy( 'noindex' );
397        }
398        if ( isset( $pageProperties['index'] ) ) {
399            $parserOutput->setIndexPolicy( 'index' );
400        }
401
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']}" )
408        ];
409
410        $unwatchedPageThreshold = $config->get( MainConfigNames::UnwatchedPageThreshold );
411        if ( $this->getAuthority()->isAllowed( 'unwatchedpages' ) ||
412            ( $unwatchedPageThreshold !== false &&
413                $pageCounts['watchers'] >= $unwatchedPageThreshold )
414        ) {
415            // Number of page watchers
416            $pageInfo['header-basic'][] = [
417                $this->msg( 'pageinfo-watchers' ),
418                $lang->formatNum( $pageCounts['watchers'] )
419            ];
420
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' )
425                ) {
426                    $value = $lang->formatNum( $visiting );
427                } else {
428                    $value = $this->msg( 'pageinfo-few-visiting-watchers' );
429                }
430                $pageInfo['header-basic'][] = [
431                    $this->msg( 'pageinfo-visiting-watchers' )
432                        ->numParams( ceil( $config->get( MainConfigNames::WatchersMaxAge ) / 86400 ) ),
433                    $value
434                ];
435            }
436        } elseif ( $unwatchedPageThreshold !== false ) {
437            $pageInfo['header-basic'][] = [
438                $this->msg( 'pageinfo-watchers' ),
439                $this->msg( 'pageinfo-few-watchers' )->numParams( $unwatchedPageThreshold )
440            ];
441        }
442
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(),
449                [],
450                [
451                    'hidelinks' => 1,
452                    'hidetrans' => 1,
453                    'hideimages' => $title->getNamespace() === NS_FILE
454                ]
455            ),
456            $this->msg( 'pageinfo-redirects-value' )
457                ->numParams( count( $title->getRedirectsHere() ) )
458        ];
459
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' )
465            ];
466        }
467
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() . '/'
473            );
474            $pageInfo['header-basic'][] = [
475                $linkRenderer->makeLink(
476                    $prefixIndex,
477                    $this->msg( 'pageinfo-subpages-name' )->text()
478                ),
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' ] )
488                    )
489            ];
490        }
491
492        if ( $title->inNamespace( NS_CATEGORY ) ) {
493            $category = Category::newFromTitle( $title );
494
495            $allCount = $category->getMemberCount();
496            $subcatCount = $category->getSubcatCount();
497            $fileCount = $category->getFileCount();
498            $pageCount = $category->getPageCount( Category::COUNT_CONTENT_PAGES );
499
500            $pageInfo['category-info'] = [
501                [
502                    $this->msg( 'pageinfo-category-total' ),
503                    $lang->formatNum( $allCount )
504                ],
505                [
506                    $this->msg( 'pageinfo-category-pages' ),
507                    $lang->formatNum( $pageCount )
508                ],
509                [
510                    $this->msg( 'pageinfo-category-subcats' ),
511                    $lang->formatNum( $subcatCount )
512                ],
513                [
514                    $this->msg( 'pageinfo-category-files' ),
515                    $lang->formatNum( $fileCount )
516                ]
517            ];
518        }
519
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
529                ];
530            }
531        }
532
533        // Page protection
534        $pageInfo['header-restrictions'] = [];
535
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];
540
541            foreach ( $sources as $sourcePageIdentity ) {
542                $cascadingFrom .= Html::rawElement(
543                    'li',
544                    [],
545                    $linkRenderer->makeKnownLink( $sourcePageIdentity )
546                );
547            }
548
549            $cascadingFrom = Html::rawElement( 'ul', [], $cascadingFrom );
550            $pageInfo['header-restrictions'][] = [
551                $this->msg( 'pageinfo-protect-cascading-from' ),
552                $cascadingFrom
553            ];
554        }
555
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' )
561            ];
562        }
563
564        // Page protection
565        foreach ( $this->restrictionStore->listApplicableRestrictionTypes( $title ) as $restrictionType ) {
566            $protections = $this->restrictionStore->getRestrictions( $title, $restrictionType );
567
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;
574
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;
581                    }
582                    // Intentional fall-through if message is disabled (or non-existent)
583
584                default:
585                    // Require "$1" permission
586                    $message = $this->msg( "protect-fallback", $lang->commaList( $protections ) )->parse();
587                    break;
588            }
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;
595
596            // Messages: restriction-edit, restriction-move, restriction-create,
597            // restriction-upload
598            $pageInfo['header-restrictions'][] = [
599                $this->msg( "restriction-$restrictionType" ), $message
600            ];
601        }
602        $protectLog = SpecialPage::getTitleFor( 'Log' );
603        $pageInfo['header-restrictions'][] = [
604            'below',
605            $linkRenderer->makeKnownLink(
606                $protectLog,
607                $this->msg( 'pageinfo-view-protect-log' )->text(),
608                [],
609                [ 'type' => 'protect', 'page' => $title->getPrefixedText() ]
610            ),
611        ];
612
613        if ( !$this->getWikiPage()->exists() ) {
614            return $pageInfo;
615        }
616
617        // Edit history
618        $pageInfo['header-edits'] = [];
619
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() );
628            }
629        }
630
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() );
636            }
637        }
638
639        $batch->execute();
640
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 )
651            ];
652
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 ),
659                    [],
660                    [ 'oldid' => $firstRev->getId() ]
661                )
662            ];
663        }
664
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 )
675            ];
676
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 ),
683                    [],
684                    [ 'oldid' => $this->getWikiPage()->getLatest() ]
685                )
686            ];
687        }
688
689        // Total number of edits
690        $pageInfo['header-edits'][] = [
691            $this->msg( 'pageinfo-edits' ),
692            $lang->formatNum( $pageCounts['edits'] )
693        ];
694
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'] )
700            ];
701        }
702
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 ) )
708            ),
709            $lang->formatNum( $pageCounts['recent_edits'] )
710        ];
711
712        // Recent number of distinct authors
713        $pageInfo['header-edits'][] = [
714            $this->msg( 'pageinfo-recent-authors' ),
715            $lang->formatNum( $pageCounts['recent_authors'] )
716        ];
717
718        // Array of magic word IDs
719        $wordIDs = $this->magicWordFactory->getDoubleUnderscoreArray()->getNames();
720
721        // Array of IDs => localized magic words
722        $localizedWords = $this->contentLanguage->getMagicWords();
723
724        $listItems = [];
725        foreach ( $pageProperties as $property => $value ) {
726            if ( in_array( $property, $wordIDs ) ) {
727                $listItems[] = Html::element( 'li', [], $localizedWords[$property][1] );
728            }
729        }
730
731        $localizedList = Html::rawElement( 'ul', [], implode( '', $listItems ) );
732        $hiddenCategories = $this->getWikiPage()->getHiddenCategories();
733
734        if (
735            count( $listItems ) > 0 ||
736            count( $hiddenCategories ) > 0 ||
737            $pageCounts['transclusion']['from'] > 0 ||
738            $pageCounts['transclusion']['to'] > 0
739        ) {
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 );
746            }
747
748            // Page properties
749            $pageInfo['header-properties'] = [];
750
751            // Magic words
752            if ( count( $listItems ) > 0 ) {
753                $pageInfo['header-properties'][] = [
754                    $this->msg( 'pageinfo-magic-words' )->numParams( count( $listItems ) ),
755                    $localizedList
756                ];
757            }
758
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 )
765                ];
766            }
767
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;
774                }
775
776                $templateListFormatter = new TemplatesOnThisPageFormatter(
777                    $this->getContext(),
778                    $linkRenderer,
779                    $this->linkBatchFactory,
780                    $this->restrictionStore
781                );
782
783                $pageInfo['header-properties'][] = [
784                    $this->msg( 'pageinfo-templates' )
785                        ->numParams( $pageCounts['transclusion']['from'] ),
786                    $templateListFormatter->format( $transcludedTemplates, false, $more )
787                ];
788            }
789
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(),
795                        [],
796                        [ 'hidelinks' => 1, 'hideredirs' => 1 ]
797                    );
798                } else {
799                    $more = null;
800                }
801
802                $templateListFormatter = new TemplatesOnThisPageFormatter(
803                    $this->getContext(),
804                    $linkRenderer,
805                    $this->linkBatchFactory,
806                    $this->restrictionStore
807                );
808
809                $pageInfo['header-properties'][] = [
810                    $this->msg( 'pageinfo-transclusions' )
811                        ->numParams( $pageCounts['transclusion']['to'] ),
812                    $templateListFormatter->format( $transcludedTargets, false, $more )
813                ];
814            }
815        }
816
817        return $pageInfo;
818    }
819
820    /**
821     * Get namespace protection message for title or null if no namespace protection
822     * has been applied
823     *
824     * @param Title $title
825     * @return ?string HTML
826     */
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;
850            }
851        }
852        if ( $rights ) {
853            return $this->msg( 'protect-fallback', $this->getLanguage()->commaList( $rights ) )->parse();
854        } else {
855            return null;
856        }
857    }
858
859    /**
860     * Returns page counts that would be too "expensive" to retrieve by normal means.
861     *
862     * @return array
863     */
864    private function pageCounts() {
865        $page = $this->getWikiPage();
866        $fname = __METHOD__;
867        $config = $this->context->getConfig();
868        $cache = $this->wanObjectCache;
869
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();
876
877                $dbr = $this->dbProvider->getReplicaDatabase();
878                $setOpts += Database::getCacheSetOptions( $dbr );
879
880                $field = 'rev_actor';
881                $pageField = 'rev_page';
882
883                $watchedItemStore = $this->watchedItemStore;
884
885                $result = [];
886                $result['watchers'] = $watchedItemStore->countWatchers( $title );
887
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 )
893                    );
894                }
895
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;
904
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();
915                }
916
917                // "Recent" threshold defined by RCMaxAge setting
918                $threshold = $dbr->timestamp( time() - $config->get( MainConfigNames::RCMaxAge ) );
919
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;
929
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();
938
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() )
946                    );
947
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();
964
965                    // Subpages of this page (total)
966                    $result['subpages']['total'] = $result['subpages']['redirects']
967                        + $result['subpages']['nonredirects'];
968                }
969
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();
980                }
981
982                $result['transclusion']['from'] = (int)$dbr->newSelectQueryBuilder()
983                    ->select( 'COUNT(*)' )
984                    ->from( 'templatelinks' )
985                    ->where( [ 'tl_from' => $title->getArticleID() ] )
986                    ->caller( $fname )
987                    ->fetchField();
988
989                return $result;
990            }
991        );
992    }
993
994    /**
995     * Returns the name that goes in the "<h1>" page title.
996     *
997     * @return string
998     */
999    protected function getPageTitle() {
1000        return $this->msg( 'pageinfo-title' )->plaintextParams( $this->getTitle()->getPrefixedText() );
1001    }
1002
1003    /**
1004     * Returns the description that goes below the "<h1>" tag.
1005     *
1006     * @return string
1007     */
1008    protected function getDescription() {
1009        return '';
1010    }
1011
1012    /**
1013     * @param WANObjectCache $cache
1014     * @param PageIdentity $page
1015     * @param int $revId
1016     * @return string
1017     */
1018    protected static function getCacheKey( WANObjectCache $cache, PageIdentity $page, $revId ) {
1019        return $cache->makeKey( 'infoaction', md5( (string)$page ), $revId, self::VERSION );
1020    }
1021}