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