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