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