MediaWiki  master
ApiQueryInfo.php
Go to the documentation of this file.
1 <?php
25 
31 class ApiQueryInfo extends ApiQueryBase {
32 
33  private $fld_protection = false, $fld_talkid = false,
34  $fld_subjectid = false, $fld_url = false,
35  $fld_readable = false, $fld_watched = false,
39 
40  private $params;
41 
43  private $titles;
45  private $missing;
47  private $everything;
48 
51 
54  private $showZeroWatchers = false;
55 
56  private $tokenFunctions;
57 
58  private $countTestedActions = 0;
59 
60  public function __construct( ApiQuery $query, $moduleName ) {
61  parent::__construct( $query, $moduleName, 'in' );
62  }
63 
68  public function requestExtraData( $pageSet ) {
69  $pageSet->requestField( 'page_restrictions' );
70  // If the pageset is resolving redirects we won't get page_is_redirect.
71  // But we can't know for sure until the pageset is executed (revids may
72  // turn it off), so request it unconditionally.
73  $pageSet->requestField( 'page_is_redirect' );
74  $pageSet->requestField( 'page_is_new' );
75  $config = $this->getConfig();
76  $pageSet->requestField( 'page_touched' );
77  $pageSet->requestField( 'page_latest' );
78  $pageSet->requestField( 'page_len' );
79  $pageSet->requestField( 'page_content_model' );
80  if ( $config->get( 'PageLanguageUseDB' ) ) {
81  $pageSet->requestField( 'page_lang' );
82  }
83  }
84 
92  protected function getTokenFunctions() {
93  // Don't call the hooks twice
94  if ( isset( $this->tokenFunctions ) ) {
95  return $this->tokenFunctions;
96  }
97 
98  // If we're in a mode that breaks the same-origin policy, no tokens can
99  // be obtained
100  if ( $this->lacksSameOriginSecurity() ) {
101  return [];
102  }
103 
104  $this->tokenFunctions = [
105  'edit' => [ self::class, 'getEditToken' ],
106  'delete' => [ self::class, 'getDeleteToken' ],
107  'protect' => [ self::class, 'getProtectToken' ],
108  'move' => [ self::class, 'getMoveToken' ],
109  'block' => [ self::class, 'getBlockToken' ],
110  'unblock' => [ self::class, 'getUnblockToken' ],
111  'email' => [ self::class, 'getEmailToken' ],
112  'import' => [ self::class, 'getImportToken' ],
113  'watch' => [ self::class, 'getWatchToken' ],
114  ];
115  Hooks::run( 'APIQueryInfoTokens', [ &$this->tokenFunctions ], '1.24' );
116 
117  return $this->tokenFunctions;
118  }
119 
121  protected static $cachedTokens = [];
122 
126  public static function resetTokenCache() {
127  self::$cachedTokens = [];
128  }
129 
133  public static function getEditToken( $pageid, $title ) {
134  // We could check for $title->userCan('edit') here,
135  // but that's too expensive for this purpose
136  // and would break caching
137  global $wgUser;
138  if ( !MediaWikiServices::getInstance()->getPermissionManager()
139  ->userHasRight( $wgUser, 'edit' ) ) {
140  return false;
141  }
142 
143  // The token is always the same, let's exploit that
144  if ( !isset( self::$cachedTokens['edit'] ) ) {
145  self::$cachedTokens['edit'] = $wgUser->getEditToken();
146  }
147 
148  return self::$cachedTokens['edit'];
149  }
150 
154  public static function getDeleteToken( $pageid, $title ) {
155  global $wgUser;
156  if ( !MediaWikiServices::getInstance()->getPermissionManager()
157  ->userHasRight( $wgUser, 'delete' ) ) {
158  return false;
159  }
160 
161  // The token is always the same, let's exploit that
162  if ( !isset( self::$cachedTokens['delete'] ) ) {
163  self::$cachedTokens['delete'] = $wgUser->getEditToken();
164  }
165 
166  return self::$cachedTokens['delete'];
167  }
168 
172  public static function getProtectToken( $pageid, $title ) {
173  global $wgUser;
174  if ( !MediaWikiServices::getInstance()->getPermissionManager()
175  ->userHasRight( $wgUser, 'protect' ) ) {
176  return false;
177  }
178 
179  // The token is always the same, let's exploit that
180  if ( !isset( self::$cachedTokens['protect'] ) ) {
181  self::$cachedTokens['protect'] = $wgUser->getEditToken();
182  }
183 
184  return self::$cachedTokens['protect'];
185  }
186 
190  public static function getMoveToken( $pageid, $title ) {
191  global $wgUser;
192  if ( !MediaWikiServices::getInstance()->getPermissionManager()
193  ->userHasRight( $wgUser, 'move' ) ) {
194  return false;
195  }
196 
197  // The token is always the same, let's exploit that
198  if ( !isset( self::$cachedTokens['move'] ) ) {
199  self::$cachedTokens['move'] = $wgUser->getEditToken();
200  }
201 
202  return self::$cachedTokens['move'];
203  }
204 
208  public static function getBlockToken( $pageid, $title ) {
209  global $wgUser;
210  if ( !MediaWikiServices::getInstance()->getPermissionManager()
211  ->userHasRight( $wgUser, 'block' ) ) {
212  return false;
213  }
214 
215  // The token is always the same, let's exploit that
216  if ( !isset( self::$cachedTokens['block'] ) ) {
217  self::$cachedTokens['block'] = $wgUser->getEditToken();
218  }
219 
220  return self::$cachedTokens['block'];
221  }
222 
226  public static function getUnblockToken( $pageid, $title ) {
227  // Currently, this is exactly the same as the block token
228  return self::getBlockToken( $pageid, $title );
229  }
230 
234  public static function getEmailToken( $pageid, $title ) {
235  global $wgUser;
236  if ( !$wgUser->canSendEmail() || $wgUser->isBlockedFromEmailuser() ) {
237  return false;
238  }
239 
240  // The token is always the same, let's exploit that
241  if ( !isset( self::$cachedTokens['email'] ) ) {
242  self::$cachedTokens['email'] = $wgUser->getEditToken();
243  }
244 
245  return self::$cachedTokens['email'];
246  }
247 
251  public static function getImportToken( $pageid, $title ) {
252  global $wgUser;
253  if ( !MediaWikiServices::getInstance()
255  ->userHasAnyRight( $wgUser, 'import', 'importupload' ) ) {
256  return false;
257  }
258 
259  // The token is always the same, let's exploit that
260  if ( !isset( self::$cachedTokens['import'] ) ) {
261  self::$cachedTokens['import'] = $wgUser->getEditToken();
262  }
263 
264  return self::$cachedTokens['import'];
265  }
266 
270  public static function getWatchToken( $pageid, $title ) {
271  global $wgUser;
272  if ( !$wgUser->isLoggedIn() ) {
273  return false;
274  }
275 
276  // The token is always the same, let's exploit that
277  if ( !isset( self::$cachedTokens['watch'] ) ) {
278  self::$cachedTokens['watch'] = $wgUser->getEditToken( 'watch' );
279  }
280 
281  return self::$cachedTokens['watch'];
282  }
283 
287  public static function getOptionsToken( $pageid, $title ) {
288  global $wgUser;
289  if ( !$wgUser->isLoggedIn() ) {
290  return false;
291  }
292 
293  // The token is always the same, let's exploit that
294  if ( !isset( self::$cachedTokens['options'] ) ) {
295  self::$cachedTokens['options'] = $wgUser->getEditToken();
296  }
297 
298  return self::$cachedTokens['options'];
299  }
300 
301  public function execute() {
302  $this->params = $this->extractRequestParams();
303  if ( $this->params['prop'] !== null ) {
304  $prop = array_flip( $this->params['prop'] );
305  $this->fld_protection = isset( $prop['protection'] );
306  $this->fld_watched = isset( $prop['watched'] );
307  $this->fld_watchers = isset( $prop['watchers'] );
308  $this->fld_visitingwatchers = isset( $prop['visitingwatchers'] );
309  $this->fld_notificationtimestamp = isset( $prop['notificationtimestamp'] );
310  $this->fld_talkid = isset( $prop['talkid'] );
311  $this->fld_subjectid = isset( $prop['subjectid'] );
312  $this->fld_url = isset( $prop['url'] );
313  $this->fld_readable = isset( $prop['readable'] );
314  $this->fld_preload = isset( $prop['preload'] );
315  $this->fld_displaytitle = isset( $prop['displaytitle'] );
316  $this->fld_varianttitles = isset( $prop['varianttitles'] );
317  }
318 
319  $pageSet = $this->getPageSet();
320  $this->titles = $pageSet->getGoodTitles();
321  $this->missing = $pageSet->getMissingTitles();
322  $this->everything = $this->titles + $this->missing;
323  $result = $this->getResult();
324 
325  uasort( $this->everything, [ Title::class, 'compare' ] );
326  if ( $this->params['continue'] !== null ) {
327  // Throw away any titles we're gonna skip so they don't
328  // clutter queries
329  $cont = explode( '|', $this->params['continue'] );
330  $this->dieContinueUsageIf( count( $cont ) != 2 );
331  $conttitle = Title::makeTitleSafe( $cont[0], $cont[1] );
332  foreach ( $this->everything as $pageid => $title ) {
333  if ( Title::compare( $title, $conttitle ) >= 0 ) {
334  break;
335  }
336  unset( $this->titles[$pageid] );
337  unset( $this->missing[$pageid] );
338  unset( $this->everything[$pageid] );
339  }
340  }
341 
342  $this->pageRestrictions = $pageSet->getCustomField( 'page_restrictions' );
343  // when resolving redirects, no page will have this field
344  $this->pageIsRedir = !$pageSet->isResolvingRedirects()
345  ? $pageSet->getCustomField( 'page_is_redirect' )
346  : [];
347  $this->pageIsNew = $pageSet->getCustomField( 'page_is_new' );
348 
349  $this->pageTouched = $pageSet->getCustomField( 'page_touched' );
350  $this->pageLatest = $pageSet->getCustomField( 'page_latest' );
351  $this->pageLength = $pageSet->getCustomField( 'page_len' );
352 
353  // Get protection info if requested
354  if ( $this->fld_protection ) {
355  $this->getProtectionInfo();
356  }
357 
358  if ( $this->fld_watched || $this->fld_notificationtimestamp ) {
359  $this->getWatchedInfo();
360  }
361 
362  if ( $this->fld_watchers ) {
363  $this->getWatcherInfo();
364  }
365 
366  if ( $this->fld_visitingwatchers ) {
367  $this->getVisitingWatcherInfo();
368  }
369 
370  // Run the talkid/subjectid query if requested
371  if ( $this->fld_talkid || $this->fld_subjectid ) {
372  $this->getTSIDs();
373  }
374 
375  if ( $this->fld_displaytitle ) {
376  $this->getDisplayTitle();
377  }
378 
379  if ( $this->fld_varianttitles ) {
380  $this->getVariantTitles();
381  }
382 
384  foreach ( $this->everything as $pageid => $title ) {
385  $pageInfo = $this->extractPageInfo( $pageid, $title );
386  $fit = $pageInfo !== null && $result->addValue( [
387  'query',
388  'pages'
389  ], $pageid, $pageInfo );
390  if ( !$fit ) {
391  $this->setContinueEnumParameter( 'continue',
392  $title->getNamespace() . '|' .
393  $title->getText() );
394  break;
395  }
396  }
397  }
398 
405  private function extractPageInfo( $pageid, $title ) {
406  $pageInfo = [];
407  // $title->exists() needs pageid, which is not set for all title objects
408  $titleExists = $pageid > 0;
409  $ns = $title->getNamespace();
410  $dbkey = $title->getDBkey();
411 
412  $pageInfo['contentmodel'] = $title->getContentModel();
413 
414  $pageLanguage = $title->getPageLanguage();
415  $pageInfo['pagelanguage'] = $pageLanguage->getCode();
416  $pageInfo['pagelanguagehtmlcode'] = $pageLanguage->getHtmlCode();
417  $pageInfo['pagelanguagedir'] = $pageLanguage->getDir();
418 
419  $user = $this->getUser();
420 
421  if ( $titleExists ) {
422  $pageInfo['touched'] = wfTimestamp( TS_ISO_8601, $this->pageTouched[$pageid] );
423  $pageInfo['lastrevid'] = (int)$this->pageLatest[$pageid];
424  $pageInfo['length'] = (int)$this->pageLength[$pageid];
425 
426  if ( isset( $this->pageIsRedir[$pageid] ) && $this->pageIsRedir[$pageid] ) {
427  $pageInfo['redirect'] = true;
428  }
429  if ( $this->pageIsNew[$pageid] ) {
430  $pageInfo['new'] = true;
431  }
432  }
433 
434  if ( $this->params['token'] !== null ) {
436  $pageInfo['starttimestamp'] = wfTimestamp( TS_ISO_8601, time() );
437  foreach ( $this->params['token'] as $t ) {
438  $val = call_user_func( $tokenFunctions[$t], $pageid, $title );
439  if ( $val === false ) {
440  $this->addWarning( [ 'apiwarn-tokennotallowed', $t ] );
441  } else {
442  $pageInfo[$t . 'token'] = $val;
443  }
444  }
445  }
446 
447  if ( $this->fld_protection ) {
448  $pageInfo['protection'] = [];
449  if ( isset( $this->protections[$ns][$dbkey] ) ) {
450  $pageInfo['protection'] =
451  $this->protections[$ns][$dbkey];
452  }
453  ApiResult::setIndexedTagName( $pageInfo['protection'], 'pr' );
454 
455  $pageInfo['restrictiontypes'] = [];
456  if ( isset( $this->restrictionTypes[$ns][$dbkey] ) ) {
457  $pageInfo['restrictiontypes'] =
458  $this->restrictionTypes[$ns][$dbkey];
459  }
460  ApiResult::setIndexedTagName( $pageInfo['restrictiontypes'], 'rt' );
461  }
462 
463  if ( $this->fld_watched && $this->watched !== null ) {
464  $pageInfo['watched'] = $this->watched[$ns][$dbkey];
465  }
466 
467  if ( $this->fld_watchers ) {
468  if ( $this->watchers !== null && $this->watchers[$ns][$dbkey] !== 0 ) {
469  $pageInfo['watchers'] = $this->watchers[$ns][$dbkey];
470  } elseif ( $this->showZeroWatchers ) {
471  $pageInfo['watchers'] = 0;
472  }
473  }
474 
475  if ( $this->fld_visitingwatchers ) {
476  if ( $this->visitingwatchers !== null && $this->visitingwatchers[$ns][$dbkey] !== 0 ) {
477  $pageInfo['visitingwatchers'] = $this->visitingwatchers[$ns][$dbkey];
478  } elseif ( $this->showZeroWatchers ) {
479  $pageInfo['visitingwatchers'] = 0;
480  }
481  }
482 
483  if ( $this->fld_notificationtimestamp ) {
484  $pageInfo['notificationtimestamp'] = '';
485  if ( $this->notificationtimestamps[$ns][$dbkey] ) {
486  $pageInfo['notificationtimestamp'] =
487  wfTimestamp( TS_ISO_8601, $this->notificationtimestamps[$ns][$dbkey] );
488  }
489  }
490 
491  if ( $this->fld_talkid && isset( $this->talkids[$ns][$dbkey] ) ) {
492  $pageInfo['talkid'] = $this->talkids[$ns][$dbkey];
493  }
494 
495  if ( $this->fld_subjectid && isset( $this->subjectids[$ns][$dbkey] ) ) {
496  $pageInfo['subjectid'] = $this->subjectids[$ns][$dbkey];
497  }
498 
499  if ( $this->fld_url ) {
500  $pageInfo['fullurl'] = wfExpandUrl( $title->getFullURL(), PROTO_CURRENT );
501  $pageInfo['editurl'] = wfExpandUrl( $title->getFullURL( 'action=edit' ), PROTO_CURRENT );
502  $pageInfo['canonicalurl'] = wfExpandUrl( $title->getFullURL(), PROTO_CANONICAL );
503  }
504  if ( $this->fld_readable ) {
505  $pageInfo['readable'] = $this->getPermissionManager()->userCan(
506  'read', $user, $title
507  );
508  }
509 
510  if ( $this->fld_preload ) {
511  if ( $titleExists ) {
512  $pageInfo['preload'] = '';
513  } else {
514  $text = null;
515  Hooks::run( 'EditFormPreloadText', [ &$text, &$title ] );
516 
517  $pageInfo['preload'] = $text;
518  }
519  }
520 
521  if ( $this->fld_displaytitle ) {
522  if ( isset( $this->displaytitles[$pageid] ) ) {
523  $pageInfo['displaytitle'] = $this->displaytitles[$pageid];
524  } else {
525  $pageInfo['displaytitle'] = $title->getPrefixedText();
526  }
527  }
528 
529  if ( $this->fld_varianttitles && isset( $this->variantTitles[$pageid] ) ) {
530  $pageInfo['varianttitles'] = $this->variantTitles[$pageid];
531  }
532 
533  if ( $this->params['testactions'] ) {
534  $limit = $this->getMain()->canApiHighLimits() ? self::LIMIT_SML2 : self::LIMIT_SML1;
535  if ( $this->countTestedActions >= $limit ) {
536  return null; // force a continuation
537  }
538 
539  $detailLevel = $this->params['testactionsdetail'];
540  $rigor = $detailLevel === 'quick'
541  ? PermissionManager::RIGOR_QUICK
542  // Not using RIGOR_SECURE here, because that results in master connection
543  : PermissionManager::RIGOR_FULL;
544  $errorFormatter = $this->getErrorFormatter();
545  if ( $errorFormatter->getFormat() === 'bc' ) {
546  // Eew, no. Use a more modern format here.
547  $errorFormatter = $errorFormatter->newWithFormat( 'plaintext' );
548  }
549 
550  $user = $this->getUser();
551  $pageInfo['actions'] = [];
552  foreach ( $this->params['testactions'] as $action ) {
553  $this->countTestedActions++;
554 
555  if ( $detailLevel === 'boolean' ) {
556  $pageInfo['actions'][$action] = $this->getPermissionManager()->userCan(
557  $action, $user, $title
558  );
559  } else {
560  $pageInfo['actions'][$action] = $errorFormatter->arrayFromStatus( $this->errorArrayToStatus(
561  $this->getPermissionManager()->getPermissionErrors(
562  $action, $user, $title, $rigor
563  ),
564  $user
565  ) );
566  }
567  }
568  }
569 
570  return $pageInfo;
571  }
572 
576  private function getProtectionInfo() {
577  $this->protections = [];
578  $db = $this->getDB();
579 
580  // Get normal protections for existing titles
581  if ( count( $this->titles ) ) {
582  $this->resetQueryParams();
583  $this->addTables( 'page_restrictions' );
584  $this->addFields( [ 'pr_page', 'pr_type', 'pr_level',
585  'pr_expiry', 'pr_cascade' ] );
586  $this->addWhereFld( 'pr_page', array_keys( $this->titles ) );
587 
588  $res = $this->select( __METHOD__ );
589  foreach ( $res as $row ) {
591  $title = $this->titles[$row->pr_page];
592  $a = [
593  'type' => $row->pr_type,
594  'level' => $row->pr_level,
595  'expiry' => ApiResult::formatExpiry( $row->pr_expiry )
596  ];
597  if ( $row->pr_cascade ) {
598  $a['cascade'] = true;
599  }
600  $this->protections[$title->getNamespace()][$title->getDBkey()][] = $a;
601  }
602  // Also check old restrictions
603  foreach ( $this->titles as $pageId => $title ) {
604  if ( $this->pageRestrictions[$pageId] ) {
605  $namespace = $title->getNamespace();
606  $dbKey = $title->getDBkey();
607  $restrictions = explode( ':', trim( $this->pageRestrictions[$pageId] ) );
608  foreach ( $restrictions as $restrict ) {
609  $temp = explode( '=', trim( $restrict ) );
610  if ( count( $temp ) == 1 ) {
611  // old old format should be treated as edit/move restriction
612  $restriction = trim( $temp[0] );
613 
614  if ( $restriction == '' ) {
615  continue;
616  }
617  $this->protections[$namespace][$dbKey][] = [
618  'type' => 'edit',
619  'level' => $restriction,
620  'expiry' => 'infinity',
621  ];
622  $this->protections[$namespace][$dbKey][] = [
623  'type' => 'move',
624  'level' => $restriction,
625  'expiry' => 'infinity',
626  ];
627  } else {
628  $restriction = trim( $temp[1] );
629  if ( $restriction == '' ) {
630  continue;
631  }
632  $this->protections[$namespace][$dbKey][] = [
633  'type' => $temp[0],
634  'level' => $restriction,
635  'expiry' => 'infinity',
636  ];
637  }
638  }
639  }
640  }
641  }
642 
643  // Get protections for missing titles
644  if ( count( $this->missing ) ) {
645  $this->resetQueryParams();
646  $lb = new LinkBatch( $this->missing );
647  $this->addTables( 'protected_titles' );
648  $this->addFields( [ 'pt_title', 'pt_namespace', 'pt_create_perm', 'pt_expiry' ] );
649  $this->addWhere( $lb->constructSet( 'pt', $db ) );
650  $res = $this->select( __METHOD__ );
651  foreach ( $res as $row ) {
652  $this->protections[$row->pt_namespace][$row->pt_title][] = [
653  'type' => 'create',
654  'level' => $row->pt_create_perm,
655  'expiry' => ApiResult::formatExpiry( $row->pt_expiry )
656  ];
657  }
658  }
659 
660  // Separate good and missing titles into files and other pages
661  // and populate $this->restrictionTypes
662  $images = $others = [];
663  foreach ( $this->everything as $title ) {
664  if ( $title->getNamespace() == NS_FILE ) {
665  $images[] = $title->getDBkey();
666  } else {
667  $others[] = $title;
668  }
669  // Applicable protection types
670  $this->restrictionTypes[$title->getNamespace()][$title->getDBkey()] =
671  array_values( $title->getRestrictionTypes() );
672  }
673 
674  if ( count( $others ) ) {
675  // Non-images: check templatelinks
676  $lb = new LinkBatch( $others );
677  $this->resetQueryParams();
678  $this->addTables( [ 'page_restrictions', 'page', 'templatelinks' ] );
679  $this->addFields( [ 'pr_type', 'pr_level', 'pr_expiry',
680  'page_title', 'page_namespace',
681  'tl_title', 'tl_namespace' ] );
682  $this->addWhere( $lb->constructSet( 'tl', $db ) );
683  $this->addWhere( 'pr_page = page_id' );
684  $this->addWhere( 'pr_page = tl_from' );
685  $this->addWhereFld( 'pr_cascade', 1 );
686 
687  $res = $this->select( __METHOD__ );
688  foreach ( $res as $row ) {
689  $source = Title::makeTitle( $row->page_namespace, $row->page_title );
690  $this->protections[$row->tl_namespace][$row->tl_title][] = [
691  'type' => $row->pr_type,
692  'level' => $row->pr_level,
693  'expiry' => ApiResult::formatExpiry( $row->pr_expiry ),
694  'source' => $source->getPrefixedText()
695  ];
696  }
697  }
698 
699  if ( count( $images ) ) {
700  // Images: check imagelinks
701  $this->resetQueryParams();
702  $this->addTables( [ 'page_restrictions', 'page', 'imagelinks' ] );
703  $this->addFields( [ 'pr_type', 'pr_level', 'pr_expiry',
704  'page_title', 'page_namespace', 'il_to' ] );
705  $this->addWhere( 'pr_page = page_id' );
706  $this->addWhere( 'pr_page = il_from' );
707  $this->addWhereFld( 'pr_cascade', 1 );
708  $this->addWhereFld( 'il_to', $images );
709 
710  $res = $this->select( __METHOD__ );
711  foreach ( $res as $row ) {
712  $source = Title::makeTitle( $row->page_namespace, $row->page_title );
713  $this->protections[NS_FILE][$row->il_to][] = [
714  'type' => $row->pr_type,
715  'level' => $row->pr_level,
716  'expiry' => ApiResult::formatExpiry( $row->pr_expiry ),
717  'source' => $source->getPrefixedText()
718  ];
719  }
720  }
721  }
722 
727  private function getTSIDs() {
728  $getTitles = $this->talkids = $this->subjectids = [];
729  $nsInfo = MediaWikiServices::getInstance()->getNamespaceInfo();
730 
732  foreach ( $this->everything as $t ) {
733  if ( $nsInfo->isTalk( $t->getNamespace() ) ) {
734  if ( $this->fld_subjectid ) {
735  $getTitles[] = $t->getSubjectPage();
736  }
737  } elseif ( $this->fld_talkid ) {
738  $getTitles[] = $t->getTalkPage();
739  }
740  }
741  if ( $getTitles === [] ) {
742  return;
743  }
744 
745  $db = $this->getDB();
746 
747  // Construct a custom WHERE clause that matches
748  // all titles in $getTitles
749  $lb = new LinkBatch( $getTitles );
750  $this->resetQueryParams();
751  $this->addTables( 'page' );
752  $this->addFields( [ 'page_title', 'page_namespace', 'page_id' ] );
753  $this->addWhere( $lb->constructSet( 'page', $db ) );
754  $res = $this->select( __METHOD__ );
755  foreach ( $res as $row ) {
756  if ( $nsInfo->isTalk( $row->page_namespace ) ) {
757  $this->talkids[$nsInfo->getSubject( $row->page_namespace )][$row->page_title] =
758  (int)( $row->page_id );
759  } else {
760  $this->subjectids[$nsInfo->getTalk( $row->page_namespace )][$row->page_title] =
761  (int)( $row->page_id );
762  }
763  }
764  }
765 
766  private function getDisplayTitle() {
767  $this->displaytitles = [];
768 
769  $pageIds = array_keys( $this->titles );
770 
771  if ( $pageIds === [] ) {
772  return;
773  }
774 
775  $this->resetQueryParams();
776  $this->addTables( 'page_props' );
777  $this->addFields( [ 'pp_page', 'pp_value' ] );
778  $this->addWhereFld( 'pp_page', $pageIds );
779  $this->addWhereFld( 'pp_propname', 'displaytitle' );
780  $res = $this->select( __METHOD__ );
781 
782  foreach ( $res as $row ) {
783  $this->displaytitles[$row->pp_page] = $row->pp_value;
784  }
785  }
786 
787  private function getVariantTitles() {
788  if ( $this->titles === [] ) {
789  return;
790  }
791  $this->variantTitles = [];
792  foreach ( $this->titles as $pageId => $t ) {
793  $this->variantTitles[$pageId] = isset( $this->displaytitles[$pageId] )
794  ? $this->getAllVariants( $this->displaytitles[$pageId] )
795  : $this->getAllVariants( $t->getText(), $t->getNamespace() );
796  }
797  }
798 
799  private function getAllVariants( $text, $ns = NS_MAIN ) {
800  $result = [];
801  $contLang = MediaWikiServices::getInstance()->getContentLanguage();
802  foreach ( $contLang->getVariants() as $variant ) {
803  $convertTitle = $contLang->autoConvert( $text, $variant );
804  if ( $ns !== NS_MAIN ) {
805  $convertNs = $contLang->convertNamespace( $ns, $variant );
806  $convertTitle = $convertNs . ':' . $convertTitle;
807  }
808  $result[$variant] = $convertTitle;
809  }
810  return $result;
811  }
812 
817  private function getWatchedInfo() {
818  $user = $this->getUser();
819 
820  if ( $user->isAnon() || count( $this->everything ) == 0
821  || !$this->getPermissionManager()->userHasRight( $user, 'viewmywatchlist' )
822  ) {
823  return;
824  }
825 
826  $this->watched = [];
827  $this->notificationtimestamps = [];
828 
829  $store = MediaWikiServices::getInstance()->getWatchedItemStore();
830  $timestamps = $store->getNotificationTimestampsBatch( $user, $this->everything );
831 
832  if ( $this->fld_watched ) {
833  foreach ( $timestamps as $namespaceId => $dbKeys ) {
834  $this->watched[$namespaceId] = array_map(
835  function ( $x ) {
836  return $x !== false;
837  },
838  $dbKeys
839  );
840  }
841  }
842  if ( $this->fld_notificationtimestamp ) {
843  $this->notificationtimestamps = $timestamps;
844  }
845  }
846 
850  private function getWatcherInfo() {
851  if ( count( $this->everything ) == 0 ) {
852  return;
853  }
854 
855  $user = $this->getUser();
856  $canUnwatchedpages = $this->getPermissionManager()->userHasRight( $user, 'unwatchedpages' );
857  $unwatchedPageThreshold = $this->getConfig()->get( 'UnwatchedPageThreshold' );
858  if ( !$canUnwatchedpages && !is_int( $unwatchedPageThreshold ) ) {
859  return;
860  }
861 
862  $this->showZeroWatchers = $canUnwatchedpages;
863 
864  $countOptions = [];
865  if ( !$canUnwatchedpages ) {
866  $countOptions['minimumWatchers'] = $unwatchedPageThreshold;
867  }
868 
869  $this->watchers = MediaWikiServices::getInstance()->getWatchedItemStore()->countWatchersMultiple(
870  $this->everything,
871  $countOptions
872  );
873  }
874 
881  private function getVisitingWatcherInfo() {
882  $config = $this->getConfig();
883  $user = $this->getUser();
884  $db = $this->getDB();
885 
886  $canUnwatchedpages = $this->getPermissionManager()->userHasRight( $user, 'unwatchedpages' );
887  $unwatchedPageThreshold = $this->getConfig()->get( 'UnwatchedPageThreshold' );
888  if ( !$canUnwatchedpages && !is_int( $unwatchedPageThreshold ) ) {
889  return;
890  }
891 
892  $this->showZeroWatchers = $canUnwatchedpages;
893 
894  $titlesWithThresholds = [];
895  if ( $this->titles ) {
896  $lb = new LinkBatch( $this->titles );
897 
898  // Fetch last edit timestamps for pages
899  $this->resetQueryParams();
900  $this->addTables( [ 'page', 'revision' ] );
901  $this->addFields( [ 'page_namespace', 'page_title', 'rev_timestamp' ] );
902  $this->addWhere( [
903  'page_latest = rev_id',
904  $lb->constructSet( 'page', $db ),
905  ] );
906  $this->addOption( 'GROUP BY', [ 'page_namespace', 'page_title' ] );
907  $timestampRes = $this->select( __METHOD__ );
908 
909  $age = $config->get( 'WatchersMaxAge' );
910  $timestamps = [];
911  foreach ( $timestampRes as $row ) {
912  $revTimestamp = wfTimestamp( TS_UNIX, (int)$row->rev_timestamp );
913  $timestamps[$row->page_namespace][$row->page_title] = (int)$revTimestamp - $age;
914  }
915  $titlesWithThresholds = array_map(
916  function ( LinkTarget $target ) use ( $timestamps ) {
917  return [
918  $target, $timestamps[$target->getNamespace()][$target->getDBkey()]
919  ];
920  },
922  );
923  }
924 
925  if ( $this->missing ) {
926  $titlesWithThresholds = array_merge(
927  $titlesWithThresholds,
928  array_map(
929  function ( LinkTarget $target ) {
930  return [ $target, null ];
931  },
933  )
934  );
935  }
936  $store = MediaWikiServices::getInstance()->getWatchedItemStore();
937  $this->visitingwatchers = $store->countVisitingWatchersMultiple(
938  $titlesWithThresholds,
939  !$canUnwatchedpages ? $unwatchedPageThreshold : null
940  );
941  }
942 
943  public function getCacheMode( $params ) {
944  // Other props depend on something about the current user
945  $publicProps = [
946  'protection',
947  'talkid',
948  'subjectid',
949  'url',
950  'preload',
951  'displaytitle',
952  'varianttitles',
953  ];
954  if ( array_diff( (array)$params['prop'], $publicProps ) ) {
955  return 'private';
956  }
957 
958  // testactions also depends on the current user
959  if ( $params['testactions'] ) {
960  return 'private';
961  }
962 
963  if ( $params['token'] !== null ) {
964  return 'private';
965  }
966 
967  return 'public';
968  }
969 
970  public function getAllowedParams() {
971  return [
972  'prop' => [
973  ApiBase::PARAM_ISMULTI => true,
975  'protection',
976  'talkid',
977  'watched', # private
978  'watchers', # private
979  'visitingwatchers', # private
980  'notificationtimestamp', # private
981  'subjectid',
982  'url',
983  'readable', # private
984  'preload',
985  'displaytitle',
986  'varianttitles',
987  // If you add more properties here, please consider whether they
988  // need to be added to getCacheMode()
989  ],
992  'readable' => true, // Since 1.32
993  ],
994  ],
995  'testactions' => [
996  ApiBase::PARAM_TYPE => 'string',
997  ApiBase::PARAM_ISMULTI => true,
998  ],
999  'testactionsdetail' => [
1000  ApiBase::PARAM_TYPE => [ 'boolean', 'full', 'quick' ],
1001  ApiBase::PARAM_DFLT => 'boolean',
1003  ],
1004  'token' => [
1005  ApiBase::PARAM_DEPRECATED => true,
1006  ApiBase::PARAM_ISMULTI => true,
1007  ApiBase::PARAM_TYPE => array_keys( $this->getTokenFunctions() )
1008  ],
1009  'continue' => [
1010  ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
1011  ],
1012  ];
1013  }
1014 
1015  protected function getExamplesMessages() {
1016  return [
1017  'action=query&prop=info&titles=Main%20Page'
1018  => 'apihelp-query+info-example-simple',
1019  'action=query&prop=info&inprop=protection&titles=Main%20Page'
1020  => 'apihelp-query+info-example-protection',
1021  ];
1022  }
1023 
1024  public function getHelpUrls() {
1025  return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Info';
1026  }
1027 }
ApiQueryInfo\$talkids
$talkids
Definition: ApiQueryInfo.php:53
ApiQueryInfo\extractPageInfo
extractPageInfo( $pageid, $title)
Get a result array with information about a title.
Definition: ApiQueryInfo.php:405
ContextSource\getConfig
getConfig()
Definition: ContextSource.php:63
ApiQueryInfo\$everything
Title[] $everything
Definition: ApiQueryInfo.php:47
ApiQueryBase\addFields
addFields( $value)
Add a set of fields to select to the internal array.
Definition: ApiQueryBase.php:208
ApiQuery
This is the main query class.
Definition: ApiQuery.php:37
PROTO_CANONICAL
const PROTO_CANONICAL
Definition: Defines.php:212
ApiBase\addWarning
addWarning( $msg, $code=null, $data=null)
Add a warning for this module.
Definition: ApiBase.php:1298
ApiQueryInfo\$fld_url
$fld_url
Definition: ApiQueryInfo.php:34
ApiQueryInfo\$subjectids
$subjectids
Definition: ApiQueryInfo.php:53
ApiQueryInfo\$displaytitles
$displaytitles
Definition: ApiQueryInfo.php:53
ApiQueryBase\resetQueryParams
resetQueryParams()
Blank the internal arrays with query parameters.
Definition: ApiQueryBase.php:152
LinkBatch
Class representing a list of titles The execute() method checks them all for existence and adds them ...
Definition: LinkBatch.php:35
ApiQueryInfo\getProtectionInfo
getProtectionInfo()
Get information about protections and put it in $protections.
Definition: ApiQueryInfo.php:576
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:144
ApiQueryInfo\getUnblockToken
static getUnblockToken( $pageid, $title)
Definition: ApiQueryInfo.php:226
ApiQueryInfo\$pageTouched
$pageTouched
Definition: ApiQueryInfo.php:49
ApiQueryInfo\$showZeroWatchers
$showZeroWatchers
Definition: ApiQueryInfo.php:54
ApiBase\PARAM_HELP_MSG
const PARAM_HELP_MSG
(string|array|Message) Specify an alternative i18n documentation message for this parameter.
Definition: ApiBase.php:96
ApiQueryInfo\resetTokenCache
static resetTokenCache()
Definition: ApiQueryInfo.php:126
wfTimestamp
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Definition: GlobalFunctions.php:1806
ApiQueryInfo\$tokenFunctions
$tokenFunctions
Definition: ApiQueryInfo.php:56
ApiBase\PARAM_TYPE
const PARAM_TYPE
(boolean) Inverse of IntegerDef::PARAM_IGNORE_RANGE
Definition: ApiBase.php:60
ApiBase\getResult
getResult()
Get the result object.
Definition: ApiBase.php:538
ApiQueryInfo\getVisitingWatcherInfo
getVisitingWatcherInfo()
Get the count of watchers who have visited recent edits and put it in $this->visitingwatchers.
Definition: ApiQueryInfo.php:881
NS_FILE
const NS_FILE
Definition: Defines.php:75
ApiQueryBase\addOption
addOption( $name, $value=null)
Add an option such as LIMIT or USE INDEX.
Definition: ApiQueryBase.php:374
$res
$res
Definition: testCompression.php:57
ContextSource\getUser
getUser()
Definition: ContextSource.php:120
ApiQueryInfo
A query module to show basic page information.
Definition: ApiQueryInfo.php:31
ApiBase\PARAM_DEPRECATED_VALUES
const PARAM_DEPRECATED_VALUES
(boolean) Inverse of IntegerDef::PARAM_IGNORE_RANGE
Definition: ApiBase.php:72
ApiBase\lacksSameOriginSecurity
lacksSameOriginSecurity()
Returns true if the current request breaks the same-origin policy.
Definition: ApiBase.php:466
ApiQueryInfo\$countTestedActions
$countTestedActions
Definition: ApiQueryInfo.php:58
ApiQueryInfo\getAllVariants
getAllVariants( $text, $ns=NS_MAIN)
Definition: ApiQueryInfo.php:799
NS_MAIN
const NS_MAIN
Definition: Defines.php:69
ApiQueryInfo\$fld_varianttitles
$fld_varianttitles
Definition: ApiQueryInfo.php:38
ApiBase\PARAM_DEPRECATED
const PARAM_DEPRECATED
(boolean) Inverse of IntegerDef::PARAM_IGNORE_RANGE
Definition: ApiBase.php:65
MediaWiki\Linker\LinkTarget\getNamespace
getNamespace()
Get the namespace index.
ApiQueryInfo\$visitingwatchers
$visitingwatchers
Definition: ApiQueryInfo.php:52
ApiQueryInfo\getEmailToken
static getEmailToken( $pageid, $title)
Definition: ApiQueryInfo.php:234
ApiQueryInfo\getProtectToken
static getProtectToken( $pageid, $title)
Definition: ApiQueryInfo.php:172
ApiQueryBase
This is a base class for all Query modules.
Definition: ApiQueryBase.php:35
ApiQueryInfo\getWatchToken
static getWatchToken( $pageid, $title)
Definition: ApiQueryInfo.php:270
ApiQueryInfo\$pageRestrictions
$pageRestrictions
Definition: ApiQueryInfo.php:49
ApiQueryBase\getDB
getDB()
Get the Query database connection (read-only)
Definition: ApiQueryBase.php:113
PROTO_CURRENT
const PROTO_CURRENT
Definition: Defines.php:211
ApiQueryBase\addTables
addTables( $tables, $alias=null)
Add a set of tables to the internal array.
Definition: ApiQueryBase.php:178
ApiQueryBase\select
select( $method, $extraQuery=[], array &$hookData=null)
Execute a SELECT query based on the values in the internal arrays.
Definition: ApiQueryBase.php:395
ApiQueryInfo\$titles
Title[] $titles
Definition: ApiQueryInfo.php:43
ApiBase\extractRequestParams
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition: ApiBase.php:659
ApiQueryInfo\$fld_talkid
$fld_talkid
Definition: ApiQueryInfo.php:33
$title
$title
Definition: testCompression.php:38
Title\makeTitle
static makeTitle( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:595
ApiQueryInfo\$fld_displaytitle
$fld_displaytitle
Definition: ApiQueryInfo.php:38
ApiQueryInfo\$notificationtimestamps
$notificationtimestamps
Definition: ApiQueryInfo.php:53
ApiQueryInfo\getDeleteToken
static getDeleteToken( $pageid, $title)
Definition: ApiQueryInfo.php:154
ApiQueryInfo\getTSIDs
getTSIDs()
Get talk page IDs (if requested) and subject page IDs (if requested) and put them in $talkids and $su...
Definition: ApiQueryInfo.php:727
ApiQueryInfo\getWatchedInfo
getWatchedInfo()
Get information about watched status and put it in $this->watched and $this->notificationtimestamps.
Definition: ApiQueryInfo.php:817
ApiQueryInfo\$watched
$watched
Definition: ApiQueryInfo.php:52
ApiQueryInfo\$params
$params
Definition: ApiQueryInfo.php:40
ApiQueryInfo\getHelpUrls
getHelpUrls()
Return links to more detailed help pages about the module.
Definition: ApiQueryInfo.php:1024
Title\makeTitleSafe
static makeTitleSafe( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:621
MediaWiki\Permissions\PermissionManager
A service class for checking permissions To obtain an instance, use MediaWikiServices::getInstance()-...
Definition: PermissionManager.php:48
ApiResult\setIndexedTagName
static setIndexedTagName(array &$arr, $tag)
Set the tag name for numeric-keyed values in XML format.
Definition: ApiResult.php:604
ApiQueryInfo\getImportToken
static getImportToken( $pageid, $title)
Definition: ApiQueryInfo.php:251
ApiQueryInfo\$pageIsNew
$pageIsNew
Definition: ApiQueryInfo.php:49
ApiQueryInfo\getExamplesMessages
getExamplesMessages()
Returns usage examples for this module.
Definition: ApiQueryInfo.php:1015
ApiBase\dieContinueUsageIf
dieContinueUsageIf( $condition)
Die with the 'badcontinue' error.
Definition: ApiBase.php:1559
ApiQueryInfo\getTokenFunctions
getTokenFunctions()
Get an array mapping token names to their handler functions.
Definition: ApiQueryInfo.php:92
ApiBase\LIMIT_SML2
const LIMIT_SML2
Slow query, apihighlimits limit.
Definition: ApiBase.php:160
ApiQueryInfo\$fld_preload
$fld_preload
Definition: ApiQueryInfo.php:38
ApiBase\getPermissionManager
getPermissionManager()
Obtain a PermissionManager instance that subclasses may use in their authorization checks.
Definition: ApiBase.php:608
MediaWiki\Linker\LinkTarget\getDBkey
getDBkey()
Get the main part with underscores.
ApiQueryBase\addWhereFld
addWhereFld( $field, $value)
Equivalent to addWhere( [ $field => $value ] )
Definition: ApiQueryBase.php:278
ApiQueryBase\getPageSet
getPageSet()
Get the PageSet object to work on.
Definition: ApiQueryBase.php:138
ApiQueryInfo\$fld_watchers
$fld_watchers
Definition: ApiQueryInfo.php:36
ApiQueryInfo\getCacheMode
getCacheMode( $params)
Get the cache mode for the data generated by this module.
Definition: ApiQueryInfo.php:943
ApiQueryInfo\$fld_subjectid
$fld_subjectid
Definition: ApiQueryInfo.php:34
Title
Represents a title within MediaWiki.
Definition: Title.php:42
ApiQueryInfo\$fld_watched
$fld_watched
Definition: ApiQueryInfo.php:35
ApiQueryInfo\getDisplayTitle
getDisplayTitle()
Definition: ApiQueryInfo.php:766
ApiQueryInfo\$fld_protection
$fld_protection
Definition: ApiQueryInfo.php:33
ApiQueryInfo\$watchers
$watchers
Definition: ApiQueryInfo.php:52
ApiQueryInfo\getEditToken
static getEditToken( $pageid, $title)
Definition: ApiQueryInfo.php:133
ApiQueryInfo\$pageLatest
$pageLatest
Definition: ApiQueryInfo.php:50
ApiBase\PARAM_DFLT
const PARAM_DFLT
(boolean) Inverse of IntegerDef::PARAM_IGNORE_RANGE
Definition: ApiBase.php:58
ApiQueryInfo\$restrictionTypes
$restrictionTypes
Definition: ApiQueryInfo.php:52
ApiQueryInfo\getAllowedParams
getAllowedParams()
Returns an array of allowed parameters (parameter name) => (default value) or (parameter name) => (ar...
Definition: ApiQueryInfo.php:970
ApiBase\PARAM_ISMULTI
const PARAM_ISMULTI
(boolean) Inverse of IntegerDef::PARAM_IGNORE_RANGE
Definition: ApiBase.php:59
ApiQueryInfo\$protections
$protections
Definition: ApiQueryInfo.php:52
$source
$source
Definition: mwdoc-filter.php:34
ApiQueryInfo\getMoveToken
static getMoveToken( $pageid, $title)
Definition: ApiQueryInfo.php:190
ApiResult\formatExpiry
static formatExpiry( $expiry, $infinity='infinity')
Format an expiry timestamp for API output.
Definition: ApiResult.php:1193
ApiQueryInfo\getOptionsToken
static getOptionsToken( $pageid, $title)
Definition: ApiQueryInfo.php:287
ApiBase\getMain
getMain()
Get the main module.
Definition: ApiBase.php:434
ApiQueryInfo\$fld_notificationtimestamp
$fld_notificationtimestamp
Definition: ApiQueryInfo.php:37
ApiQueryBase\addWhere
addWhere( $value)
Add a set of WHERE clauses to the internal array.
Definition: ApiQueryBase.php:241
Title\compare
static compare(LinkTarget $a, LinkTarget $b)
Callback for usort() to do title sorts by (namespace, title)
Definition: Title.php:849
$t
$t
Definition: testCompression.php:74
ApiQueryBase\setContinueEnumParameter
setContinueEnumParameter( $paramName, $paramValue)
Set a query-continue value.
Definition: ApiQueryBase.php:512
ApiQueryInfo\$pageIsRedir
$pageIsRedir
Definition: ApiQueryInfo.php:49
MediaWiki\Linker\LinkTarget
Definition: LinkTarget.php:26
ApiQueryInfo\getBlockToken
static getBlockToken( $pageid, $title)
Definition: ApiQueryInfo.php:208
ApiQueryInfo\$cachedTokens
static string[] $cachedTokens
Definition: ApiQueryInfo.php:121
ApiBase\PARAM_HELP_MSG_PER_VALUE
const PARAM_HELP_MSG_PER_VALUE
((string|array|Message)[]) When PARAM_TYPE is an array, this is an array mapping those values to $msg...
Definition: ApiBase.php:129
ApiQueryInfo\getVariantTitles
getVariantTitles()
Definition: ApiQueryInfo.php:787
ApiQueryInfo\$fld_readable
$fld_readable
Definition: ApiQueryInfo.php:35
ApiQueryInfo\requestExtraData
requestExtraData( $pageSet)
Definition: ApiQueryInfo.php:68
ApiQueryInfo\$fld_visitingwatchers
$fld_visitingwatchers
Definition: ApiQueryInfo.php:36
ApiQueryInfo\execute
execute()
Evaluates the parameters, performs the requested query, and sets up the result.
Definition: ApiQueryInfo.php:301
Hooks\run
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:133
ApiQueryInfo\getWatcherInfo
getWatcherInfo()
Get the count of watchers and put it in $this->watchers.
Definition: ApiQueryInfo.php:850
ApiBase\errorArrayToStatus
errorArrayToStatus(array $errors, User $user=null)
Turn an array of message keys or key+param arrays into a Status.
Definition: ApiBase.php:1190
ApiQueryInfo\$pageLength
$pageLength
Definition: ApiQueryInfo.php:50
ApiBase\getErrorFormatter
getErrorFormatter()
Get the error formatter.
Definition: ApiBase.php:552
ApiQueryInfo\$missing
Title[] $missing
Definition: ApiQueryInfo.php:45
ApiQueryInfo\$variantTitles
$variantTitles
Definition: ApiQueryInfo.php:53
ApiBase\LIMIT_SML1
const LIMIT_SML1
Slow query, standard limit.
Definition: ApiBase.php:158
wfExpandUrl
wfExpandUrl( $url, $defaultProto=PROTO_CURRENT)
Expand a potentially local URL to a fully-qualified URL.
Definition: GlobalFunctions.php:491
ApiQueryInfo\__construct
__construct(ApiQuery $query, $moduleName)
Definition: ApiQueryInfo.php:60