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