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