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