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