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