fix some spacing
[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
27 /**
28 * This class contains a list of pages that the client has requested.
29 * Initially, when the client passes in titles=, pageids=, or revisions=
30 * parameter, an instance of the ApiPageSet class will normalize titles,
31 * determine if the pages/revisions exist, and prefetch any additional page
32 * data requested.
33 *
34 * When a generator is used, the result of the generator will become the input
35 * for the second instance of this class, and all subsequent actions will use
36 * the second instance for all their work.
37 *
38 * @ingroup API
39 * @since 1.21 derives from ApiBase instead of ApiQueryBase
40 */
41 class ApiPageSet extends ApiBase {
42
43 /**
44 * Constructor flag: The new instance of ApiPageSet will ignore the 'generator=' parameter
45 * @since 1.21
46 */
47 const DISABLE_GENERATORS = 1;
48
49 private $mDbSource;
50 private $mParams;
51 private $mResolveRedirects;
52 private $mConvertTitles;
53 private $mAllowGenerator;
54
55 private $mAllPages = array(); // [ns][dbkey] => page_id or negative when missing
56 private $mTitles = array();
57 private $mGoodTitles = array();
58 private $mMissingTitles = array();
59 private $mInvalidTitles = array();
60 private $mMissingPageIDs = array();
61 private $mRedirectTitles = array();
62 private $mSpecialTitles = array();
63 private $mNormalizedTitles = array();
64 private $mInterwikiTitles = array();
65 private $mPendingRedirectIDs = array();
66 private $mConvertedTitles = array();
67 private $mGoodRevIDs = array();
68 private $mMissingRevIDs = array();
69 private $mFakePageId = -1;
70 private $mCacheMode = 'public';
71 private $mRequestedPageFields = array();
72 private $mDefaultNamespace = NS_MAIN;
73
74 /**
75 * Constructor
76 * @param $dbSource ApiBase Module implementing getDB().
77 * Allows PageSet to reuse existing db connection from the shared state like ApiQuery.
78 * @param $flags int Zero or more flags like DISABLE_GENERATORS
79 * @param $defaultNamespace int the namespace to use if none is specified by a prefix.
80 * @since 1.21 accepts $flags instead of two boolean values
81 */
82 public function __construct( ApiBase $dbSource, $flags = 0, $defaultNamespace = NS_MAIN ) {
83 parent::__construct( $dbSource->getMain(), $dbSource->getModuleName() );
84 $this->mDbSource = $dbSource;
85 $this->mAllowGenerator = ( $flags & ApiPageSet::DISABLE_GENERATORS ) == 0;
86 $this->mDefaultNamespace = $defaultNamespace;
87
88 $this->profileIn();
89 $this->mParams = $this->extractRequestParams();
90 $this->mResolveRedirects = $this->mParams['redirects'];
91 $this->mConvertTitles = $this->mParams['converttitles'];
92 $this->profileOut();
93 }
94
95 /**
96 * In case execute() is not called, call this method to mark all relevant parameters as used
97 * This prevents unused parameters from being reported as warnings
98 */
99 public function executeDryRun() {
100 $this->executeInternal( true );
101 }
102
103 /**
104 * Populate the PageSet from the request parameters.
105 */
106 public function execute() {
107 $this->executeInternal( false );
108 }
109
110 /**
111 * Populate the PageSet from the request parameters.
112 * @param bool $isDryRun If true, instantiates generator, but only to mark relevant parameters as used
113 */
114 private function executeInternal( $isDryRun ) {
115 $this->profileIn();
116
117 $generatorName = $this->mAllowGenerator ? $this->mParams['generator'] : null;
118 if ( isset( $generatorName ) ) {
119 $dbSource = $this->mDbSource;
120 $isQuery = $dbSource instanceof ApiQuery;
121 if ( !$isQuery ) {
122 // If the parent container of this pageset is not ApiQuery, we must create it to run generator
123 $dbSource = $this->getMain()->getModuleManager()->getModule( 'query' );
124 // Enable profiling for query module because it will be used for db sql profiling
125 $dbSource->profileIn();
126 }
127 $generator = $dbSource->getModuleManager()->getModule( $generatorName, null, true );
128 if ( $generator === null ) {
129 $this->dieUsage( 'Unknown generator=' . $generatorName, 'badgenerator' );
130 }
131 if ( !$generator instanceof ApiQueryGeneratorBase ) {
132 $this->dieUsage( "Module $generatorName cannot be used as a generator", 'badgenerator' );
133 }
134 // Create a temporary pageset to store generator's output,
135 // add any additional fields generator may need, and execute pageset to populate titles/pageids
136 $tmpPageSet = new ApiPageSet( $dbSource, ApiPageSet::DISABLE_GENERATORS );
137 $generator->setGeneratorMode( $tmpPageSet );
138 $this->mCacheMode = $generator->getCacheMode( $generator->extractRequestParams() );
139
140 if ( !$isDryRun ) {
141 $generator->requestExtraData( $tmpPageSet );
142 }
143 $tmpPageSet->executeInternal( $isDryRun );
144
145 // populate this pageset with the generator output
146 $this->profileOut();
147 $generator->profileIn();
148
149 if ( !$isDryRun ) {
150 $generator->executeGenerator( $this );
151 wfRunHooks( 'APIQueryGeneratorAfterExecute', array( &$generator, &$this ) );
152 $this->resolvePendingRedirects();
153 } else {
154 // Prevent warnings from being reported on these parameters
155 $main = $this->getMain();
156 foreach ( $generator->extractRequestParams() as $paramName => $param ) {
157 $main->getVal( $generator->encodeParamName( $paramName ) );
158 }
159 }
160 $generator->profileOut();
161 $this->profileIn();
162
163 if ( !$isQuery ) {
164 // If this pageset is not part of the query, we called profileIn() above
165 $dbSource->profileOut();
166 }
167 } else {
168 // Only one of the titles/pageids/revids is allowed at the same time
169 $dataSource = null;
170 if ( isset( $this->mParams['titles'] ) ) {
171 $dataSource = 'titles';
172 }
173 if ( isset( $this->mParams['pageids'] ) ) {
174 if ( isset( $dataSource ) ) {
175 $this->dieUsage( "Cannot use 'pageids' at the same time as '$dataSource'", 'multisource' );
176 }
177 $dataSource = 'pageids';
178 }
179 if ( isset( $this->mParams['revids'] ) ) {
180 if ( isset( $dataSource ) ) {
181 $this->dieUsage( "Cannot use 'revids' at the same time as '$dataSource'", 'multisource' );
182 }
183 $dataSource = 'revids';
184 }
185
186 if ( !$isDryRun ) {
187 // Populate page information with the original user input
188 switch( $dataSource ) {
189 case 'titles':
190 $this->initFromTitles( $this->mParams['titles'] );
191 break;
192 case 'pageids':
193 $this->initFromPageIds( $this->mParams['pageids'] );
194 break;
195 case 'revids':
196 if ( $this->mResolveRedirects ) {
197 $this->setWarning( 'Redirect resolution cannot be used together with the revids= parameter. ' .
198 'Any redirects the revids= point to have not been resolved.' );
199 }
200 $this->mResolveRedirects = false;
201 $this->initFromRevIDs( $this->mParams['revids'] );
202 break;
203 default:
204 // Do nothing - some queries do not need any of the data sources.
205 break;
206 }
207 }
208 }
209 $this->profileOut();
210 }
211
212 /**
213 * Check whether this PageSet is resolving redirects
214 * @return bool
215 */
216 public function isResolvingRedirects() {
217 return $this->mResolveRedirects;
218 }
219
220 /**
221 * Request an additional field from the page table.
222 * Must be called before execute()
223 * @param $fieldName string Field name
224 */
225 public function requestField( $fieldName ) {
226 $this->mRequestedPageFields[$fieldName] = null;
227 }
228
229 /**
230 * Get the value of a custom field previously requested through
231 * requestField()
232 * @param $fieldName string Field name
233 * @return mixed Field value
234 */
235 public function getCustomField( $fieldName ) {
236 return $this->mRequestedPageFields[$fieldName];
237 }
238
239 /**
240 * Get the fields that have to be queried from the page table:
241 * the ones requested through requestField() and a few basic ones
242 * we always need
243 * @return array of field names
244 */
245 public function getPageTableFields() {
246 // Ensure we get minimum required fields
247 // DON'T change this order
248 $pageFlds = array(
249 'page_namespace' => null,
250 'page_title' => null,
251 'page_id' => null,
252 );
253
254 if ( $this->mResolveRedirects ) {
255 $pageFlds['page_is_redirect'] = null;
256 }
257
258 // only store non-default fields
259 $this->mRequestedPageFields = array_diff_key( $this->mRequestedPageFields, $pageFlds );
260
261 $pageFlds = array_merge( $pageFlds, $this->mRequestedPageFields );
262 return array_keys( $pageFlds );
263 }
264
265 /**
266 * Returns an array [ns][dbkey] => page_id for all requested titles.
267 * page_id is a unique negative number in case title was not found.
268 * Invalid titles will also have negative page IDs and will be in namespace 0
269 * @return array
270 */
271 public function getAllTitlesByNamespace() {
272 return $this->mAllPages;
273 }
274
275 /**
276 * All Title objects provided.
277 * @return array of Title objects
278 */
279 public function getTitles() {
280 return $this->mTitles;
281 }
282
283 /**
284 * Returns the number of unique pages (not revisions) in the set.
285 * @return int
286 */
287 public function getTitleCount() {
288 return count( $this->mTitles );
289 }
290
291 /**
292 * Title objects that were found in the database.
293 * @return array page_id (int) => Title (obj)
294 */
295 public function getGoodTitles() {
296 return $this->mGoodTitles;
297 }
298
299 /**
300 * Returns the number of found unique pages (not revisions) in the set.
301 * @return int
302 */
303 public function getGoodTitleCount() {
304 return count( $this->mGoodTitles );
305 }
306
307 /**
308 * Title objects that were NOT found in the database.
309 * The array's index will be negative for each item
310 * @return array of Title objects
311 */
312 public function getMissingTitles() {
313 return $this->mMissingTitles;
314 }
315
316 /**
317 * Titles that were deemed invalid by Title::newFromText()
318 * The array's index will be unique and negative for each item
319 * @return array of strings (not Title objects)
320 */
321 public function getInvalidTitles() {
322 return $this->mInvalidTitles;
323 }
324
325 /**
326 * Page IDs that were not found in the database
327 * @return array of page IDs
328 */
329 public function getMissingPageIDs() {
330 return $this->mMissingPageIDs;
331 }
332
333 /**
334 * Get a list of redirect resolutions - maps a title to its redirect
335 * target, as an array of output-ready arrays
336 * @return array
337 */
338 public function getRedirectTitles() {
339 return $this->mRedirectTitles;
340 }
341
342 /**
343 * Get a list of redirect resolutions - maps a title to its redirect
344 * target.
345 * @param $result ApiResult
346 * @return array of prefixed_title (string) => Title object
347 * @since 1.21
348 */
349 public function getRedirectTitlesAsResult( $result = null ) {
350 $values = array();
351 foreach ( $this->getRedirectTitles() as $titleStrFrom => $titleTo ) {
352 $r = array(
353 'from' => strval( $titleStrFrom ),
354 'to' => $titleTo->getPrefixedText(),
355 );
356 if ( $titleTo->getFragment() !== '' ) {
357 $r['tofragment'] = $titleTo->getFragment();
358 }
359 $values[] = $r;
360 }
361 if ( !empty( $values ) && $result ) {
362 $result->setIndexedTagName( $values, 'r' );
363 }
364 return $values;
365 }
366
367 /**
368 * Get a list of title normalizations - maps a title to its normalized
369 * version.
370 * @return array raw_prefixed_title (string) => prefixed_title (string)
371 */
372 public function getNormalizedTitles() {
373 return $this->mNormalizedTitles;
374 }
375
376 /**
377 * Get a list of title normalizations - maps a title to its normalized
378 * version in the form of result array.
379 * @param $result ApiResult
380 * @return array of raw_prefixed_title (string) => prefixed_title (string)
381 * @since 1.21
382 */
383 public function getNormalizedTitlesAsResult( $result = null ) {
384 $values = array();
385 foreach ( $this->getNormalizedTitles() as $rawTitleStr => $titleStr ) {
386 $values[] = array(
387 'from' => $rawTitleStr,
388 'to' => $titleStr
389 );
390 }
391 if ( !empty( $values ) && $result ) {
392 $result->setIndexedTagName( $values, 'n' );
393 }
394 return $values;
395 }
396
397 /**
398 * Get a list of title conversions - maps a title to its converted
399 * version.
400 * @return array raw_prefixed_title (string) => prefixed_title (string)
401 */
402 public function getConvertedTitles() {
403 return $this->mConvertedTitles;
404 }
405
406 /**
407 * Get a list of title conversions - maps a title to its converted
408 * version as a result array.
409 * @param $result ApiResult
410 * @return array of (from, to) strings
411 * @since 1.21
412 */
413 public function getConvertedTitlesAsResult( $result = null ) {
414 $values = array();
415 foreach ( $this->getConvertedTitles() as $rawTitleStr => $titleStr ) {
416 $values[] = array(
417 'from' => $rawTitleStr,
418 'to' => $titleStr
419 );
420 }
421 if ( !empty( $values ) && $result ) {
422 $result->setIndexedTagName( $values, 'c' );
423 }
424 return $values;
425 }
426
427 /**
428 * Get a list of interwiki titles - maps a title to its interwiki
429 * prefix.
430 * @return array raw_prefixed_title (string) => interwiki_prefix (string)
431 */
432 public function getInterwikiTitles() {
433 return $this->mInterwikiTitles;
434 }
435
436 /**
437 * Get a list of interwiki titles - maps a title to its interwiki
438 * prefix as result.
439 * @param $result ApiResult
440 * @param $iwUrl boolean
441 * @return array raw_prefixed_title (string) => interwiki_prefix (string)
442 * @since 1.21
443 */
444 public function getInterwikiTitlesAsResult( $result = null, $iwUrl = false ) {
445 $values = array();
446 foreach ( $this->getInterwikiTitles() as $rawTitleStr => $interwikiStr ) {
447 $item = array(
448 'title' => $rawTitleStr,
449 'iw' => $interwikiStr,
450 );
451 if ( $iwUrl ) {
452 $title = Title::newFromText( $rawTitleStr );
453 $item['url'] = $title->getFullURL( '', false, PROTO_CURRENT );
454 }
455 $values[] = $item;
456 }
457 if ( !empty( $values ) && $result ) {
458 $result->setIndexedTagName( $values, 'i' );
459 }
460 return $values;
461 }
462
463 /**
464 * Get the list of revision IDs (requested with the revids= parameter)
465 * @return array revID (int) => pageID (int)
466 */
467 public function getRevisionIDs() {
468 return $this->mGoodRevIDs;
469 }
470
471 /**
472 * Revision IDs that were not found in the database
473 * @return array of revision IDs
474 */
475 public function getMissingRevisionIDs() {
476 return $this->mMissingRevIDs;
477 }
478
479 /**
480 * Revision IDs that were not found in the database as result array.
481 * @param $result ApiResult
482 * @return array of revision IDs
483 * @since 1.21
484 */
485 public function getMissingRevisionIDsAsResult( $result = null ) {
486 $values = array();
487 foreach ( $this->getMissingRevisionIDs() as $revid ) {
488 $values[$revid] = array(
489 'revid' => $revid
490 );
491 }
492 if ( !empty( $values ) && $result ) {
493 $result->setIndexedTagName( $values, 'rev' );
494 }
495 return $values;
496 }
497
498 /**
499 * Get the list of titles with negative namespace
500 * @return array Title
501 */
502 public function getSpecialTitles() {
503 return $this->mSpecialTitles;
504 }
505
506 /**
507 * Returns the number of revisions (requested with revids= parameter).
508 * @return int Number of revisions.
509 */
510 public function getRevisionCount() {
511 return count( $this->getRevisionIDs() );
512 }
513
514 /**
515 * Populate this PageSet from a list of Titles
516 * @param $titles array of Title objects
517 */
518 public function populateFromTitles( $titles ) {
519 $this->profileIn();
520 $this->initFromTitles( $titles );
521 $this->profileOut();
522 }
523
524 /**
525 * Populate this PageSet from a list of page IDs
526 * @param $pageIDs array of page IDs
527 */
528 public function populateFromPageIDs( $pageIDs ) {
529 $this->profileIn();
530 $this->initFromPageIds( $pageIDs );
531 $this->profileOut();
532 }
533
534 /**
535 * Populate this PageSet from a rowset returned from the database
536 * @param $db DatabaseBase object
537 * @param $queryResult ResultWrapper Query result object
538 */
539 public function populateFromQueryResult( $db, $queryResult ) {
540 $this->profileIn();
541 $this->initFromQueryResult( $queryResult );
542 $this->profileOut();
543 }
544
545 /**
546 * Populate this PageSet from a list of revision IDs
547 * @param $revIDs array of revision IDs
548 */
549 public function populateFromRevisionIDs( $revIDs ) {
550 $this->profileIn();
551 $this->initFromRevIDs( $revIDs );
552 $this->profileOut();
553 }
554
555 /**
556 * Extract all requested fields from the row received from the database
557 * @param $row Result row
558 */
559 public function processDbRow( $row ) {
560 // Store Title object in various data structures
561 $title = Title::newFromRow( $row );
562
563 $pageId = intval( $row->page_id );
564 $this->mAllPages[$row->page_namespace][$row->page_title] = $pageId;
565 $this->mTitles[] = $title;
566
567 if ( $this->mResolveRedirects && $row->page_is_redirect == '1' ) {
568 $this->mPendingRedirectIDs[$pageId] = $title;
569 } else {
570 $this->mGoodTitles[$pageId] = $title;
571 }
572
573 foreach ( $this->mRequestedPageFields as $fieldName => &$fieldValues ) {
574 $fieldValues[$pageId] = $row-> $fieldName;
575 }
576 }
577
578 /**
579 * Do not use, does nothing, will be removed
580 * @deprecated 1.21
581 */
582 public function finishPageSetGeneration() {
583 wfDeprecated( __METHOD__, '1.21' );
584 }
585
586 /**
587 * This method populates internal variables with page information
588 * based on the given array of title strings.
589 *
590 * Steps:
591 * #1 For each title, get data from `page` table
592 * #2 If page was not found in the DB, store it as missing
593 *
594 * Additionally, when resolving redirects:
595 * #3 If no more redirects left, stop.
596 * #4 For each redirect, get its target from the `redirect` table.
597 * #5 Substitute the original LinkBatch object with the new list
598 * #6 Repeat from step #1
599 *
600 * @param $titles array of Title objects or strings
601 */
602 private function initFromTitles( $titles ) {
603 // Get validated and normalized title objects
604 $linkBatch = $this->processTitlesArray( $titles );
605 if ( $linkBatch->isEmpty() ) {
606 return;
607 }
608
609 $db = $this->getDB();
610 $set = $linkBatch->constructSet( 'page', $db );
611
612 // Get pageIDs data from the `page` table
613 $this->profileDBIn();
614 $res = $db->select( 'page', $this->getPageTableFields(), $set,
615 __METHOD__ );
616 $this->profileDBOut();
617
618 // Hack: get the ns:titles stored in array(ns => array(titles)) format
619 $this->initFromQueryResult( $res, $linkBatch->data, true ); // process Titles
620
621 // Resolve any found redirects
622 $this->resolvePendingRedirects();
623 }
624
625 /**
626 * Does the same as initFromTitles(), but is based on page IDs instead
627 * @param $pageids array of page IDs
628 */
629 private function initFromPageIds( $pageids ) {
630 if ( !$pageids ) {
631 return;
632 }
633
634 $pageids = array_map( 'intval', $pageids ); // paranoia
635 $remaining = array_flip( $pageids );
636
637 $pageids = self::getPositiveIntegers( $pageids );
638
639 $res = null;
640 if ( !empty( $pageids ) ) {
641 $set = array(
642 'page_id' => $pageids
643 );
644 $db = $this->getDB();
645
646 // Get pageIDs data from the `page` table
647 $this->profileDBIn();
648 $res = $db->select( 'page', $this->getPageTableFields(), $set,
649 __METHOD__ );
650 $this->profileDBOut();
651 }
652
653 $this->initFromQueryResult( $res, $remaining, false ); // process PageIDs
654
655 // Resolve any found redirects
656 $this->resolvePendingRedirects();
657 }
658
659 /**
660 * Iterate through the result of the query on 'page' table,
661 * and for each row create and store title object and save any extra fields requested.
662 * @param $res ResultWrapper DB Query result
663 * @param $remaining array of either pageID or ns/title elements (optional).
664 * If given, any missing items will go to $mMissingPageIDs and $mMissingTitles
665 * @param $processTitles bool Must be provided together with $remaining.
666 * If true, treat $remaining as an array of [ns][title]
667 * If false, treat it as an array of [pageIDs]
668 */
669 private function initFromQueryResult( $res, &$remaining = null, $processTitles = null ) {
670 if ( !is_null( $remaining ) && is_null( $processTitles ) ) {
671 ApiBase::dieDebug( __METHOD__, 'Missing $processTitles parameter when $remaining is provided' );
672 }
673
674 $usernames = array();
675 if ( $res ) {
676 foreach ( $res as $row ) {
677 $pageId = intval( $row->page_id );
678
679 // Remove found page from the list of remaining items
680 if ( isset( $remaining ) ) {
681 if ( $processTitles ) {
682 unset( $remaining[$row->page_namespace][$row->page_title] );
683 } else {
684 unset( $remaining[$pageId] );
685 }
686 }
687
688 // Store any extra fields requested by modules
689 $this->processDbRow( $row );
690
691 // Need gender information
692 if ( MWNamespace::hasGenderDistinction( $row->page_namespace ) ) {
693 $usernames[] = $row->page_title;
694 }
695 }
696 }
697
698 if ( isset( $remaining ) ) {
699 // Any items left in the $remaining list are added as missing
700 if ( $processTitles ) {
701 // The remaining titles in $remaining are non-existent pages
702 foreach ( $remaining as $ns => $dbkeys ) {
703 foreach ( array_keys( $dbkeys ) as $dbkey ) {
704 $title = Title::makeTitle( $ns, $dbkey );
705 $this->mAllPages[$ns][$dbkey] = $this->mFakePageId;
706 $this->mMissingTitles[$this->mFakePageId] = $title;
707 $this->mFakePageId--;
708 $this->mTitles[] = $title;
709
710 // need gender information
711 if ( MWNamespace::hasGenderDistinction( $ns ) ) {
712 $usernames[] = $dbkey;
713 }
714 }
715 }
716 } else {
717 // The remaining pageids do not exist
718 if ( !$this->mMissingPageIDs ) {
719 $this->mMissingPageIDs = array_keys( $remaining );
720 } else {
721 $this->mMissingPageIDs = array_merge( $this->mMissingPageIDs, array_keys( $remaining ) );
722 }
723 }
724 }
725
726 // Get gender information
727 $genderCache = GenderCache::singleton();
728 $genderCache->doQuery( $usernames, __METHOD__ );
729 }
730
731 /**
732 * Does the same as initFromTitles(), but is based on revision IDs
733 * instead
734 * @param $revids array of revision IDs
735 */
736 private function initFromRevIDs( $revids ) {
737 if ( !$revids ) {
738 return;
739 }
740
741 $revids = array_map( 'intval', $revids ); // paranoia
742 $db = $this->getDB();
743 $pageids = array();
744 $remaining = array_flip( $revids );
745
746 $revids = self::getPositiveIntegers( $revids );
747
748 if ( !empty( $revids ) ) {
749 $tables = array( 'revision', 'page' );
750 $fields = array( 'rev_id', 'rev_page' );
751 $where = array( 'rev_id' => $revids, 'rev_page = page_id' );
752
753 // Get pageIDs data from the `page` table
754 $this->profileDBIn();
755 $res = $db->select( $tables, $fields, $where, __METHOD__ );
756 foreach ( $res as $row ) {
757 $revid = intval( $row->rev_id );
758 $pageid = intval( $row->rev_page );
759 $this->mGoodRevIDs[$revid] = $pageid;
760 $pageids[$pageid] = '';
761 unset( $remaining[$revid] );
762 }
763 $this->profileDBOut();
764 }
765
766 $this->mMissingRevIDs = array_keys( $remaining );
767
768 // Populate all the page information
769 $this->initFromPageIds( array_keys( $pageids ) );
770 }
771
772 /**
773 * Resolve any redirects in the result if redirect resolution was
774 * requested. This function is called repeatedly until all redirects
775 * have been resolved.
776 */
777 private function resolvePendingRedirects() {
778 if ( $this->mResolveRedirects ) {
779 $db = $this->getDB();
780 $pageFlds = $this->getPageTableFields();
781
782 // Repeat until all redirects have been resolved
783 // The infinite loop is prevented by keeping all known pages in $this->mAllPages
784 while ( $this->mPendingRedirectIDs ) {
785 // Resolve redirects by querying the pagelinks table, and repeat the process
786 // Create a new linkBatch object for the next pass
787 $linkBatch = $this->getRedirectTargets();
788
789 if ( $linkBatch->isEmpty() ) {
790 break;
791 }
792
793 $set = $linkBatch->constructSet( 'page', $db );
794 if ( $set === false ) {
795 break;
796 }
797
798 // Get pageIDs data from the `page` table
799 $this->profileDBIn();
800 $res = $db->select( 'page', $pageFlds, $set, __METHOD__ );
801 $this->profileDBOut();
802
803 // Hack: get the ns:titles stored in array(ns => array(titles)) format
804 $this->initFromQueryResult( $res, $linkBatch->data, true );
805 }
806 }
807 }
808
809 /**
810 * Get the targets of the pending redirects from the database
811 *
812 * Also creates entries in the redirect table for redirects that don't
813 * have one.
814 * @return LinkBatch
815 */
816 private function getRedirectTargets() {
817 $lb = new LinkBatch();
818 $db = $this->getDB();
819
820 $this->profileDBIn();
821 $res = $db->select(
822 'redirect',
823 array(
824 'rd_from',
825 'rd_namespace',
826 'rd_fragment',
827 'rd_interwiki',
828 'rd_title'
829 ), array( 'rd_from' => array_keys( $this->mPendingRedirectIDs ) ),
830 __METHOD__
831 );
832 $this->profileDBOut();
833 foreach ( $res as $row ) {
834 $rdfrom = intval( $row->rd_from );
835 $from = $this->mPendingRedirectIDs[$rdfrom]->getPrefixedText();
836 $to = Title::makeTitle( $row->rd_namespace, $row->rd_title, $row->rd_fragment, $row->rd_interwiki );
837 unset( $this->mPendingRedirectIDs[$rdfrom] );
838 if ( !isset( $this->mAllPages[$row->rd_namespace][$row->rd_title] ) ) {
839 $lb->add( $row->rd_namespace, $row->rd_title );
840 }
841 $this->mRedirectTitles[$from] = $to;
842 }
843
844 if ( $this->mPendingRedirectIDs ) {
845 // We found pages that aren't in the redirect table
846 // Add them
847 foreach ( $this->mPendingRedirectIDs as $id => $title ) {
848 $page = WikiPage::factory( $title );
849 $rt = $page->insertRedirect();
850 if ( !$rt ) {
851 // What the hell. Let's just ignore this
852 continue;
853 }
854 $lb->addObj( $rt );
855 $this->mRedirectTitles[$title->getPrefixedText()] = $rt;
856 unset( $this->mPendingRedirectIDs[$id] );
857 }
858 }
859 return $lb;
860 }
861
862 /**
863 * Get the cache mode for the data generated by this module.
864 * All PageSet users should take into account whether this returns a more-restrictive
865 * cache mode than the using module itself. For possible return values and other
866 * details about cache modes, see ApiMain::setCacheMode()
867 *
868 * Public caching will only be allowed if *all* the modules that supply
869 * data for a given request return a cache mode of public.
870 *
871 * @param $params
872 * @return string
873 * @since 1.21
874 */
875 public function getCacheMode( $params = null ) {
876 return $this->mCacheMode;
877 }
878
879 /**
880 * Given an array of title strings, convert them into Title objects.
881 * Alternatively, an array of Title objects may be given.
882 * This method validates access rights for the title,
883 * and appends normalization values to the output.
884 *
885 * @param $titles array of Title objects or strings
886 * @return LinkBatch
887 */
888 private function processTitlesArray( $titles ) {
889 $usernames = array();
890 $linkBatch = new LinkBatch();
891
892 foreach ( $titles as $title ) {
893 if ( is_string( $title ) ) {
894 $titleObj = Title::newFromText( $title, $this->mDefaultNamespace );
895 } else {
896 $titleObj = $title;
897 }
898 if ( !$titleObj ) {
899 // Handle invalid titles gracefully
900 $this->mAllpages[0][$title] = $this->mFakePageId;
901 $this->mInvalidTitles[$this->mFakePageId] = $title;
902 $this->mFakePageId--;
903 continue; // There's nothing else we can do
904 }
905 $unconvertedTitle = $titleObj->getPrefixedText();
906 $titleWasConverted = false;
907 if ( $titleObj->isExternal() ) {
908 // This title is an interwiki link.
909 $this->mInterwikiTitles[$unconvertedTitle] = $titleObj->getInterwiki();
910 } else {
911 // Variants checking
912 global $wgContLang;
913 if ( $this->mConvertTitles &&
914 count( $wgContLang->getVariants() ) > 1 &&
915 !$titleObj->exists() ) {
916 // Language::findVariantLink will modify titleText and titleObj into
917 // the canonical variant if possible
918 $titleText = is_string( $title ) ? $title : $titleObj->getPrefixedText();
919 $wgContLang->findVariantLink( $titleText, $titleObj );
920 $titleWasConverted = $unconvertedTitle !== $titleObj->getPrefixedText();
921 }
922
923 if ( $titleObj->getNamespace() < 0 ) {
924 // Handle Special and Media pages
925 $titleObj = $titleObj->fixSpecialName();
926 $this->mSpecialTitles[$this->mFakePageId] = $titleObj;
927 $this->mFakePageId--;
928 } else {
929 // Regular page
930 $linkBatch->addObj( $titleObj );
931 }
932 }
933
934 // Make sure we remember the original title that was
935 // given to us. This way the caller can correlate new
936 // titles with the originally requested when e.g. the
937 // namespace is localized or the capitalization is
938 // different
939 if ( $titleWasConverted ) {
940 $this->mConvertedTitles[$unconvertedTitle] = $titleObj->getPrefixedText();
941 // In this case the page can't be Special.
942 if ( is_string( $title ) && $title !== $unconvertedTitle ) {
943 $this->mNormalizedTitles[$title] = $unconvertedTitle;
944 }
945 } elseif ( is_string( $title ) && $title !== $titleObj->getPrefixedText() ) {
946 $this->mNormalizedTitles[$title] = $titleObj->getPrefixedText();
947 }
948
949 // Need gender information
950 if ( MWNamespace::hasGenderDistinction( $titleObj->getNamespace() ) ) {
951 $usernames[] = $titleObj->getText();
952 }
953 }
954 // Get gender information
955 $genderCache = GenderCache::singleton();
956 $genderCache->doQuery( $usernames, __METHOD__ );
957
958 return $linkBatch;
959 }
960
961 /**
962 * Get the database connection (read-only)
963 * @return DatabaseBase
964 */
965 protected function getDB() {
966 return $this->mDbSource->getDB();
967 }
968
969 /**
970 * Returns the input array of integers with all values < 0 removed
971 *
972 * @param $array array
973 * @return array
974 */
975 private static function getPositiveIntegers( $array ) {
976 // bug 25734 API: possible issue with revids validation
977 // It seems with a load of revision rows, MySQL gets upset
978 // Remove any < 0 integers, as they can't be valid
979 foreach ( $array as $i => $int ) {
980 if ( $int < 0 ) {
981 unset( $array[$i] );
982 }
983 }
984
985 return $array;
986 }
987
988 public function getAllowedParams( $flags = 0 ) {
989 $result = array(
990 'titles' => array(
991 ApiBase::PARAM_ISMULTI => true
992 ),
993 'pageids' => array(
994 ApiBase::PARAM_TYPE => 'integer',
995 ApiBase::PARAM_ISMULTI => true
996 ),
997 'revids' => array(
998 ApiBase::PARAM_TYPE => 'integer',
999 ApiBase::PARAM_ISMULTI => true
1000 ),
1001 'redirects' => false,
1002 'converttitles' => false,
1003 );
1004 if ( $this->mAllowGenerator ) {
1005 if ( $flags & ApiBase::GET_VALUES_FOR_HELP ) {
1006 $result['generator'] = array(
1007 ApiBase::PARAM_TYPE => $this->getGenerators()
1008 );
1009 } else {
1010 $result['generator'] = null;
1011 }
1012 }
1013 return $result;
1014 }
1015
1016 private static $generators = null;
1017
1018 /**
1019 * Get an array of all available generators
1020 * @return array
1021 */
1022 private function getGenerators() {
1023 if ( self::$generators === null ) {
1024 $query = $this->mDbSource;
1025 if ( !( $query instanceof ApiQuery ) ) {
1026 // If the parent container of this pageset is not ApiQuery,
1027 // we must create it to get module manager
1028 $query = $this->getMain()->getModuleManager()->getModule( 'query' );
1029 }
1030 $gens = array();
1031 $mgr = $query->getModuleManager();
1032 foreach ( $mgr->getNamesWithClasses() as $name => $class ) {
1033 if ( is_subclass_of( $class, 'ApiQueryGeneratorBase' ) ) {
1034 $gens[] = $name;
1035 }
1036 }
1037 sort( $gens );
1038 self::$generators = $gens;
1039 }
1040 return self::$generators;
1041 }
1042
1043 public function getParamDescription() {
1044 return array(
1045 'titles' => 'A list of titles to work on',
1046 'pageids' => 'A list of page IDs to work on',
1047 'revids' => 'A list of revision IDs to work on',
1048 'generator' => array( 'Get the list of pages to work on by executing the specified query module.',
1049 'NOTE: generator parameter names must be prefixed with a \'g\', see examples' ),
1050 'redirects' => 'Automatically resolve redirects',
1051 'converttitles' => array( 'Convert titles to other variants if necessary. Only works if the wiki\'s content language supports variant conversion.',
1052 'Languages that support variant conversion include ' . implode( ', ', LanguageConverter::$languagesWithVariants ) ),
1053 );
1054 }
1055
1056 public function getPossibleErrors() {
1057 return array_merge( parent::getPossibleErrors(), array(
1058 array( 'code' => 'multisource', 'info' => "Cannot use 'pageids' at the same time as 'dataSource'" ),
1059 array( 'code' => 'multisource', 'info' => "Cannot use 'revids' at the same time as 'dataSource'" ),
1060 array( 'code' => 'badgenerator', 'info' => 'Module $generatorName cannot be used as a generator' ),
1061 ) );
1062 }
1063 }