Add link to protect log to action=info
[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 $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 ID (number not localised, as it's a database ID)
268 $pageInfo['header-basic'][] = [ $this->msg( 'pageinfo-article-id' ), $id ];
269
270 // Language in which the page content is (supposed to be) written
271 $pageLang = $title->getPageLanguage()->getCode();
272
273 $pageLangHtml = $pageLang . ' - ' .
274 Language::fetchLanguageName( $pageLang, $lang->getCode() );
275 // Link to Special:PageLanguage with pre-filled page title if user has permissions
276 if ( $config->get( 'PageLanguageUseDB' )
277 && $title->userCan( 'pagelang', $user )
278 ) {
279 $pageLangHtml .= ' ' . $this->msg( 'parentheses' )->rawParams( $linkRenderer->makeLink(
280 SpecialPage::getTitleValueFor( 'PageLanguage', $title->getPrefixedText() ),
281 $this->msg( 'pageinfo-language-change' )->text()
282 ) )->escaped();
283 }
284
285 $pageInfo['header-basic'][] = [
286 $this->msg( 'pageinfo-language' )->escaped(),
287 $pageLangHtml
288 ];
289
290 // Content model of the page
291 $modelHtml = htmlspecialchars( ContentHandler::getLocalizedName( $title->getContentModel() ) );
292 // If the user can change it, add a link to Special:ChangeContentModel
293 if ( $config->get( 'ContentHandlerUseDB' )
294 && $title->userCan( 'editcontentmodel', $user )
295 ) {
296 $modelHtml .= ' ' . $this->msg( 'parentheses' )->rawParams( $linkRenderer->makeLink(
297 SpecialPage::getTitleValueFor( 'ChangeContentModel', $title->getPrefixedText() ),
298 $this->msg( 'pageinfo-content-model-change' )->text()
299 ) )->escaped();
300 }
301
302 $pageInfo['header-basic'][] = [
303 $this->msg( 'pageinfo-content-model' ),
304 $modelHtml
305 ];
306
307 if ( $title->inNamespace( NS_USER ) ) {
308 $pageUser = User::newFromName( $title->getRootText() );
309 if ( $pageUser && $pageUser->getId() && !$pageUser->isHidden() ) {
310 $pageInfo['header-basic'][] = [
311 $this->msg( 'pageinfo-user-id' ),
312 $pageUser->getId()
313 ];
314 }
315 }
316
317 // Search engine status
318 $pOutput = new ParserOutput();
319 if ( isset( $pageProperties['noindex'] ) ) {
320 $pOutput->setIndexPolicy( 'noindex' );
321 }
322 if ( isset( $pageProperties['index'] ) ) {
323 $pOutput->setIndexPolicy( 'index' );
324 }
325
326 // Use robot policy logic
327 $policy = $this->page->getRobotPolicy( 'view', $pOutput );
328 $pageInfo['header-basic'][] = [
329 // Messages: pageinfo-robot-index, pageinfo-robot-noindex
330 $this->msg( 'pageinfo-robot-policy' ),
331 $this->msg( "pageinfo-robot-${policy['index']}" )
332 ];
333
334 $unwatchedPageThreshold = $config->get( 'UnwatchedPageThreshold' );
335 if (
336 $user->isAllowed( 'unwatchedpages' ) ||
337 ( $unwatchedPageThreshold !== false &&
338 $pageCounts['watchers'] >= $unwatchedPageThreshold )
339 ) {
340 // Number of page watchers
341 $pageInfo['header-basic'][] = [
342 $this->msg( 'pageinfo-watchers' ),
343 $lang->formatNum( $pageCounts['watchers'] )
344 ];
345 if (
346 $config->get( 'ShowUpdatedMarker' ) &&
347 isset( $pageCounts['visitingWatchers'] )
348 ) {
349 $minToDisclose = $config->get( 'UnwatchedPageSecret' );
350 if ( $pageCounts['visitingWatchers'] > $minToDisclose ||
351 $user->isAllowed( 'unwatchedpages' ) ) {
352 $pageInfo['header-basic'][] = [
353 $this->msg( 'pageinfo-visiting-watchers' ),
354 $lang->formatNum( $pageCounts['visitingWatchers'] )
355 ];
356 } else {
357 $pageInfo['header-basic'][] = [
358 $this->msg( 'pageinfo-visiting-watchers' ),
359 $this->msg( 'pageinfo-few-visiting-watchers' )
360 ];
361 }
362 }
363 } elseif ( $unwatchedPageThreshold !== false ) {
364 $pageInfo['header-basic'][] = [
365 $this->msg( 'pageinfo-watchers' ),
366 $this->msg( 'pageinfo-few-watchers' )->numParams( $unwatchedPageThreshold )
367 ];
368 }
369
370 // Redirects to this page
371 $whatLinksHere = SpecialPage::getTitleFor( 'Whatlinkshere', $title->getPrefixedText() );
372 $pageInfo['header-basic'][] = [
373 $linkRenderer->makeLink(
374 $whatLinksHere,
375 $this->msg( 'pageinfo-redirects-name' )->text(),
376 [],
377 [
378 'hidelinks' => 1,
379 'hidetrans' => 1,
380 'hideimages' => $title->getNamespace() == NS_FILE
381 ]
382 ),
383 $this->msg( 'pageinfo-redirects-value' )
384 ->numParams( count( $title->getRedirectsHere() ) )
385 ];
386
387 // Is it counted as a content page?
388 if ( $this->page->isCountable() ) {
389 $pageInfo['header-basic'][] = [
390 $this->msg( 'pageinfo-contentpage' ),
391 $this->msg( 'pageinfo-contentpage-yes' )
392 ];
393 }
394
395 // Subpages of this page, if subpages are enabled for the current NS
396 if ( MWNamespace::hasSubpages( $title->getNamespace() ) ) {
397 $prefixIndex = SpecialPage::getTitleFor(
398 'Prefixindex', $title->getPrefixedText() . '/' );
399 $pageInfo['header-basic'][] = [
400 $linkRenderer->makeLink(
401 $prefixIndex,
402 $this->msg( 'pageinfo-subpages-name' )->text()
403 ),
404 $this->msg( 'pageinfo-subpages-value' )
405 ->numParams(
406 $pageCounts['subpages']['total'],
407 $pageCounts['subpages']['redirects'],
408 $pageCounts['subpages']['nonredirects'] )
409 ];
410 }
411
412 if ( $title->inNamespace( NS_CATEGORY ) ) {
413 $category = Category::newFromTitle( $title );
414
415 // $allCount is the total number of cat members,
416 // not the count of how many members are normal pages.
417 $allCount = (int)$category->getPageCount();
418 $subcatCount = (int)$category->getSubcatCount();
419 $fileCount = (int)$category->getFileCount();
420 $pagesCount = $allCount - $subcatCount - $fileCount;
421
422 $pageInfo['category-info'] = [
423 [
424 $this->msg( 'pageinfo-category-total' ),
425 $lang->formatNum( $allCount )
426 ],
427 [
428 $this->msg( 'pageinfo-category-pages' ),
429 $lang->formatNum( $pagesCount )
430 ],
431 [
432 $this->msg( 'pageinfo-category-subcats' ),
433 $lang->formatNum( $subcatCount )
434 ],
435 [
436 $this->msg( 'pageinfo-category-files' ),
437 $lang->formatNum( $fileCount )
438 ]
439 ];
440 }
441
442 // Display image SHA-1 value
443 if ( $title->inNamespace( NS_FILE ) ) {
444 $fileObj = wfFindFile( $title );
445 if ( $fileObj !== false ) {
446 // Convert the base-36 sha1 value obtained from database to base-16
447 $output = Wikimedia\base_convert( $fileObj->getSha1(), 36, 16, 40 );
448 $pageInfo['header-basic'][] = [
449 $this->msg( 'pageinfo-file-hash' ),
450 $output
451 ];
452 }
453 }
454
455 // Page protection
456 $pageInfo['header-restrictions'] = [];
457
458 // Is this page affected by the cascading protection of something which includes it?
459 if ( $title->isCascadeProtected() ) {
460 $cascadingFrom = '';
461 $sources = $title->getCascadeProtectionSources()[0];
462
463 foreach ( $sources as $sourceTitle ) {
464 $cascadingFrom .= Html::rawElement(
465 'li', [], $linkRenderer->makeKnownLink( $sourceTitle ) );
466 }
467
468 $cascadingFrom = Html::rawElement( 'ul', [], $cascadingFrom );
469 $pageInfo['header-restrictions'][] = [
470 $this->msg( 'pageinfo-protect-cascading-from' ),
471 $cascadingFrom
472 ];
473 }
474
475 // Is out protection set to cascade to other pages?
476 if ( $title->areRestrictionsCascading() ) {
477 $pageInfo['header-restrictions'][] = [
478 $this->msg( 'pageinfo-protect-cascading' ),
479 $this->msg( 'pageinfo-protect-cascading-yes' )
480 ];
481 }
482
483 // Page protection
484 foreach ( $title->getRestrictionTypes() as $restrictionType ) {
485 $protectionLevel = implode( ', ', $title->getRestrictions( $restrictionType ) );
486
487 if ( $protectionLevel == '' ) {
488 // Allow all users
489 $message = $this->msg( 'protect-default' )->escaped();
490 } else {
491 // Administrators only
492 // Messages: protect-level-autoconfirmed, protect-level-sysop
493 $message = $this->msg( "protect-level-$protectionLevel" );
494 if ( $message->isDisabled() ) {
495 // Require "$1" permission
496 $message = $this->msg( "protect-fallback", $protectionLevel )->parse();
497 } else {
498 $message = $message->escaped();
499 }
500 }
501 $expiry = $title->getRestrictionExpiry( $restrictionType );
502 $formattedexpiry = $this->msg( 'parentheses',
503 $lang->formatExpiry( $expiry ) )->escaped();
504 $message .= $this->msg( 'word-separator' )->escaped() . $formattedexpiry;
505
506 // Messages: restriction-edit, restriction-move, restriction-create,
507 // restriction-upload
508 $pageInfo['header-restrictions'][] = [
509 $this->msg( "restriction-$restrictionType" ), $message
510 ];
511 }
512 $protectLog = SpecialPage::getTitleFor( 'Log' );
513 $pageInfo['header-restrictions'][] = [
514 'below',
515 $linkRenderer->makeKnownLink(
516 $protectLog,
517 $this->msg( 'pageinfo-view-protect-log' )->text(),
518 [],
519 [ 'type' => 'protect', 'page' => $title->getPrefixedText() ]
520 ),
521 ];
522
523 if ( !$this->page->exists() ) {
524 return $pageInfo;
525 }
526
527 // Edit history
528 $pageInfo['header-edits'] = [];
529
530 $firstRev = $this->page->getOldestRevision();
531 $lastRev = $this->page->getRevision();
532 $batch = new LinkBatch;
533
534 if ( $firstRev ) {
535 $firstRevUser = $firstRev->getUserText( Revision::FOR_THIS_USER );
536 if ( $firstRevUser !== '' ) {
537 $firstRevUserTitle = Title::makeTitle( NS_USER, $firstRevUser );
538 $batch->addObj( $firstRevUserTitle );
539 $batch->addObj( $firstRevUserTitle->getTalkPage() );
540 }
541 }
542
543 if ( $lastRev ) {
544 $lastRevUser = $lastRev->getUserText( Revision::FOR_THIS_USER );
545 if ( $lastRevUser !== '' ) {
546 $lastRevUserTitle = Title::makeTitle( NS_USER, $lastRevUser );
547 $batch->addObj( $lastRevUserTitle );
548 $batch->addObj( $lastRevUserTitle->getTalkPage() );
549 }
550 }
551
552 $batch->execute();
553
554 if ( $firstRev ) {
555 // Page creator
556 $pageInfo['header-edits'][] = [
557 $this->msg( 'pageinfo-firstuser' ),
558 Linker::revUserTools( $firstRev )
559 ];
560
561 // Date of page creation
562 $pageInfo['header-edits'][] = [
563 $this->msg( 'pageinfo-firsttime' ),
564 $linkRenderer->makeKnownLink(
565 $title,
566 $lang->userTimeAndDate( $firstRev->getTimestamp(), $user ),
567 [],
568 [ 'oldid' => $firstRev->getId() ]
569 )
570 ];
571 }
572
573 if ( $lastRev ) {
574 // Latest editor
575 $pageInfo['header-edits'][] = [
576 $this->msg( 'pageinfo-lastuser' ),
577 Linker::revUserTools( $lastRev )
578 ];
579
580 // Date of latest edit
581 $pageInfo['header-edits'][] = [
582 $this->msg( 'pageinfo-lasttime' ),
583 $linkRenderer->makeKnownLink(
584 $title,
585 $lang->userTimeAndDate( $this->page->getTimestamp(), $user ),
586 [],
587 [ 'oldid' => $this->page->getLatest() ]
588 )
589 ];
590 }
591
592 // Total number of edits
593 $pageInfo['header-edits'][] = [
594 $this->msg( 'pageinfo-edits' ), $lang->formatNum( $pageCounts['edits'] )
595 ];
596
597 // Total number of distinct authors
598 if ( $pageCounts['authors'] > 0 ) {
599 $pageInfo['header-edits'][] = [
600 $this->msg( 'pageinfo-authors' ), $lang->formatNum( $pageCounts['authors'] )
601 ];
602 }
603
604 // Recent number of edits (within past 30 days)
605 $pageInfo['header-edits'][] = [
606 $this->msg( 'pageinfo-recent-edits',
607 $lang->formatDuration( $config->get( 'RCMaxAge' ) ) ),
608 $lang->formatNum( $pageCounts['recent_edits'] )
609 ];
610
611 // Recent number of distinct authors
612 $pageInfo['header-edits'][] = [
613 $this->msg( 'pageinfo-recent-authors' ),
614 $lang->formatNum( $pageCounts['recent_authors'] )
615 ];
616
617 // Array of MagicWord objects
618 $magicWords = $services->getMagicWordFactory()->getDoubleUnderscoreArray();
619
620 // Array of magic word IDs
621 $wordIDs = $magicWords->names;
622
623 // Array of IDs => localized magic words
624 $localizedWords = $services->getContentLanguage()->getMagicWords();
625
626 $listItems = [];
627 foreach ( $pageProperties as $property => $value ) {
628 if ( in_array( $property, $wordIDs ) ) {
629 $listItems[] = Html::element( 'li', [], $localizedWords[$property][1] );
630 }
631 }
632
633 $localizedList = Html::rawElement( 'ul', [], implode( '', $listItems ) );
634 $hiddenCategories = $this->page->getHiddenCategories();
635
636 if (
637 count( $listItems ) > 0 ||
638 count( $hiddenCategories ) > 0 ||
639 $pageCounts['transclusion']['from'] > 0 ||
640 $pageCounts['transclusion']['to'] > 0
641 ) {
642 $options = [ 'LIMIT' => $config->get( 'PageInfoTransclusionLimit' ) ];
643 $transcludedTemplates = $title->getTemplateLinksFrom( $options );
644 if ( $config->get( 'MiserMode' ) ) {
645 $transcludedTargets = [];
646 } else {
647 $transcludedTargets = $title->getTemplateLinksTo( $options );
648 }
649
650 // Page properties
651 $pageInfo['header-properties'] = [];
652
653 // Magic words
654 if ( count( $listItems ) > 0 ) {
655 $pageInfo['header-properties'][] = [
656 $this->msg( 'pageinfo-magic-words' )->numParams( count( $listItems ) ),
657 $localizedList
658 ];
659 }
660
661 // Hidden categories
662 if ( count( $hiddenCategories ) > 0 ) {
663 $pageInfo['header-properties'][] = [
664 $this->msg( 'pageinfo-hidden-categories' )
665 ->numParams( count( $hiddenCategories ) ),
666 Linker::formatHiddenCategories( $hiddenCategories )
667 ];
668 }
669
670 // Transcluded templates
671 if ( $pageCounts['transclusion']['from'] > 0 ) {
672 if ( $pageCounts['transclusion']['from'] > count( $transcludedTemplates ) ) {
673 $more = $this->msg( 'morenotlisted' )->escaped();
674 } else {
675 $more = null;
676 }
677
678 $templateListFormatter = new TemplatesOnThisPageFormatter(
679 $this->getContext(),
680 $linkRenderer
681 );
682
683 $pageInfo['header-properties'][] = [
684 $this->msg( 'pageinfo-templates' )
685 ->numParams( $pageCounts['transclusion']['from'] ),
686 $templateListFormatter->format( $transcludedTemplates, false, $more )
687 ];
688 }
689
690 if ( !$config->get( 'MiserMode' ) && $pageCounts['transclusion']['to'] > 0 ) {
691 if ( $pageCounts['transclusion']['to'] > count( $transcludedTargets ) ) {
692 $more = $linkRenderer->makeLink(
693 $whatLinksHere,
694 $this->msg( 'moredotdotdot' )->text(),
695 [],
696 [ 'hidelinks' => 1, 'hideredirs' => 1 ]
697 );
698 } else {
699 $more = null;
700 }
701
702 $templateListFormatter = new TemplatesOnThisPageFormatter(
703 $this->getContext(),
704 $linkRenderer
705 );
706
707 $pageInfo['header-properties'][] = [
708 $this->msg( 'pageinfo-transclusions' )
709 ->numParams( $pageCounts['transclusion']['to'] ),
710 $templateListFormatter->format( $transcludedTargets, false, $more )
711 ];
712 }
713 }
714
715 return $pageInfo;
716 }
717
718 /**
719 * Returns page counts that would be too "expensive" to retrieve by normal means.
720 *
721 * @param WikiPage|Article|Page $page
722 * @return array
723 */
724 protected function pageCounts( Page $page ) {
725 $fname = __METHOD__;
726 $config = $this->context->getConfig();
727 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
728
729 return $cache->getWithSetCallback(
730 self::getCacheKey( $cache, $page->getTitle(), $page->getLatest() ),
731 WANObjectCache::TTL_WEEK,
732 function ( $oldValue, &$ttl, &$setOpts ) use ( $page, $config, $fname ) {
733 global $wgActorTableSchemaMigrationStage;
734
735 $title = $page->getTitle();
736 $id = $title->getArticleID();
737
738 $dbr = wfGetDB( DB_REPLICA );
739 $dbrWatchlist = wfGetDB( DB_REPLICA, 'watchlist' );
740 $setOpts += Database::getCacheSetOptions( $dbr, $dbrWatchlist );
741
742 if ( $wgActorTableSchemaMigrationStage === MIGRATION_NEW ) {
743 $tables = [ 'revision_actor_temp' ];
744 $field = 'revactor_actor';
745 $pageField = 'revactor_page';
746 $tsField = 'revactor_timestamp';
747 $joins = [];
748 } elseif ( $wgActorTableSchemaMigrationStage === MIGRATION_OLD ) {
749 $tables = [ 'revision' ];
750 $field = 'rev_user_text';
751 $pageField = 'rev_page';
752 $tsField = 'rev_timestamp';
753 $joins = [];
754 } else {
755 $tables = [ 'revision', 'revision_actor_temp', 'actor' ];
756 $field = 'COALESCE( actor_name, rev_user_text)';
757 $pageField = 'rev_page';
758 $tsField = 'rev_timestamp';
759 $joins = [
760 'revision_actor_temp' => [ 'LEFT JOIN', 'revactor_rev = rev_id' ],
761 'actor' => [ 'LEFT JOIN', 'revactor_actor = actor_id' ],
762 ];
763 }
764
765 $watchedItemStore = MediaWikiServices::getInstance()->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 ( MWNamespace::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 }