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