Localisation updates from https://translatewiki.net.
[mediawiki.git] / includes / api / ApiQueryInfo.php
blobe62a9064eed260e9d9d312558d0d9a52a9ab7ccc
1 <?php
2 /**
3 * Copyright © 2006 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
20 * @file
23 namespace MediaWiki\Api;
25 use MediaWiki\Cache\LinkBatchFactory;
26 use MediaWiki\EditPage\IntroMessageBuilder;
27 use MediaWiki\EditPage\PreloadedContentBuilder;
28 use MediaWiki\Language\ILanguageConverter;
29 use MediaWiki\Language\Language;
30 use MediaWiki\Languages\LanguageConverterFactory;
31 use MediaWiki\Linker\LinksMigration;
32 use MediaWiki\Linker\LinkTarget;
33 use MediaWiki\MainConfigNames;
34 use MediaWiki\Page\PageIdentity;
35 use MediaWiki\Page\PageReference;
36 use MediaWiki\ParamValidator\TypeDef\TitleDef;
37 use MediaWiki\Permissions\PermissionStatus;
38 use MediaWiki\Permissions\RestrictionStore;
39 use MediaWiki\Revision\RevisionLookup;
40 use MediaWiki\Title\NamespaceInfo;
41 use MediaWiki\Title\Title;
42 use MediaWiki\Title\TitleFactory;
43 use MediaWiki\Title\TitleFormatter;
44 use MediaWiki\Title\TitleValue;
45 use MediaWiki\User\TempUser\TempUserCreator;
46 use MediaWiki\User\UserFactory;
47 use MediaWiki\Utils\UrlUtils;
48 use MediaWiki\Watchlist\WatchedItem;
49 use MediaWiki\Watchlist\WatchedItemStore;
50 use MessageLocalizer;
51 use Wikimedia\ParamValidator\ParamValidator;
52 use Wikimedia\ParamValidator\TypeDef\EnumDef;
54 /**
55 * A query module to show basic page information.
57 * @ingroup API
59 class ApiQueryInfo extends ApiQueryBase {
61 private ILanguageConverter $languageConverter;
62 private LinkBatchFactory $linkBatchFactory;
63 private NamespaceInfo $namespaceInfo;
64 private TitleFactory $titleFactory;
65 private TitleFormatter $titleFormatter;
66 private WatchedItemStore $watchedItemStore;
67 private RestrictionStore $restrictionStore;
68 private LinksMigration $linksMigration;
69 private TempUserCreator $tempUserCreator;
70 private UserFactory $userFactory;
71 private IntroMessageBuilder $introMessageBuilder;
72 private PreloadedContentBuilder $preloadedContentBuilder;
73 private RevisionLookup $revisionLookup;
74 private UrlUtils $urlUtils;
76 private bool $fld_protection = false;
77 private bool $fld_talkid = false;
78 private bool $fld_subjectid = false;
79 private bool $fld_url = false;
80 private bool $fld_readable = false;
81 private bool $fld_watched = false;
82 private bool $fld_watchers = false;
83 private bool $fld_visitingwatchers = false;
84 private bool $fld_notificationtimestamp = false;
85 private bool $fld_preload = false;
86 private bool $fld_preloadcontent = false;
87 private bool $fld_editintro = false;
88 private bool $fld_displaytitle = false;
89 private bool $fld_varianttitles = false;
91 /**
92 * @var bool Whether to include link class information for the
93 * given page titles.
95 private $fld_linkclasses = false;
97 /**
98 * @var bool Whether to include the name of the associated page
100 private $fld_associatedpage = false;
102 /** @var array */
103 private $params;
105 /** @var array<int,PageIdentity> */
106 private $titles;
107 /** @var array<int,PageIdentity> */
108 private $missing;
109 /** @var array<int,PageIdentity> */
110 private $everything;
113 * @var array<int,bool> [page_id] => page_is_redirect database field, guaranteed to be
114 * initialized via execute()
116 private $pageIsRedir;
118 * @var array<int,bool> [page_id] => page_is_new database field, guaranteed to be
119 * initialized via execute()
121 private $pageIsNew;
123 * @var array<int,int> [page_id] => page_touched database field, guaranteed to be
124 * initialized via execute()
126 private $pageTouched;
128 * @var array<int,int> [page_id] => page_latest database field, guaranteed to be
129 * initialized via execute()
131 private $pageLatest;
133 * @var array<int,int> [page_id] => page_len database field, guaranteed to be
134 * initialized via execute()
136 private $pageLength;
138 /** @var array[][][] */
139 private $protections;
140 /** @var string[][][] */
141 private $restrictionTypes;
142 /** @var bool[][] */
143 private $watched;
144 /** @var int[][] */
145 private $watchers;
146 /** @var int[][] */
147 private $visitingwatchers;
148 /** @var string[][] */
149 private $notificationtimestamps;
150 /** @var int[][] */
151 private $talkids;
152 /** @var int[][] */
153 private $subjectids;
154 /** @var string[][] */
155 private $displaytitles;
156 /** @var string[][] */
157 private $variantTitles;
160 * Watchlist expiries that corresponds with the $watched property. Keyed by namespace and title.
161 * @var array<int,array<string,string>>
163 private $watchlistExpiries;
166 * @var array<int,string[]> Mapping of page id to list of 'extra link
167 * classes' for the given page
169 private $linkClasses;
171 /** @var bool */
172 private $showZeroWatchers = false;
174 /** @var int */
175 private $countTestedActions = 0;
177 public function __construct(
178 ApiQuery $queryModule,
179 string $moduleName,
180 Language $contentLanguage,
181 LinkBatchFactory $linkBatchFactory,
182 NamespaceInfo $namespaceInfo,
183 TitleFactory $titleFactory,
184 TitleFormatter $titleFormatter,
185 WatchedItemStore $watchedItemStore,
186 LanguageConverterFactory $languageConverterFactory,
187 RestrictionStore $restrictionStore,
188 LinksMigration $linksMigration,
189 TempUserCreator $tempUserCreator,
190 UserFactory $userFactory,
191 IntroMessageBuilder $introMessageBuilder,
192 PreloadedContentBuilder $preloadedContentBuilder,
193 RevisionLookup $revisionLookup,
194 UrlUtils $urlUtils
196 parent::__construct( $queryModule, $moduleName, 'in' );
197 $this->languageConverter = $languageConverterFactory->getLanguageConverter( $contentLanguage );
198 $this->linkBatchFactory = $linkBatchFactory;
199 $this->namespaceInfo = $namespaceInfo;
200 $this->titleFactory = $titleFactory;
201 $this->titleFormatter = $titleFormatter;
202 $this->watchedItemStore = $watchedItemStore;
203 $this->restrictionStore = $restrictionStore;
204 $this->linksMigration = $linksMigration;
205 $this->tempUserCreator = $tempUserCreator;
206 $this->userFactory = $userFactory;
207 $this->introMessageBuilder = $introMessageBuilder;
208 $this->preloadedContentBuilder = $preloadedContentBuilder;
209 $this->revisionLookup = $revisionLookup;
210 $this->urlUtils = $urlUtils;
214 * @param ApiPageSet $pageSet
215 * @return void
217 public function requestExtraData( $pageSet ) {
218 // If the pageset is resolving redirects we won't get page_is_redirect.
219 // But we can't know for sure until the pageset is executed (revids may
220 // turn it off), so request it unconditionally.
221 $pageSet->requestField( 'page_is_redirect' );
222 $pageSet->requestField( 'page_is_new' );
223 $config = $this->getConfig();
224 $pageSet->requestField( 'page_touched' );
225 $pageSet->requestField( 'page_latest' );
226 $pageSet->requestField( 'page_len' );
227 $pageSet->requestField( 'page_content_model' );
228 if ( $config->get( MainConfigNames::PageLanguageUseDB ) ) {
229 $pageSet->requestField( 'page_lang' );
233 public function execute() {
234 $this->params = $this->extractRequestParams();
235 if ( $this->params['prop'] !== null ) {
236 $prop = array_fill_keys( $this->params['prop'], true );
237 $this->fld_protection = isset( $prop['protection'] );
238 $this->fld_watched = isset( $prop['watched'] );
239 $this->fld_watchers = isset( $prop['watchers'] );
240 $this->fld_visitingwatchers = isset( $prop['visitingwatchers'] );
241 $this->fld_notificationtimestamp = isset( $prop['notificationtimestamp'] );
242 $this->fld_talkid = isset( $prop['talkid'] );
243 $this->fld_subjectid = isset( $prop['subjectid'] );
244 $this->fld_url = isset( $prop['url'] );
245 $this->fld_readable = isset( $prop['readable'] );
246 $this->fld_preload = isset( $prop['preload'] );
247 $this->fld_preloadcontent = isset( $prop['preloadcontent'] );
248 $this->fld_editintro = isset( $prop['editintro'] );
249 $this->fld_displaytitle = isset( $prop['displaytitle'] );
250 $this->fld_varianttitles = isset( $prop['varianttitles'] );
251 $this->fld_linkclasses = isset( $prop['linkclasses'] );
252 $this->fld_associatedpage = isset( $prop['associatedpage'] );
255 $pageSet = $this->getPageSet();
256 $this->titles = $pageSet->getGoodPages();
257 $this->missing = $pageSet->getMissingPages();
258 $this->everything = $this->titles + $this->missing;
259 $result = $this->getResult();
261 if (
262 ( $this->fld_preloadcontent || $this->fld_editintro ) &&
263 ( count( $this->everything ) > 1 || count( $this->getPageSet()->getRevisionIDs() ) > 1 )
265 // This is relatively slow, so disallow doing it for multiple pages, just in case.
266 // (Also, handling multiple revisions would be tricky.)
267 $this->dieWithError(
268 [ 'apierror-info-singlepagerevision', $this->getModulePrefix() ], 'invalidparammix'
272 uasort( $this->everything, [ Title::class, 'compare' ] );
273 if ( $this->params['continue'] !== null ) {
274 // Throw away any titles we're gonna skip so they don't
275 // clutter queries
276 $cont = $this->parseContinueParamOrDie( $this->params['continue'], [ 'int', 'string' ] );
277 $conttitle = $this->titleFactory->makeTitleSafe( $cont[0], $cont[1] );
278 $this->dieContinueUsageIf( !$conttitle );
279 foreach ( $this->everything as $pageid => $page ) {
280 if ( Title::compare( $page, $conttitle ) >= 0 ) {
281 break;
283 unset( $this->titles[$pageid] );
284 unset( $this->missing[$pageid] );
285 unset( $this->everything[$pageid] );
289 // when resolving redirects, no page will have this field
290 $this->pageIsRedir = !$pageSet->isResolvingRedirects()
291 ? $pageSet->getCustomField( 'page_is_redirect' )
292 : [];
293 $this->pageIsNew = $pageSet->getCustomField( 'page_is_new' );
295 $this->pageTouched = $pageSet->getCustomField( 'page_touched' );
296 $this->pageLatest = $pageSet->getCustomField( 'page_latest' );
297 $this->pageLength = $pageSet->getCustomField( 'page_len' );
299 // Get protection info if requested
300 if ( $this->fld_protection ) {
301 $this->getProtectionInfo();
304 if ( $this->fld_watched || $this->fld_notificationtimestamp ) {
305 $this->getWatchedInfo();
308 if ( $this->fld_watchers ) {
309 $this->getWatcherInfo();
312 if ( $this->fld_visitingwatchers ) {
313 $this->getVisitingWatcherInfo();
316 // Run the talkid/subjectid query if requested
317 if ( $this->fld_talkid || $this->fld_subjectid ) {
318 $this->getTSIDs();
321 if ( $this->fld_displaytitle ) {
322 $this->getDisplayTitle();
325 if ( $this->fld_varianttitles ) {
326 $this->getVariantTitles();
329 if ( $this->fld_linkclasses ) {
330 $this->getLinkClasses( $this->params['linkcontext'] );
333 /** @var PageIdentity $page */
334 foreach ( $this->everything as $pageid => $page ) {
335 $pageInfo = $this->extractPageInfo( $pageid, $page );
336 $fit = $pageInfo !== null && $result->addValue( [
337 'query',
338 'pages'
339 ], $pageid, $pageInfo );
340 if ( !$fit ) {
341 $this->setContinueEnumParameter( 'continue',
342 $page->getNamespace() . '|' .
343 $this->titleFormatter->getText( $page ) );
344 break;
350 * Get a result array with information about a title
351 * @param int $pageid Page ID (negative for missing titles)
352 * @param PageIdentity $page
353 * @return array|null
355 private function extractPageInfo( $pageid, $page ) {
356 $title = $this->titleFactory->newFromPageIdentity( $page );
357 $pageInfo = [];
358 // $page->exists() needs pageid, which is not set for all title objects
359 $pageExists = $pageid > 0;
360 $ns = $page->getNamespace();
361 $dbkey = $page->getDBkey();
363 $pageInfo['contentmodel'] = $title->getContentModel();
365 $pageLanguage = $title->getPageLanguage();
366 $pageInfo['pagelanguage'] = $pageLanguage->getCode();
367 $pageInfo['pagelanguagehtmlcode'] = $pageLanguage->getHtmlCode();
368 $pageInfo['pagelanguagedir'] = $pageLanguage->getDir();
370 if ( $pageExists ) {
371 $pageInfo['touched'] = wfTimestamp( TS_ISO_8601, $this->pageTouched[$pageid] );
372 $pageInfo['lastrevid'] = (int)$this->pageLatest[$pageid];
373 $pageInfo['length'] = (int)$this->pageLength[$pageid];
375 if ( isset( $this->pageIsRedir[$pageid] ) && $this->pageIsRedir[$pageid] ) {
376 $pageInfo['redirect'] = true;
378 if ( $this->pageIsNew[$pageid] ) {
379 $pageInfo['new'] = true;
383 if ( $this->fld_protection ) {
384 $pageInfo['protection'] = [];
385 if ( isset( $this->protections[$ns][$dbkey] ) ) {
386 $pageInfo['protection'] =
387 $this->protections[$ns][$dbkey];
389 ApiResult::setIndexedTagName( $pageInfo['protection'], 'pr' );
391 $pageInfo['restrictiontypes'] = [];
392 if ( isset( $this->restrictionTypes[$ns][$dbkey] ) ) {
393 $pageInfo['restrictiontypes'] =
394 $this->restrictionTypes[$ns][$dbkey];
396 ApiResult::setIndexedTagName( $pageInfo['restrictiontypes'], 'rt' );
399 if ( $this->fld_watched ) {
400 $pageInfo['watched'] = false;
402 if ( isset( $this->watched[$ns][$dbkey] ) ) {
403 $pageInfo['watched'] = $this->watched[$ns][$dbkey];
406 if ( isset( $this->watchlistExpiries[$ns][$dbkey] ) ) {
407 $pageInfo['watchlistexpiry'] = $this->watchlistExpiries[$ns][$dbkey];
411 if ( $this->fld_watchers ) {
412 if ( $this->watchers !== null && $this->watchers[$ns][$dbkey] !== 0 ) {
413 $pageInfo['watchers'] = $this->watchers[$ns][$dbkey];
414 } elseif ( $this->showZeroWatchers ) {
415 $pageInfo['watchers'] = 0;
419 if ( $this->fld_visitingwatchers ) {
420 if ( $this->visitingwatchers !== null && $this->visitingwatchers[$ns][$dbkey] !== 0 ) {
421 $pageInfo['visitingwatchers'] = $this->visitingwatchers[$ns][$dbkey];
422 } elseif ( $this->showZeroWatchers ) {
423 $pageInfo['visitingwatchers'] = 0;
427 if ( $this->fld_notificationtimestamp ) {
428 $pageInfo['notificationtimestamp'] = '';
429 if ( isset( $this->notificationtimestamps[$ns][$dbkey] ) ) {
430 $pageInfo['notificationtimestamp'] =
431 wfTimestamp( TS_ISO_8601, $this->notificationtimestamps[$ns][$dbkey] );
435 if ( $this->fld_talkid && isset( $this->talkids[$ns][$dbkey] ) ) {
436 $pageInfo['talkid'] = $this->talkids[$ns][$dbkey];
439 if ( $this->fld_subjectid && isset( $this->subjectids[$ns][$dbkey] ) ) {
440 $pageInfo['subjectid'] = $this->subjectids[$ns][$dbkey];
443 if ( $this->fld_associatedpage && $ns >= NS_MAIN ) {
444 $pageInfo['associatedpage'] = $this->titleFormatter->getPrefixedText(
445 $this->namespaceInfo->getAssociatedPage( TitleValue::newFromPage( $page ) )
449 if ( $this->fld_url ) {
450 $pageInfo['fullurl'] = (string)$this->urlUtils->expand(
451 $title->getFullURL(), PROTO_CURRENT
453 $pageInfo['editurl'] = (string)$this->urlUtils->expand(
454 $title->getFullURL( 'action=edit' ), PROTO_CURRENT
456 $pageInfo['canonicalurl'] = (string)$this->urlUtils->expand(
457 $title->getFullURL(), PROTO_CANONICAL
460 if ( $this->fld_readable ) {
461 $pageInfo['readable'] = $this->getAuthority()->definitelyCan( 'read', $page );
464 if ( $this->fld_preload ) {
465 if ( $pageExists ) {
466 $pageInfo['preload'] = '';
467 } else {
468 $text = null;
469 // @phan-suppress-next-line PhanTypeMismatchArgument Type mismatch on pass-by-ref args
470 $this->getHookRunner()->onEditFormPreloadText( $text, $title );
472 $pageInfo['preload'] = $text;
476 if ( $this->fld_preloadcontent ) {
477 $newSection = $this->params['preloadnewsection'];
478 // Preloaded content is not supported for already existing pages or sections.
479 // The actual page/section content should be shown for editing (from prop=revisions API).
480 if ( !$pageExists || $newSection ) {
481 $content = $this->preloadedContentBuilder->getPreloadedContent(
482 $title->toPageIdentity(),
483 $this->getAuthority(),
484 $this->params['preloadcustom'],
485 $this->params['preloadparams'] ?? [],
486 $newSection ? 'new' : null
488 $defaultContent = $newSection ? null :
489 $this->preloadedContentBuilder->getDefaultContent( $title->toPageIdentity() );
490 $contentIsDefault = $defaultContent ? $content->equals( $defaultContent ) : $content->isEmpty();
491 // Adapted from ApiQueryRevisionsBase::extractAllSlotInfo.
492 // The preloaded content fills the main slot.
493 $pageInfo['preloadcontent']['contentmodel'] = $content->getModel();
494 $pageInfo['preloadcontent']['contentformat'] = $content->getDefaultFormat();
495 ApiResult::setContentValue( $pageInfo['preloadcontent'], 'content', $content->serialize() );
496 // If the preloaded content generated from these parameters is the same as
497 // the default page content, the user should be discouraged from saving the page
498 // (e.g. by disabling the save button until changes are made, or displaying a warning).
499 $pageInfo['preloadisdefault'] = $contentIsDefault;
503 if ( $this->fld_editintro ) {
504 // Use $page as the context page in every processed message (T300184)
505 $localizerWithPage = new class( $this, $page ) implements MessageLocalizer {
506 private MessageLocalizer $base;
507 private PageReference $page;
509 public function __construct( MessageLocalizer $base, PageReference $page ) {
510 $this->base = $base;
511 $this->page = $page;
515 * @inheritDoc
517 public function msg( $key, ...$params ) {
518 return $this->base->msg( $key, ...$params )->page( $this->page );
522 $styleParamMap = [
523 'lessframes' => IntroMessageBuilder::LESS_FRAMES,
524 'moreframes' => IntroMessageBuilder::MORE_FRAMES,
526 // If we got here, there is exactly one page and revision in the query
527 $revId = array_key_first( $this->getPageSet()->getLiveRevisionIDs() );
528 $revRecord = $revId ? $this->revisionLookup->getRevisionById( $revId ) : null;
530 $messages = $this->introMessageBuilder->getIntroMessages(
531 $styleParamMap[ $this->params['editintrostyle'] ],
532 $this->params['editintroskip'] ?? [],
533 $localizerWithPage,
534 $title->toPageIdentity(),
535 $revRecord,
536 $this->getAuthority(),
537 $this->params['editintrocustom'],
538 // Maybe expose these as parameters in the future, but for now it doesn't seem worth it:
539 null,
540 false
542 ApiResult::setIndexedTagName( $messages, 'ei' );
543 ApiResult::setArrayType( $messages, 'kvp', 'key' );
545 $pageInfo['editintro'] = $messages;
548 if ( $this->fld_displaytitle ) {
549 $pageInfo['displaytitle'] = $this->displaytitles[$pageid] ??
550 htmlspecialchars( $this->titleFormatter->getPrefixedText( $page ), ENT_NOQUOTES );
553 if ( $this->fld_varianttitles && isset( $this->variantTitles[$pageid] ) ) {
554 $pageInfo['varianttitles'] = $this->variantTitles[$pageid];
557 if ( $this->fld_linkclasses && isset( $this->linkClasses[$pageid] ) ) {
558 $pageInfo['linkclasses'] = $this->linkClasses[$pageid];
561 if ( $this->params['testactions'] ) {
562 $limit = $this->getMain()->canApiHighLimits() ? self::LIMIT_SML2 : self::LIMIT_SML1;
563 if ( $this->countTestedActions >= $limit ) {
564 return null; // force a continuation
567 $detailLevel = $this->params['testactionsdetail'];
568 $errorFormatter = $this->getErrorFormatter();
569 if ( $errorFormatter->getFormat() === 'bc' ) {
570 // Eew, no. Use a more modern format here.
571 $errorFormatter = $errorFormatter->newWithFormat( 'plaintext' );
574 $pageInfo['actions'] = [];
575 if ( $this->params['testactionsautocreate'] ) {
576 $pageInfo['wouldautocreate'] = [];
579 foreach ( $this->params['testactions'] as $action ) {
580 $this->countTestedActions++;
582 $shouldAutoCreate = $this->tempUserCreator->shouldAutoCreate( $this->getUser(), $action );
584 if ( $shouldAutoCreate ) {
585 $authority = $this->userFactory->newTempPlaceholder();
586 } else {
587 $authority = $this->getAuthority();
590 if ( $detailLevel === 'boolean' ) {
591 $pageInfo['actions'][$action] = $authority->authorizeRead( $action, $page );
592 } else {
593 $status = new PermissionStatus();
594 if ( $detailLevel === 'quick' ) {
595 $authority->probablyCan( $action, $page, $status );
596 } else {
597 $authority->definitelyCan( $action, $page, $status );
599 $this->addBlockInfoToStatus( $status );
600 $pageInfo['actions'][$action] = $errorFormatter->arrayFromStatus( $status );
603 if ( $this->params['testactionsautocreate'] ) {
604 $pageInfo['wouldautocreate'][$action] = $shouldAutoCreate;
609 return $pageInfo;
613 * Get information about protections and put it in $protections
615 private function getProtectionInfo() {
616 $this->protections = [];
617 $db = $this->getDB();
619 // Get normal protections for existing titles
620 if ( count( $this->titles ) ) {
621 $this->resetQueryParams();
622 $this->addTables( 'page_restrictions' );
623 $this->addFields( [ 'pr_page', 'pr_type', 'pr_level',
624 'pr_expiry', 'pr_cascade' ] );
625 $this->addWhereFld( 'pr_page', array_keys( $this->titles ) );
627 $res = $this->select( __METHOD__ );
628 foreach ( $res as $row ) {
629 /** @var PageReference $page */
630 $page = $this->titles[$row->pr_page];
631 $a = [
632 'type' => $row->pr_type,
633 'level' => $row->pr_level,
634 'expiry' => ApiResult::formatExpiry( $row->pr_expiry )
636 if ( $row->pr_cascade ) {
637 $a['cascade'] = true;
639 $this->protections[$page->getNamespace()][$page->getDBkey()][] = $a;
643 // Get protections for missing titles
644 if ( count( $this->missing ) ) {
645 $this->resetQueryParams();
646 $lb = $this->linkBatchFactory->newLinkBatch( $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 )
660 // Separate good and missing titles into files and other pages
661 // and populate $this->restrictionTypes
662 $images = $others = [];
663 foreach ( $this->everything as $page ) {
664 if ( $page->getNamespace() === NS_FILE ) {
665 $images[] = $page->getDBkey();
666 } else {
667 $others[] = $page;
669 // Applicable protection types
670 $this->restrictionTypes[$page->getNamespace()][$page->getDBkey()] =
671 array_values( $this->restrictionStore->listApplicableRestrictionTypes( $page ) );
674 [ $blNamespace, $blTitle ] = $this->linksMigration->getTitleFields( 'templatelinks' );
675 $queryInfo = $this->linksMigration->getQueryInfo( 'templatelinks' );
677 if ( count( $others ) ) {
678 // Non-images: check templatelinks
679 $lb = $this->linkBatchFactory->newLinkBatch( $others );
680 $this->resetQueryParams();
681 $this->addTables( array_merge( [ 'page_restrictions', 'page' ], $queryInfo['tables'] ) );
682 // templatelinks must use PRIMARY index and not the tl_target_id.
683 $this->addOption( 'USE INDEX', [ 'templatelinks' => 'PRIMARY' ] );
684 $this->addFields( [ 'pr_type', 'pr_level', 'pr_expiry',
685 'page_title', 'page_namespace',
686 $blNamespace, $blTitle ] );
687 $this->addWhere( $lb->constructSet( 'tl', $db ) );
688 $this->addWhere( 'pr_page = page_id' );
689 $this->addWhere( 'pr_page = tl_from' );
690 $this->addWhereFld( 'pr_cascade', 1 );
691 $this->addJoinConds( $queryInfo['joins'] );
693 $res = $this->select( __METHOD__ );
694 foreach ( $res as $row ) {
695 $this->protections[$row->$blNamespace][$row->$blTitle][] = [
696 'type' => $row->pr_type,
697 'level' => $row->pr_level,
698 'expiry' => ApiResult::formatExpiry( $row->pr_expiry ),
699 'source' => $this->titleFormatter->formatTitle( $row->page_namespace, $row->page_title ),
704 if ( count( $images ) ) {
705 // Images: check imagelinks
706 $this->resetQueryParams();
707 $this->addTables( [ 'page_restrictions', 'page', 'imagelinks' ] );
708 $this->addFields( [ 'pr_type', 'pr_level', 'pr_expiry',
709 'page_title', 'page_namespace', 'il_to' ] );
710 $this->addWhere( 'pr_page = page_id' );
711 $this->addWhere( 'pr_page = il_from' );
712 $this->addWhereFld( 'pr_cascade', 1 );
713 $this->addWhereFld( 'il_to', $images );
715 $res = $this->select( __METHOD__ );
716 foreach ( $res as $row ) {
717 $this->protections[NS_FILE][$row->il_to][] = [
718 'type' => $row->pr_type,
719 'level' => $row->pr_level,
720 'expiry' => ApiResult::formatExpiry( $row->pr_expiry ),
721 'source' => $this->titleFormatter->formatTitle( $row->page_namespace, $row->page_title ),
728 * Get talk page IDs (if requested) and subject page IDs (if requested)
729 * and put them in $talkids and $subjectids
731 private function getTSIDs() {
732 $getTitles = $this->talkids = $this->subjectids = [];
733 $nsInfo = $this->namespaceInfo;
735 /** @var PageReference $page */
736 foreach ( $this->everything as $page ) {
737 if ( $nsInfo->isTalk( $page->getNamespace() ) ) {
738 if ( $this->fld_subjectid ) {
739 $getTitles[] = $nsInfo->getSubjectPage( TitleValue::newFromPage( $page ) );
741 } elseif ( $this->fld_talkid ) {
742 $getTitles[] = $nsInfo->getTalkPage( TitleValue::newFromPage( $page ) );
745 if ( $getTitles === [] ) {
746 return;
749 $db = $this->getDB();
751 // Construct a custom WHERE clause that matches
752 // all titles in $getTitles
753 $lb = $this->linkBatchFactory->newLinkBatch( $getTitles );
754 $this->resetQueryParams();
755 $this->addTables( 'page' );
756 $this->addFields( [ 'page_title', 'page_namespace', 'page_id' ] );
757 $this->addWhere( $lb->constructSet( 'page', $db ) );
758 $res = $this->select( __METHOD__ );
759 foreach ( $res as $row ) {
760 if ( $nsInfo->isTalk( $row->page_namespace ) ) {
761 $this->talkids[$nsInfo->getSubject( $row->page_namespace )][$row->page_title] =
762 (int)( $row->page_id );
763 } else {
764 $this->subjectids[$nsInfo->getTalk( $row->page_namespace )][$row->page_title] =
765 (int)( $row->page_id );
770 private function getDisplayTitle() {
771 $this->displaytitles = [];
773 $pageIds = array_keys( $this->titles );
775 if ( $pageIds === [] ) {
776 return;
779 $this->resetQueryParams();
780 $this->addTables( 'page_props' );
781 $this->addFields( [ 'pp_page', 'pp_value' ] );
782 $this->addWhereFld( 'pp_page', $pageIds );
783 $this->addWhereFld( 'pp_propname', 'displaytitle' );
784 $res = $this->select( __METHOD__ );
786 foreach ( $res as $row ) {
787 $this->displaytitles[$row->pp_page] = $row->pp_value;
792 * Fetch the set of extra link classes associated with links to the
793 * set of titles ("link colours"), as they would appear on the
794 * given context page.
795 * @param ?LinkTarget $context_title The page context in which link
796 * colors are determined.
798 private function getLinkClasses( ?LinkTarget $context_title = null ) {
799 if ( $this->titles === [] ) {
800 return;
802 // For compatibility with legacy GetLinkColours hook:
803 // $pagemap maps from page id to title (as prefixed db key)
804 // $classes maps from title (prefixed db key) to a space-separated
805 // list of link classes ("link colours").
806 // The hook should not modify $pagemap, and should only append to
807 // $classes (being careful to maintain space separation).
808 $classes = [];
809 $pagemap = [];
810 foreach ( $this->titles as $pageId => $page ) {
811 $pdbk = $this->titleFormatter->getPrefixedDBkey( $page );
812 $pagemap[$pageId] = $pdbk;
813 $classes[$pdbk] = isset( $this->pageIsRedir[$pageId] ) && $this->pageIsRedir[$pageId] ? 'mw-redirect' : '';
815 // legacy hook requires a real Title, not a LinkTarget
816 $context_title = $this->titleFactory->newFromLinkTarget(
817 $context_title ?? $this->titleFactory->newMainPage()
819 $this->getHookRunner()->onGetLinkColours(
820 $pagemap, $classes, $context_title
823 // This API class expects the class list to be:
824 // (a) indexed by pageid, not title, and
825 // (b) a proper array of strings (possibly zero-length),
826 // not a single space-separated string (possibly the empty string)
827 $this->linkClasses = [];
828 foreach ( $this->titles as $pageId => $page ) {
829 $pdbk = $this->titleFormatter->getPrefixedDBkey( $page );
830 $this->linkClasses[$pageId] = preg_split(
831 '/\s+/', $classes[$pdbk] ?? '', -1, PREG_SPLIT_NO_EMPTY
836 private function getVariantTitles() {
837 if ( $this->titles === [] ) {
838 return;
840 $this->variantTitles = [];
841 foreach ( $this->titles as $pageId => $page ) {
842 $this->variantTitles[$pageId] = isset( $this->displaytitles[$pageId] )
843 ? $this->getAllVariants( $this->displaytitles[$pageId] )
844 : $this->getAllVariants( $this->titleFormatter->getText( $page ), $page->getNamespace() );
848 private function getAllVariants( $text, $ns = NS_MAIN ) {
849 $result = [];
850 foreach ( $this->languageConverter->getVariants() as $variant ) {
851 $convertTitle = $this->languageConverter->autoConvert( $text, $variant );
852 if ( $ns !== NS_MAIN ) {
853 $convertNs = $this->languageConverter->convertNamespace( $ns, $variant );
854 $convertTitle = $convertNs . ':' . $convertTitle;
856 $result[$variant] = $convertTitle;
858 return $result;
862 * Get information about watched status and put it in $this->watched
863 * and $this->notificationtimestamps
865 private function getWatchedInfo() {
866 $user = $this->getUser();
868 if ( !$user->isRegistered() || count( $this->everything ) == 0
869 || !$this->getAuthority()->isAllowed( 'viewmywatchlist' )
871 return;
874 $this->watched = [];
875 $this->watchlistExpiries = [];
876 $this->notificationtimestamps = [];
878 /** @var WatchedItem[] $items */
879 $items = $this->watchedItemStore->loadWatchedItemsBatch( $user, $this->everything );
881 foreach ( $items as $item ) {
882 $nsId = $item->getTarget()->getNamespace();
883 $dbKey = $item->getTarget()->getDBkey();
885 if ( $this->fld_watched ) {
886 $this->watched[$nsId][$dbKey] = true;
888 $expiry = $item->getExpiry( TS_ISO_8601 );
889 if ( $expiry ) {
890 $this->watchlistExpiries[$nsId][$dbKey] = $expiry;
894 if ( $this->fld_notificationtimestamp ) {
895 $this->notificationtimestamps[$nsId][$dbKey] = $item->getNotificationTimestamp();
901 * Get the count of watchers and put it in $this->watchers
903 private function getWatcherInfo() {
904 if ( count( $this->everything ) == 0 ) {
905 return;
908 $canUnwatchedpages = $this->getAuthority()->isAllowed( 'unwatchedpages' );
909 $unwatchedPageThreshold =
910 $this->getConfig()->get( MainConfigNames::UnwatchedPageThreshold );
911 if ( !$canUnwatchedpages && !is_int( $unwatchedPageThreshold ) ) {
912 return;
915 $this->showZeroWatchers = $canUnwatchedpages;
917 $countOptions = [];
918 if ( !$canUnwatchedpages ) {
919 $countOptions['minimumWatchers'] = $unwatchedPageThreshold;
922 $this->watchers = $this->watchedItemStore->countWatchersMultiple(
923 $this->everything,
924 $countOptions
929 * Get the count of watchers who have visited recent edits and put it in
930 * $this->visitingwatchers
932 * Based on InfoAction::pageCounts
934 private function getVisitingWatcherInfo() {
935 $config = $this->getConfig();
936 $db = $this->getDB();
938 $canUnwatchedpages = $this->getAuthority()->isAllowed( 'unwatchedpages' );
939 $unwatchedPageThreshold = $config->get( MainConfigNames::UnwatchedPageThreshold );
940 if ( !$canUnwatchedpages && !is_int( $unwatchedPageThreshold ) ) {
941 return;
944 $this->showZeroWatchers = $canUnwatchedpages;
946 $titlesWithThresholds = [];
947 if ( $this->titles ) {
948 $lb = $this->linkBatchFactory->newLinkBatch( $this->titles );
950 // Fetch last edit timestamps for pages
951 $this->resetQueryParams();
952 $this->addTables( [ 'page', 'revision' ] );
953 $this->addFields( [ 'page_namespace', 'page_title', 'rev_timestamp' ] );
954 $this->addWhere( [
955 'page_latest = rev_id',
956 $lb->constructSet( 'page', $db ),
957 ] );
958 $this->addOption( 'GROUP BY', [ 'page_namespace', 'page_title' ] );
959 $timestampRes = $this->select( __METHOD__ );
961 $age = $config->get( MainConfigNames::WatchersMaxAge );
962 $timestamps = [];
963 foreach ( $timestampRes as $row ) {
964 $revTimestamp = wfTimestamp( TS_UNIX, (int)$row->rev_timestamp );
965 $timestamps[$row->page_namespace][$row->page_title] = (int)$revTimestamp - $age;
967 $titlesWithThresholds = array_map(
968 static function ( PageReference $target ) use ( $timestamps ) {
969 return [
970 $target, $timestamps[$target->getNamespace()][$target->getDBkey()]
973 $this->titles
977 if ( $this->missing ) {
978 $titlesWithThresholds = array_merge(
979 $titlesWithThresholds,
980 array_map(
981 static function ( PageReference $target ) {
982 return [ $target, null ];
984 $this->missing
988 $this->visitingwatchers = $this->watchedItemStore->countVisitingWatchersMultiple(
989 $titlesWithThresholds,
990 !$canUnwatchedpages ? $unwatchedPageThreshold : null
994 public function getCacheMode( $params ) {
995 // Other props depend on something about the current user
996 $publicProps = [
997 'protection',
998 'talkid',
999 'subjectid',
1000 'associatedpage',
1001 'url',
1002 'preload',
1003 'displaytitle',
1004 'varianttitles',
1006 if ( array_diff( (array)$params['prop'], $publicProps ) ) {
1007 return 'private';
1010 // testactions also depends on the current user
1011 if ( $params['testactions'] ) {
1012 return 'private';
1015 return 'public';
1018 public function getAllowedParams() {
1019 return [
1020 'prop' => [
1021 ParamValidator::PARAM_ISMULTI => true,
1022 ParamValidator::PARAM_TYPE => [
1023 'protection',
1024 'talkid',
1025 'watched', # private
1026 'watchers', # private
1027 'visitingwatchers', # private
1028 'notificationtimestamp', # private
1029 'subjectid',
1030 'associatedpage',
1031 'url',
1032 'readable', # private
1033 'preload',
1034 'preloadcontent', # private: checks current user's permissions
1035 'editintro', # private: checks current user's permissions
1036 'displaytitle',
1037 'varianttitles',
1038 'linkclasses', # private: stub length (and possibly hook colors)
1039 // If you add more properties here, please consider whether they
1040 // need to be added to getCacheMode()
1042 ApiBase::PARAM_HELP_MSG_PER_VALUE => [],
1043 EnumDef::PARAM_DEPRECATED_VALUES => [
1044 'readable' => true, // Since 1.32
1045 'preload' => true, // Since 1.41
1048 'linkcontext' => [
1049 ParamValidator::PARAM_TYPE => 'title',
1050 ParamValidator::PARAM_DEFAULT => $this->titleFactory->newMainPage()->getPrefixedText(),
1051 TitleDef::PARAM_RETURN_OBJECT => true,
1053 'testactions' => [
1054 ParamValidator::PARAM_TYPE => 'string',
1055 ParamValidator::PARAM_ISMULTI => true,
1057 'testactionsdetail' => [
1058 ParamValidator::PARAM_TYPE => [ 'boolean', 'full', 'quick' ],
1059 ParamValidator::PARAM_DEFAULT => 'boolean',
1060 ApiBase::PARAM_HELP_MSG_PER_VALUE => [],
1062 'testactionsautocreate' => false,
1063 'preloadcustom' => [
1064 // This should be a valid and existing page title, but we don't want to validate it here,
1065 // because it's usually someone else's fault. It could emit a warning in the future.
1066 ParamValidator::PARAM_TYPE => 'string',
1067 ApiBase::PARAM_HELP_MSG_INFO => [ [ 'preloadcontentonly' ] ],
1069 'preloadparams' => [
1070 ParamValidator::PARAM_ISMULTI => true,
1071 ApiBase::PARAM_HELP_MSG_INFO => [ [ 'preloadcontentonly' ] ],
1073 'preloadnewsection' => [
1074 ParamValidator::PARAM_TYPE => 'boolean',
1075 ParamValidator::PARAM_DEFAULT => false,
1076 ApiBase::PARAM_HELP_MSG_INFO => [ [ 'preloadcontentonly' ] ],
1078 'editintrostyle' => [
1079 ParamValidator::PARAM_TYPE => [ 'lessframes', 'moreframes' ],
1080 ParamValidator::PARAM_DEFAULT => 'moreframes',
1081 ApiBase::PARAM_HELP_MSG_INFO => [ [ 'editintroonly' ] ],
1083 'editintroskip' => [
1084 ParamValidator::PARAM_TYPE => 'string',
1085 ParamValidator::PARAM_ISMULTI => true,
1086 ApiBase::PARAM_HELP_MSG_INFO => [ [ 'editintroonly' ] ],
1088 'editintrocustom' => [
1089 // This should be a valid and existing page title, but we don't want to validate it here,
1090 // because it's usually someone else's fault. It could emit a warning in the future.
1091 ParamValidator::PARAM_TYPE => 'string',
1092 ApiBase::PARAM_HELP_MSG_INFO => [ [ 'editintroonly' ] ],
1094 'continue' => [
1095 ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
1100 protected function getExamplesMessages() {
1101 $title = Title::newMainPage()->getPrefixedText();
1102 $mp = rawurlencode( $title );
1104 return [
1105 "action=query&prop=info&titles={$mp}"
1106 => 'apihelp-query+info-example-simple',
1107 "action=query&prop=info&inprop=protection&titles={$mp}"
1108 => 'apihelp-query+info-example-protection',
1112 public function getHelpUrls() {
1113 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Info';
1117 /** @deprecated class alias since 1.43 */
1118 class_alias( ApiQueryInfo::class, 'ApiQueryInfo' );