Don't call localisation functions when initializing pageset
[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 $values[] = $r;
454 }
455 if ( !empty( $values ) && $result ) {
456 $result->setIndexedTagName( $values, 'r' );
457 }
458
459 return $values;
460 }
461
462 /**
463 * Get a list of title normalizations - maps a title to its normalized
464 * version.
465 * @return array Array of raw_prefixed_title (string) => prefixed_title (string)
466 */
467 public function getNormalizedTitles() {
468 return $this->mNormalizedTitles;
469 }
470
471 /**
472 * Get a list of title normalizations - maps a title to its normalized
473 * version in the form of result array.
474 * @param ApiResult $result
475 * @return array Array of raw_prefixed_title (string) => prefixed_title (string)
476 * @since 1.21
477 */
478 public function getNormalizedTitlesAsResult( $result = null ) {
479 $values = array();
480 foreach ( $this->getNormalizedTitles() as $rawTitleStr => $titleStr ) {
481 $values[] = array(
482 'from' => $rawTitleStr,
483 'to' => $titleStr
484 );
485 }
486 if ( !empty( $values ) && $result ) {
487 $result->setIndexedTagName( $values, 'n' );
488 }
489
490 return $values;
491 }
492
493 /**
494 * Get a list of title conversions - maps a title to its converted
495 * version.
496 * @return array Array of raw_prefixed_title (string) => prefixed_title (string)
497 */
498 public function getConvertedTitles() {
499 return $this->mConvertedTitles;
500 }
501
502 /**
503 * Get a list of title conversions - maps a title to its converted
504 * version as a result array.
505 * @param ApiResult $result
506 * @return array Array of (from, to) strings
507 * @since 1.21
508 */
509 public function getConvertedTitlesAsResult( $result = null ) {
510 $values = array();
511 foreach ( $this->getConvertedTitles() as $rawTitleStr => $titleStr ) {
512 $values[] = array(
513 'from' => $rawTitleStr,
514 'to' => $titleStr
515 );
516 }
517 if ( !empty( $values ) && $result ) {
518 $result->setIndexedTagName( $values, 'c' );
519 }
520
521 return $values;
522 }
523
524 /**
525 * Get a list of interwiki titles - maps a title to its interwiki
526 * prefix.
527 * @return array Array of raw_prefixed_title (string) => interwiki_prefix (string)
528 */
529 public function getInterwikiTitles() {
530 return $this->mInterwikiTitles;
531 }
532
533 /**
534 * Get a list of interwiki titles - maps a title to its interwiki
535 * prefix as result.
536 * @param ApiResult $result
537 * @param bool $iwUrl
538 * @return array Array of raw_prefixed_title (string) => interwiki_prefix (string)
539 * @since 1.21
540 */
541 public function getInterwikiTitlesAsResult( $result = null, $iwUrl = false ) {
542 $values = array();
543 foreach ( $this->getInterwikiTitles() as $rawTitleStr => $interwikiStr ) {
544 $item = array(
545 'title' => $rawTitleStr,
546 'iw' => $interwikiStr,
547 );
548 if ( $iwUrl ) {
549 $title = Title::newFromText( $rawTitleStr );
550 $item['url'] = $title->getFullURL( '', false, PROTO_CURRENT );
551 }
552 $values[] = $item;
553 }
554 if ( !empty( $values ) && $result ) {
555 $result->setIndexedTagName( $values, 'i' );
556 }
557
558 return $values;
559 }
560
561 /**
562 * Get an array of invalid/special/missing titles.
563 *
564 * @param array $invalidChecks List of types of invalid titles to include.
565 * Recognized values are:
566 * - invalidTitles: Titles from $this->getInvalidTitles()
567 * - special: Titles from $this->getSpecialTitles()
568 * - missingIds: ids from $this->getMissingPageIDs()
569 * - missingRevIds: ids from $this->getMissingRevisionIDs()
570 * - missingTitles: Titles from $this->getMissingTitles()
571 * - interwikiTitles: Titles from $this->getInterwikiTitlesAsResult()
572 * @return array Array suitable for inclusion in the response
573 * @since 1.23
574 */
575 public function getInvalidTitlesAndRevisions( $invalidChecks = array( 'invalidTitles',
576 'special', 'missingIds', 'missingRevIds', 'missingTitles', 'interwikiTitles' )
577 ) {
578 $result = array();
579 if ( in_array( "invalidTitles", $invalidChecks ) ) {
580 self::addValues( $result, $this->getInvalidTitles(), 'invalid', 'title' );
581 }
582 if ( in_array( "special", $invalidChecks ) ) {
583 self::addValues( $result, $this->getSpecialTitles(), 'special', 'title' );
584 }
585 if ( in_array( "missingIds", $invalidChecks ) ) {
586 self::addValues( $result, $this->getMissingPageIDs(), 'missing', 'pageid' );
587 }
588 if ( in_array( "missingRevIds", $invalidChecks ) ) {
589 self::addValues( $result, $this->getMissingRevisionIDs(), 'missing', 'revid' );
590 }
591 if ( in_array( "missingTitles", $invalidChecks ) ) {
592 self::addValues( $result, $this->getMissingTitles(), 'missing' );
593 }
594 if ( in_array( "interwikiTitles", $invalidChecks ) ) {
595 self::addValues( $result, $this->getInterwikiTitlesAsResult() );
596 }
597
598 return $result;
599 }
600
601 /**
602 * Get the list of valid revision IDs (requested with the revids= parameter)
603 * @return array Array of revID (int) => pageID (int)
604 */
605 public function getRevisionIDs() {
606 return $this->mGoodRevIDs;
607 }
608
609 /**
610 * Get the list of non-deleted revision IDs (requested with the revids= parameter)
611 * @return array Array of revID (int) => pageID (int)
612 */
613 public function getLiveRevisionIDs() {
614 return $this->mLiveRevIDs;
615 }
616
617 /**
618 * Get the list of revision IDs that were associated with deleted titles.
619 * @return array Array of revID (int) => pageID (int)
620 */
621 public function getDeletedRevisionIDs() {
622 return $this->mDeletedRevIDs;
623 }
624
625 /**
626 * Revision IDs that were not found in the database
627 * @return array Array of revision IDs
628 */
629 public function getMissingRevisionIDs() {
630 return $this->mMissingRevIDs;
631 }
632
633 /**
634 * Revision IDs that were not found in the database as result array.
635 * @param ApiResult $result
636 * @return array Array of revision IDs
637 * @since 1.21
638 */
639 public function getMissingRevisionIDsAsResult( $result = null ) {
640 $values = array();
641 foreach ( $this->getMissingRevisionIDs() as $revid ) {
642 $values[$revid] = array(
643 'revid' => $revid
644 );
645 }
646 if ( !empty( $values ) && $result ) {
647 $result->setIndexedTagName( $values, 'rev' );
648 }
649
650 return $values;
651 }
652
653 /**
654 * Get the list of titles with negative namespace
655 * @return Title[]
656 */
657 public function getSpecialTitles() {
658 return $this->mSpecialTitles;
659 }
660
661 /**
662 * Returns the number of revisions (requested with revids= parameter).
663 * @return int Number of revisions.
664 */
665 public function getRevisionCount() {
666 return count( $this->getRevisionIDs() );
667 }
668
669 /**
670 * Populate this PageSet from a list of Titles
671 * @param array $titles Array of Title objects
672 */
673 public function populateFromTitles( $titles ) {
674 $this->profileIn();
675 $this->initFromTitles( $titles );
676 $this->profileOut();
677 }
678
679 /**
680 * Populate this PageSet from a list of page IDs
681 * @param array $pageIDs Array of page IDs
682 */
683 public function populateFromPageIDs( $pageIDs ) {
684 $this->profileIn();
685 $this->initFromPageIds( $pageIDs );
686 $this->profileOut();
687 }
688
689 /**
690 * Populate this PageSet from a rowset returned from the database
691 *
692 * Note that the query result must include the columns returned by
693 * $this->getPageTableFields().
694 *
695 * @param DatabaseBase $db
696 * @param ResultWrapper $queryResult Query result object
697 */
698 public function populateFromQueryResult( $db, $queryResult ) {
699 $this->profileIn();
700 $this->initFromQueryResult( $queryResult );
701 $this->profileOut();
702 }
703
704 /**
705 * Populate this PageSet from a list of revision IDs
706 * @param array $revIDs Array of revision IDs
707 */
708 public function populateFromRevisionIDs( $revIDs ) {
709 $this->profileIn();
710 $this->initFromRevIDs( $revIDs );
711 $this->profileOut();
712 }
713
714 /**
715 * Extract all requested fields from the row received from the database
716 * @param stdClass $row Result row
717 */
718 public function processDbRow( $row ) {
719 // Store Title object in various data structures
720 $title = Title::newFromRow( $row );
721
722 $pageId = intval( $row->page_id );
723 $this->mAllPages[$row->page_namespace][$row->page_title] = $pageId;
724 $this->mTitles[] = $title;
725
726 if ( $this->mResolveRedirects && $row->page_is_redirect == '1' ) {
727 $this->mPendingRedirectIDs[$pageId] = $title;
728 } else {
729 $this->mGoodPages[$row->page_namespace][$row->page_title] = $pageId;
730 $this->mGoodAndMissingPages[$row->page_namespace][$row->page_title] = $pageId;
731 $this->mGoodTitles[$pageId] = $title;
732 }
733
734 foreach ( $this->mRequestedPageFields as $fieldName => &$fieldValues ) {
735 $fieldValues[$pageId] = $row->$fieldName;
736 }
737 }
738
739 /**
740 * Do not use, does nothing, will be removed
741 * @deprecated since 1.21
742 */
743 public function finishPageSetGeneration() {
744 wfDeprecated( __METHOD__, '1.21' );
745 }
746
747 /**
748 * This method populates internal variables with page information
749 * based on the given array of title strings.
750 *
751 * Steps:
752 * #1 For each title, get data from `page` table
753 * #2 If page was not found in the DB, store it as missing
754 *
755 * Additionally, when resolving redirects:
756 * #3 If no more redirects left, stop.
757 * #4 For each redirect, get its target from the `redirect` table.
758 * #5 Substitute the original LinkBatch object with the new list
759 * #6 Repeat from step #1
760 *
761 * @param array $titles Array of Title objects or strings
762 */
763 private function initFromTitles( $titles ) {
764 // Get validated and normalized title objects
765 $linkBatch = $this->processTitlesArray( $titles );
766 if ( $linkBatch->isEmpty() ) {
767 return;
768 }
769
770 $db = $this->getDB();
771 $set = $linkBatch->constructSet( 'page', $db );
772
773 // Get pageIDs data from the `page` table
774 $this->profileDBIn();
775 $res = $db->select( 'page', $this->getPageTableFields(), $set,
776 __METHOD__ );
777 $this->profileDBOut();
778
779 // Hack: get the ns:titles stored in array(ns => array(titles)) format
780 $this->initFromQueryResult( $res, $linkBatch->data, true ); // process Titles
781
782 // Resolve any found redirects
783 $this->resolvePendingRedirects();
784 }
785
786 /**
787 * Does the same as initFromTitles(), but is based on page IDs instead
788 * @param array $pageids Array of page IDs
789 */
790 private function initFromPageIds( $pageids ) {
791 if ( !$pageids ) {
792 return;
793 }
794
795 $pageids = array_map( 'intval', $pageids ); // paranoia
796 $remaining = array_flip( $pageids );
797
798 $pageids = self::getPositiveIntegers( $pageids );
799
800 $res = null;
801 if ( !empty( $pageids ) ) {
802 $set = array(
803 'page_id' => $pageids
804 );
805 $db = $this->getDB();
806
807 // Get pageIDs data from the `page` table
808 $this->profileDBIn();
809 $res = $db->select( 'page', $this->getPageTableFields(), $set,
810 __METHOD__ );
811 $this->profileDBOut();
812 }
813
814 $this->initFromQueryResult( $res, $remaining, false ); // process PageIDs
815
816 // Resolve any found redirects
817 $this->resolvePendingRedirects();
818 }
819
820 /**
821 * Iterate through the result of the query on 'page' table,
822 * and for each row create and store title object and save any extra fields requested.
823 * @param ResultWrapper $res DB Query result
824 * @param array $remaining Array of either pageID or ns/title elements (optional).
825 * If given, any missing items will go to $mMissingPageIDs and $mMissingTitles
826 * @param bool $processTitles Must be provided together with $remaining.
827 * If true, treat $remaining as an array of [ns][title]
828 * If false, treat it as an array of [pageIDs]
829 */
830 private function initFromQueryResult( $res, &$remaining = null, $processTitles = null ) {
831 if ( !is_null( $remaining ) && is_null( $processTitles ) ) {
832 ApiBase::dieDebug( __METHOD__, 'Missing $processTitles parameter when $remaining is provided' );
833 }
834
835 $usernames = array();
836 if ( $res ) {
837 foreach ( $res as $row ) {
838 $pageId = intval( $row->page_id );
839
840 // Remove found page from the list of remaining items
841 if ( isset( $remaining ) ) {
842 if ( $processTitles ) {
843 unset( $remaining[$row->page_namespace][$row->page_title] );
844 } else {
845 unset( $remaining[$pageId] );
846 }
847 }
848
849 // Store any extra fields requested by modules
850 $this->processDbRow( $row );
851
852 // Need gender information
853 if ( MWNamespace::hasGenderDistinction( $row->page_namespace ) ) {
854 $usernames[] = $row->page_title;
855 }
856 }
857 }
858
859 if ( isset( $remaining ) ) {
860 // Any items left in the $remaining list are added as missing
861 if ( $processTitles ) {
862 // The remaining titles in $remaining are non-existent pages
863 foreach ( $remaining as $ns => $dbkeys ) {
864 foreach ( array_keys( $dbkeys ) as $dbkey ) {
865 $title = Title::makeTitle( $ns, $dbkey );
866 $this->mAllPages[$ns][$dbkey] = $this->mFakePageId;
867 $this->mMissingPages[$ns][$dbkey] = $this->mFakePageId;
868 $this->mGoodAndMissingPages[$ns][$dbkey] = $this->mFakePageId;
869 $this->mMissingTitles[$this->mFakePageId] = $title;
870 $this->mFakePageId--;
871 $this->mTitles[] = $title;
872
873 // need gender information
874 if ( MWNamespace::hasGenderDistinction( $ns ) ) {
875 $usernames[] = $dbkey;
876 }
877 }
878 }
879 } else {
880 // The remaining pageids do not exist
881 if ( !$this->mMissingPageIDs ) {
882 $this->mMissingPageIDs = array_keys( $remaining );
883 } else {
884 $this->mMissingPageIDs = array_merge( $this->mMissingPageIDs, array_keys( $remaining ) );
885 }
886 }
887 }
888
889 // Get gender information
890 $genderCache = GenderCache::singleton();
891 $genderCache->doQuery( $usernames, __METHOD__ );
892 }
893
894 /**
895 * Does the same as initFromTitles(), but is based on revision IDs
896 * instead
897 * @param array $revids Array of revision IDs
898 */
899 private function initFromRevIDs( $revids ) {
900 if ( !$revids ) {
901 return;
902 }
903
904 $revids = array_map( 'intval', $revids ); // paranoia
905 $db = $this->getDB();
906 $pageids = array();
907 $remaining = array_flip( $revids );
908
909 $revids = self::getPositiveIntegers( $revids );
910
911 if ( !empty( $revids ) ) {
912 $tables = array( 'revision', 'page' );
913 $fields = array( 'rev_id', 'rev_page' );
914 $where = array( 'rev_id' => $revids, 'rev_page = page_id' );
915
916 // Get pageIDs data from the `page` table
917 $this->profileDBIn();
918 $res = $db->select( $tables, $fields, $where, __METHOD__ );
919 foreach ( $res as $row ) {
920 $revid = intval( $row->rev_id );
921 $pageid = intval( $row->rev_page );
922 $this->mGoodRevIDs[$revid] = $pageid;
923 $this->mLiveRevIDs[$revid] = $pageid;
924 $pageids[$pageid] = '';
925 unset( $remaining[$revid] );
926 }
927 $this->profileDBOut();
928 }
929
930 $this->mMissingRevIDs = array_keys( $remaining );
931
932 // Populate all the page information
933 $this->initFromPageIds( array_keys( $pageids ) );
934
935 // If the user can see deleted revisions, pull out the corresponding
936 // titles from the archive table and include them too. We ignore
937 // ar_page_id because deleted revisions are tied by title, not page_id.
938 if ( !empty( $this->mMissingRevIDs ) && $this->getUser()->isAllowed( 'deletedhistory' ) ) {
939 $remaining = array_flip( $this->mMissingRevIDs );
940 $tables = array( 'archive' );
941 $fields = array( 'ar_rev_id', 'ar_namespace', 'ar_title' );
942 $where = array( 'ar_rev_id' => $this->mMissingRevIDs );
943
944 $this->profileDBIn();
945 $res = $db->select( $tables, $fields, $where, __METHOD__ );
946 $titles = array();
947 foreach ( $res as $row ) {
948 $revid = intval( $row->ar_rev_id );
949 $titles[$revid] = Title::makeTitle( $row->ar_namespace, $row->ar_title );
950 unset( $remaining[$revid] );
951 }
952 $this->profileDBOut();
953
954 $this->initFromTitles( $titles );
955
956 foreach ( $titles as $revid => $title ) {
957 $ns = $title->getNamespace();
958 $dbkey = $title->getDBkey();
959
960 // Handle converted titles
961 if ( !isset( $this->mAllPages[$ns][$dbkey] ) &&
962 isset( $this->mConvertedTitles[$title->getPrefixedText()] )
963 ) {
964 $title = Title::newFromText( $this->mConvertedTitles[$title->getPrefixedText()] );
965 $ns = $title->getNamespace();
966 $dbkey = $title->getDBkey();
967 }
968
969 if ( isset( $this->mAllPages[$ns][$dbkey] ) ) {
970 $this->mGoodRevIDs[$revid] = $this->mAllPages[$ns][$dbkey];
971 $this->mDeletedRevIDs[$revid] = $this->mAllPages[$ns][$dbkey];
972 } else {
973 $remaining[$revid] = true;
974 }
975 }
976
977 $this->mMissingRevIDs = array_keys( $remaining );
978 }
979 }
980
981 /**
982 * Resolve any redirects in the result if redirect resolution was
983 * requested. This function is called repeatedly until all redirects
984 * have been resolved.
985 */
986 private function resolvePendingRedirects() {
987 if ( $this->mResolveRedirects ) {
988 $db = $this->getDB();
989 $pageFlds = $this->getPageTableFields();
990
991 // Repeat until all redirects have been resolved
992 // The infinite loop is prevented by keeping all known pages in $this->mAllPages
993 while ( $this->mPendingRedirectIDs ) {
994 // Resolve redirects by querying the pagelinks table, and repeat the process
995 // Create a new linkBatch object for the next pass
996 $linkBatch = $this->getRedirectTargets();
997
998 if ( $linkBatch->isEmpty() ) {
999 break;
1000 }
1001
1002 $set = $linkBatch->constructSet( 'page', $db );
1003 if ( $set === false ) {
1004 break;
1005 }
1006
1007 // Get pageIDs data from the `page` table
1008 $this->profileDBIn();
1009 $res = $db->select( 'page', $pageFlds, $set, __METHOD__ );
1010 $this->profileDBOut();
1011
1012 // Hack: get the ns:titles stored in array(ns => array(titles)) format
1013 $this->initFromQueryResult( $res, $linkBatch->data, true );
1014 }
1015 }
1016 }
1017
1018 /**
1019 * Get the targets of the pending redirects from the database
1020 *
1021 * Also creates entries in the redirect table for redirects that don't
1022 * have one.
1023 * @return LinkBatch
1024 */
1025 private function getRedirectTargets() {
1026 $lb = new LinkBatch();
1027 $db = $this->getDB();
1028
1029 $this->profileDBIn();
1030 $res = $db->select(
1031 'redirect',
1032 array(
1033 'rd_from',
1034 'rd_namespace',
1035 'rd_fragment',
1036 'rd_interwiki',
1037 'rd_title'
1038 ), array( 'rd_from' => array_keys( $this->mPendingRedirectIDs ) ),
1039 __METHOD__
1040 );
1041 $this->profileDBOut();
1042 foreach ( $res as $row ) {
1043 $rdfrom = intval( $row->rd_from );
1044 $from = $this->mPendingRedirectIDs[$rdfrom]->getPrefixedText();
1045 $to = Title::makeTitle(
1046 $row->rd_namespace,
1047 $row->rd_title,
1048 $row->rd_fragment,
1049 $row->rd_interwiki
1050 );
1051 unset( $this->mPendingRedirectIDs[$rdfrom] );
1052 if ( !$to->isExternal() && !isset( $this->mAllPages[$row->rd_namespace][$row->rd_title] ) ) {
1053 $lb->add( $row->rd_namespace, $row->rd_title );
1054 }
1055 $this->mRedirectTitles[$from] = $to;
1056 }
1057
1058 if ( $this->mPendingRedirectIDs ) {
1059 // We found pages that aren't in the redirect table
1060 // Add them
1061 foreach ( $this->mPendingRedirectIDs as $id => $title ) {
1062 $page = WikiPage::factory( $title );
1063 $rt = $page->insertRedirect();
1064 if ( !$rt ) {
1065 // What the hell. Let's just ignore this
1066 continue;
1067 }
1068 $lb->addObj( $rt );
1069 $this->mRedirectTitles[$title->getPrefixedText()] = $rt;
1070 unset( $this->mPendingRedirectIDs[$id] );
1071 }
1072 }
1073
1074 return $lb;
1075 }
1076
1077 /**
1078 * Get the cache mode for the data generated by this module.
1079 * All PageSet users should take into account whether this returns a more-restrictive
1080 * cache mode than the using module itself. For possible return values and other
1081 * details about cache modes, see ApiMain::setCacheMode()
1082 *
1083 * Public caching will only be allowed if *all* the modules that supply
1084 * data for a given request return a cache mode of public.
1085 *
1086 * @param array|null $params
1087 * @return string
1088 * @since 1.21
1089 */
1090 public function getCacheMode( $params = null ) {
1091 return $this->mCacheMode;
1092 }
1093
1094 /**
1095 * Given an array of title strings, convert them into Title objects.
1096 * Alternatively, an array of Title objects may be given.
1097 * This method validates access rights for the title,
1098 * and appends normalization values to the output.
1099 *
1100 * @param array $titles Array of Title objects or strings
1101 * @return LinkBatch
1102 */
1103 private function processTitlesArray( $titles ) {
1104 $usernames = array();
1105 $linkBatch = new LinkBatch();
1106
1107 foreach ( $titles as $title ) {
1108 if ( is_string( $title ) ) {
1109 $titleObj = Title::newFromText( $title, $this->mDefaultNamespace );
1110 } else {
1111 $titleObj = $title;
1112 }
1113 if ( !$titleObj ) {
1114 // Handle invalid titles gracefully
1115 $this->mAllPages[0][$title] = $this->mFakePageId;
1116 $this->mInvalidTitles[$this->mFakePageId] = $title;
1117 $this->mFakePageId--;
1118 continue; // There's nothing else we can do
1119 }
1120 $unconvertedTitle = $titleObj->getPrefixedText();
1121 $titleWasConverted = false;
1122 if ( $titleObj->isExternal() ) {
1123 // This title is an interwiki link.
1124 $this->mInterwikiTitles[$unconvertedTitle] = $titleObj->getInterwiki();
1125 } else {
1126 // Variants checking
1127 global $wgContLang;
1128 if ( $this->mConvertTitles &&
1129 count( $wgContLang->getVariants() ) > 1 &&
1130 !$titleObj->exists()
1131 ) {
1132 // Language::findVariantLink will modify titleText and titleObj into
1133 // the canonical variant if possible
1134 $titleText = is_string( $title ) ? $title : $titleObj->getPrefixedText();
1135 $wgContLang->findVariantLink( $titleText, $titleObj );
1136 $titleWasConverted = $unconvertedTitle !== $titleObj->getPrefixedText();
1137 }
1138
1139 if ( $titleObj->getNamespace() < 0 ) {
1140 // Handle Special and Media pages
1141 $titleObj = $titleObj->fixSpecialName();
1142 $this->mSpecialTitles[$this->mFakePageId] = $titleObj;
1143 $this->mFakePageId--;
1144 } else {
1145 // Regular page
1146 $linkBatch->addObj( $titleObj );
1147 }
1148 }
1149
1150 // Make sure we remember the original title that was
1151 // given to us. This way the caller can correlate new
1152 // titles with the originally requested when e.g. the
1153 // namespace is localized or the capitalization is
1154 // different
1155 if ( $titleWasConverted ) {
1156 $this->mConvertedTitles[$unconvertedTitle] = $titleObj->getPrefixedText();
1157 // In this case the page can't be Special.
1158 if ( is_string( $title ) && $title !== $unconvertedTitle ) {
1159 $this->mNormalizedTitles[$title] = $unconvertedTitle;
1160 }
1161 } elseif ( is_string( $title ) && $title !== $titleObj->getPrefixedText() ) {
1162 $this->mNormalizedTitles[$title] = $titleObj->getPrefixedText();
1163 }
1164
1165 // Need gender information
1166 if ( MWNamespace::hasGenderDistinction( $titleObj->getNamespace() ) ) {
1167 $usernames[] = $titleObj->getText();
1168 }
1169 }
1170 // Get gender information
1171 $genderCache = GenderCache::singleton();
1172 $genderCache->doQuery( $usernames, __METHOD__ );
1173
1174 return $linkBatch;
1175 }
1176
1177 /**
1178 * Set data for a title.
1179 *
1180 * This data may be extracted into an ApiResult using
1181 * self::populateGeneratorData. This should generally be limited to
1182 * data that is likely to be particularly useful to end users rather than
1183 * just being a dump of everything returned in non-generator mode.
1184 *
1185 * Redirects here will *not* be followed, even if 'redirects' was
1186 * specified, since in the case of multiple redirects we can't know which
1187 * source's data to use on the target.
1188 *
1189 * @param Title $title
1190 * @param array $data
1191 */
1192 public function setGeneratorData( Title $title, array $data ) {
1193 $ns = $title->getNamespace();
1194 $dbkey = $title->getDBkey();
1195 $this->mGeneratorData[$ns][$dbkey] = $data;
1196 }
1197
1198 /**
1199 * Populate the generator data for all titles in the result
1200 *
1201 * The page data may be inserted into an ApiResult object or into an
1202 * associative array. The $path parameter specifies the path within the
1203 * ApiResult or array to find the "pages" node.
1204 *
1205 * The "pages" node itself must be an associative array mapping the page ID
1206 * or fake page ID values returned by this pageset (see
1207 * self::getAllTitlesByNamespace() and self::getSpecialTitles()) to
1208 * associative arrays of page data. Each of those subarrays will have the
1209 * data from self::setGeneratorData() merged in.
1210 *
1211 * Data that was set by self::setGeneratorData() for pages not in the
1212 * "pages" node will be ignored.
1213 *
1214 * @param ApiResult|array &$result
1215 * @param array $path
1216 * @return bool Whether the data fit
1217 */
1218 public function populateGeneratorData( &$result, array $path = array() ) {
1219 if ( $result instanceof ApiResult ) {
1220 $data = $result->getData();
1221 } else {
1222 $data = &$result;
1223 }
1224 foreach ( $path as $key ) {
1225 if ( !isset( $data[$key] ) ) {
1226 // Path isn't in $result, so nothing to add, so everything
1227 // "fits"
1228 return true;
1229 }
1230 $data = &$data[$key];
1231 }
1232 foreach ( $this->mGeneratorData as $ns => $dbkeys ) {
1233 if ( $ns === -1 ) {
1234 $pages = array();
1235 foreach ( $this->mSpecialTitles as $id => $title ) {
1236 $pages[$title->getDBkey()] = $id;
1237 }
1238 } else {
1239 if ( !isset( $this->mAllPages[$ns] ) ) {
1240 // No known titles in the whole namespace. Skip it.
1241 continue;
1242 }
1243 $pages = $this->mAllPages[$ns];
1244 }
1245 foreach ( $dbkeys as $dbkey => $genData ) {
1246 if ( !isset( $pages[$dbkey] ) ) {
1247 // Unknown title. Forget it.
1248 continue;
1249 }
1250 $pageId = $pages[$dbkey];
1251 if ( !isset( $data[$pageId] ) ) {
1252 // $pageId didn't make it into the result. Ignore it.
1253 continue;
1254 }
1255
1256 if ( $result instanceof ApiResult ) {
1257 $path2 = array_merge( $path, array( $pageId ) );
1258 foreach ( $genData as $key => $value ) {
1259 if ( !$result->addValue( $path2, $key, $value ) ) {
1260 return false;
1261 }
1262 }
1263 } else {
1264 $data[$pageId] = array_merge( $data[$pageId], $genData );
1265 }
1266 }
1267 }
1268 return true;
1269 }
1270
1271 /**
1272 * Get the database connection (read-only)
1273 * @return DatabaseBase
1274 */
1275 protected function getDB() {
1276 return $this->mDbSource->getDB();
1277 }
1278
1279 /**
1280 * Returns the input array of integers with all values < 0 removed
1281 *
1282 * @param array $array
1283 * @return array
1284 */
1285 private static function getPositiveIntegers( $array ) {
1286 // bug 25734 API: possible issue with revids validation
1287 // It seems with a load of revision rows, MySQL gets upset
1288 // Remove any < 0 integers, as they can't be valid
1289 foreach ( $array as $i => $int ) {
1290 if ( $int < 0 ) {
1291 unset( $array[$i] );
1292 }
1293 }
1294
1295 return $array;
1296 }
1297
1298 public function getAllowedParams( $flags = 0 ) {
1299 $result = array(
1300 'titles' => array(
1301 ApiBase::PARAM_ISMULTI => true,
1302 ApiBase::PARAM_HELP_MSG => 'api-pageset-param-titles',
1303 ),
1304 'pageids' => array(
1305 ApiBase::PARAM_TYPE => 'integer',
1306 ApiBase::PARAM_ISMULTI => true,
1307 ApiBase::PARAM_HELP_MSG => 'api-pageset-param-pageids',
1308 ),
1309 'revids' => array(
1310 ApiBase::PARAM_TYPE => 'integer',
1311 ApiBase::PARAM_ISMULTI => true,
1312 ApiBase::PARAM_HELP_MSG => 'api-pageset-param-revids',
1313 ),
1314 'generator' => array(
1315 ApiBase::PARAM_TYPE => null,
1316 ApiBase::PARAM_VALUE_LINKS => array(),
1317 ApiBase::PARAM_HELP_MSG => 'api-pageset-param-generator',
1318 ),
1319 'redirects' => array(
1320 ApiBase::PARAM_DFLT => false,
1321 ApiBase::PARAM_HELP_MSG => $this->mAllowGenerator
1322 ? 'api-pageset-param-redirects-generator'
1323 : 'api-pageset-param-redirects-nogenerator',
1324 ),
1325 'converttitles' => array(
1326 ApiBase::PARAM_DFLT => false,
1327 ApiBase::PARAM_HELP_MSG => array(
1328 'api-pageset-param-converttitles',
1329 new DeferredStringifier(
1330 function ( IContextSource $context ) {
1331 return $context->getLanguage()
1332 ->commaList( LanguageConverter::$languagesWithVariants );
1333 },
1334 $this
1335 )
1336 ),
1337 ),
1338 );
1339
1340 if ( !$this->mAllowGenerator ) {
1341 unset( $result['generator'] );
1342 } elseif ( $flags & ApiBase::GET_VALUES_FOR_HELP ) {
1343 foreach ( $this->getGenerators() as $g ) {
1344 $result['generator'][ApiBase::PARAM_TYPE][] = $g;
1345 $result['generator'][ApiBase::PARAM_VALUE_LINKS][$g] = "Special:ApiHelp/query+$g";
1346 }
1347 }
1348
1349 return $result;
1350 }
1351
1352 private static $generators = null;
1353
1354 /**
1355 * Get an array of all available generators
1356 * @return array
1357 */
1358 private function getGenerators() {
1359 if ( self::$generators === null ) {
1360 $query = $this->mDbSource;
1361 if ( !( $query instanceof ApiQuery ) ) {
1362 // If the parent container of this pageset is not ApiQuery,
1363 // we must create it to get module manager
1364 $query = $this->getMain()->getModuleManager()->getModule( 'query' );
1365 }
1366 $gens = array();
1367 $mgr = $query->getModuleManager();
1368 foreach ( $mgr->getNamesWithClasses() as $name => $class ) {
1369 if ( is_subclass_of( $class, 'ApiQueryGeneratorBase' ) ) {
1370 $gens[] = $name;
1371 }
1372 }
1373 sort( $gens );
1374 self::$generators = $gens;
1375 }
1376
1377 return self::$generators;
1378 }
1379 }