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