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