Merge "RevisionStoreDbTestBase, remove redundant needsDB override"
[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, $fld_varianttitles = 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, $variantTitles;
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 $this->fld_varianttitles = isset( $prop['varianttitles'] );
310 }
311
312 $pageSet = $this->getPageSet();
313 $this->titles = $pageSet->getGoodTitles();
314 $this->missing = $pageSet->getMissingTitles();
315 $this->everything = $this->titles + $this->missing;
316 $result = $this->getResult();
317
318 uasort( $this->everything, [ Title::class, 'compare' ] );
319 if ( !is_null( $this->params['continue'] ) ) {
320 // Throw away any titles we're gonna skip so they don't
321 // clutter queries
322 $cont = explode( '|', $this->params['continue'] );
323 $this->dieContinueUsageIf( count( $cont ) != 2 );
324 $conttitle = Title::makeTitleSafe( $cont[0], $cont[1] );
325 foreach ( $this->everything as $pageid => $title ) {
326 if ( Title::compare( $title, $conttitle ) >= 0 ) {
327 break;
328 }
329 unset( $this->titles[$pageid] );
330 unset( $this->missing[$pageid] );
331 unset( $this->everything[$pageid] );
332 }
333 }
334
335 $this->pageRestrictions = $pageSet->getCustomField( 'page_restrictions' );
336 // when resolving redirects, no page will have this field
337 $this->pageIsRedir = !$pageSet->isResolvingRedirects()
338 ? $pageSet->getCustomField( 'page_is_redirect' )
339 : [];
340 $this->pageIsNew = $pageSet->getCustomField( 'page_is_new' );
341
342 $this->pageTouched = $pageSet->getCustomField( 'page_touched' );
343 $this->pageLatest = $pageSet->getCustomField( 'page_latest' );
344 $this->pageLength = $pageSet->getCustomField( 'page_len' );
345
346 // Get protection info if requested
347 if ( $this->fld_protection ) {
348 $this->getProtectionInfo();
349 }
350
351 if ( $this->fld_watched || $this->fld_notificationtimestamp ) {
352 $this->getWatchedInfo();
353 }
354
355 if ( $this->fld_watchers ) {
356 $this->getWatcherInfo();
357 }
358
359 if ( $this->fld_visitingwatchers ) {
360 $this->getVisitingWatcherInfo();
361 }
362
363 // Run the talkid/subjectid query if requested
364 if ( $this->fld_talkid || $this->fld_subjectid ) {
365 $this->getTSIDs();
366 }
367
368 if ( $this->fld_displaytitle ) {
369 $this->getDisplayTitle();
370 }
371
372 if ( $this->fld_varianttitles ) {
373 $this->getVariantTitles();
374 }
375
376 /** @var Title $title */
377 foreach ( $this->everything as $pageid => $title ) {
378 $pageInfo = $this->extractPageInfo( $pageid, $title );
379 $fit = $pageInfo !== null && $result->addValue( [
380 'query',
381 'pages'
382 ], $pageid, $pageInfo );
383 if ( !$fit ) {
384 $this->setContinueEnumParameter( 'continue',
385 $title->getNamespace() . '|' .
386 $title->getText() );
387 break;
388 }
389 }
390 }
391
392 /**
393 * Get a result array with information about a title
394 * @param int $pageid Page ID (negative for missing titles)
395 * @param Title $title
396 * @return array|null
397 */
398 private function extractPageInfo( $pageid, $title ) {
399 $pageInfo = [];
400 // $title->exists() needs pageid, which is not set for all title objects
401 $titleExists = $pageid > 0;
402 $ns = $title->getNamespace();
403 $dbkey = $title->getDBkey();
404
405 $pageInfo['contentmodel'] = $title->getContentModel();
406
407 $pageLanguage = $title->getPageLanguage();
408 $pageInfo['pagelanguage'] = $pageLanguage->getCode();
409 $pageInfo['pagelanguagehtmlcode'] = $pageLanguage->getHtmlCode();
410 $pageInfo['pagelanguagedir'] = $pageLanguage->getDir();
411
412 if ( $titleExists ) {
413 $pageInfo['touched'] = wfTimestamp( TS_ISO_8601, $this->pageTouched[$pageid] );
414 $pageInfo['lastrevid'] = intval( $this->pageLatest[$pageid] );
415 $pageInfo['length'] = intval( $this->pageLength[$pageid] );
416
417 if ( isset( $this->pageIsRedir[$pageid] ) && $this->pageIsRedir[$pageid] ) {
418 $pageInfo['redirect'] = true;
419 }
420 if ( $this->pageIsNew[$pageid] ) {
421 $pageInfo['new'] = true;
422 }
423 }
424
425 if ( !is_null( $this->params['token'] ) ) {
426 $tokenFunctions = $this->getTokenFunctions();
427 $pageInfo['starttimestamp'] = wfTimestamp( TS_ISO_8601, time() );
428 foreach ( $this->params['token'] as $t ) {
429 $val = call_user_func( $tokenFunctions[$t], $pageid, $title );
430 if ( $val === false ) {
431 $this->addWarning( [ 'apiwarn-tokennotallowed', $t ] );
432 } else {
433 $pageInfo[$t . 'token'] = $val;
434 }
435 }
436 }
437
438 if ( $this->fld_protection ) {
439 $pageInfo['protection'] = [];
440 if ( isset( $this->protections[$ns][$dbkey] ) ) {
441 $pageInfo['protection'] =
442 $this->protections[$ns][$dbkey];
443 }
444 ApiResult::setIndexedTagName( $pageInfo['protection'], 'pr' );
445
446 $pageInfo['restrictiontypes'] = [];
447 if ( isset( $this->restrictionTypes[$ns][$dbkey] ) ) {
448 $pageInfo['restrictiontypes'] =
449 $this->restrictionTypes[$ns][$dbkey];
450 }
451 ApiResult::setIndexedTagName( $pageInfo['restrictiontypes'], 'rt' );
452 }
453
454 if ( $this->fld_watched && $this->watched !== null ) {
455 $pageInfo['watched'] = $this->watched[$ns][$dbkey];
456 }
457
458 if ( $this->fld_watchers ) {
459 if ( $this->watchers !== null && $this->watchers[$ns][$dbkey] !== 0 ) {
460 $pageInfo['watchers'] = $this->watchers[$ns][$dbkey];
461 } elseif ( $this->showZeroWatchers ) {
462 $pageInfo['watchers'] = 0;
463 }
464 }
465
466 if ( $this->fld_visitingwatchers ) {
467 if ( $this->visitingwatchers !== null && $this->visitingwatchers[$ns][$dbkey] !== 0 ) {
468 $pageInfo['visitingwatchers'] = $this->visitingwatchers[$ns][$dbkey];
469 } elseif ( $this->showZeroWatchers ) {
470 $pageInfo['visitingwatchers'] = 0;
471 }
472 }
473
474 if ( $this->fld_notificationtimestamp ) {
475 $pageInfo['notificationtimestamp'] = '';
476 if ( $this->notificationtimestamps[$ns][$dbkey] ) {
477 $pageInfo['notificationtimestamp'] =
478 wfTimestamp( TS_ISO_8601, $this->notificationtimestamps[$ns][$dbkey] );
479 }
480 }
481
482 if ( $this->fld_talkid && isset( $this->talkids[$ns][$dbkey] ) ) {
483 $pageInfo['talkid'] = $this->talkids[$ns][$dbkey];
484 }
485
486 if ( $this->fld_subjectid && isset( $this->subjectids[$ns][$dbkey] ) ) {
487 $pageInfo['subjectid'] = $this->subjectids[$ns][$dbkey];
488 }
489
490 if ( $this->fld_url ) {
491 $pageInfo['fullurl'] = wfExpandUrl( $title->getFullURL(), PROTO_CURRENT );
492 $pageInfo['editurl'] = wfExpandUrl( $title->getFullURL( 'action=edit' ), PROTO_CURRENT );
493 $pageInfo['canonicalurl'] = wfExpandUrl( $title->getFullURL(), PROTO_CANONICAL );
494 }
495 if ( $this->fld_readable ) {
496 $pageInfo['readable'] = $title->userCan( 'read', $this->getUser() );
497 }
498
499 if ( $this->fld_preload ) {
500 if ( $titleExists ) {
501 $pageInfo['preload'] = '';
502 } else {
503 $text = null;
504 Hooks::run( 'EditFormPreloadText', [ &$text, &$title ] );
505
506 $pageInfo['preload'] = $text;
507 }
508 }
509
510 if ( $this->fld_displaytitle ) {
511 if ( isset( $this->displaytitles[$pageid] ) ) {
512 $pageInfo['displaytitle'] = $this->displaytitles[$pageid];
513 } else {
514 $pageInfo['displaytitle'] = $title->getPrefixedText();
515 }
516 }
517
518 if ( $this->fld_varianttitles ) {
519 if ( isset( $this->variantTitles[$pageid] ) ) {
520 $pageInfo['varianttitles'] = $this->variantTitles[$pageid];
521 }
522 }
523
524 if ( $this->params['testactions'] ) {
525 $limit = $this->getMain()->canApiHighLimits() ? self::LIMIT_SML2 : self::LIMIT_SML1;
526 if ( $this->countTestedActions >= $limit ) {
527 return null; // force a continuation
528 }
529
530 $user = $this->getUser();
531 $pageInfo['actions'] = [];
532 foreach ( $this->params['testactions'] as $action ) {
533 $this->countTestedActions++;
534 $pageInfo['actions'][$action] = $title->userCan( $action, $user );
535 }
536 }
537
538 return $pageInfo;
539 }
540
541 /**
542 * Get information about protections and put it in $protections
543 */
544 private function getProtectionInfo() {
545 $this->protections = [];
546 $db = $this->getDB();
547
548 // Get normal protections for existing titles
549 if ( count( $this->titles ) ) {
550 $this->resetQueryParams();
551 $this->addTables( 'page_restrictions' );
552 $this->addFields( [ 'pr_page', 'pr_type', 'pr_level',
553 'pr_expiry', 'pr_cascade' ] );
554 $this->addWhereFld( 'pr_page', array_keys( $this->titles ) );
555
556 $res = $this->select( __METHOD__ );
557 foreach ( $res as $row ) {
558 /** @var Title $title */
559 $title = $this->titles[$row->pr_page];
560 $a = [
561 'type' => $row->pr_type,
562 'level' => $row->pr_level,
563 'expiry' => ApiResult::formatExpiry( $row->pr_expiry )
564 ];
565 if ( $row->pr_cascade ) {
566 $a['cascade'] = true;
567 }
568 $this->protections[$title->getNamespace()][$title->getDBkey()][] = $a;
569 }
570 // Also check old restrictions
571 foreach ( $this->titles as $pageId => $title ) {
572 if ( $this->pageRestrictions[$pageId] ) {
573 $namespace = $title->getNamespace();
574 $dbKey = $title->getDBkey();
575 $restrictions = explode( ':', trim( $this->pageRestrictions[$pageId] ) );
576 foreach ( $restrictions as $restrict ) {
577 $temp = explode( '=', trim( $restrict ) );
578 if ( count( $temp ) == 1 ) {
579 // old old format should be treated as edit/move restriction
580 $restriction = trim( $temp[0] );
581
582 if ( $restriction == '' ) {
583 continue;
584 }
585 $this->protections[$namespace][$dbKey][] = [
586 'type' => 'edit',
587 'level' => $restriction,
588 'expiry' => 'infinity',
589 ];
590 $this->protections[$namespace][$dbKey][] = [
591 'type' => 'move',
592 'level' => $restriction,
593 'expiry' => 'infinity',
594 ];
595 } else {
596 $restriction = trim( $temp[1] );
597 if ( $restriction == '' ) {
598 continue;
599 }
600 $this->protections[$namespace][$dbKey][] = [
601 'type' => $temp[0],
602 'level' => $restriction,
603 'expiry' => 'infinity',
604 ];
605 }
606 }
607 }
608 }
609 }
610
611 // Get protections for missing titles
612 if ( count( $this->missing ) ) {
613 $this->resetQueryParams();
614 $lb = new LinkBatch( $this->missing );
615 $this->addTables( 'protected_titles' );
616 $this->addFields( [ 'pt_title', 'pt_namespace', 'pt_create_perm', 'pt_expiry' ] );
617 $this->addWhere( $lb->constructSet( 'pt', $db ) );
618 $res = $this->select( __METHOD__ );
619 foreach ( $res as $row ) {
620 $this->protections[$row->pt_namespace][$row->pt_title][] = [
621 'type' => 'create',
622 'level' => $row->pt_create_perm,
623 'expiry' => ApiResult::formatExpiry( $row->pt_expiry )
624 ];
625 }
626 }
627
628 // Separate good and missing titles into files and other pages
629 // and populate $this->restrictionTypes
630 $images = $others = [];
631 foreach ( $this->everything as $title ) {
632 if ( $title->getNamespace() == NS_FILE ) {
633 $images[] = $title->getDBkey();
634 } else {
635 $others[] = $title;
636 }
637 // Applicable protection types
638 $this->restrictionTypes[$title->getNamespace()][$title->getDBkey()] =
639 array_values( $title->getRestrictionTypes() );
640 }
641
642 if ( count( $others ) ) {
643 // Non-images: check templatelinks
644 $lb = new LinkBatch( $others );
645 $this->resetQueryParams();
646 $this->addTables( [ 'page_restrictions', 'page', 'templatelinks' ] );
647 $this->addFields( [ 'pr_type', 'pr_level', 'pr_expiry',
648 'page_title', 'page_namespace',
649 'tl_title', 'tl_namespace' ] );
650 $this->addWhere( $lb->constructSet( 'tl', $db ) );
651 $this->addWhere( 'pr_page = page_id' );
652 $this->addWhere( 'pr_page = tl_from' );
653 $this->addWhereFld( 'pr_cascade', 1 );
654
655 $res = $this->select( __METHOD__ );
656 foreach ( $res as $row ) {
657 $source = Title::makeTitle( $row->page_namespace, $row->page_title );
658 $this->protections[$row->tl_namespace][$row->tl_title][] = [
659 'type' => $row->pr_type,
660 'level' => $row->pr_level,
661 'expiry' => ApiResult::formatExpiry( $row->pr_expiry ),
662 'source' => $source->getPrefixedText()
663 ];
664 }
665 }
666
667 if ( count( $images ) ) {
668 // Images: check imagelinks
669 $this->resetQueryParams();
670 $this->addTables( [ 'page_restrictions', 'page', 'imagelinks' ] );
671 $this->addFields( [ 'pr_type', 'pr_level', 'pr_expiry',
672 'page_title', 'page_namespace', 'il_to' ] );
673 $this->addWhere( 'pr_page = page_id' );
674 $this->addWhere( 'pr_page = il_from' );
675 $this->addWhereFld( 'pr_cascade', 1 );
676 $this->addWhereFld( 'il_to', $images );
677
678 $res = $this->select( __METHOD__ );
679 foreach ( $res as $row ) {
680 $source = Title::makeTitle( $row->page_namespace, $row->page_title );
681 $this->protections[NS_FILE][$row->il_to][] = [
682 'type' => $row->pr_type,
683 'level' => $row->pr_level,
684 'expiry' => ApiResult::formatExpiry( $row->pr_expiry ),
685 'source' => $source->getPrefixedText()
686 ];
687 }
688 }
689 }
690
691 /**
692 * Get talk page IDs (if requested) and subject page IDs (if requested)
693 * and put them in $talkids and $subjectids
694 */
695 private function getTSIDs() {
696 $getTitles = $this->talkids = $this->subjectids = [];
697
698 /** @var Title $t */
699 foreach ( $this->everything as $t ) {
700 if ( MWNamespace::isTalk( $t->getNamespace() ) ) {
701 if ( $this->fld_subjectid ) {
702 $getTitles[] = $t->getSubjectPage();
703 }
704 } elseif ( $this->fld_talkid ) {
705 $getTitles[] = $t->getTalkPage();
706 }
707 }
708 if ( !count( $getTitles ) ) {
709 return;
710 }
711
712 $db = $this->getDB();
713
714 // Construct a custom WHERE clause that matches
715 // all titles in $getTitles
716 $lb = new LinkBatch( $getTitles );
717 $this->resetQueryParams();
718 $this->addTables( 'page' );
719 $this->addFields( [ 'page_title', 'page_namespace', 'page_id' ] );
720 $this->addWhere( $lb->constructSet( 'page', $db ) );
721 $res = $this->select( __METHOD__ );
722 foreach ( $res as $row ) {
723 if ( MWNamespace::isTalk( $row->page_namespace ) ) {
724 $this->talkids[MWNamespace::getSubject( $row->page_namespace )][$row->page_title] =
725 intval( $row->page_id );
726 } else {
727 $this->subjectids[MWNamespace::getTalk( $row->page_namespace )][$row->page_title] =
728 intval( $row->page_id );
729 }
730 }
731 }
732
733 private function getDisplayTitle() {
734 $this->displaytitles = [];
735
736 $pageIds = array_keys( $this->titles );
737
738 if ( !count( $pageIds ) ) {
739 return;
740 }
741
742 $this->resetQueryParams();
743 $this->addTables( 'page_props' );
744 $this->addFields( [ 'pp_page', 'pp_value' ] );
745 $this->addWhereFld( 'pp_page', $pageIds );
746 $this->addWhereFld( 'pp_propname', 'displaytitle' );
747 $res = $this->select( __METHOD__ );
748
749 foreach ( $res as $row ) {
750 $this->displaytitles[$row->pp_page] = $row->pp_value;
751 }
752 }
753
754 private function getVariantTitles() {
755 if ( !count( $this->titles ) ) {
756 return;
757 }
758 $this->variantTitles = [];
759 foreach ( $this->titles as $pageId => $t ) {
760 $this->variantTitles[$pageId] = isset( $this->displaytitles[$pageId] )
761 ? $this->getAllVariants( $this->displaytitles[$pageId] )
762 : $this->getAllVariants( $t->getText(), $t->getNamespace() );
763 }
764 }
765
766 private function getAllVariants( $text, $ns = NS_MAIN ) {
767 $result = [];
768 $contLang = MediaWikiServices::getInstance()->getContentLanguage();
769 foreach ( $contLang->getVariants() as $variant ) {
770 $convertTitle = $contLang->autoConvert( $text, $variant );
771 if ( $ns !== NS_MAIN ) {
772 $convertNs = $contLang->convertNamespace( $ns, $variant );
773 $convertTitle = $convertNs . ':' . $convertTitle;
774 }
775 $result[$variant] = $convertTitle;
776 }
777 return $result;
778 }
779
780 /**
781 * Get information about watched status and put it in $this->watched
782 * and $this->notificationtimestamps
783 */
784 private function getWatchedInfo() {
785 $user = $this->getUser();
786
787 if ( $user->isAnon() || count( $this->everything ) == 0
788 || !$user->isAllowed( 'viewmywatchlist' )
789 ) {
790 return;
791 }
792
793 $this->watched = [];
794 $this->notificationtimestamps = [];
795
796 $store = MediaWikiServices::getInstance()->getWatchedItemStore();
797 $timestamps = $store->getNotificationTimestampsBatch( $user, $this->everything );
798
799 if ( $this->fld_watched ) {
800 foreach ( $timestamps as $namespaceId => $dbKeys ) {
801 $this->watched[$namespaceId] = array_map(
802 function ( $x ) {
803 return $x !== false;
804 },
805 $dbKeys
806 );
807 }
808 }
809 if ( $this->fld_notificationtimestamp ) {
810 $this->notificationtimestamps = $timestamps;
811 }
812 }
813
814 /**
815 * Get the count of watchers and put it in $this->watchers
816 */
817 private function getWatcherInfo() {
818 if ( count( $this->everything ) == 0 ) {
819 return;
820 }
821
822 $user = $this->getUser();
823 $canUnwatchedpages = $user->isAllowed( 'unwatchedpages' );
824 $unwatchedPageThreshold = $this->getConfig()->get( 'UnwatchedPageThreshold' );
825 if ( !$canUnwatchedpages && !is_int( $unwatchedPageThreshold ) ) {
826 return;
827 }
828
829 $this->showZeroWatchers = $canUnwatchedpages;
830
831 $countOptions = [];
832 if ( !$canUnwatchedpages ) {
833 $countOptions['minimumWatchers'] = $unwatchedPageThreshold;
834 }
835
836 $this->watchers = MediaWikiServices::getInstance()->getWatchedItemStore()->countWatchersMultiple(
837 $this->everything,
838 $countOptions
839 );
840 }
841
842 /**
843 * Get the count of watchers who have visited recent edits and put it in
844 * $this->visitingwatchers
845 *
846 * Based on InfoAction::pageCounts
847 */
848 private function getVisitingWatcherInfo() {
849 $config = $this->getConfig();
850 $user = $this->getUser();
851 $db = $this->getDB();
852
853 $canUnwatchedpages = $user->isAllowed( 'unwatchedpages' );
854 $unwatchedPageThreshold = $this->getConfig()->get( 'UnwatchedPageThreshold' );
855 if ( !$canUnwatchedpages && !is_int( $unwatchedPageThreshold ) ) {
856 return;
857 }
858
859 $this->showZeroWatchers = $canUnwatchedpages;
860
861 $titlesWithThresholds = [];
862 if ( $this->titles ) {
863 $lb = new LinkBatch( $this->titles );
864
865 // Fetch last edit timestamps for pages
866 $this->resetQueryParams();
867 $this->addTables( [ 'page', 'revision' ] );
868 $this->addFields( [ 'page_namespace', 'page_title', 'rev_timestamp' ] );
869 $this->addWhere( [
870 'page_latest = rev_id',
871 $lb->constructSet( 'page', $db ),
872 ] );
873 $this->addOption( 'GROUP BY', [ 'page_namespace', 'page_title' ] );
874 $timestampRes = $this->select( __METHOD__ );
875
876 $age = $config->get( 'WatchersMaxAge' );
877 $timestamps = [];
878 foreach ( $timestampRes as $row ) {
879 $revTimestamp = wfTimestamp( TS_UNIX, (int)$row->rev_timestamp );
880 $timestamps[$row->page_namespace][$row->page_title] = $revTimestamp - $age;
881 }
882 $titlesWithThresholds = array_map(
883 function ( LinkTarget $target ) use ( $timestamps ) {
884 return [
885 $target, $timestamps[$target->getNamespace()][$target->getDBkey()]
886 ];
887 },
888 $this->titles
889 );
890 }
891
892 if ( $this->missing ) {
893 $titlesWithThresholds = array_merge(
894 $titlesWithThresholds,
895 array_map(
896 function ( LinkTarget $target ) {
897 return [ $target, null ];
898 },
899 $this->missing
900 )
901 );
902 }
903 $store = MediaWikiServices::getInstance()->getWatchedItemStore();
904 $this->visitingwatchers = $store->countVisitingWatchersMultiple(
905 $titlesWithThresholds,
906 !$canUnwatchedpages ? $unwatchedPageThreshold : null
907 );
908 }
909
910 public function getCacheMode( $params ) {
911 // Other props depend on something about the current user
912 $publicProps = [
913 'protection',
914 'talkid',
915 'subjectid',
916 'url',
917 'preload',
918 'displaytitle',
919 'varianttitles',
920 ];
921 if ( array_diff( (array)$params['prop'], $publicProps ) ) {
922 return 'private';
923 }
924
925 // testactions also depends on the current user
926 if ( $params['testactions'] ) {
927 return 'private';
928 }
929
930 if ( !is_null( $params['token'] ) ) {
931 return 'private';
932 }
933
934 return 'public';
935 }
936
937 public function getAllowedParams() {
938 return [
939 'prop' => [
940 ApiBase::PARAM_ISMULTI => true,
941 ApiBase::PARAM_TYPE => [
942 'protection',
943 'talkid',
944 'watched', # private
945 'watchers', # private
946 'visitingwatchers', # private
947 'notificationtimestamp', # private
948 'subjectid',
949 'url',
950 'readable', # private
951 'preload',
952 'displaytitle',
953 'varianttitles',
954 // If you add more properties here, please consider whether they
955 // need to be added to getCacheMode()
956 ],
957 ApiBase::PARAM_HELP_MSG_PER_VALUE => [],
958 ],
959 'testactions' => [
960 ApiBase::PARAM_TYPE => 'string',
961 ApiBase::PARAM_ISMULTI => true,
962 ],
963 'token' => [
964 ApiBase::PARAM_DEPRECATED => true,
965 ApiBase::PARAM_ISMULTI => true,
966 ApiBase::PARAM_TYPE => array_keys( $this->getTokenFunctions() )
967 ],
968 'continue' => [
969 ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
970 ],
971 ];
972 }
973
974 protected function getExamplesMessages() {
975 return [
976 'action=query&prop=info&titles=Main%20Page'
977 => 'apihelp-query+info-example-simple',
978 'action=query&prop=info&inprop=protection&titles=Main%20Page'
979 => 'apihelp-query+info-example-protection',
980 ];
981 }
982
983 public function getHelpUrls() {
984 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Info';
985 }
986 }