Merge "Add SPARQL client to core"
[lhc/web/wiklou.git] / includes / api / ApiQueryInfo.php
1 <?php
2 /**
3 * Copyright © 2006 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
4 *
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.
9 *
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.
14 *
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
19 *
20 * @file
21 */
22 use MediaWiki\MediaWikiServices;
23 use MediaWiki\Linker\LinkTarget;
24
25 /**
26 * A query module to show basic page information.
27 *
28 * @ingroup API
29 */
30 class ApiQueryInfo extends ApiQueryBase {
31
32 private $fld_protection = false, $fld_talkid = false,
33 $fld_subjectid = false, $fld_url = false,
34 $fld_readable = false, $fld_watched = false,
35 $fld_watchers = false, $fld_visitingwatchers = false,
36 $fld_notificationtimestamp = false,
37 $fld_preload = false, $fld_displaytitle = false;
38
39 private $params;
40
41 /** @var Title[] */
42 private $titles;
43 /** @var Title[] */
44 private $missing;
45 /** @var Title[] */
46 private $everything;
47
48 private $pageRestrictions, $pageIsRedir, $pageIsNew, $pageTouched,
49 $pageLatest, $pageLength;
50
51 private $protections, $restrictionTypes, $watched, $watchers, $visitingwatchers,
52 $notificationtimestamps, $talkids, $subjectids, $displaytitles;
53 private $showZeroWatchers = false;
54
55 private $tokenFunctions;
56
57 private $countTestedActions = 0;
58
59 public function __construct( ApiQuery $query, $moduleName ) {
60 parent::__construct( $query, $moduleName, 'in' );
61 }
62
63 /**
64 * @param ApiPageSet $pageSet
65 * @return void
66 */
67 public function requestExtraData( $pageSet ) {
68 $pageSet->requestField( 'page_restrictions' );
69 // If the pageset is resolving redirects we won't get page_is_redirect.
70 // But we can't know for sure until the pageset is executed (revids may
71 // turn it off), so request it unconditionally.
72 $pageSet->requestField( 'page_is_redirect' );
73 $pageSet->requestField( 'page_is_new' );
74 $config = $this->getConfig();
75 $pageSet->requestField( 'page_touched' );
76 $pageSet->requestField( 'page_latest' );
77 $pageSet->requestField( 'page_len' );
78 if ( $config->get( 'ContentHandlerUseDB' ) ) {
79 $pageSet->requestField( 'page_content_model' );
80 }
81 if ( $config->get( 'PageLanguageUseDB' ) ) {
82 $pageSet->requestField( 'page_lang' );
83 }
84 }
85
86 /**
87 * Get an array mapping token names to their handler functions.
88 * The prototype for a token function is func($pageid, $title)
89 * it should return a token or false (permission denied)
90 * @deprecated since 1.24
91 * @return array [ tokenname => function ]
92 */
93 protected function getTokenFunctions() {
94 // Don't call the hooks twice
95 if ( isset( $this->tokenFunctions ) ) {
96 return $this->tokenFunctions;
97 }
98
99 // If we're in a mode that breaks the same-origin policy, no tokens can
100 // be obtained
101 if ( $this->lacksSameOriginSecurity() ) {
102 return [];
103 }
104
105 $this->tokenFunctions = [
106 'edit' => [ self::class, 'getEditToken' ],
107 'delete' => [ self::class, 'getDeleteToken' ],
108 'protect' => [ self::class, 'getProtectToken' ],
109 'move' => [ self::class, 'getMoveToken' ],
110 'block' => [ self::class, 'getBlockToken' ],
111 'unblock' => [ self::class, 'getUnblockToken' ],
112 'email' => [ self::class, 'getEmailToken' ],
113 'import' => [ self::class, 'getImportToken' ],
114 'watch' => [ self::class, 'getWatchToken' ],
115 ];
116 Hooks::run( 'APIQueryInfoTokens', [ &$this->tokenFunctions ] );
117
118 return $this->tokenFunctions;
119 }
120
121 static protected $cachedTokens = [];
122
123 /**
124 * @deprecated since 1.24
125 */
126 public static function resetTokenCache() {
127 self::$cachedTokens = [];
128 }
129
130 /**
131 * @deprecated since 1.24
132 */
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 ( !$wgUser->isAllowed( 'edit' ) ) {
139 return false;
140 }
141
142 // The token is always the same, let's exploit that
143 if ( !isset( self::$cachedTokens['edit'] ) ) {
144 self::$cachedTokens['edit'] = $wgUser->getEditToken();
145 }
146
147 return self::$cachedTokens['edit'];
148 }
149
150 /**
151 * @deprecated since 1.24
152 */
153 public static function getDeleteToken( $pageid, $title ) {
154 global $wgUser;
155 if ( !$wgUser->isAllowed( 'delete' ) ) {
156 return false;
157 }
158
159 // The token is always the same, let's exploit that
160 if ( !isset( self::$cachedTokens['delete'] ) ) {
161 self::$cachedTokens['delete'] = $wgUser->getEditToken();
162 }
163
164 return self::$cachedTokens['delete'];
165 }
166
167 /**
168 * @deprecated since 1.24
169 */
170 public static function getProtectToken( $pageid, $title ) {
171 global $wgUser;
172 if ( !$wgUser->isAllowed( 'protect' ) ) {
173 return false;
174 }
175
176 // The token is always the same, let's exploit that
177 if ( !isset( self::$cachedTokens['protect'] ) ) {
178 self::$cachedTokens['protect'] = $wgUser->getEditToken();
179 }
180
181 return self::$cachedTokens['protect'];
182 }
183
184 /**
185 * @deprecated since 1.24
186 */
187 public static function getMoveToken( $pageid, $title ) {
188 global $wgUser;
189 if ( !$wgUser->isAllowed( 'move' ) ) {
190 return false;
191 }
192
193 // The token is always the same, let's exploit that
194 if ( !isset( self::$cachedTokens['move'] ) ) {
195 self::$cachedTokens['move'] = $wgUser->getEditToken();
196 }
197
198 return self::$cachedTokens['move'];
199 }
200
201 /**
202 * @deprecated since 1.24
203 */
204 public static function getBlockToken( $pageid, $title ) {
205 global $wgUser;
206 if ( !$wgUser->isAllowed( 'block' ) ) {
207 return false;
208 }
209
210 // The token is always the same, let's exploit that
211 if ( !isset( self::$cachedTokens['block'] ) ) {
212 self::$cachedTokens['block'] = $wgUser->getEditToken();
213 }
214
215 return self::$cachedTokens['block'];
216 }
217
218 /**
219 * @deprecated since 1.24
220 */
221 public static function getUnblockToken( $pageid, $title ) {
222 // Currently, this is exactly the same as the block token
223 return self::getBlockToken( $pageid, $title );
224 }
225
226 /**
227 * @deprecated since 1.24
228 */
229 public static function getEmailToken( $pageid, $title ) {
230 global $wgUser;
231 if ( !$wgUser->canSendEmail() || $wgUser->isBlockedFromEmailuser() ) {
232 return false;
233 }
234
235 // The token is always the same, let's exploit that
236 if ( !isset( self::$cachedTokens['email'] ) ) {
237 self::$cachedTokens['email'] = $wgUser->getEditToken();
238 }
239
240 return self::$cachedTokens['email'];
241 }
242
243 /**
244 * @deprecated since 1.24
245 */
246 public static function getImportToken( $pageid, $title ) {
247 global $wgUser;
248 if ( !$wgUser->isAllowedAny( 'import', 'importupload' ) ) {
249 return false;
250 }
251
252 // The token is always the same, let's exploit that
253 if ( !isset( self::$cachedTokens['import'] ) ) {
254 self::$cachedTokens['import'] = $wgUser->getEditToken();
255 }
256
257 return self::$cachedTokens['import'];
258 }
259
260 /**
261 * @deprecated since 1.24
262 */
263 public static function getWatchToken( $pageid, $title ) {
264 global $wgUser;
265 if ( !$wgUser->isLoggedIn() ) {
266 return false;
267 }
268
269 // The token is always the same, let's exploit that
270 if ( !isset( self::$cachedTokens['watch'] ) ) {
271 self::$cachedTokens['watch'] = $wgUser->getEditToken( 'watch' );
272 }
273
274 return self::$cachedTokens['watch'];
275 }
276
277 /**
278 * @deprecated since 1.24
279 */
280 public static function getOptionsToken( $pageid, $title ) {
281 global $wgUser;
282 if ( !$wgUser->isLoggedIn() ) {
283 return false;
284 }
285
286 // The token is always the same, let's exploit that
287 if ( !isset( self::$cachedTokens['options'] ) ) {
288 self::$cachedTokens['options'] = $wgUser->getEditToken();
289 }
290
291 return self::$cachedTokens['options'];
292 }
293
294 public function execute() {
295 $this->params = $this->extractRequestParams();
296 if ( !is_null( $this->params['prop'] ) ) {
297 $prop = array_flip( $this->params['prop'] );
298 $this->fld_protection = isset( $prop['protection'] );
299 $this->fld_watched = isset( $prop['watched'] );
300 $this->fld_watchers = isset( $prop['watchers'] );
301 $this->fld_visitingwatchers = isset( $prop['visitingwatchers'] );
302 $this->fld_notificationtimestamp = isset( $prop['notificationtimestamp'] );
303 $this->fld_talkid = isset( $prop['talkid'] );
304 $this->fld_subjectid = isset( $prop['subjectid'] );
305 $this->fld_url = isset( $prop['url'] );
306 $this->fld_readable = isset( $prop['readable'] );
307 $this->fld_preload = isset( $prop['preload'] );
308 $this->fld_displaytitle = isset( $prop['displaytitle'] );
309 }
310
311 $pageSet = $this->getPageSet();
312 $this->titles = $pageSet->getGoodTitles();
313 $this->missing = $pageSet->getMissingTitles();
314 $this->everything = $this->titles + $this->missing;
315 $result = $this->getResult();
316
317 uasort( $this->everything, [ Title::class, 'compare' ] );
318 if ( !is_null( $this->params['continue'] ) ) {
319 // Throw away any titles we're gonna skip so they don't
320 // clutter queries
321 $cont = explode( '|', $this->params['continue'] );
322 $this->dieContinueUsageIf( count( $cont ) != 2 );
323 $conttitle = Title::makeTitleSafe( $cont[0], $cont[1] );
324 foreach ( $this->everything as $pageid => $title ) {
325 if ( Title::compare( $title, $conttitle ) >= 0 ) {
326 break;
327 }
328 unset( $this->titles[$pageid] );
329 unset( $this->missing[$pageid] );
330 unset( $this->everything[$pageid] );
331 }
332 }
333
334 $this->pageRestrictions = $pageSet->getCustomField( 'page_restrictions' );
335 // when resolving redirects, no page will have this field
336 $this->pageIsRedir = !$pageSet->isResolvingRedirects()
337 ? $pageSet->getCustomField( 'page_is_redirect' )
338 : [];
339 $this->pageIsNew = $pageSet->getCustomField( 'page_is_new' );
340
341 $this->pageTouched = $pageSet->getCustomField( 'page_touched' );
342 $this->pageLatest = $pageSet->getCustomField( 'page_latest' );
343 $this->pageLength = $pageSet->getCustomField( 'page_len' );
344
345 // Get protection info if requested
346 if ( $this->fld_protection ) {
347 $this->getProtectionInfo();
348 }
349
350 if ( $this->fld_watched || $this->fld_notificationtimestamp ) {
351 $this->getWatchedInfo();
352 }
353
354 if ( $this->fld_watchers ) {
355 $this->getWatcherInfo();
356 }
357
358 if ( $this->fld_visitingwatchers ) {
359 $this->getVisitingWatcherInfo();
360 }
361
362 // Run the talkid/subjectid query if requested
363 if ( $this->fld_talkid || $this->fld_subjectid ) {
364 $this->getTSIDs();
365 }
366
367 if ( $this->fld_displaytitle ) {
368 $this->getDisplayTitle();
369 }
370
371 /** @var Title $title */
372 foreach ( $this->everything as $pageid => $title ) {
373 $pageInfo = $this->extractPageInfo( $pageid, $title );
374 $fit = $pageInfo !== null && $result->addValue( [
375 'query',
376 'pages'
377 ], $pageid, $pageInfo );
378 if ( !$fit ) {
379 $this->setContinueEnumParameter( 'continue',
380 $title->getNamespace() . '|' .
381 $title->getText() );
382 break;
383 }
384 }
385 }
386
387 /**
388 * Get a result array with information about a title
389 * @param int $pageid Page ID (negative for missing titles)
390 * @param Title $title
391 * @return array|null
392 */
393 private function extractPageInfo( $pageid, $title ) {
394 $pageInfo = [];
395 // $title->exists() needs pageid, which is not set for all title objects
396 $titleExists = $pageid > 0;
397 $ns = $title->getNamespace();
398 $dbkey = $title->getDBkey();
399
400 $pageInfo['contentmodel'] = $title->getContentModel();
401
402 $pageLanguage = $title->getPageLanguage();
403 $pageInfo['pagelanguage'] = $pageLanguage->getCode();
404 $pageInfo['pagelanguagehtmlcode'] = $pageLanguage->getHtmlCode();
405 $pageInfo['pagelanguagedir'] = $pageLanguage->getDir();
406
407 if ( $titleExists ) {
408 $pageInfo['touched'] = wfTimestamp( TS_ISO_8601, $this->pageTouched[$pageid] );
409 $pageInfo['lastrevid'] = intval( $this->pageLatest[$pageid] );
410 $pageInfo['length'] = intval( $this->pageLength[$pageid] );
411
412 if ( isset( $this->pageIsRedir[$pageid] ) && $this->pageIsRedir[$pageid] ) {
413 $pageInfo['redirect'] = true;
414 }
415 if ( $this->pageIsNew[$pageid] ) {
416 $pageInfo['new'] = true;
417 }
418 }
419
420 if ( !is_null( $this->params['token'] ) ) {
421 $tokenFunctions = $this->getTokenFunctions();
422 $pageInfo['starttimestamp'] = wfTimestamp( TS_ISO_8601, time() );
423 foreach ( $this->params['token'] as $t ) {
424 $val = call_user_func( $tokenFunctions[$t], $pageid, $title );
425 if ( $val === false ) {
426 $this->addWarning( [ 'apiwarn-tokennotallowed', $t ] );
427 } else {
428 $pageInfo[$t . 'token'] = $val;
429 }
430 }
431 }
432
433 if ( $this->fld_protection ) {
434 $pageInfo['protection'] = [];
435 if ( isset( $this->protections[$ns][$dbkey] ) ) {
436 $pageInfo['protection'] =
437 $this->protections[$ns][$dbkey];
438 }
439 ApiResult::setIndexedTagName( $pageInfo['protection'], 'pr' );
440
441 $pageInfo['restrictiontypes'] = [];
442 if ( isset( $this->restrictionTypes[$ns][$dbkey] ) ) {
443 $pageInfo['restrictiontypes'] =
444 $this->restrictionTypes[$ns][$dbkey];
445 }
446 ApiResult::setIndexedTagName( $pageInfo['restrictiontypes'], 'rt' );
447 }
448
449 if ( $this->fld_watched && $this->watched !== null ) {
450 $pageInfo['watched'] = $this->watched[$ns][$dbkey];
451 }
452
453 if ( $this->fld_watchers ) {
454 if ( $this->watchers !== null && $this->watchers[$ns][$dbkey] !== 0 ) {
455 $pageInfo['watchers'] = $this->watchers[$ns][$dbkey];
456 } elseif ( $this->showZeroWatchers ) {
457 $pageInfo['watchers'] = 0;
458 }
459 }
460
461 if ( $this->fld_visitingwatchers ) {
462 if ( $this->visitingwatchers !== null && $this->visitingwatchers[$ns][$dbkey] !== 0 ) {
463 $pageInfo['visitingwatchers'] = $this->visitingwatchers[$ns][$dbkey];
464 } elseif ( $this->showZeroWatchers ) {
465 $pageInfo['visitingwatchers'] = 0;
466 }
467 }
468
469 if ( $this->fld_notificationtimestamp ) {
470 $pageInfo['notificationtimestamp'] = '';
471 if ( $this->notificationtimestamps[$ns][$dbkey] ) {
472 $pageInfo['notificationtimestamp'] =
473 wfTimestamp( TS_ISO_8601, $this->notificationtimestamps[$ns][$dbkey] );
474 }
475 }
476
477 if ( $this->fld_talkid && isset( $this->talkids[$ns][$dbkey] ) ) {
478 $pageInfo['talkid'] = $this->talkids[$ns][$dbkey];
479 }
480
481 if ( $this->fld_subjectid && isset( $this->subjectids[$ns][$dbkey] ) ) {
482 $pageInfo['subjectid'] = $this->subjectids[$ns][$dbkey];
483 }
484
485 if ( $this->fld_url ) {
486 $pageInfo['fullurl'] = wfExpandUrl( $title->getFullURL(), PROTO_CURRENT );
487 $pageInfo['editurl'] = wfExpandUrl( $title->getFullURL( 'action=edit' ), PROTO_CURRENT );
488 $pageInfo['canonicalurl'] = wfExpandUrl( $title->getFullURL(), PROTO_CANONICAL );
489 }
490 if ( $this->fld_readable ) {
491 $pageInfo['readable'] = $title->userCan( 'read', $this->getUser() );
492 }
493
494 if ( $this->fld_preload ) {
495 if ( $titleExists ) {
496 $pageInfo['preload'] = '';
497 } else {
498 $text = null;
499 Hooks::run( 'EditFormPreloadText', [ &$text, &$title ] );
500
501 $pageInfo['preload'] = $text;
502 }
503 }
504
505 if ( $this->fld_displaytitle ) {
506 if ( isset( $this->displaytitles[$pageid] ) ) {
507 $pageInfo['displaytitle'] = $this->displaytitles[$pageid];
508 } else {
509 $pageInfo['displaytitle'] = $title->getPrefixedText();
510 }
511 }
512
513 if ( $this->params['testactions'] ) {
514 $limit = $this->getMain()->canApiHighLimits() ? self::LIMIT_SML1 : self::LIMIT_SML2;
515 if ( $this->countTestedActions >= $limit ) {
516 return null; // force a continuation
517 }
518
519 $user = $this->getUser();
520 $pageInfo['actions'] = [];
521 foreach ( $this->params['testactions'] as $action ) {
522 $this->countTestedActions++;
523 $pageInfo['actions'][$action] = $title->userCan( $action, $user );
524 }
525 }
526
527 return $pageInfo;
528 }
529
530 /**
531 * Get information about protections and put it in $protections
532 */
533 private function getProtectionInfo() {
534 $this->protections = [];
535 $db = $this->getDB();
536
537 // Get normal protections for existing titles
538 if ( count( $this->titles ) ) {
539 $this->resetQueryParams();
540 $this->addTables( 'page_restrictions' );
541 $this->addFields( [ 'pr_page', 'pr_type', 'pr_level',
542 'pr_expiry', 'pr_cascade' ] );
543 $this->addWhereFld( 'pr_page', array_keys( $this->titles ) );
544
545 $res = $this->select( __METHOD__ );
546 foreach ( $res as $row ) {
547 /** @var Title $title */
548 $title = $this->titles[$row->pr_page];
549 $a = [
550 'type' => $row->pr_type,
551 'level' => $row->pr_level,
552 'expiry' => ApiResult::formatExpiry( $row->pr_expiry )
553 ];
554 if ( $row->pr_cascade ) {
555 $a['cascade'] = true;
556 }
557 $this->protections[$title->getNamespace()][$title->getDBkey()][] = $a;
558 }
559 // Also check old restrictions
560 foreach ( $this->titles as $pageId => $title ) {
561 if ( $this->pageRestrictions[$pageId] ) {
562 $namespace = $title->getNamespace();
563 $dbKey = $title->getDBkey();
564 $restrictions = explode( ':', trim( $this->pageRestrictions[$pageId] ) );
565 foreach ( $restrictions as $restrict ) {
566 $temp = explode( '=', trim( $restrict ) );
567 if ( count( $temp ) == 1 ) {
568 // old old format should be treated as edit/move restriction
569 $restriction = trim( $temp[0] );
570
571 if ( $restriction == '' ) {
572 continue;
573 }
574 $this->protections[$namespace][$dbKey][] = [
575 'type' => 'edit',
576 'level' => $restriction,
577 'expiry' => 'infinity',
578 ];
579 $this->protections[$namespace][$dbKey][] = [
580 'type' => 'move',
581 'level' => $restriction,
582 'expiry' => 'infinity',
583 ];
584 } else {
585 $restriction = trim( $temp[1] );
586 if ( $restriction == '' ) {
587 continue;
588 }
589 $this->protections[$namespace][$dbKey][] = [
590 'type' => $temp[0],
591 'level' => $restriction,
592 'expiry' => 'infinity',
593 ];
594 }
595 }
596 }
597 }
598 }
599
600 // Get protections for missing titles
601 if ( count( $this->missing ) ) {
602 $this->resetQueryParams();
603 $lb = new LinkBatch( $this->missing );
604 $this->addTables( 'protected_titles' );
605 $this->addFields( [ 'pt_title', 'pt_namespace', 'pt_create_perm', 'pt_expiry' ] );
606 $this->addWhere( $lb->constructSet( 'pt', $db ) );
607 $res = $this->select( __METHOD__ );
608 foreach ( $res as $row ) {
609 $this->protections[$row->pt_namespace][$row->pt_title][] = [
610 'type' => 'create',
611 'level' => $row->pt_create_perm,
612 'expiry' => ApiResult::formatExpiry( $row->pt_expiry )
613 ];
614 }
615 }
616
617 // Separate good and missing titles into files and other pages
618 // and populate $this->restrictionTypes
619 $images = $others = [];
620 foreach ( $this->everything as $title ) {
621 if ( $title->getNamespace() == NS_FILE ) {
622 $images[] = $title->getDBkey();
623 } else {
624 $others[] = $title;
625 }
626 // Applicable protection types
627 $this->restrictionTypes[$title->getNamespace()][$title->getDBkey()] =
628 array_values( $title->getRestrictionTypes() );
629 }
630
631 if ( count( $others ) ) {
632 // Non-images: check templatelinks
633 $lb = new LinkBatch( $others );
634 $this->resetQueryParams();
635 $this->addTables( [ 'page_restrictions', 'page', 'templatelinks' ] );
636 $this->addFields( [ 'pr_type', 'pr_level', 'pr_expiry',
637 'page_title', 'page_namespace',
638 'tl_title', 'tl_namespace' ] );
639 $this->addWhere( $lb->constructSet( 'tl', $db ) );
640 $this->addWhere( 'pr_page = page_id' );
641 $this->addWhere( 'pr_page = tl_from' );
642 $this->addWhereFld( 'pr_cascade', 1 );
643
644 $res = $this->select( __METHOD__ );
645 foreach ( $res as $row ) {
646 $source = Title::makeTitle( $row->page_namespace, $row->page_title );
647 $this->protections[$row->tl_namespace][$row->tl_title][] = [
648 'type' => $row->pr_type,
649 'level' => $row->pr_level,
650 'expiry' => ApiResult::formatExpiry( $row->pr_expiry ),
651 'source' => $source->getPrefixedText()
652 ];
653 }
654 }
655
656 if ( count( $images ) ) {
657 // Images: check imagelinks
658 $this->resetQueryParams();
659 $this->addTables( [ 'page_restrictions', 'page', 'imagelinks' ] );
660 $this->addFields( [ 'pr_type', 'pr_level', 'pr_expiry',
661 'page_title', 'page_namespace', 'il_to' ] );
662 $this->addWhere( 'pr_page = page_id' );
663 $this->addWhere( 'pr_page = il_from' );
664 $this->addWhereFld( 'pr_cascade', 1 );
665 $this->addWhereFld( 'il_to', $images );
666
667 $res = $this->select( __METHOD__ );
668 foreach ( $res as $row ) {
669 $source = Title::makeTitle( $row->page_namespace, $row->page_title );
670 $this->protections[NS_FILE][$row->il_to][] = [
671 'type' => $row->pr_type,
672 'level' => $row->pr_level,
673 'expiry' => ApiResult::formatExpiry( $row->pr_expiry ),
674 'source' => $source->getPrefixedText()
675 ];
676 }
677 }
678 }
679
680 /**
681 * Get talk page IDs (if requested) and subject page IDs (if requested)
682 * and put them in $talkids and $subjectids
683 */
684 private function getTSIDs() {
685 $getTitles = $this->talkids = $this->subjectids = [];
686
687 /** @var Title $t */
688 foreach ( $this->everything as $t ) {
689 if ( MWNamespace::isTalk( $t->getNamespace() ) ) {
690 if ( $this->fld_subjectid ) {
691 $getTitles[] = $t->getSubjectPage();
692 }
693 } elseif ( $this->fld_talkid ) {
694 $getTitles[] = $t->getTalkPage();
695 }
696 }
697 if ( !count( $getTitles ) ) {
698 return;
699 }
700
701 $db = $this->getDB();
702
703 // Construct a custom WHERE clause that matches
704 // all titles in $getTitles
705 $lb = new LinkBatch( $getTitles );
706 $this->resetQueryParams();
707 $this->addTables( 'page' );
708 $this->addFields( [ 'page_title', 'page_namespace', 'page_id' ] );
709 $this->addWhere( $lb->constructSet( 'page', $db ) );
710 $res = $this->select( __METHOD__ );
711 foreach ( $res as $row ) {
712 if ( MWNamespace::isTalk( $row->page_namespace ) ) {
713 $this->talkids[MWNamespace::getSubject( $row->page_namespace )][$row->page_title] =
714 intval( $row->page_id );
715 } else {
716 $this->subjectids[MWNamespace::getTalk( $row->page_namespace )][$row->page_title] =
717 intval( $row->page_id );
718 }
719 }
720 }
721
722 private function getDisplayTitle() {
723 $this->displaytitles = [];
724
725 $pageIds = array_keys( $this->titles );
726
727 if ( !count( $pageIds ) ) {
728 return;
729 }
730
731 $this->resetQueryParams();
732 $this->addTables( 'page_props' );
733 $this->addFields( [ 'pp_page', 'pp_value' ] );
734 $this->addWhereFld( 'pp_page', $pageIds );
735 $this->addWhereFld( 'pp_propname', 'displaytitle' );
736 $res = $this->select( __METHOD__ );
737
738 foreach ( $res as $row ) {
739 $this->displaytitles[$row->pp_page] = $row->pp_value;
740 }
741 }
742
743 /**
744 * Get information about watched status and put it in $this->watched
745 * and $this->notificationtimestamps
746 */
747 private function getWatchedInfo() {
748 $user = $this->getUser();
749
750 if ( $user->isAnon() || count( $this->everything ) == 0
751 || !$user->isAllowed( 'viewmywatchlist' )
752 ) {
753 return;
754 }
755
756 $this->watched = [];
757 $this->notificationtimestamps = [];
758
759 $store = MediaWikiServices::getInstance()->getWatchedItemStore();
760 $timestamps = $store->getNotificationTimestampsBatch( $user, $this->everything );
761
762 if ( $this->fld_watched ) {
763 foreach ( $timestamps as $namespaceId => $dbKeys ) {
764 $this->watched[$namespaceId] = array_map(
765 function ( $x ) {
766 return $x !== false;
767 },
768 $dbKeys
769 );
770 }
771 }
772 if ( $this->fld_notificationtimestamp ) {
773 $this->notificationtimestamps = $timestamps;
774 }
775 }
776
777 /**
778 * Get the count of watchers and put it in $this->watchers
779 */
780 private function getWatcherInfo() {
781 if ( count( $this->everything ) == 0 ) {
782 return;
783 }
784
785 $user = $this->getUser();
786 $canUnwatchedpages = $user->isAllowed( 'unwatchedpages' );
787 $unwatchedPageThreshold = $this->getConfig()->get( 'UnwatchedPageThreshold' );
788 if ( !$canUnwatchedpages && !is_int( $unwatchedPageThreshold ) ) {
789 return;
790 }
791
792 $this->showZeroWatchers = $canUnwatchedpages;
793
794 $countOptions = [];
795 if ( !$canUnwatchedpages ) {
796 $countOptions['minimumWatchers'] = $unwatchedPageThreshold;
797 }
798
799 $this->watchers = MediaWikiServices::getInstance()->getWatchedItemStore()->countWatchersMultiple(
800 $this->everything,
801 $countOptions
802 );
803 }
804
805 /**
806 * Get the count of watchers who have visited recent edits and put it in
807 * $this->visitingwatchers
808 *
809 * Based on InfoAction::pageCounts
810 */
811 private function getVisitingWatcherInfo() {
812 $config = $this->getConfig();
813 $user = $this->getUser();
814 $db = $this->getDB();
815
816 $canUnwatchedpages = $user->isAllowed( 'unwatchedpages' );
817 $unwatchedPageThreshold = $this->getConfig()->get( 'UnwatchedPageThreshold' );
818 if ( !$canUnwatchedpages && !is_int( $unwatchedPageThreshold ) ) {
819 return;
820 }
821
822 $this->showZeroWatchers = $canUnwatchedpages;
823
824 $titlesWithThresholds = [];
825 if ( $this->titles ) {
826 $lb = new LinkBatch( $this->titles );
827
828 // Fetch last edit timestamps for pages
829 $this->resetQueryParams();
830 $this->addTables( [ 'page', 'revision' ] );
831 $this->addFields( [ 'page_namespace', 'page_title', 'rev_timestamp' ] );
832 $this->addWhere( [
833 'page_latest = rev_id',
834 $lb->constructSet( 'page', $db ),
835 ] );
836 $this->addOption( 'GROUP BY', [ 'page_namespace', 'page_title' ] );
837 $timestampRes = $this->select( __METHOD__ );
838
839 $age = $config->get( 'WatchersMaxAge' );
840 $timestamps = [];
841 foreach ( $timestampRes as $row ) {
842 $revTimestamp = wfTimestamp( TS_UNIX, (int)$row->rev_timestamp );
843 $timestamps[$row->page_namespace][$row->page_title] = $revTimestamp - $age;
844 }
845 $titlesWithThresholds = array_map(
846 function ( LinkTarget $target ) use ( $timestamps ) {
847 return [
848 $target, $timestamps[$target->getNamespace()][$target->getDBkey()]
849 ];
850 },
851 $this->titles
852 );
853 }
854
855 if ( $this->missing ) {
856 $titlesWithThresholds = array_merge(
857 $titlesWithThresholds,
858 array_map(
859 function ( LinkTarget $target ) {
860 return [ $target, null ];
861 },
862 $this->missing
863 )
864 );
865 }
866 $store = MediaWikiServices::getInstance()->getWatchedItemStore();
867 $this->visitingwatchers = $store->countVisitingWatchersMultiple(
868 $titlesWithThresholds,
869 !$canUnwatchedpages ? $unwatchedPageThreshold : null
870 );
871 }
872
873 public function getCacheMode( $params ) {
874 // Other props depend on something about the current user
875 $publicProps = [
876 'protection',
877 'talkid',
878 'subjectid',
879 'url',
880 'preload',
881 'displaytitle',
882 ];
883 if ( array_diff( (array)$params['prop'], $publicProps ) ) {
884 return 'private';
885 }
886
887 // testactions also depends on the current user
888 if ( $params['testactions'] ) {
889 return 'private';
890 }
891
892 if ( !is_null( $params['token'] ) ) {
893 return 'private';
894 }
895
896 return 'public';
897 }
898
899 public function getAllowedParams() {
900 return [
901 'prop' => [
902 ApiBase::PARAM_ISMULTI => true,
903 ApiBase::PARAM_TYPE => [
904 'protection',
905 'talkid',
906 'watched', # private
907 'watchers', # private
908 'visitingwatchers', # private
909 'notificationtimestamp', # private
910 'subjectid',
911 'url',
912 'readable', # private
913 'preload',
914 'displaytitle',
915 // If you add more properties here, please consider whether they
916 // need to be added to getCacheMode()
917 ],
918 ApiBase::PARAM_HELP_MSG_PER_VALUE => [],
919 ],
920 'testactions' => [
921 ApiBase::PARAM_TYPE => 'string',
922 ApiBase::PARAM_ISMULTI => true,
923 ],
924 'token' => [
925 ApiBase::PARAM_DEPRECATED => true,
926 ApiBase::PARAM_ISMULTI => true,
927 ApiBase::PARAM_TYPE => array_keys( $this->getTokenFunctions() )
928 ],
929 'continue' => [
930 ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
931 ],
932 ];
933 }
934
935 protected function getExamplesMessages() {
936 return [
937 'action=query&prop=info&titles=Main%20Page'
938 => 'apihelp-query+info-example-simple',
939 'action=query&prop=info&inprop=protection&titles=Main%20Page'
940 => 'apihelp-query+info-example-protection',
941 ];
942 }
943
944 public function getHelpUrls() {
945 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Info';
946 }
947 }