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