MediaWiki  master
InfoAction.php
Go to the documentation of this file.
1 <?php
27 
33 class InfoAction extends FormlessAction {
34  const VERSION = 1;
35 
41  public function getName() {
42  return 'info';
43  }
44 
50  public function requiresUnblock() {
51  return false;
52  }
53 
59  public function requiresWrite() {
60  return false;
61  }
62 
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 
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  // "Help" button
107  $this->addHelpLink( 'Page information' );
108 
109  // Page header
110  if ( !$this->msg( 'pageinfo-header' )->isDisabled() ) {
111  $content .= $this->msg( 'pageinfo-header' )->parse();
112  }
113 
114  // Hide "This page is a member of # hidden categories" explanation
115  $content .= Html::element( 'style', [],
116  '.mw-hiddenCategoriesExplanation { display: none; }' ) . "\n";
117 
118  // Hide "Templates used on this page" explanation
119  $content .= Html::element( 'style', [],
120  '.mw-templatesUsedExplanation { display: none; }' ) . "\n";
121 
122  // Get page information
123  $pageInfo = $this->pageInfo();
124 
125  // Allow extensions to add additional information
126  Hooks::run( 'InfoAction', [ $this->getContext(), &$pageInfo ] );
127 
128  // Render page information
129  foreach ( $pageInfo as $header => $infoTable ) {
130  // Messages:
131  // pageinfo-header-basic, pageinfo-header-edits, pageinfo-header-restrictions,
132  // pageinfo-header-properties, pageinfo-category-info
133  $content .= $this->makeHeader(
134  $this->msg( "pageinfo-${header}" )->text(),
135  "mw-pageinfo-${header}"
136  ) . "\n";
137  $table = "\n";
138  $below = "";
139  foreach ( $infoTable as $infoRow ) {
140  if ( $infoRow[0] == "below" ) {
141  $below = $infoRow[1] . "\n";
142  continue;
143  }
144  $name = ( $infoRow[0] instanceof Message ) ? $infoRow[0]->escaped() : $infoRow[0];
145  $value = ( $infoRow[1] instanceof Message ) ? $infoRow[1]->escaped() : $infoRow[1];
146  $id = ( $infoRow[0] instanceof Message ) ? $infoRow[0]->getKey() : null;
147  $table = $this->addRow( $table, $name, $value, $id ) . "\n";
148  }
149  $content = $this->addTable( $content, $table ) . "\n" . $below;
150  }
151 
152  // Page footer
153  if ( !$this->msg( 'pageinfo-footer' )->isDisabled() ) {
154  $content .= $this->msg( 'pageinfo-footer' )->parse();
155  }
156 
157  return $content;
158  }
159 
167  protected function makeHeader( $header, $canonicalId ) {
168  $spanAttribs = [ 'class' => 'mw-headline', 'id' => Sanitizer::escapeIdForAttribute( $header ) ];
169  $h2Attribs = [ 'id' => Sanitizer::escapeIdForAttribute( $canonicalId ) ];
170 
171  return Html::rawElement( 'h2', $h2Attribs, Html::element( 'span', $spanAttribs, $header ) );
172  }
173 
183  protected function addRow( $table, $name, $value, $id ) {
184  return $table .
186  'tr',
187  $id === null ? [] : [ 'id' => 'mw-' . $id ],
188  Html::rawElement( 'td', [ 'style' => 'vertical-align: top;' ], $name ) .
189  Html::rawElement( 'td', [], $value )
190  );
191  }
192 
200  protected function addTable( $content, $table ) {
201  return $content . Html::rawElement( 'table', [ 'class' => 'wikitable mw-page-info' ],
202  $table );
203  }
204 
217  protected function pageInfo() {
218  $services = MediaWikiServices::getInstance();
219 
220  $user = $this->getUser();
221  $lang = $this->getLanguage();
222  $title = $this->getTitle();
223  $id = $title->getArticleID();
224  $config = $this->context->getConfig();
225  $linkRenderer = $services->getLinkRenderer();
226 
227  $pageCounts = $this->pageCounts( $this->page );
228 
229  $props = PageProps::getInstance()->getAllProperties( $title );
230  $pageProperties = $props[$id] ?? [];
231 
232  // Basic information
233  $pageInfo = [];
234  $pageInfo['header-basic'] = [];
235 
236  // Display title
237  $displayTitle = $pageProperties['displaytitle'] ?? $title->getPrefixedText();
238 
239  $pageInfo['header-basic'][] = [
240  $this->msg( 'pageinfo-display-title' ), $displayTitle
241  ];
242 
243  // Is it a redirect? If so, where to?
244  $redirectTarget = $this->page->getRedirectTarget();
245  if ( $redirectTarget !== null ) {
246  $pageInfo['header-basic'][] = [
247  $this->msg( 'pageinfo-redirectsto' ),
248  $linkRenderer->makeLink( $redirectTarget ) .
249  $this->msg( 'word-separator' )->escaped() .
250  $this->msg( 'parentheses' )->rawParams( $linkRenderer->makeLink(
251  $redirectTarget,
252  $this->msg( 'pageinfo-redirectsto-info' )->text(),
253  [],
254  [ 'action' => 'info' ]
255  ) )->escaped()
256  ];
257  }
258 
259  // Default sort key
260  $sortKey = $pageProperties['defaultsort'] ?? $title->getCategorySortkey();
261 
262  $sortKey = htmlspecialchars( $sortKey );
263  $pageInfo['header-basic'][] = [ $this->msg( 'pageinfo-default-sort' ), $sortKey ];
264 
265  // Page length (in bytes)
266  $pageInfo['header-basic'][] = [
267  $this->msg( 'pageinfo-length' ), $lang->formatNum( $title->getLength() )
268  ];
269 
270  // Page namespace
271  $pageNamespace = $title->getNsText();
272  if ( $pageNamespace ) {
273  $pageInfo['header-basic'][] = [ $this->msg( 'pageinfo-namespace' ), $pageNamespace ];
274  }
275 
276  // Page ID (number not localised, as it's a database ID)
277  $pageInfo['header-basic'][] = [ $this->msg( 'pageinfo-article-id' ), $id ];
278 
279  // Language in which the page content is (supposed to be) written
280  $pageLang = $title->getPageLanguage()->getCode();
281 
282  $permissionManager = MediaWikiServices::getInstance()->getPermissionManager();
283 
284  $pageLangHtml = $pageLang . ' - ' .
285  Language::fetchLanguageName( $pageLang, $lang->getCode() );
286  // Link to Special:PageLanguage with pre-filled page title if user has permissions
287  if ( $config->get( 'PageLanguageUseDB' )
288  && $permissionManager->userCan( 'pagelang', $user, $title )
289  ) {
290  $pageLangHtml .= ' ' . $this->msg( 'parentheses' )->rawParams( $linkRenderer->makeLink(
291  SpecialPage::getTitleValueFor( 'PageLanguage', $title->getPrefixedText() ),
292  $this->msg( 'pageinfo-language-change' )->text()
293  ) )->escaped();
294  }
295 
296  $pageInfo['header-basic'][] = [
297  $this->msg( 'pageinfo-language' )->escaped(),
298  $pageLangHtml
299  ];
300 
301  // Content model of the page
302  $modelHtml = htmlspecialchars( ContentHandler::getLocalizedName( $title->getContentModel() ) );
303  // If the user can change it, add a link to Special:ChangeContentModel
304  if ( $config->get( 'ContentHandlerUseDB' )
305  && $permissionManager->userCan( 'editcontentmodel', $user, $title )
306  ) {
307  $modelHtml .= ' ' . $this->msg( 'parentheses' )->rawParams( $linkRenderer->makeLink(
308  SpecialPage::getTitleValueFor( 'ChangeContentModel', $title->getPrefixedText() ),
309  $this->msg( 'pageinfo-content-model-change' )->text()
310  ) )->escaped();
311  }
312 
313  $pageInfo['header-basic'][] = [
314  $this->msg( 'pageinfo-content-model' ),
315  $modelHtml
316  ];
317 
318  if ( $title->inNamespace( NS_USER ) ) {
319  $pageUser = User::newFromName( $title->getRootText() );
320  if ( $pageUser && $pageUser->getId() && !$pageUser->isHidden() ) {
321  $pageInfo['header-basic'][] = [
322  $this->msg( 'pageinfo-user-id' ),
323  $pageUser->getId()
324  ];
325  }
326  }
327 
328  // Search engine status
329  $pOutput = new ParserOutput();
330  if ( isset( $pageProperties['noindex'] ) ) {
331  $pOutput->setIndexPolicy( 'noindex' );
332  }
333  if ( isset( $pageProperties['index'] ) ) {
334  $pOutput->setIndexPolicy( 'index' );
335  }
336 
337  // Use robot policy logic
338  $policy = $this->page->getRobotPolicy( 'view', $pOutput );
339  $pageInfo['header-basic'][] = [
340  // Messages: pageinfo-robot-index, pageinfo-robot-noindex
341  $this->msg( 'pageinfo-robot-policy' ),
342  $this->msg( "pageinfo-robot-${policy['index']}" )
343  ];
344 
345  $unwatchedPageThreshold = $config->get( 'UnwatchedPageThreshold' );
346  if (
347  $user->isAllowed( 'unwatchedpages' ) ||
348  ( $unwatchedPageThreshold !== false &&
349  $pageCounts['watchers'] >= $unwatchedPageThreshold )
350  ) {
351  // Number of page watchers
352  $pageInfo['header-basic'][] = [
353  $this->msg( 'pageinfo-watchers' ),
354  $lang->formatNum( $pageCounts['watchers'] )
355  ];
356  if (
357  $config->get( 'ShowUpdatedMarker' ) &&
358  isset( $pageCounts['visitingWatchers'] )
359  ) {
360  $minToDisclose = $config->get( 'UnwatchedPageSecret' );
361  if ( $pageCounts['visitingWatchers'] > $minToDisclose ||
362  $user->isAllowed( 'unwatchedpages' ) ) {
363  $pageInfo['header-basic'][] = [
364  $this->msg( 'pageinfo-visiting-watchers' ),
365  $lang->formatNum( $pageCounts['visitingWatchers'] )
366  ];
367  } else {
368  $pageInfo['header-basic'][] = [
369  $this->msg( 'pageinfo-visiting-watchers' ),
370  $this->msg( 'pageinfo-few-visiting-watchers' )
371  ];
372  }
373  }
374  } elseif ( $unwatchedPageThreshold !== false ) {
375  $pageInfo['header-basic'][] = [
376  $this->msg( 'pageinfo-watchers' ),
377  $this->msg( 'pageinfo-few-watchers' )->numParams( $unwatchedPageThreshold )
378  ];
379  }
380 
381  // Redirects to this page
382  $whatLinksHere = SpecialPage::getTitleFor( 'Whatlinkshere', $title->getPrefixedText() );
383  $pageInfo['header-basic'][] = [
384  $linkRenderer->makeLink(
385  $whatLinksHere,
386  $this->msg( 'pageinfo-redirects-name' )->text(),
387  [],
388  [
389  'hidelinks' => 1,
390  'hidetrans' => 1,
391  'hideimages' => $title->getNamespace() == NS_FILE
392  ]
393  ),
394  $this->msg( 'pageinfo-redirects-value' )
395  ->numParams( count( $title->getRedirectsHere() ) )
396  ];
397 
398  // Is it counted as a content page?
399  if ( $this->page->isCountable() ) {
400  $pageInfo['header-basic'][] = [
401  $this->msg( 'pageinfo-contentpage' ),
402  $this->msg( 'pageinfo-contentpage-yes' )
403  ];
404  }
405 
406  // Subpages of this page, if subpages are enabled for the current NS
407  if ( $services->getNamespaceInfo()->hasSubpages( $title->getNamespace() ) ) {
408  $prefixIndex = SpecialPage::getTitleFor(
409  'Prefixindex', $title->getPrefixedText() . '/' );
410  $pageInfo['header-basic'][] = [
411  $linkRenderer->makeLink(
412  $prefixIndex,
413  $this->msg( 'pageinfo-subpages-name' )->text()
414  ),
415  $this->msg( 'pageinfo-subpages-value' )
416  ->numParams(
417  $pageCounts['subpages']['total'],
418  $pageCounts['subpages']['redirects'],
419  $pageCounts['subpages']['nonredirects'] )
420  ];
421  }
422 
423  if ( $title->inNamespace( NS_CATEGORY ) ) {
424  $category = Category::newFromTitle( $title );
425 
426  // $allCount is the total number of cat members,
427  // not the count of how many members are normal pages.
428  $allCount = (int)$category->getPageCount();
429  $subcatCount = (int)$category->getSubcatCount();
430  $fileCount = (int)$category->getFileCount();
431  $pagesCount = $allCount - $subcatCount - $fileCount;
432 
433  $pageInfo['category-info'] = [
434  [
435  $this->msg( 'pageinfo-category-total' ),
436  $lang->formatNum( $allCount )
437  ],
438  [
439  $this->msg( 'pageinfo-category-pages' ),
440  $lang->formatNum( $pagesCount )
441  ],
442  [
443  $this->msg( 'pageinfo-category-subcats' ),
444  $lang->formatNum( $subcatCount )
445  ],
446  [
447  $this->msg( 'pageinfo-category-files' ),
448  $lang->formatNum( $fileCount )
449  ]
450  ];
451  }
452 
453  // Display image SHA-1 value
454  if ( $title->inNamespace( NS_FILE ) ) {
455  $fileObj = $services->getRepoGroup()->findFile( $title );
456  if ( $fileObj !== false ) {
457  // Convert the base-36 sha1 value obtained from database to base-16
458  $output = Wikimedia\base_convert( $fileObj->getSha1(), 36, 16, 40 );
459  $pageInfo['header-basic'][] = [
460  $this->msg( 'pageinfo-file-hash' ),
461  $output
462  ];
463  }
464  }
465 
466  // Page protection
467  $pageInfo['header-restrictions'] = [];
468 
469  // Is this page affected by the cascading protection of something which includes it?
470  if ( $title->isCascadeProtected() ) {
471  $cascadingFrom = '';
472  $sources = $title->getCascadeProtectionSources()[0];
473 
474  foreach ( $sources as $sourceTitle ) {
475  $cascadingFrom .= Html::rawElement(
476  'li', [], $linkRenderer->makeKnownLink( $sourceTitle ) );
477  }
478 
479  $cascadingFrom = Html::rawElement( 'ul', [], $cascadingFrom );
480  $pageInfo['header-restrictions'][] = [
481  $this->msg( 'pageinfo-protect-cascading-from' ),
482  $cascadingFrom
483  ];
484  }
485 
486  // Is out protection set to cascade to other pages?
487  if ( $title->areRestrictionsCascading() ) {
488  $pageInfo['header-restrictions'][] = [
489  $this->msg( 'pageinfo-protect-cascading' ),
490  $this->msg( 'pageinfo-protect-cascading-yes' )
491  ];
492  }
493 
494  // Page protection
495  foreach ( $title->getRestrictionTypes() as $restrictionType ) {
496  $protectionLevel = implode( ', ', $title->getRestrictions( $restrictionType ) );
497 
498  if ( $protectionLevel == '' ) {
499  // Allow all users
500  $message = $this->msg( 'protect-default' )->escaped();
501  } else {
502  // Administrators only
503  // Messages: protect-level-autoconfirmed, protect-level-sysop
504  $message = $this->msg( "protect-level-$protectionLevel" );
505  if ( $message->isDisabled() ) {
506  // Require "$1" permission
507  $message = $this->msg( "protect-fallback", $protectionLevel )->parse();
508  } else {
509  $message = $message->escaped();
510  }
511  }
512  $expiry = $title->getRestrictionExpiry( $restrictionType );
513  $formattedexpiry = $this->msg( 'parentheses',
514  $lang->formatExpiry( $expiry ) )->escaped();
515  $message .= $this->msg( 'word-separator' )->escaped() . $formattedexpiry;
516 
517  // Messages: restriction-edit, restriction-move, restriction-create,
518  // restriction-upload
519  $pageInfo['header-restrictions'][] = [
520  $this->msg( "restriction-$restrictionType" ), $message
521  ];
522  }
523  $protectLog = SpecialPage::getTitleFor( 'Log' );
524  $pageInfo['header-restrictions'][] = [
525  'below',
526  $linkRenderer->makeKnownLink(
527  $protectLog,
528  $this->msg( 'pageinfo-view-protect-log' )->text(),
529  [],
530  [ 'type' => 'protect', 'page' => $title->getPrefixedText() ]
531  ),
532  ];
533 
534  if ( !$this->page->exists() ) {
535  return $pageInfo;
536  }
537 
538  // Edit history
539  $pageInfo['header-edits'] = [];
540 
541  $firstRev = $this->page->getOldestRevision();
542  $lastRev = $this->page->getRevision();
543  $batch = new LinkBatch;
544 
545  if ( $firstRev ) {
546  $firstRevUser = $firstRev->getUserText( Revision::FOR_THIS_USER );
547  if ( $firstRevUser !== '' ) {
548  $firstRevUserTitle = Title::makeTitle( NS_USER, $firstRevUser );
549  $batch->addObj( $firstRevUserTitle );
550  $batch->addObj( $firstRevUserTitle->getTalkPage() );
551  }
552  }
553 
554  if ( $lastRev ) {
555  $lastRevUser = $lastRev->getUserText( Revision::FOR_THIS_USER );
556  if ( $lastRevUser !== '' ) {
557  $lastRevUserTitle = Title::makeTitle( NS_USER, $lastRevUser );
558  $batch->addObj( $lastRevUserTitle );
559  $batch->addObj( $lastRevUserTitle->getTalkPage() );
560  }
561  }
562 
563  $batch->execute();
564 
565  if ( $firstRev ) {
566  // Page creator
567  $pageInfo['header-edits'][] = [
568  $this->msg( 'pageinfo-firstuser' ),
569  Linker::revUserTools( $firstRev )
570  ];
571 
572  // Date of page creation
573  $pageInfo['header-edits'][] = [
574  $this->msg( 'pageinfo-firsttime' ),
575  $linkRenderer->makeKnownLink(
576  $title,
577  $lang->userTimeAndDate( $firstRev->getTimestamp(), $user ),
578  [],
579  [ 'oldid' => $firstRev->getId() ]
580  )
581  ];
582  }
583 
584  if ( $lastRev ) {
585  // Latest editor
586  $pageInfo['header-edits'][] = [
587  $this->msg( 'pageinfo-lastuser' ),
588  Linker::revUserTools( $lastRev )
589  ];
590 
591  // Date of latest edit
592  $pageInfo['header-edits'][] = [
593  $this->msg( 'pageinfo-lasttime' ),
594  $linkRenderer->makeKnownLink(
595  $title,
596  $lang->userTimeAndDate( $this->page->getTimestamp(), $user ),
597  [],
598  [ 'oldid' => $this->page->getLatest() ]
599  )
600  ];
601  }
602 
603  // Total number of edits
604  $pageInfo['header-edits'][] = [
605  $this->msg( 'pageinfo-edits' ), $lang->formatNum( $pageCounts['edits'] )
606  ];
607 
608  // Total number of distinct authors
609  if ( $pageCounts['authors'] > 0 ) {
610  $pageInfo['header-edits'][] = [
611  $this->msg( 'pageinfo-authors' ), $lang->formatNum( $pageCounts['authors'] )
612  ];
613  }
614 
615  // Recent number of edits (within past 30 days)
616  $pageInfo['header-edits'][] = [
617  $this->msg( 'pageinfo-recent-edits',
618  $lang->formatDuration( $config->get( 'RCMaxAge' ) ) ),
619  $lang->formatNum( $pageCounts['recent_edits'] )
620  ];
621 
622  // Recent number of distinct authors
623  $pageInfo['header-edits'][] = [
624  $this->msg( 'pageinfo-recent-authors' ),
625  $lang->formatNum( $pageCounts['recent_authors'] )
626  ];
627 
628  // Array of MagicWord objects
629  $magicWords = $services->getMagicWordFactory()->getDoubleUnderscoreArray();
630 
631  // Array of magic word IDs
632  $wordIDs = $magicWords->names;
633 
634  // Array of IDs => localized magic words
635  $localizedWords = $services->getContentLanguage()->getMagicWords();
636 
637  $listItems = [];
638  foreach ( $pageProperties as $property => $value ) {
639  if ( in_array( $property, $wordIDs ) ) {
640  $listItems[] = Html::element( 'li', [], $localizedWords[$property][1] );
641  }
642  }
643 
644  $localizedList = Html::rawElement( 'ul', [], implode( '', $listItems ) );
645  $hiddenCategories = $this->page->getHiddenCategories();
646 
647  if (
648  count( $listItems ) > 0 ||
649  count( $hiddenCategories ) > 0 ||
650  $pageCounts['transclusion']['from'] > 0 ||
651  $pageCounts['transclusion']['to'] > 0
652  ) {
653  $options = [ 'LIMIT' => $config->get( 'PageInfoTransclusionLimit' ) ];
654  $transcludedTemplates = $title->getTemplateLinksFrom( $options );
655  if ( $config->get( 'MiserMode' ) ) {
656  $transcludedTargets = [];
657  } else {
658  $transcludedTargets = $title->getTemplateLinksTo( $options );
659  }
660 
661  // Page properties
662  $pageInfo['header-properties'] = [];
663 
664  // Magic words
665  if ( count( $listItems ) > 0 ) {
666  $pageInfo['header-properties'][] = [
667  $this->msg( 'pageinfo-magic-words' )->numParams( count( $listItems ) ),
668  $localizedList
669  ];
670  }
671 
672  // Hidden categories
673  if ( count( $hiddenCategories ) > 0 ) {
674  $pageInfo['header-properties'][] = [
675  $this->msg( 'pageinfo-hidden-categories' )
676  ->numParams( count( $hiddenCategories ) ),
677  Linker::formatHiddenCategories( $hiddenCategories )
678  ];
679  }
680 
681  // Transcluded templates
682  if ( $pageCounts['transclusion']['from'] > 0 ) {
683  if ( $pageCounts['transclusion']['from'] > count( $transcludedTemplates ) ) {
684  $more = $this->msg( 'morenotlisted' )->escaped();
685  } else {
686  $more = null;
687  }
688 
689  $templateListFormatter = new TemplatesOnThisPageFormatter(
690  $this->getContext(),
692  );
693 
694  $pageInfo['header-properties'][] = [
695  $this->msg( 'pageinfo-templates' )
696  ->numParams( $pageCounts['transclusion']['from'] ),
697  $templateListFormatter->format( $transcludedTemplates, false, $more )
698  ];
699  }
700 
701  if ( !$config->get( 'MiserMode' ) && $pageCounts['transclusion']['to'] > 0 ) {
702  if ( $pageCounts['transclusion']['to'] > count( $transcludedTargets ) ) {
703  $more = $linkRenderer->makeLink(
704  $whatLinksHere,
705  $this->msg( 'moredotdotdot' )->text(),
706  [],
707  [ 'hidelinks' => 1, 'hideredirs' => 1 ]
708  );
709  } else {
710  $more = null;
711  }
712 
713  $templateListFormatter = new TemplatesOnThisPageFormatter(
714  $this->getContext(),
716  );
717 
718  $pageInfo['header-properties'][] = [
719  $this->msg( 'pageinfo-transclusions' )
720  ->numParams( $pageCounts['transclusion']['to'] ),
721  $templateListFormatter->format( $transcludedTargets, false, $more )
722  ];
723  }
724  }
725 
726  return $pageInfo;
727  }
728 
735  protected function pageCounts( Page $page ) {
736  $fname = __METHOD__;
737  $config = $this->context->getConfig();
738  $services = MediaWikiServices::getInstance();
739  $cache = $services->getMainWANObjectCache();
740 
741  return $cache->getWithSetCallback(
742  self::getCacheKey( $cache, $page->getTitle(), $page->getLatest() ),
744  function ( $oldValue, &$ttl, &$setOpts ) use ( $page, $config, $fname, $services ) {
746 
747  $title = $page->getTitle();
748  $id = $title->getArticleID();
749 
750  $dbr = wfGetDB( DB_REPLICA );
751  $dbrWatchlist = wfGetDB( DB_REPLICA, 'watchlist' );
752  $setOpts += Database::getCacheSetOptions( $dbr, $dbrWatchlist );
753 
754  if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_READ_NEW ) {
755  $tables = [ 'revision_actor_temp' ];
756  $field = 'revactor_actor';
757  $pageField = 'revactor_page';
758  $tsField = 'revactor_timestamp';
759  $joins = [];
760  } else {
761  $tables = [ 'revision' ];
762  $field = 'rev_user_text';
763  $pageField = 'rev_page';
764  $tsField = 'rev_timestamp';
765  $joins = [];
766  }
767 
768  $watchedItemStore = $services->getWatchedItemStore();
769 
770  $result = [];
771  $result['watchers'] = $watchedItemStore->countWatchers( $title );
772 
773  if ( $config->get( 'ShowUpdatedMarker' ) ) {
774  $updated = wfTimestamp( TS_UNIX, $page->getTimestamp() );
775  $result['visitingWatchers'] = $watchedItemStore->countVisitingWatchers(
776  $title,
777  $updated - $config->get( 'WatchersMaxAge' )
778  );
779  }
780 
781  // Total number of edits
782  $edits = (int)$dbr->selectField(
783  'revision',
784  'COUNT(*)',
785  [ 'rev_page' => $id ],
786  $fname
787  );
788  $result['edits'] = $edits;
789 
790  // Total number of distinct authors
791  if ( $config->get( 'MiserMode' ) ) {
792  $result['authors'] = 0;
793  } else {
794  $result['authors'] = (int)$dbr->selectField(
795  $tables,
796  "COUNT(DISTINCT $field)",
797  [ $pageField => $id ],
798  $fname,
799  [],
800  $joins
801  );
802  }
803 
804  // "Recent" threshold defined by RCMaxAge setting
805  $threshold = $dbr->timestamp( time() - $config->get( 'RCMaxAge' ) );
806 
807  // Recent number of edits
808  $edits = (int)$dbr->selectField(
809  'revision',
810  'COUNT(rev_page)',
811  [
812  'rev_page' => $id,
813  "rev_timestamp >= " . $dbr->addQuotes( $threshold )
814  ],
815  $fname
816  );
817  $result['recent_edits'] = $edits;
818 
819  // Recent number of distinct authors
820  $result['recent_authors'] = (int)$dbr->selectField(
821  $tables,
822  "COUNT(DISTINCT $field)",
823  [
824  $pageField => $id,
825  "$tsField >= " . $dbr->addQuotes( $threshold )
826  ],
827  $fname,
828  [],
829  $joins
830  );
831 
832  // Subpages (if enabled)
833  if ( $services->getNamespaceInfo()->hasSubpages( $title->getNamespace() ) ) {
834  $conds = [ 'page_namespace' => $title->getNamespace() ];
835  $conds[] = 'page_title ' .
836  $dbr->buildLike( $title->getDBkey() . '/', $dbr->anyString() );
837 
838  // Subpages of this page (redirects)
839  $conds['page_is_redirect'] = 1;
840  $result['subpages']['redirects'] = (int)$dbr->selectField(
841  'page',
842  'COUNT(page_id)',
843  $conds,
844  $fname
845  );
846 
847  // Subpages of this page (non-redirects)
848  $conds['page_is_redirect'] = 0;
849  $result['subpages']['nonredirects'] = (int)$dbr->selectField(
850  'page',
851  'COUNT(page_id)',
852  $conds,
853  $fname
854  );
855 
856  // Subpages of this page (total)
857  $result['subpages']['total'] = $result['subpages']['redirects']
858  + $result['subpages']['nonredirects'];
859  }
860 
861  // Counts for the number of transclusion links (to/from)
862  if ( $config->get( 'MiserMode' ) ) {
863  $result['transclusion']['to'] = 0;
864  } else {
865  $result['transclusion']['to'] = (int)$dbr->selectField(
866  'templatelinks',
867  'COUNT(tl_from)',
868  [
869  'tl_namespace' => $title->getNamespace(),
870  'tl_title' => $title->getDBkey()
871  ],
872  $fname
873  );
874  }
875 
876  $result['transclusion']['from'] = (int)$dbr->selectField(
877  'templatelinks',
878  'COUNT(*)',
879  [ 'tl_from' => $title->getArticleID() ],
880  $fname
881  );
882 
883  return $result;
884  }
885  );
886  }
887 
893  protected function getPageTitle() {
894  return $this->msg( 'pageinfo-title', $this->getTitle()->getPrefixedText() )->text();
895  }
896 
901  protected function getContributors() {
902  $contributors = $this->page->getContributors();
903  $real_names = [];
904  $user_names = [];
905  $anon_ips = [];
906  $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
907 
908  # Sift for real versus user names
909 
910  foreach ( $contributors as $user ) {
911  $page = $user->isAnon()
912  ? SpecialPage::getTitleFor( 'Contributions', $user->getName() )
913  : $user->getUserPage();
914 
915  $hiddenPrefs = $this->context->getConfig()->get( 'HiddenPrefs' );
916  if ( $user->getId() == 0 ) {
917  $anon_ips[] = $linkRenderer->makeLink( $page, $user->getName() );
918  } elseif ( !in_array( 'realname', $hiddenPrefs ) && $user->getRealName() ) {
919  $real_names[] = $linkRenderer->makeLink( $page, $user->getRealName() );
920  } else {
921  $user_names[] = $linkRenderer->makeLink( $page, $user->getName() );
922  }
923  }
924 
925  $lang = $this->getLanguage();
926 
927  $real = $lang->listToText( $real_names );
928 
929  # "ThisSite user(s) A, B and C"
930  if ( count( $user_names ) ) {
931  $user = $this->msg( 'siteusers' )
932  ->rawParams( $lang->listToText( $user_names ) )
933  ->params( count( $user_names ) )->escaped();
934  } else {
935  $user = false;
936  }
937 
938  if ( count( $anon_ips ) ) {
939  $anon = $this->msg( 'anonusers' )
940  ->rawParams( $lang->listToText( $anon_ips ) )
941  ->params( count( $anon_ips ) )->escaped();
942  } else {
943  $anon = false;
944  }
945 
946  # This is the big list, all mooshed together. We sift for blank strings
947  $fulllist = [];
948  foreach ( [ $real, $user, $anon ] as $s ) {
949  if ( $s !== '' ) {
950  array_push( $fulllist, $s );
951  }
952  }
953 
954  $count = count( $fulllist );
955 
956  # "Based on work by ..."
957  return $count
958  ? $this->msg( 'othercontribs' )->rawParams(
959  $lang->listToText( $fulllist ) )->params( $count )->escaped()
960  : '';
961  }
962 
968  protected function getDescription() {
969  return '';
970  }
971 
978  protected static function getCacheKey( WANObjectCache $cache, Title $title, $revId ) {
979  return $cache->makeKey( 'infoaction', md5( $title->getPrefixedText() ), $revId, self::VERSION );
980  }
981 }
static getTitleValueFor( $name, $subpage=false, $fragment='')
Get a localised TitleValue object for a specified special page name.
Definition: SpecialPage.php:98
const FOR_THIS_USER
Definition: Revision.php:55
static getCacheKey(WANObjectCache $cache, Title $title, $revId)
Definition: InfoAction.php:978
addTable( $content, $table)
Adds a table to the content that will be added to the output.
Definition: InfoAction.php:200
static element( $element, $attribs=[], $contents='')
Identical to rawElement(), but HTML-escapes $contents (like Xml::element()).
Definition: Html.php:231
const VERSION
Definition: InfoAction.php:34
$property
addRow( $table, $name, $value, $id)
Adds a row to a table that will be added to the content.
Definition: InfoAction.php:183
static newFromTitle( $title)
Factory function.
Definition: Category.php:146
addHelpLink( $to, $overrideBaseUrl=false)
Adds help link with an icon via page indicators.
Definition: Action.php:394
getTitle()
Shortcut to get the Title object from the page.
Definition: Action.php:247
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return an< a > element with HTML attributes $attribs and contents $html will be returned If you return $ret will be returned and may include noclasses after processing after in associative array form before processing starts Return false to skip default processing and return $ret $linkRenderer
Definition: hooks.txt:1963
Handles formatting for the "templates used on this page" lists.
int $wgActorTableSchemaMigrationStage
Actor table schema migration stage.
if(!isset( $args[0])) $lang
pageInfo()
Returns an array of info groups (will be rendered as tables), keyed by group ID.
Definition: InfoAction.php:217
getUser()
Shortcut to get the User being used for this instance.
Definition: Action.php:218
static rawElement( $element, $attribs=[], $contents='')
Returns an HTML element in a string.
Definition: Html.php:209
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
$value
onView()
Shows page information on GET request.
Definition: InfoAction.php:87
const SCHEMA_COMPAT_READ_NEW
Definition: Defines.php:283
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency MediaWikiServices
Definition: injection.txt:23
requiresUnblock()
Whether this action can still be executed by a blocked user.
Definition: InfoAction.php:50
getPrefixedText()
Get the prefixed title with spaces.
Definition: Title.php:1722
getLanguage()
Shortcut to get the user Language being used for this instance.
Definition: Action.php:237
$contributors
target page
static getLocalizedName( $name, Language $lang=null)
Returns the localized name for a given content model.
static newFromTitle(LinkTarget $linkTarget, $id=0, $flags=0)
Load either the current, or a specified, revision that&#39;s attached to a given link target...
Definition: Revision.php:137
This list may contain false positives That usually means there is additional text with links below the first Each row contains links to the first and second as well as the first line of the second redirect text
this hook is for auditing only RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist & $tables
Definition: hooks.txt:960
static formatHiddenCategories( $hiddencats)
Returns HTML for the "hidden categories on this page" list.
Definition: Linker.php:1991
pageCounts(Page $page)
Returns page counts that would be too "expensive" to retrieve by normal means.
Definition: InfoAction.php:735
static configuration should be added through ResourceLoaderGetConfigVars instead can be used to get the real title e g db for database replication lag or jobqueue for job queue size converted to pseudo seconds It is possible to add more fields and they will be returned to the user in the API response after the basic globals have been set but before ordinary actions take place $output
Definition: hooks.txt:2198
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page. Return false to stop further processing of the tag $reader:XMLReader object & $pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUnknownUser':When a user doesn 't exist locally, this hook is called to give extensions an opportunity to auto-create it. If the auto-creation is successful, return false. $name:User name 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports. & $fullInterwikiPrefix:Interwiki prefix, may contain colons. & $pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable. Can be used to lazy-load the import sources list. & $importSources:The value of $wgImportSources. Modify as necessary. See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. & $title:Title object for the current page & $request:WebRequest & $ignoreRedirect:boolean to skip redirect check & $target:Title/string of redirect target & $article:Article object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) & $article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() & $ip:IP being check & $result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links:Array with elements of the form "language:title" in the order that they will be output. & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LanguageSelector':Hook to change the language selector available on a page. $out:The output page. $cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED since 1.28! Use HtmlPageLinkRendererBegin instead. Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) $result
Definition: hooks.txt:1961
$batch
Definition: linkcache.txt:23
Class representing a list of titles The execute() method checks them all for existence and adds them ...
Definition: LinkBatch.php:34
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Interface for type hinting (accepts WikiPage, Article, ImagePage, CategoryPage)
Definition: Page.php:24
static invalidateCache(Title $title, $revid=null)
Clear the info cache for a given Title.
Definition: InfoAction.php:70
static configuration should be added through ResourceLoaderGetConfigVars instead can be used to get the real title e g db for database replication lag or jobqueue for job queue size converted to pseudo seconds It is possible to add more fields and they will be returned to the user in the API response after the basic globals have been set but before ordinary actions take place or wrap services the preferred way to define a new service is the $wgServiceWiringFiles array $services
Definition: hooks.txt:2198
static escapeIdForAttribute( $id, $mode=self::ID_PRIMARY)
Given a section name or other user-generated or otherwise unsafe string, escapes it to be a valid HTM...
Definition: Sanitizer.php:1295
$cache
Definition: mcc.php:33
const NS_CATEGORY
Definition: Defines.php:74
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped & $options
Definition: hooks.txt:1963
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not null
Definition: hooks.txt:767
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:912
getContext()
Get the IContextSource in use here.
Definition: Action.php:179
const NS_FILE
Definition: Defines.php:66
Displays information about a page.
Definition: InfoAction.php:33
static getTitleFor( $name, $subpage=false, $fragment='')
Get a localised Title object for a specified special page name If you don&#39;t need a full Title object...
Definition: SpecialPage.php:83
$header
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
if(defined( 'MW_SETUP_CALLBACK')) $fname
Customization point after all loading (constants, functions, classes, DefaultSettings, LocalSettings).
Definition: Setup.php:131
$page
Page on which we&#39;re performing the action.
Definition: Action.php:46
requiresWrite()
Whether this action requires the wiki not to be locked.
Definition: InfoAction.php:59
static makeTitle( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:590
An action which just does something, without showing a form first.
static fetchLanguageName( $code, $inLanguage=self::AS_AUTONYMS, $include=self::ALL)
Definition: Language.php:937
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
static getInstance()
Definition: PageProps.php:66
getDescription()
Returns the description that goes below the "<h1>" tag.
Definition: InfoAction.php:968
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:271
makeHeader( $header, $canonicalId)
Creates a header that can be added to the output.
Definition: InfoAction.php:167
getName()
Returns the name of the action this object responds to.
Definition: InfoAction.php:41
getPageTitle()
Returns the name that goes in the "<h1>" page title.
Definition: InfoAction.php:893
const DB_REPLICA
Definition: defines.php:25
getContributors()
Get a list of contributors of $article.
Definition: InfoAction.php:901
static newFromName( $name, $validate='valid')
Static factory method for creation from username.
Definition: User.php:535
msg( $key)
Get a Message object with context set Parameters are the same as wfMessage()
Definition: Action.php:257
$content
Definition: pageupdater.txt:72
makeKey( $class, $component=null)
return true to allow those checks to and false if checking is done & $user
Definition: hooks.txt:1454
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:200
magicword txt Magic Words are some phrases used in the wikitext They are used for two that looks like templates but that don t accept any parameter *Parser functions(like {{fullurl:...}}, {{#special:...}}) $magicWords['en']
Definition: magicword.txt:33
static revUserTools( $rev, $isPublic=false, $useParentheses=true)
Generate a user tool link cluster if the current user is allowed to view it.
Definition: Linker.php:1118