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