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