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