ApiPageSet: Follow RedirectSpecialArticle redirects
[lhc/web/wiklou.git] / includes / api / ApiPageSet.php
1 <?php
2 /**
3 *
4 *
5 * Created on Sep 24, 2006
6 *
7 * Copyright © 2006, 2013 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * http://www.gnu.org/copyleft/gpl.html
23 *
24 * @file
25 */
26 use MediaWiki\MediaWikiServices;
27 use Wikimedia\Rdbms\ResultWrapper;
28
29 /**
30 * This class contains a list of pages that the client has requested.
31 * Initially, when the client passes in titles=, pageids=, or revisions=
32 * parameter, an instance of the ApiPageSet class will normalize titles,
33 * determine if the pages/revisions exist, and prefetch any additional page
34 * data requested.
35 *
36 * When a generator is used, the result of the generator will become the input
37 * for the second instance of this class, and all subsequent actions will use
38 * the second instance for all their work.
39 *
40 * @ingroup API
41 * @since 1.21 derives from ApiBase instead of ApiQueryBase
42 */
43 class ApiPageSet extends ApiBase {
44 /**
45 * Constructor flag: The new instance of ApiPageSet will ignore the 'generator=' parameter
46 * @since 1.21
47 */
48 const DISABLE_GENERATORS = 1;
49
50 private $mDbSource;
51 private $mParams;
52 private $mResolveRedirects;
53 private $mConvertTitles;
54 private $mAllowGenerator;
55
56 private $mAllPages = []; // [ns][dbkey] => page_id or negative when missing
57 private $mTitles = [];
58 private $mGoodAndMissingPages = []; // [ns][dbkey] => page_id or negative when missing
59 private $mGoodPages = []; // [ns][dbkey] => page_id
60 private $mGoodTitles = [];
61 private $mMissingPages = []; // [ns][dbkey] => fake page_id
62 private $mMissingTitles = [];
63 /** @var array [fake_page_id] => [ 'title' => $title, 'invalidreason' => $reason ] */
64 private $mInvalidTitles = [];
65 private $mMissingPageIDs = [];
66 private $mRedirectTitles = [];
67 private $mSpecialTitles = [];
68 private $mAllSpecials = []; // separate from mAllPages to avoid breaking getAllTitlesByNamespace()
69 private $mNormalizedTitles = [];
70 private $mInterwikiTitles = [];
71 /** @var Title[] */
72 private $mPendingRedirectIDs = [];
73 private $mPendingRedirectSpecialPages = []; // [dbkey] => [ Title $from, Title $to ]
74 private $mResolvedRedirectTitles = [];
75 private $mConvertedTitles = [];
76 private $mGoodRevIDs = [];
77 private $mLiveRevIDs = [];
78 private $mDeletedRevIDs = [];
79 private $mMissingRevIDs = [];
80 private $mGeneratorData = []; // [ns][dbkey] => data array
81 private $mFakePageId = -1;
82 private $mCacheMode = 'public';
83 private $mRequestedPageFields = [];
84 /** @var int */
85 private $mDefaultNamespace = NS_MAIN;
86 /** @var callable|null */
87 private $mRedirectMergePolicy;
88
89 /**
90 * Add all items from $values into the result
91 * @param array $result Output
92 * @param array $values Values to add
93 * @param string[] $flags The names of boolean flags to mark this element
94 * @param string $name If given, name of the value
95 */
96 private static function addValues( array &$result, $values, $flags = [], $name = null ) {
97 foreach ( $values as $val ) {
98 if ( $val instanceof Title ) {
99 $v = [];
100 ApiQueryBase::addTitleInfo( $v, $val );
101 } elseif ( $name !== null ) {
102 $v = [ $name => $val ];
103 } else {
104 $v = $val;
105 }
106 foreach ( $flags as $flag ) {
107 $v[$flag] = true;
108 }
109 $result[] = $v;
110 }
111 }
112
113 /**
114 * @param ApiBase $dbSource Module implementing getDB().
115 * Allows PageSet to reuse existing db connection from the shared state like ApiQuery.
116 * @param int $flags Zero or more flags like DISABLE_GENERATORS
117 * @param int $defaultNamespace The namespace to use if none is specified by a prefix.
118 * @since 1.21 accepts $flags instead of two boolean values
119 */
120 public function __construct( ApiBase $dbSource, $flags = 0, $defaultNamespace = NS_MAIN ) {
121 parent::__construct( $dbSource->getMain(), $dbSource->getModuleName() );
122 $this->mDbSource = $dbSource;
123 $this->mAllowGenerator = ( $flags & ApiPageSet::DISABLE_GENERATORS ) == 0;
124 $this->mDefaultNamespace = $defaultNamespace;
125
126 $this->mParams = $this->extractRequestParams();
127 $this->mResolveRedirects = $this->mParams['redirects'];
128 $this->mConvertTitles = $this->mParams['converttitles'];
129 }
130
131 /**
132 * In case execute() is not called, call this method to mark all relevant parameters as used
133 * This prevents unused parameters from being reported as warnings
134 */
135 public function executeDryRun() {
136 $this->executeInternal( true );
137 }
138
139 /**
140 * Populate the PageSet from the request parameters.
141 */
142 public function execute() {
143 $this->executeInternal( false );
144 }
145
146 /**
147 * Populate the PageSet from the request parameters.
148 * @param bool $isDryRun If true, instantiates generator, but only to mark
149 * relevant parameters as used
150 */
151 private function executeInternal( $isDryRun ) {
152 $generatorName = $this->mAllowGenerator ? $this->mParams['generator'] : null;
153 if ( isset( $generatorName ) ) {
154 $dbSource = $this->mDbSource;
155 if ( !$dbSource instanceof ApiQuery ) {
156 // If the parent container of this pageset is not ApiQuery, we must create it to run generator
157 $dbSource = $this->getMain()->getModuleManager()->getModule( 'query' );
158 }
159 $generator = $dbSource->getModuleManager()->getModule( $generatorName, null, true );
160 if ( $generator === null ) {
161 $this->dieWithError( [ 'apierror-badgenerator-unknown', $generatorName ], 'badgenerator' );
162 }
163 if ( !$generator instanceof ApiQueryGeneratorBase ) {
164 $this->dieWithError( [ 'apierror-badgenerator-notgenerator', $generatorName ], 'badgenerator' );
165 }
166 // Create a temporary pageset to store generator's output,
167 // add any additional fields generator may need, and execute pageset to populate titles/pageids
168 $tmpPageSet = new ApiPageSet( $dbSource, ApiPageSet::DISABLE_GENERATORS );
169 $generator->setGeneratorMode( $tmpPageSet );
170 $this->mCacheMode = $generator->getCacheMode( $generator->extractRequestParams() );
171
172 if ( !$isDryRun ) {
173 $generator->requestExtraData( $tmpPageSet );
174 }
175 $tmpPageSet->executeInternal( $isDryRun );
176
177 // populate this pageset with the generator output
178 if ( !$isDryRun ) {
179 $generator->executeGenerator( $this );
180
181 // Avoid PHP 7.1 warning of passing $this by reference
182 $apiModule = $this;
183 Hooks::run( 'APIQueryGeneratorAfterExecute', [ &$generator, &$apiModule ] );
184 } else {
185 // Prevent warnings from being reported on these parameters
186 $main = $this->getMain();
187 foreach ( $generator->extractRequestParams() as $paramName => $param ) {
188 $main->markParamsUsed( $generator->encodeParamName( $paramName ) );
189 }
190 }
191
192 if ( !$isDryRun ) {
193 $this->resolvePendingRedirects();
194 }
195 } else {
196 // Only one of the titles/pageids/revids is allowed at the same time
197 $dataSource = null;
198 if ( isset( $this->mParams['titles'] ) ) {
199 $dataSource = 'titles';
200 }
201 if ( isset( $this->mParams['pageids'] ) ) {
202 if ( isset( $dataSource ) ) {
203 $this->dieWithError(
204 [
205 'apierror-invalidparammix-cannotusewith',
206 $this->encodeParamName( 'pageids' ),
207 $this->encodeParamName( $dataSource )
208 ],
209 'multisource'
210 );
211 }
212 $dataSource = 'pageids';
213 }
214 if ( isset( $this->mParams['revids'] ) ) {
215 if ( isset( $dataSource ) ) {
216 $this->dieWithError(
217 [
218 'apierror-invalidparammix-cannotusewith',
219 $this->encodeParamName( 'revids' ),
220 $this->encodeParamName( $dataSource )
221 ],
222 'multisource'
223 );
224 }
225 $dataSource = 'revids';
226 }
227
228 if ( !$isDryRun ) {
229 // Populate page information with the original user input
230 switch ( $dataSource ) {
231 case 'titles':
232 $this->initFromTitles( $this->mParams['titles'] );
233 break;
234 case 'pageids':
235 $this->initFromPageIds( $this->mParams['pageids'] );
236 break;
237 case 'revids':
238 if ( $this->mResolveRedirects ) {
239 $this->addWarning( 'apiwarn-redirectsandrevids' );
240 }
241 $this->mResolveRedirects = false;
242 $this->initFromRevIDs( $this->mParams['revids'] );
243 break;
244 default:
245 // Do nothing - some queries do not need any of the data sources.
246 break;
247 }
248 }
249 }
250 }
251
252 /**
253 * Check whether this PageSet is resolving redirects
254 * @return bool
255 */
256 public function isResolvingRedirects() {
257 return $this->mResolveRedirects;
258 }
259
260 /**
261 * Return the parameter name that is the source of data for this PageSet
262 *
263 * If multiple source parameters are specified (e.g. titles and pageids),
264 * one will be named arbitrarily.
265 *
266 * @return string|null
267 */
268 public function getDataSource() {
269 if ( $this->mAllowGenerator && isset( $this->mParams['generator'] ) ) {
270 return 'generator';
271 }
272 if ( isset( $this->mParams['titles'] ) ) {
273 return 'titles';
274 }
275 if ( isset( $this->mParams['pageids'] ) ) {
276 return 'pageids';
277 }
278 if ( isset( $this->mParams['revids'] ) ) {
279 return 'revids';
280 }
281
282 return null;
283 }
284
285 /**
286 * Request an additional field from the page table.
287 * Must be called before execute()
288 * @param string $fieldName Field name
289 */
290 public function requestField( $fieldName ) {
291 $this->mRequestedPageFields[$fieldName] = null;
292 }
293
294 /**
295 * Get the value of a custom field previously requested through
296 * requestField()
297 * @param string $fieldName Field name
298 * @return mixed Field value
299 */
300 public function getCustomField( $fieldName ) {
301 return $this->mRequestedPageFields[$fieldName];
302 }
303
304 /**
305 * Get the fields that have to be queried from the page table:
306 * the ones requested through requestField() and a few basic ones
307 * we always need
308 * @return array Array of field names
309 */
310 public function getPageTableFields() {
311 // Ensure we get minimum required fields
312 // DON'T change this order
313 $pageFlds = [
314 'page_namespace' => null,
315 'page_title' => null,
316 'page_id' => null,
317 ];
318
319 if ( $this->mResolveRedirects ) {
320 $pageFlds['page_is_redirect'] = null;
321 }
322
323 if ( $this->getConfig()->get( 'ContentHandlerUseDB' ) ) {
324 $pageFlds['page_content_model'] = null;
325 }
326
327 if ( $this->getConfig()->get( 'PageLanguageUseDB' ) ) {
328 $pageFlds['page_lang'] = null;
329 }
330
331 foreach ( LinkCache::getSelectFields() as $field ) {
332 $pageFlds[$field] = null;
333 }
334
335 $pageFlds = array_merge( $pageFlds, $this->mRequestedPageFields );
336
337 return array_keys( $pageFlds );
338 }
339
340 /**
341 * Returns an array [ns][dbkey] => page_id for all requested titles.
342 * page_id is a unique negative number in case title was not found.
343 * Invalid titles will also have negative page IDs and will be in namespace 0
344 * @return array
345 */
346 public function getAllTitlesByNamespace() {
347 return $this->mAllPages;
348 }
349
350 /**
351 * All Title objects provided.
352 * @return Title[]
353 */
354 public function getTitles() {
355 return $this->mTitles;
356 }
357
358 /**
359 * Returns the number of unique pages (not revisions) in the set.
360 * @return int
361 */
362 public function getTitleCount() {
363 return count( $this->mTitles );
364 }
365
366 /**
367 * Returns an array [ns][dbkey] => page_id for all good titles.
368 * @return array
369 */
370 public function getGoodTitlesByNamespace() {
371 return $this->mGoodPages;
372 }
373
374 /**
375 * Title objects that were found in the database.
376 * @return Title[] Array page_id (int) => Title (obj)
377 */
378 public function getGoodTitles() {
379 return $this->mGoodTitles;
380 }
381
382 /**
383 * Returns the number of found unique pages (not revisions) in the set.
384 * @return int
385 */
386 public function getGoodTitleCount() {
387 return count( $this->mGoodTitles );
388 }
389
390 /**
391 * Returns an array [ns][dbkey] => fake_page_id for all missing titles.
392 * fake_page_id is a unique negative number.
393 * @return array
394 */
395 public function getMissingTitlesByNamespace() {
396 return $this->mMissingPages;
397 }
398
399 /**
400 * Title objects that were NOT found in the database.
401 * The array's index will be negative for each item
402 * @return Title[]
403 */
404 public function getMissingTitles() {
405 return $this->mMissingTitles;
406 }
407
408 /**
409 * Returns an array [ns][dbkey] => page_id for all good and missing titles.
410 * @return array
411 */
412 public function getGoodAndMissingTitlesByNamespace() {
413 return $this->mGoodAndMissingPages;
414 }
415
416 /**
417 * Title objects for good and missing titles.
418 * @return array
419 */
420 public function getGoodAndMissingTitles() {
421 return $this->mGoodTitles + $this->mMissingTitles;
422 }
423
424 /**
425 * Titles that were deemed invalid by Title::newFromText()
426 * The array's index will be unique and negative for each item
427 * @deprecated since 1.26, use self::getInvalidTitlesAndReasons()
428 * @return string[] Array of strings (not Title objects)
429 */
430 public function getInvalidTitles() {
431 wfDeprecated( __METHOD__, '1.26' );
432 return array_map( function ( $t ) {
433 return $t['title'];
434 }, $this->mInvalidTitles );
435 }
436
437 /**
438 * Titles that were deemed invalid by Title::newFromText()
439 * The array's index will be unique and negative for each item
440 * @return array[] Array of arrays with 'title' and 'invalidreason' properties
441 */
442 public function getInvalidTitlesAndReasons() {
443 return $this->mInvalidTitles;
444 }
445
446 /**
447 * Page IDs that were not found in the database
448 * @return array Array of page IDs
449 */
450 public function getMissingPageIDs() {
451 return $this->mMissingPageIDs;
452 }
453
454 /**
455 * Get a list of redirect resolutions - maps a title to its redirect
456 * target, as an array of output-ready arrays
457 * @return Title[]
458 */
459 public function getRedirectTitles() {
460 return $this->mRedirectTitles;
461 }
462
463 /**
464 * Get a list of redirect resolutions - maps a title to its redirect
465 * target. Includes generator data for redirect source when available.
466 * @param ApiResult $result
467 * @return array Array of prefixed_title (string) => Title object
468 * @since 1.21
469 */
470 public function getRedirectTitlesAsResult( $result = null ) {
471 $values = [];
472 foreach ( $this->getRedirectTitles() as $titleStrFrom => $titleTo ) {
473 $r = [
474 'from' => strval( $titleStrFrom ),
475 'to' => $titleTo->getPrefixedText(),
476 ];
477 if ( $titleTo->hasFragment() ) {
478 $r['tofragment'] = $titleTo->getFragment();
479 }
480 if ( $titleTo->isExternal() ) {
481 $r['tointerwiki'] = $titleTo->getInterwiki();
482 }
483 if ( isset( $this->mResolvedRedirectTitles[$titleStrFrom] ) ) {
484 $titleFrom = $this->mResolvedRedirectTitles[$titleStrFrom];
485 $ns = $titleFrom->getNamespace();
486 $dbkey = $titleFrom->getDBkey();
487 if ( isset( $this->mGeneratorData[$ns][$dbkey] ) ) {
488 $r = array_merge( $this->mGeneratorData[$ns][$dbkey], $r );
489 }
490 }
491
492 $values[] = $r;
493 }
494 if ( !empty( $values ) && $result ) {
495 ApiResult::setIndexedTagName( $values, 'r' );
496 }
497
498 return $values;
499 }
500
501 /**
502 * Get a list of title normalizations - maps a title to its normalized
503 * version.
504 * @return array Array of raw_prefixed_title (string) => prefixed_title (string)
505 */
506 public function getNormalizedTitles() {
507 return $this->mNormalizedTitles;
508 }
509
510 /**
511 * Get a list of title normalizations - maps a title to its normalized
512 * version in the form of result array.
513 * @param ApiResult $result
514 * @return array Array of raw_prefixed_title (string) => prefixed_title (string)
515 * @since 1.21
516 */
517 public function getNormalizedTitlesAsResult( $result = null ) {
518 global $wgContLang;
519
520 $values = [];
521 foreach ( $this->getNormalizedTitles() as $rawTitleStr => $titleStr ) {
522 $encode = ( $wgContLang->normalize( $rawTitleStr ) !== $rawTitleStr );
523 $values[] = [
524 'fromencoded' => $encode,
525 'from' => $encode ? rawurlencode( $rawTitleStr ) : $rawTitleStr,
526 'to' => $titleStr
527 ];
528 }
529 if ( !empty( $values ) && $result ) {
530 ApiResult::setIndexedTagName( $values, 'n' );
531 }
532
533 return $values;
534 }
535
536 /**
537 * Get a list of title conversions - maps a title to its converted
538 * version.
539 * @return array Array of raw_prefixed_title (string) => prefixed_title (string)
540 */
541 public function getConvertedTitles() {
542 return $this->mConvertedTitles;
543 }
544
545 /**
546 * Get a list of title conversions - maps a title to its converted
547 * version as a result array.
548 * @param ApiResult $result
549 * @return array Array of (from, to) strings
550 * @since 1.21
551 */
552 public function getConvertedTitlesAsResult( $result = null ) {
553 $values = [];
554 foreach ( $this->getConvertedTitles() as $rawTitleStr => $titleStr ) {
555 $values[] = [
556 'from' => $rawTitleStr,
557 'to' => $titleStr
558 ];
559 }
560 if ( !empty( $values ) && $result ) {
561 ApiResult::setIndexedTagName( $values, 'c' );
562 }
563
564 return $values;
565 }
566
567 /**
568 * Get a list of interwiki titles - maps a title to its interwiki
569 * prefix.
570 * @return array Array of raw_prefixed_title (string) => interwiki_prefix (string)
571 */
572 public function getInterwikiTitles() {
573 return $this->mInterwikiTitles;
574 }
575
576 /**
577 * Get a list of interwiki titles - maps a title to its interwiki
578 * prefix as result.
579 * @param ApiResult $result
580 * @param bool $iwUrl
581 * @return array Array of raw_prefixed_title (string) => interwiki_prefix (string)
582 * @since 1.21
583 */
584 public function getInterwikiTitlesAsResult( $result = null, $iwUrl = false ) {
585 $values = [];
586 foreach ( $this->getInterwikiTitles() as $rawTitleStr => $interwikiStr ) {
587 $item = [
588 'title' => $rawTitleStr,
589 'iw' => $interwikiStr,
590 ];
591 if ( $iwUrl ) {
592 $title = Title::newFromText( $rawTitleStr );
593 $item['url'] = $title->getFullURL( '', false, PROTO_CURRENT );
594 }
595 $values[] = $item;
596 }
597 if ( !empty( $values ) && $result ) {
598 ApiResult::setIndexedTagName( $values, 'i' );
599 }
600
601 return $values;
602 }
603
604 /**
605 * Get an array of invalid/special/missing titles.
606 *
607 * @param array $invalidChecks List of types of invalid titles to include.
608 * Recognized values are:
609 * - invalidTitles: Titles and reasons from $this->getInvalidTitlesAndReasons()
610 * - special: Titles from $this->getSpecialTitles()
611 * - missingIds: ids from $this->getMissingPageIDs()
612 * - missingRevIds: ids from $this->getMissingRevisionIDs()
613 * - missingTitles: Titles from $this->getMissingTitles()
614 * - interwikiTitles: Titles from $this->getInterwikiTitlesAsResult()
615 * @return array Array suitable for inclusion in the response
616 * @since 1.23
617 */
618 public function getInvalidTitlesAndRevisions( $invalidChecks = [ 'invalidTitles',
619 'special', 'missingIds', 'missingRevIds', 'missingTitles', 'interwikiTitles' ]
620 ) {
621 $result = [];
622 if ( in_array( 'invalidTitles', $invalidChecks ) ) {
623 self::addValues( $result, $this->getInvalidTitlesAndReasons(), [ 'invalid' ] );
624 }
625 if ( in_array( 'special', $invalidChecks ) ) {
626 $known = [];
627 $unknown = [];
628 foreach ( $this->getSpecialTitles() as $title ) {
629 if ( $title->isKnown() ) {
630 $known[] = $title;
631 } else {
632 $unknown[] = $title;
633 }
634 }
635 self::addValues( $result, $unknown, [ 'special', 'missing' ] );
636 self::addValues( $result, $known, [ 'special' ] );
637 }
638 if ( in_array( 'missingIds', $invalidChecks ) ) {
639 self::addValues( $result, $this->getMissingPageIDs(), [ 'missing' ], 'pageid' );
640 }
641 if ( in_array( 'missingRevIds', $invalidChecks ) ) {
642 self::addValues( $result, $this->getMissingRevisionIDs(), [ 'missing' ], 'revid' );
643 }
644 if ( in_array( 'missingTitles', $invalidChecks ) ) {
645 $known = [];
646 $unknown = [];
647 foreach ( $this->getMissingTitles() as $title ) {
648 if ( $title->isKnown() ) {
649 $known[] = $title;
650 } else {
651 $unknown[] = $title;
652 }
653 }
654 self::addValues( $result, $unknown, [ 'missing' ] );
655 self::addValues( $result, $known, [ 'missing', 'known' ] );
656 }
657 if ( in_array( 'interwikiTitles', $invalidChecks ) ) {
658 self::addValues( $result, $this->getInterwikiTitlesAsResult() );
659 }
660
661 return $result;
662 }
663
664 /**
665 * Get the list of valid revision IDs (requested with the revids= parameter)
666 * @return array Array of revID (int) => pageID (int)
667 */
668 public function getRevisionIDs() {
669 return $this->mGoodRevIDs;
670 }
671
672 /**
673 * Get the list of non-deleted revision IDs (requested with the revids= parameter)
674 * @return array Array of revID (int) => pageID (int)
675 */
676 public function getLiveRevisionIDs() {
677 return $this->mLiveRevIDs;
678 }
679
680 /**
681 * Get the list of revision IDs that were associated with deleted titles.
682 * @return array Array of revID (int) => pageID (int)
683 */
684 public function getDeletedRevisionIDs() {
685 return $this->mDeletedRevIDs;
686 }
687
688 /**
689 * Revision IDs that were not found in the database
690 * @return array Array of revision IDs
691 */
692 public function getMissingRevisionIDs() {
693 return $this->mMissingRevIDs;
694 }
695
696 /**
697 * Revision IDs that were not found in the database as result array.
698 * @param ApiResult $result
699 * @return array Array of revision IDs
700 * @since 1.21
701 */
702 public function getMissingRevisionIDsAsResult( $result = null ) {
703 $values = [];
704 foreach ( $this->getMissingRevisionIDs() as $revid ) {
705 $values[$revid] = [
706 'revid' => $revid
707 ];
708 }
709 if ( !empty( $values ) && $result ) {
710 ApiResult::setIndexedTagName( $values, 'rev' );
711 }
712
713 return $values;
714 }
715
716 /**
717 * Get the list of titles with negative namespace
718 * @return Title[]
719 */
720 public function getSpecialTitles() {
721 return $this->mSpecialTitles;
722 }
723
724 /**
725 * Returns the number of revisions (requested with revids= parameter).
726 * @return int Number of revisions.
727 */
728 public function getRevisionCount() {
729 return count( $this->getRevisionIDs() );
730 }
731
732 /**
733 * Populate this PageSet from a list of Titles
734 * @param array $titles Array of Title objects
735 */
736 public function populateFromTitles( $titles ) {
737 $this->initFromTitles( $titles );
738 }
739
740 /**
741 * Populate this PageSet from a list of page IDs
742 * @param array $pageIDs Array of page IDs
743 */
744 public function populateFromPageIDs( $pageIDs ) {
745 $this->initFromPageIds( $pageIDs );
746 }
747
748 /**
749 * Populate this PageSet from a rowset returned from the database
750 *
751 * Note that the query result must include the columns returned by
752 * $this->getPageTableFields().
753 *
754 * @param IDatabase $db
755 * @param ResultWrapper $queryResult Query result object
756 */
757 public function populateFromQueryResult( $db, $queryResult ) {
758 $this->initFromQueryResult( $queryResult );
759 }
760
761 /**
762 * Populate this PageSet from a list of revision IDs
763 * @param array $revIDs Array of revision IDs
764 */
765 public function populateFromRevisionIDs( $revIDs ) {
766 $this->initFromRevIDs( $revIDs );
767 }
768
769 /**
770 * Extract all requested fields from the row received from the database
771 * @param stdClass $row Result row
772 */
773 public function processDbRow( $row ) {
774 // Store Title object in various data structures
775 $title = Title::newFromRow( $row );
776
777 LinkCache::singleton()->addGoodLinkObjFromRow( $title, $row );
778
779 $pageId = intval( $row->page_id );
780 $this->mAllPages[$row->page_namespace][$row->page_title] = $pageId;
781 $this->mTitles[] = $title;
782
783 if ( $this->mResolveRedirects && $row->page_is_redirect == '1' ) {
784 $this->mPendingRedirectIDs[$pageId] = $title;
785 } else {
786 $this->mGoodPages[$row->page_namespace][$row->page_title] = $pageId;
787 $this->mGoodAndMissingPages[$row->page_namespace][$row->page_title] = $pageId;
788 $this->mGoodTitles[$pageId] = $title;
789 }
790
791 foreach ( $this->mRequestedPageFields as $fieldName => &$fieldValues ) {
792 $fieldValues[$pageId] = $row->$fieldName;
793 }
794 }
795
796 /**
797 * This method populates internal variables with page information
798 * based on the given array of title strings.
799 *
800 * Steps:
801 * #1 For each title, get data from `page` table
802 * #2 If page was not found in the DB, store it as missing
803 *
804 * Additionally, when resolving redirects:
805 * #3 If no more redirects left, stop.
806 * #4 For each redirect, get its target from the `redirect` table.
807 * #5 Substitute the original LinkBatch object with the new list
808 * #6 Repeat from step #1
809 *
810 * @param array $titles Array of Title objects or strings
811 */
812 private function initFromTitles( $titles ) {
813 // Get validated and normalized title objects
814 $linkBatch = $this->processTitlesArray( $titles );
815 if ( $linkBatch->isEmpty() ) {
816 // There might be special-page redirects
817 $this->resolvePendingRedirects();
818 return;
819 }
820
821 $db = $this->getDB();
822 $set = $linkBatch->constructSet( 'page', $db );
823
824 // Get pageIDs data from the `page` table
825 $res = $db->select( 'page', $this->getPageTableFields(), $set,
826 __METHOD__ );
827
828 // Hack: get the ns:titles stored in [ ns => [ titles ] ] format
829 $this->initFromQueryResult( $res, $linkBatch->data, true ); // process Titles
830
831 // Resolve any found redirects
832 $this->resolvePendingRedirects();
833 }
834
835 /**
836 * Does the same as initFromTitles(), but is based on page IDs instead
837 * @param array $pageids Array of page IDs
838 */
839 private function initFromPageIds( $pageids ) {
840 if ( !$pageids ) {
841 return;
842 }
843
844 $pageids = array_map( 'intval', $pageids ); // paranoia
845 $remaining = array_flip( $pageids );
846
847 $pageids = self::getPositiveIntegers( $pageids );
848
849 $res = null;
850 if ( !empty( $pageids ) ) {
851 $set = [
852 'page_id' => $pageids
853 ];
854 $db = $this->getDB();
855
856 // Get pageIDs data from the `page` table
857 $res = $db->select( 'page', $this->getPageTableFields(), $set,
858 __METHOD__ );
859 }
860
861 $this->initFromQueryResult( $res, $remaining, false ); // process PageIDs
862
863 // Resolve any found redirects
864 $this->resolvePendingRedirects();
865 }
866
867 /**
868 * Iterate through the result of the query on 'page' table,
869 * and for each row create and store title object and save any extra fields requested.
870 * @param ResultWrapper $res DB Query result
871 * @param array $remaining Array of either pageID or ns/title elements (optional).
872 * If given, any missing items will go to $mMissingPageIDs and $mMissingTitles
873 * @param bool $processTitles Must be provided together with $remaining.
874 * If true, treat $remaining as an array of [ns][title]
875 * If false, treat it as an array of [pageIDs]
876 */
877 private function initFromQueryResult( $res, &$remaining = null, $processTitles = null ) {
878 if ( !is_null( $remaining ) && is_null( $processTitles ) ) {
879 ApiBase::dieDebug( __METHOD__, 'Missing $processTitles parameter when $remaining is provided' );
880 }
881
882 $usernames = [];
883 if ( $res ) {
884 foreach ( $res as $row ) {
885 $pageId = intval( $row->page_id );
886
887 // Remove found page from the list of remaining items
888 if ( isset( $remaining ) ) {
889 if ( $processTitles ) {
890 unset( $remaining[$row->page_namespace][$row->page_title] );
891 } else {
892 unset( $remaining[$pageId] );
893 }
894 }
895
896 // Store any extra fields requested by modules
897 $this->processDbRow( $row );
898
899 // Need gender information
900 if ( MWNamespace::hasGenderDistinction( $row->page_namespace ) ) {
901 $usernames[] = $row->page_title;
902 }
903 }
904 }
905
906 if ( isset( $remaining ) ) {
907 // Any items left in the $remaining list are added as missing
908 if ( $processTitles ) {
909 // The remaining titles in $remaining are non-existent pages
910 $linkCache = LinkCache::singleton();
911 foreach ( $remaining as $ns => $dbkeys ) {
912 foreach ( array_keys( $dbkeys ) as $dbkey ) {
913 $title = Title::makeTitle( $ns, $dbkey );
914 $linkCache->addBadLinkObj( $title );
915 $this->mAllPages[$ns][$dbkey] = $this->mFakePageId;
916 $this->mMissingPages[$ns][$dbkey] = $this->mFakePageId;
917 $this->mGoodAndMissingPages[$ns][$dbkey] = $this->mFakePageId;
918 $this->mMissingTitles[$this->mFakePageId] = $title;
919 $this->mFakePageId--;
920 $this->mTitles[] = $title;
921
922 // need gender information
923 if ( MWNamespace::hasGenderDistinction( $ns ) ) {
924 $usernames[] = $dbkey;
925 }
926 }
927 }
928 } else {
929 // The remaining pageids do not exist
930 if ( !$this->mMissingPageIDs ) {
931 $this->mMissingPageIDs = array_keys( $remaining );
932 } else {
933 $this->mMissingPageIDs = array_merge( $this->mMissingPageIDs, array_keys( $remaining ) );
934 }
935 }
936 }
937
938 // Get gender information
939 $genderCache = MediaWikiServices::getInstance()->getGenderCache();
940 $genderCache->doQuery( $usernames, __METHOD__ );
941 }
942
943 /**
944 * Does the same as initFromTitles(), but is based on revision IDs
945 * instead
946 * @param array $revids Array of revision IDs
947 */
948 private function initFromRevIDs( $revids ) {
949 if ( !$revids ) {
950 return;
951 }
952
953 $revids = array_map( 'intval', $revids ); // paranoia
954 $db = $this->getDB();
955 $pageids = [];
956 $remaining = array_flip( $revids );
957
958 $revids = self::getPositiveIntegers( $revids );
959
960 if ( !empty( $revids ) ) {
961 $tables = [ 'revision', 'page' ];
962 $fields = [ 'rev_id', 'rev_page' ];
963 $where = [ 'rev_id' => $revids, 'rev_page = page_id' ];
964
965 // Get pageIDs data from the `page` table
966 $res = $db->select( $tables, $fields, $where, __METHOD__ );
967 foreach ( $res as $row ) {
968 $revid = intval( $row->rev_id );
969 $pageid = intval( $row->rev_page );
970 $this->mGoodRevIDs[$revid] = $pageid;
971 $this->mLiveRevIDs[$revid] = $pageid;
972 $pageids[$pageid] = '';
973 unset( $remaining[$revid] );
974 }
975 }
976
977 $this->mMissingRevIDs = array_keys( $remaining );
978
979 // Populate all the page information
980 $this->initFromPageIds( array_keys( $pageids ) );
981
982 // If the user can see deleted revisions, pull out the corresponding
983 // titles from the archive table and include them too. We ignore
984 // ar_page_id because deleted revisions are tied by title, not page_id.
985 if ( !empty( $this->mMissingRevIDs ) && $this->getUser()->isAllowed( 'deletedhistory' ) ) {
986 $remaining = array_flip( $this->mMissingRevIDs );
987 $tables = [ 'archive' ];
988 $fields = [ 'ar_rev_id', 'ar_namespace', 'ar_title' ];
989 $where = [ 'ar_rev_id' => $this->mMissingRevIDs ];
990
991 $res = $db->select( $tables, $fields, $where, __METHOD__ );
992 $titles = [];
993 foreach ( $res as $row ) {
994 $revid = intval( $row->ar_rev_id );
995 $titles[$revid] = Title::makeTitle( $row->ar_namespace, $row->ar_title );
996 unset( $remaining[$revid] );
997 }
998
999 $this->initFromTitles( $titles );
1000
1001 foreach ( $titles as $revid => $title ) {
1002 $ns = $title->getNamespace();
1003 $dbkey = $title->getDBkey();
1004
1005 // Handle converted titles
1006 if ( !isset( $this->mAllPages[$ns][$dbkey] ) &&
1007 isset( $this->mConvertedTitles[$title->getPrefixedText()] )
1008 ) {
1009 $title = Title::newFromText( $this->mConvertedTitles[$title->getPrefixedText()] );
1010 $ns = $title->getNamespace();
1011 $dbkey = $title->getDBkey();
1012 }
1013
1014 if ( isset( $this->mAllPages[$ns][$dbkey] ) ) {
1015 $this->mGoodRevIDs[$revid] = $this->mAllPages[$ns][$dbkey];
1016 $this->mDeletedRevIDs[$revid] = $this->mAllPages[$ns][$dbkey];
1017 } else {
1018 $remaining[$revid] = true;
1019 }
1020 }
1021
1022 $this->mMissingRevIDs = array_keys( $remaining );
1023 }
1024 }
1025
1026 /**
1027 * Resolve any redirects in the result if redirect resolution was
1028 * requested. This function is called repeatedly until all redirects
1029 * have been resolved.
1030 */
1031 private function resolvePendingRedirects() {
1032 if ( $this->mResolveRedirects ) {
1033 $db = $this->getDB();
1034 $pageFlds = $this->getPageTableFields();
1035
1036 // Repeat until all redirects have been resolved
1037 // The infinite loop is prevented by keeping all known pages in $this->mAllPages
1038 while ( $this->mPendingRedirectIDs || $this->mPendingRedirectSpecialPages ) {
1039 // Resolve redirects by querying the pagelinks table, and repeat the process
1040 // Create a new linkBatch object for the next pass
1041 $linkBatch = $this->getRedirectTargets();
1042
1043 if ( $linkBatch->isEmpty() ) {
1044 break;
1045 }
1046
1047 $set = $linkBatch->constructSet( 'page', $db );
1048 if ( $set === false ) {
1049 break;
1050 }
1051
1052 // Get pageIDs data from the `page` table
1053 $res = $db->select( 'page', $pageFlds, $set, __METHOD__ );
1054
1055 // Hack: get the ns:titles stored in [ns => array(titles)] format
1056 $this->initFromQueryResult( $res, $linkBatch->data, true );
1057 }
1058 }
1059 }
1060
1061 /**
1062 * Get the targets of the pending redirects from the database
1063 *
1064 * Also creates entries in the redirect table for redirects that don't
1065 * have one.
1066 * @return LinkBatch
1067 */
1068 private function getRedirectTargets() {
1069 $titlesToResolve = [];
1070 $db = $this->getDB();
1071
1072 if ( $this->mPendingRedirectIDs ) {
1073 $res = $db->select(
1074 'redirect',
1075 [
1076 'rd_from',
1077 'rd_namespace',
1078 'rd_fragment',
1079 'rd_interwiki',
1080 'rd_title'
1081 ], [ 'rd_from' => array_keys( $this->mPendingRedirectIDs ) ],
1082 __METHOD__
1083 );
1084 foreach ( $res as $row ) {
1085 $rdfrom = intval( $row->rd_from );
1086 $from = $this->mPendingRedirectIDs[$rdfrom]->getPrefixedText();
1087 $to = Title::makeTitle(
1088 $row->rd_namespace,
1089 $row->rd_title,
1090 $row->rd_fragment,
1091 $row->rd_interwiki
1092 );
1093 $this->mResolvedRedirectTitles[$from] = $this->mPendingRedirectIDs[$rdfrom];
1094 unset( $this->mPendingRedirectIDs[$rdfrom] );
1095 if ( $to->isExternal() ) {
1096 $this->mInterwikiTitles[$to->getPrefixedText()] = $to->getInterwiki();
1097 } elseif ( !isset( $this->mAllPages[$to->getNamespace()][$to->getDBkey()] ) ) {
1098 $titlesToResolve[] = $to;
1099 }
1100 $this->mRedirectTitles[$from] = $to;
1101 }
1102
1103 if ( $this->mPendingRedirectIDs ) {
1104 // We found pages that aren't in the redirect table
1105 // Add them
1106 foreach ( $this->mPendingRedirectIDs as $id => $title ) {
1107 $page = WikiPage::factory( $title );
1108 $rt = $page->insertRedirect();
1109 if ( !$rt ) {
1110 // What the hell. Let's just ignore this
1111 continue;
1112 }
1113 if ( $rt->isExternal() ) {
1114 $this->mInterwikiTitles[$rt->getPrefixedText()] = $rt->getInterwiki();
1115 } elseif ( !isset( $this->mAllPages[$rt->getNamespace()][$rt->getDBkey()] ) ) {
1116 $titlesToResolve[] = $rt;
1117 }
1118 $from = $title->getPrefixedText();
1119 $this->mResolvedRedirectTitles[$from] = $title;
1120 $this->mRedirectTitles[$from] = $rt;
1121 unset( $this->mPendingRedirectIDs[$id] );
1122 }
1123 }
1124 }
1125
1126 if ( $this->mPendingRedirectSpecialPages ) {
1127 foreach ( $this->mPendingRedirectSpecialPages as $key => list( $from, $to ) ) {
1128 $fromKey = $from->getPrefixedText();
1129 $this->mResolvedRedirectTitles[$fromKey] = $from;
1130 $this->mRedirectTitles[$fromKey] = $to;
1131 if ( $to->isExternal() ) {
1132 $this->mInterwikiTitles[$to->getPrefixedText()] = $to->getInterwiki();
1133 } elseif ( !isset( $this->mAllPages[$to->getNamespace()][$to->getDBkey()] ) ) {
1134 $titlesToResolve[] = $to;
1135 }
1136 }
1137 $this->mPendingRedirectSpecialPages = [];
1138
1139 // Set private caching since we don't know what criteria the
1140 // special pages used to decide on these redirects.
1141 $this->mCacheMode = 'private';
1142 }
1143
1144 return $this->processTitlesArray( $titlesToResolve );
1145 }
1146
1147 /**
1148 * Get the cache mode for the data generated by this module.
1149 * All PageSet users should take into account whether this returns a more-restrictive
1150 * cache mode than the using module itself. For possible return values and other
1151 * details about cache modes, see ApiMain::setCacheMode()
1152 *
1153 * Public caching will only be allowed if *all* the modules that supply
1154 * data for a given request return a cache mode of public.
1155 *
1156 * @param array|null $params
1157 * @return string
1158 * @since 1.21
1159 */
1160 public function getCacheMode( $params = null ) {
1161 return $this->mCacheMode;
1162 }
1163
1164 /**
1165 * Given an array of title strings, convert them into Title objects.
1166 * Alternatively, an array of Title objects may be given.
1167 * This method validates access rights for the title,
1168 * and appends normalization values to the output.
1169 *
1170 * @param array $titles Array of Title objects or strings
1171 * @return LinkBatch
1172 */
1173 private function processTitlesArray( $titles ) {
1174 $usernames = [];
1175 $linkBatch = new LinkBatch();
1176
1177 foreach ( $titles as $title ) {
1178 if ( is_string( $title ) ) {
1179 try {
1180 $titleObj = Title::newFromTextThrow( $title, $this->mDefaultNamespace );
1181 } catch ( MalformedTitleException $ex ) {
1182 // Handle invalid titles gracefully
1183 if ( !isset( $this->mAllPages[0][$title] ) ) {
1184 $this->mAllPages[0][$title] = $this->mFakePageId;
1185 $this->mInvalidTitles[$this->mFakePageId] = [
1186 'title' => $title,
1187 'invalidreason' => $this->getErrorFormatter()->formatException( $ex, [ 'bc' => true ] ),
1188 ];
1189 $this->mFakePageId--;
1190 }
1191 continue; // There's nothing else we can do
1192 }
1193 } else {
1194 $titleObj = $title;
1195 }
1196 $unconvertedTitle = $titleObj->getPrefixedText();
1197 $titleWasConverted = false;
1198 if ( $titleObj->isExternal() ) {
1199 // This title is an interwiki link.
1200 $this->mInterwikiTitles[$unconvertedTitle] = $titleObj->getInterwiki();
1201 } else {
1202 // Variants checking
1203 global $wgContLang;
1204 if ( $this->mConvertTitles &&
1205 count( $wgContLang->getVariants() ) > 1 &&
1206 !$titleObj->exists()
1207 ) {
1208 // Language::findVariantLink will modify titleText and titleObj into
1209 // the canonical variant if possible
1210 $titleText = is_string( $title ) ? $title : $titleObj->getPrefixedText();
1211 $wgContLang->findVariantLink( $titleText, $titleObj );
1212 $titleWasConverted = $unconvertedTitle !== $titleObj->getPrefixedText();
1213 }
1214
1215 if ( $titleObj->getNamespace() < 0 ) {
1216 // Handle Special and Media pages
1217 $titleObj = $titleObj->fixSpecialName();
1218 $ns = $titleObj->getNamespace();
1219 $dbkey = $titleObj->getDBkey();
1220 if ( !isset( $this->mAllSpecials[$ns][$dbkey] ) ) {
1221 $this->mAllSpecials[$ns][$dbkey] = $this->mFakePageId;
1222 $target = null;
1223 if ( $ns === NS_SPECIAL && $this->mResolveRedirects ) {
1224 $special = SpecialPageFactory::getPage( $dbkey );
1225 if ( $special instanceof RedirectSpecialArticle ) {
1226 // Only RedirectSpecialArticle is intended to redirect to an article, other kinds of
1227 // RedirectSpecialPage are probably applying weird URL parameters we don't want to handle.
1228 $context = new DerivativeContext( $this );
1229 $context->setTitle( $titleObj );
1230 $context->setRequest( new FauxRequest );
1231 $special->setContext( $context );
1232 list( /* $alias */, $subpage ) = SpecialPageFactory::resolveAlias( $dbkey );
1233 $target = $special->getRedirect( $subpage );
1234 }
1235 }
1236 if ( $target ) {
1237 $this->mPendingRedirectSpecialPages[$dbkey] = [ $titleObj, $target ];
1238 } else {
1239 $this->mSpecialTitles[$this->mFakePageId] = $titleObj;
1240 $this->mFakePageId--;
1241 }
1242 }
1243 } else {
1244 // Regular page
1245 $linkBatch->addObj( $titleObj );
1246 }
1247 }
1248
1249 // Make sure we remember the original title that was
1250 // given to us. This way the caller can correlate new
1251 // titles with the originally requested when e.g. the
1252 // namespace is localized or the capitalization is
1253 // different
1254 if ( $titleWasConverted ) {
1255 $this->mConvertedTitles[$unconvertedTitle] = $titleObj->getPrefixedText();
1256 // In this case the page can't be Special.
1257 if ( is_string( $title ) && $title !== $unconvertedTitle ) {
1258 $this->mNormalizedTitles[$title] = $unconvertedTitle;
1259 }
1260 } elseif ( is_string( $title ) && $title !== $titleObj->getPrefixedText() ) {
1261 $this->mNormalizedTitles[$title] = $titleObj->getPrefixedText();
1262 }
1263
1264 // Need gender information
1265 if ( MWNamespace::hasGenderDistinction( $titleObj->getNamespace() ) ) {
1266 $usernames[] = $titleObj->getText();
1267 }
1268 }
1269 // Get gender information
1270 $genderCache = MediaWikiServices::getInstance()->getGenderCache();
1271 $genderCache->doQuery( $usernames, __METHOD__ );
1272
1273 return $linkBatch;
1274 }
1275
1276 /**
1277 * Set data for a title.
1278 *
1279 * This data may be extracted into an ApiResult using
1280 * self::populateGeneratorData. This should generally be limited to
1281 * data that is likely to be particularly useful to end users rather than
1282 * just being a dump of everything returned in non-generator mode.
1283 *
1284 * Redirects here will *not* be followed, even if 'redirects' was
1285 * specified, since in the case of multiple redirects we can't know which
1286 * source's data to use on the target.
1287 *
1288 * @param Title $title
1289 * @param array $data
1290 */
1291 public function setGeneratorData( Title $title, array $data ) {
1292 $ns = $title->getNamespace();
1293 $dbkey = $title->getDBkey();
1294 $this->mGeneratorData[$ns][$dbkey] = $data;
1295 }
1296
1297 /**
1298 * Controls how generator data about a redirect source is merged into
1299 * the generator data for the redirect target. When not set no data
1300 * is merged. Note that if multiple titles redirect to the same target
1301 * the order of operations is undefined.
1302 *
1303 * Example to include generated data from redirect in target, prefering
1304 * the data generated for the destination when there is a collision:
1305 * @code
1306 * $pageSet->setRedirectMergePolicy( function( array $current, array $new ) {
1307 * return $current + $new;
1308 * } );
1309 * @endcode
1310 *
1311 * @param callable|null $callable Recieves two array arguments, first the
1312 * generator data for the redirect target and second the generator data
1313 * for the redirect source. Returns the resulting generator data to use
1314 * for the redirect target.
1315 */
1316 public function setRedirectMergePolicy( $callable ) {
1317 $this->mRedirectMergePolicy = $callable;
1318 }
1319
1320 /**
1321 * Populate the generator data for all titles in the result
1322 *
1323 * The page data may be inserted into an ApiResult object or into an
1324 * associative array. The $path parameter specifies the path within the
1325 * ApiResult or array to find the "pages" node.
1326 *
1327 * The "pages" node itself must be an associative array mapping the page ID
1328 * or fake page ID values returned by this pageset (see
1329 * self::getAllTitlesByNamespace() and self::getSpecialTitles()) to
1330 * associative arrays of page data. Each of those subarrays will have the
1331 * data from self::setGeneratorData() merged in.
1332 *
1333 * Data that was set by self::setGeneratorData() for pages not in the
1334 * "pages" node will be ignored.
1335 *
1336 * @param ApiResult|array &$result
1337 * @param array $path
1338 * @return bool Whether the data fit
1339 */
1340 public function populateGeneratorData( &$result, array $path = [] ) {
1341 if ( $result instanceof ApiResult ) {
1342 $data = $result->getResultData( $path );
1343 if ( $data === null ) {
1344 return true;
1345 }
1346 } else {
1347 $data = &$result;
1348 foreach ( $path as $key ) {
1349 if ( !isset( $data[$key] ) ) {
1350 // Path isn't in $result, so nothing to add, so everything
1351 // "fits"
1352 return true;
1353 }
1354 $data = &$data[$key];
1355 }
1356 }
1357 foreach ( $this->mGeneratorData as $ns => $dbkeys ) {
1358 if ( $ns === -1 ) {
1359 $pages = [];
1360 foreach ( $this->mSpecialTitles as $id => $title ) {
1361 $pages[$title->getDBkey()] = $id;
1362 }
1363 } else {
1364 if ( !isset( $this->mAllPages[$ns] ) ) {
1365 // No known titles in the whole namespace. Skip it.
1366 continue;
1367 }
1368 $pages = $this->mAllPages[$ns];
1369 }
1370 foreach ( $dbkeys as $dbkey => $genData ) {
1371 if ( !isset( $pages[$dbkey] ) ) {
1372 // Unknown title. Forget it.
1373 continue;
1374 }
1375 $pageId = $pages[$dbkey];
1376 if ( !isset( $data[$pageId] ) ) {
1377 // $pageId didn't make it into the result. Ignore it.
1378 continue;
1379 }
1380
1381 if ( $result instanceof ApiResult ) {
1382 $path2 = array_merge( $path, [ $pageId ] );
1383 foreach ( $genData as $key => $value ) {
1384 if ( !$result->addValue( $path2, $key, $value ) ) {
1385 return false;
1386 }
1387 }
1388 } else {
1389 $data[$pageId] = array_merge( $data[$pageId], $genData );
1390 }
1391 }
1392 }
1393
1394 // Merge data generated about redirect titles into the redirect destination
1395 if ( $this->mRedirectMergePolicy ) {
1396 foreach ( $this->mResolvedRedirectTitles as $titleFrom ) {
1397 $dest = $titleFrom;
1398 while ( isset( $this->mRedirectTitles[$dest->getPrefixedText()] ) ) {
1399 $dest = $this->mRedirectTitles[$dest->getPrefixedText()];
1400 }
1401 $fromNs = $titleFrom->getNamespace();
1402 $fromDBkey = $titleFrom->getDBkey();
1403 $toPageId = $dest->getArticleID();
1404 if ( isset( $data[$toPageId] ) &&
1405 isset( $this->mGeneratorData[$fromNs][$fromDBkey] )
1406 ) {
1407 // It is necesary to set both $data and add to $result, if an ApiResult,
1408 // to ensure multiple redirects to the same destination are all merged.
1409 $data[$toPageId] = call_user_func(
1410 $this->mRedirectMergePolicy,
1411 $data[$toPageId],
1412 $this->mGeneratorData[$fromNs][$fromDBkey]
1413 );
1414 if ( $result instanceof ApiResult ) {
1415 if ( !$result->addValue( $path, $toPageId, $data[$toPageId], ApiResult::OVERRIDE ) ) {
1416 return false;
1417 }
1418 }
1419 }
1420 }
1421 }
1422
1423 return true;
1424 }
1425
1426 /**
1427 * Get the database connection (read-only)
1428 * @return Database
1429 */
1430 protected function getDB() {
1431 return $this->mDbSource->getDB();
1432 }
1433
1434 /**
1435 * Returns the input array of integers with all values < 0 removed
1436 *
1437 * @param array $array
1438 * @return array
1439 */
1440 private static function getPositiveIntegers( $array ) {
1441 // T27734 API: possible issue with revids validation
1442 // It seems with a load of revision rows, MySQL gets upset
1443 // Remove any < 0 integers, as they can't be valid
1444 foreach ( $array as $i => $int ) {
1445 if ( $int < 0 ) {
1446 unset( $array[$i] );
1447 }
1448 }
1449
1450 return $array;
1451 }
1452
1453 public function getAllowedParams( $flags = 0 ) {
1454 $result = [
1455 'titles' => [
1456 ApiBase::PARAM_ISMULTI => true,
1457 ApiBase::PARAM_HELP_MSG => 'api-pageset-param-titles',
1458 ],
1459 'pageids' => [
1460 ApiBase::PARAM_TYPE => 'integer',
1461 ApiBase::PARAM_ISMULTI => true,
1462 ApiBase::PARAM_HELP_MSG => 'api-pageset-param-pageids',
1463 ],
1464 'revids' => [
1465 ApiBase::PARAM_TYPE => 'integer',
1466 ApiBase::PARAM_ISMULTI => true,
1467 ApiBase::PARAM_HELP_MSG => 'api-pageset-param-revids',
1468 ],
1469 'generator' => [
1470 ApiBase::PARAM_TYPE => null,
1471 ApiBase::PARAM_HELP_MSG => 'api-pageset-param-generator',
1472 ApiBase::PARAM_SUBMODULE_PARAM_PREFIX => 'g',
1473 ],
1474 'redirects' => [
1475 ApiBase::PARAM_DFLT => false,
1476 ApiBase::PARAM_HELP_MSG => $this->mAllowGenerator
1477 ? 'api-pageset-param-redirects-generator'
1478 : 'api-pageset-param-redirects-nogenerator',
1479 ],
1480 'converttitles' => [
1481 ApiBase::PARAM_DFLT => false,
1482 ApiBase::PARAM_HELP_MSG => [
1483 'api-pageset-param-converttitles',
1484 [ Message::listParam( LanguageConverter::$languagesWithVariants, 'text' ) ],
1485 ],
1486 ],
1487 ];
1488
1489 if ( !$this->mAllowGenerator ) {
1490 unset( $result['generator'] );
1491 } elseif ( $flags & ApiBase::GET_VALUES_FOR_HELP ) {
1492 $result['generator'][ApiBase::PARAM_TYPE] = 'submodule';
1493 $result['generator'][ApiBase::PARAM_SUBMODULE_MAP] = $this->getGenerators();
1494 }
1495
1496 return $result;
1497 }
1498
1499 protected function handleParamNormalization( $paramName, $value, $rawValue ) {
1500 parent::handleParamNormalization( $paramName, $value, $rawValue );
1501
1502 if ( $paramName === 'titles' ) {
1503 // For the 'titles' parameter, we want to split it like ApiBase would
1504 // and add any changed titles to $this->mNormalizedTitles
1505 $value = $this->explodeMultiValue( $value, self::LIMIT_SML2 + 1 );
1506 $l = count( $value );
1507 $rawValue = $this->explodeMultiValue( $rawValue, $l );
1508 for ( $i = 0; $i < $l; $i++ ) {
1509 if ( $value[$i] !== $rawValue[$i] ) {
1510 $this->mNormalizedTitles[$rawValue[$i]] = $value[$i];
1511 }
1512 }
1513 }
1514 }
1515
1516 private static $generators = null;
1517
1518 /**
1519 * Get an array of all available generators
1520 * @return array
1521 */
1522 private function getGenerators() {
1523 if ( self::$generators === null ) {
1524 $query = $this->mDbSource;
1525 if ( !( $query instanceof ApiQuery ) ) {
1526 // If the parent container of this pageset is not ApiQuery,
1527 // we must create it to get module manager
1528 $query = $this->getMain()->getModuleManager()->getModule( 'query' );
1529 }
1530 $gens = [];
1531 $prefix = $query->getModulePath() . '+';
1532 $mgr = $query->getModuleManager();
1533 foreach ( $mgr->getNamesWithClasses() as $name => $class ) {
1534 if ( is_subclass_of( $class, 'ApiQueryGeneratorBase' ) ) {
1535 $gens[$name] = $prefix . $name;
1536 }
1537 }
1538 ksort( $gens );
1539 self::$generators = $gens;
1540 }
1541
1542 return self::$generators;
1543 }
1544 }