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