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