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