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