Rewrite ajaxwatch.js to use the API watch action, and JQuery. Allows it to be used...
[lhc/web/wiklou.git] / includes / api / ApiPageSet.php
1 <?php
2
3 /**
4 * Created on Sep 24, 2006
5 *
6 * API for MediaWiki 1.8+
7 *
8 * Copyright © 2006 Yuri Astrakhan <Firstname><Lastname>@gmail.com
9 *
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
14 *
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
19 *
20 * You should have received a copy of the GNU General Public License along
21 * with this program; if not, write to the Free Software Foundation, Inc.,
22 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
23 * http://www.gnu.org/copyleft/gpl.html
24 */
25
26 if ( !defined( 'MEDIAWIKI' ) ) {
27 // Eclipse helper - will be ignored in production
28 require_once( 'ApiQueryBase.php' );
29 }
30
31 /**
32 * This class contains a list of pages that the client has requested.
33 * Initially, when the client passes in titles=, pageids=, or revisions=
34 * parameter, an instance of the ApiPageSet class will normalize titles,
35 * determine if the pages/revisions exist, and prefetch any additional page
36 * data requested.
37 *
38 * When a generator is used, the result of the generator will become the input
39 * for the second instance of this class, and all subsequent actions will use
40 * the second instance for all their work.
41 *
42 * @ingroup API
43 */
44 class ApiPageSet extends ApiQueryBase {
45
46 private $mAllPages; // [ns][dbkey] => page_id or negative when missing
47 private $mTitles, $mGoodTitles, $mMissingTitles, $mInvalidTitles;
48 private $mMissingPageIDs, $mRedirectTitles;
49 private $mNormalizedTitles, $mInterwikiTitles;
50 private $mResolveRedirects, $mPendingRedirectIDs;
51 private $mGoodRevIDs, $mMissingRevIDs;
52 private $mFakePageId;
53
54 private $mRequestedPageFields;
55
56 /**
57 * Constructor
58 * @param $query ApiQuery
59 * @param $resolveRedirects bool Whether redirects should be resolved
60 */
61 public function __construct( $query, $resolveRedirects = false ) {
62 parent::__construct( $query, 'query' );
63
64 $this->mAllPages = array();
65 $this->mTitles = array();
66 $this->mGoodTitles = array();
67 $this->mMissingTitles = array();
68 $this->mInvalidTitles = array();
69 $this->mMissingPageIDs = array();
70 $this->mRedirectTitles = array();
71 $this->mNormalizedTitles = array();
72 $this->mInterwikiTitles = array();
73 $this->mGoodRevIDs = array();
74 $this->mMissingRevIDs = array();
75
76 $this->mRequestedPageFields = array();
77 $this->mResolveRedirects = $resolveRedirects;
78 if ( $resolveRedirects ) {
79 $this->mPendingRedirectIDs = array();
80 }
81
82 $this->mFakePageId = - 1;
83 }
84
85 /**
86 * Check whether this PageSet is resolving redirects
87 * @return bool
88 */
89 public function isResolvingRedirects() {
90 return $this->mResolveRedirects;
91 }
92
93 /**
94 * Request an additional field from the page table. Must be called
95 * before execute()
96 * @param $fieldName string Field name
97 */
98 public function requestField( $fieldName ) {
99 $this->mRequestedPageFields[$fieldName] = null;
100 }
101
102 /**
103 * Get the value of a custom field previously requested through
104 * requestField()
105 * @param $fieldName string Field name
106 * @return mixed Field value
107 */
108 public function getCustomField( $fieldName ) {
109 return $this->mRequestedPageFields[$fieldName];
110 }
111
112 /**
113 * Get the fields that have to be queried from the page table:
114 * the ones requested through requestField() and a few basic ones
115 * we always need
116 * @return array of field names
117 */
118 public function getPageTableFields() {
119 // Ensure we get minimum required fields
120 // DON'T change this order
121 $pageFlds = array(
122 'page_namespace' => null,
123 'page_title' => null,
124 'page_id' => null,
125 );
126
127 if ( $this->mResolveRedirects ) {
128 $pageFlds['page_is_redirect'] = null;
129 }
130
131 // only store non-default fields
132 $this->mRequestedPageFields = array_diff_key( $this->mRequestedPageFields, $pageFlds );
133
134 $pageFlds = array_merge( $pageFlds, $this->mRequestedPageFields );
135 return array_keys( $pageFlds );
136 }
137
138 /**
139 * Returns an array [ns][dbkey] => page_id for all requested titles.
140 * page_id is a unique negative number in case title was not found.
141 * Invalid titles will also have negative page IDs and will be in namespace 0
142 * @return array
143 */
144 public function getAllTitlesByNamespace() {
145 return $this->mAllPages;
146 }
147
148 /**
149 * All Title objects provided.
150 * @return array of Title objects
151 */
152 public function getTitles() {
153 return $this->mTitles;
154 }
155
156 /**
157 * Returns the number of unique pages (not revisions) in the set.
158 * @return int
159 */
160 public function getTitleCount() {
161 return count( $this->mTitles );
162 }
163
164 /**
165 * Title objects that were found in the database.
166 * @return array page_id (int) => Title (obj)
167 */
168 public function getGoodTitles() {
169 return $this->mGoodTitles;
170 }
171
172 /**
173 * Returns the number of found unique pages (not revisions) in the set.
174 * @return int
175 */
176 public function getGoodTitleCount() {
177 return count( $this->mGoodTitles );
178 }
179
180 /**
181 * Title objects that were NOT found in the database.
182 * The array's index will be negative for each item
183 * @return array of Title objects
184 */
185 public function getMissingTitles() {
186 return $this->mMissingTitles;
187 }
188
189 /**
190 * Titles that were deemed invalid by Title::newFromText()
191 * The array's index will be unique and negative for each item
192 * @return array of strings (not Title objects)
193 */
194 public function getInvalidTitles() {
195 return $this->mInvalidTitles;
196 }
197
198 /**
199 * Page IDs that were not found in the database
200 * @return array of page IDs
201 */
202 public function getMissingPageIDs() {
203 return $this->mMissingPageIDs;
204 }
205
206 /**
207 * Get a list of redirect resolutions - maps a title to its redirect
208 * target.
209 * @return array prefixed_title (string) => prefixed_title (string)
210 */
211 public function getRedirectTitles() {
212 return $this->mRedirectTitles;
213 }
214
215 /**
216 * Get a list of title normalizations - maps a title to its normalized
217 * version.
218 * @return array raw_prefixed_title (string) => prefixed_title (string)
219 */
220 public function getNormalizedTitles() {
221 return $this->mNormalizedTitles;
222 }
223
224 /**
225 * Get a list of interwiki titles - maps a title to its interwiki
226 * prefix.
227 * @return array raw_prefixed_title (string) => interwiki_prefix (string)
228 */
229 public function getInterwikiTitles() {
230 return $this->mInterwikiTitles;
231 }
232
233 /**
234 * Get the list of revision IDs (requested with the revids= parameter)
235 * @return array revID (int) => pageID (int)
236 */
237 public function getRevisionIDs() {
238 return $this->mGoodRevIDs;
239 }
240
241 /**
242 * Revision IDs that were not found in the database
243 * @return array of revision IDs
244 */
245 public function getMissingRevisionIDs() {
246 return $this->mMissingRevIDs;
247 }
248
249 /**
250 * Returns the number of revisions (requested with revids= parameter)\
251 * @return int
252 */
253 public function getRevisionCount() {
254 return count( $this->getRevisionIDs() );
255 }
256
257 /**
258 * Populate the PageSet from the request parameters.
259 */
260 public function execute() {
261 $this->profileIn();
262 $params = $this->extractRequestParams();
263
264 // Only one of the titles/pageids/revids is allowed at the same time
265 $dataSource = null;
266 if ( isset( $params['titles'] ) ) {
267 $dataSource = 'titles';
268 }
269 if ( isset( $params['pageids'] ) ) {
270 if ( isset( $dataSource ) ) {
271 $this->dieUsage( "Cannot use 'pageids' at the same time as '$dataSource'", 'multisource' );
272 }
273 $dataSource = 'pageids';
274 }
275 if ( isset( $params['revids'] ) ) {
276 if ( isset( $dataSource ) ) {
277 $this->dieUsage( "Cannot use 'revids' at the same time as '$dataSource'", 'multisource' );
278 }
279 $dataSource = 'revids';
280 }
281
282 switch ( $dataSource ) {
283 case 'titles':
284 $this->initFromTitles( $params['titles'] );
285 break;
286 case 'pageids':
287 $this->initFromPageIds( $params['pageids'] );
288 break;
289 case 'revids':
290 if ( $this->mResolveRedirects ) {
291 $this->setWarning( 'Redirect resolution cannot be used together with the revids= parameter. ' .
292 'Any redirects the revids= point to have not been resolved.' );
293 }
294 $this->mResolveRedirects = false;
295 $this->initFromRevIDs( $params['revids'] );
296 break;
297 default:
298 // Do nothing - some queries do not need any of the data sources.
299 break;
300 }
301 $this->profileOut();
302 }
303
304 /**
305 * Populate this PageSet from a list of Titles
306 * @param $titles array of Title objects
307 */
308 public function populateFromTitles( $titles ) {
309 $this->profileIn();
310 $this->initFromTitles( $titles );
311 $this->profileOut();
312 }
313
314 /**
315 * Populate this PageSet from a list of page IDs
316 * @param $pageIDs array of page IDs
317 */
318 public function populateFromPageIDs( $pageIDs ) {
319 $this->profileIn();
320 $this->initFromPageIds( $pageIDs );
321 $this->profileOut();
322 }
323
324 /**
325 * Populate this PageSet from a rowset returned from the database
326 * @param $db Database object
327 * @param $queryResult Query result object
328 */
329 public function populateFromQueryResult( $db, $queryResult ) {
330 $this->profileIn();
331 $this->initFromQueryResult( $db, $queryResult );
332 $this->profileOut();
333 }
334
335 /**
336 * Populate this PageSet from a list of revision IDs
337 * @param $revIDs array of revision IDs
338 */
339 public function populateFromRevisionIDs( $revIDs ) {
340 $this->profileIn();
341 $this->initFromRevIDs( $revIDs );
342 $this->profileOut();
343 }
344
345 /**
346 * Extract all requested fields from the row received from the database
347 * @param $row Result row
348 */
349 public function processDbRow( $row ) {
350 // Store Title object in various data structures
351 $title = Title::makeTitle( $row->page_namespace, $row->page_title );
352
353 $pageId = intval( $row->page_id );
354 $this->mAllPages[$row->page_namespace][$row->page_title] = $pageId;
355 $this->mTitles[] = $title;
356
357 if ( $this->mResolveRedirects && $row->page_is_redirect == '1' ) {
358 $this->mPendingRedirectIDs[$pageId] = $title;
359 } else {
360 $this->mGoodTitles[$pageId] = $title;
361 }
362
363 foreach ( $this->mRequestedPageFields as $fieldName => &$fieldValues ) {
364 $fieldValues[$pageId] = $row-> $fieldName;
365 }
366 }
367
368 /**
369 * Resolve redirects, if applicable
370 */
371 public function finishPageSetGeneration() {
372 $this->profileIn();
373 $this->resolvePendingRedirects();
374 $this->profileOut();
375 }
376
377 /**
378 * This method populates internal variables with page information
379 * based on the given array of title strings.
380 *
381 * Steps:
382 * #1 For each title, get data from `page` table
383 * #2 If page was not found in the DB, store it as missing
384 *
385 * Additionally, when resolving redirects:
386 * #3 If no more redirects left, stop.
387 * #4 For each redirect, get its target from the `redirect` table.
388 * #5 Substitute the original LinkBatch object with the new list
389 * #6 Repeat from step #1
390 *
391 * @param $titles array of Title objects or strings
392 */
393 private function initFromTitles( $titles ) {
394 // Get validated and normalized title objects
395 $linkBatch = $this->processTitlesArray( $titles );
396 if ( $linkBatch->isEmpty() ) {
397 return;
398 }
399
400 $db = $this->getDB();
401 $set = $linkBatch->constructSet( 'page', $db );
402
403 // Get pageIDs data from the `page` table
404 $this->profileDBIn();
405 $res = $db->select( 'page', $this->getPageTableFields(), $set,
406 __METHOD__ );
407 $this->profileDBOut();
408
409 // Hack: get the ns:titles stored in array(ns => array(titles)) format
410 $this->initFromQueryResult( $db, $res, $linkBatch->data, true ); // process Titles
411
412 // Resolve any found redirects
413 $this->resolvePendingRedirects();
414 }
415
416 /**
417 * Does the same as initFromTitles(), but is based on page IDs instead
418 * @param $pageids array of page IDs
419 */
420 private function initFromPageIds( $pageids ) {
421 if ( !count( $pageids ) ) {
422 return;
423 }
424
425 $pageids = array_map( 'intval', $pageids ); // paranoia
426 $set = array(
427 'page_id' => $pageids
428 );
429 $db = $this->getDB();
430
431 // Get pageIDs data from the `page` table
432 $this->profileDBIn();
433 $res = $db->select( 'page', $this->getPageTableFields(), $set,
434 __METHOD__ );
435 $this->profileDBOut();
436
437 $remaining = array_flip( $pageids );
438 $this->initFromQueryResult( $db, $res, $remaining, false ); // process PageIDs
439
440 // Resolve any found redirects
441 $this->resolvePendingRedirects();
442 }
443
444 /**
445 * Iterate through the result of the query on 'page' table,
446 * and for each row create and store title object and save any extra fields requested.
447 * @param $db Database
448 * @param $res DB Query result
449 * @param $remaining array of either pageID or ns/title elements (optional).
450 * If given, any missing items will go to $mMissingPageIDs and $mMissingTitles
451 * @param $processTitles bool Must be provided together with $remaining.
452 * If true, treat $remaining as an array of [ns][title]
453 * If false, treat it as an array of [pageIDs]
454 */
455 private function initFromQueryResult( $db, $res, &$remaining = null, $processTitles = null ) {
456 if ( !is_null( $remaining ) && is_null( $processTitles ) ) {
457 ApiBase::dieDebug( __METHOD__, 'Missing $processTitles parameter when $remaining is provided' );
458 }
459
460 while ( $row = $db->fetchObject( $res ) ) {
461 $pageId = intval( $row->page_id );
462
463 // Remove found page from the list of remaining items
464 if ( isset( $remaining ) ) {
465 if ( $processTitles ) {
466 unset( $remaining[$row->page_namespace][$row->page_title] );
467 } else {
468 unset( $remaining[$pageId] );
469 }
470 }
471
472 // Store any extra fields requested by modules
473 $this->processDbRow( $row );
474 }
475 $db->freeResult( $res );
476
477 if ( isset( $remaining ) ) {
478 // Any items left in the $remaining list are added as missing
479 if ( $processTitles ) {
480 // The remaining titles in $remaining are non-existent pages
481 foreach ( $remaining as $ns => $dbkeys ) {
482 foreach ( $dbkeys as $dbkey => $unused ) {
483 $title = Title::makeTitle( $ns, $dbkey );
484 $this->mAllPages[$ns][$dbkey] = $this->mFakePageId;
485 $this->mMissingTitles[$this->mFakePageId] = $title;
486 $this->mFakePageId--;
487 $this->mTitles[] = $title;
488 }
489 }
490 } else {
491 // The remaining pageids do not exist
492 if ( !$this->mMissingPageIDs ) {
493 $this->mMissingPageIDs = array_keys( $remaining );
494 } else {
495 $this->mMissingPageIDs = array_merge( $this->mMissingPageIDs, array_keys( $remaining ) );
496 }
497 }
498 }
499 }
500
501 /**
502 * Does the same as initFromTitles(), but is based on revision IDs
503 * instead
504 * @param $revids array of revision IDs
505 */
506 private function initFromRevIDs( $revids ) {
507 if ( !count( $revids ) ) {
508 return;
509 }
510
511 $revids = array_map( 'intval', $revids ); // paranoia
512 $db = $this->getDB();
513 $pageids = array();
514 $remaining = array_flip( $revids );
515
516 $tables = array( 'revision', 'page' );
517 $fields = array( 'rev_id', 'rev_page' );
518 $where = array( 'rev_id' => $revids, 'rev_page = page_id' );
519
520 // Get pageIDs data from the `page` table
521 $this->profileDBIn();
522 $res = $db->select( $tables, $fields, $where, __METHOD__ );
523 while ( $row = $db->fetchObject( $res ) ) {
524 $revid = intval( $row->rev_id );
525 $pageid = intval( $row->rev_page );
526 $this->mGoodRevIDs[$revid] = $pageid;
527 $pageids[$pageid] = '';
528 unset( $remaining[$revid] );
529 }
530 $db->freeResult( $res );
531 $this->profileDBOut();
532
533 $this->mMissingRevIDs = array_keys( $remaining );
534
535 // Populate all the page information
536 $this->initFromPageIds( array_keys( $pageids ) );
537 }
538
539 /**
540 * Resolve any redirects in the result if redirect resolution was
541 * requested. This function is called repeatedly until all redirects
542 * have been resolved.
543 */
544 private function resolvePendingRedirects() {
545 if ( $this->mResolveRedirects ) {
546 $db = $this->getDB();
547 $pageFlds = $this->getPageTableFields();
548
549 // Repeat until all redirects have been resolved
550 // The infinite loop is prevented by keeping all known pages in $this->mAllPages
551 while ( $this->mPendingRedirectIDs ) {
552 // Resolve redirects by querying the pagelinks table, and repeat the process
553 // Create a new linkBatch object for the next pass
554 $linkBatch = $this->getRedirectTargets();
555
556 if ( $linkBatch->isEmpty() ) {
557 break;
558 }
559
560 $set = $linkBatch->constructSet( 'page', $db );
561 if ( $set === false ) {
562 break;
563 }
564
565 // Get pageIDs data from the `page` table
566 $this->profileDBIn();
567 $res = $db->select( 'page', $pageFlds, $set, __METHOD__ );
568 $this->profileDBOut();
569
570 // Hack: get the ns:titles stored in array(ns => array(titles)) format
571 $this->initFromQueryResult( $db, $res, $linkBatch->data, true );
572 }
573 }
574 }
575
576 /**
577 * Get the targets of the pending redirects from the database
578 *
579 * Also creates entries in the redirect table for redirects that don't
580 * have one.
581 * @return LinkBatch
582 */
583 private function getRedirectTargets() {
584 $lb = new LinkBatch();
585 $db = $this->getDB();
586
587 $this->profileDBIn();
588 $res = $db->select(
589 'redirect',
590 array(
591 'rd_from',
592 'rd_namespace',
593 'rd_title'
594 ), array( 'rd_from' => array_keys( $this->mPendingRedirectIDs ) ),
595 __METHOD__
596 );
597 $this->profileDBOut();
598
599 while ( $row = $db->fetchObject( $res ) ) {
600 $rdfrom = intval( $row->rd_from );
601 $from = $this->mPendingRedirectIDs[$rdfrom]->getPrefixedText();
602 $to = Title::makeTitle( $row->rd_namespace, $row->rd_title )->getPrefixedText();
603 unset( $this->mPendingRedirectIDs[$rdfrom] );
604 if ( !isset( $this->mAllPages[$row->rd_namespace][$row->rd_title] ) ) {
605 $lb->add( $row->rd_namespace, $row->rd_title );
606 }
607 $this->mRedirectTitles[$from] = $to;
608 }
609 $db->freeResult( $res );
610 if ( $this->mPendingRedirectIDs ) {
611 // We found pages that aren't in the redirect table
612 // Add them
613 foreach ( $this->mPendingRedirectIDs as $id => $title ) {
614 $article = new Article( $title );
615 $rt = $article->insertRedirect();
616 if ( !$rt ) {
617 // What the hell. Let's just ignore this
618 continue;
619 }
620 $lb->addObj( $rt );
621 $this->mRedirectTitles[$title->getPrefixedText()] = $rt->getPrefixedText();
622 unset( $this->mPendingRedirectIDs[$id] );
623 }
624 }
625 return $lb;
626 }
627
628 /**
629 * Given an array of title strings, convert them into Title objects.
630 * Alternativelly, an array of Title objects may be given.
631 * This method validates access rights for the title,
632 * and appends normalization values to the output.
633 *
634 * @param $titles array of Title objects or strings
635 * @return LinkBatch
636 */
637 private function processTitlesArray( $titles ) {
638 $linkBatch = new LinkBatch();
639
640 foreach ( $titles as $title ) {
641 $titleObj = is_string( $title ) ? Title::newFromText( $title ) : $title;
642 if ( !$titleObj ) {
643 // Handle invalid titles gracefully
644 $this->mAllpages[0][$title] = $this->mFakePageId;
645 $this->mInvalidTitles[$this->mFakePageId] = $title;
646 $this->mFakePageId--;
647 continue; // There's nothing else we can do
648 }
649 $iw = $titleObj->getInterwiki();
650 if ( strval( $iw ) !== '' ) {
651 // This title is an interwiki link.
652 $this->mInterwikiTitles[$titleObj->getPrefixedText()] = $iw;
653 } else {
654 // Validation
655 if ( $titleObj->getNamespace() < 0 ) {
656 $this->setWarning( 'No support for special pages has been implemented' );
657 } else {
658 $linkBatch->addObj( $titleObj );
659 }
660 }
661
662 // Make sure we remember the original title that was
663 // given to us. This way the caller can correlate new
664 // titles with the originally requested when e.g. the
665 // namespace is localized or the capitalization is
666 // different
667 if ( is_string( $title ) && $title !== $titleObj->getPrefixedText() ) {
668 $this->mNormalizedTitles[$title] = $titleObj->getPrefixedText();
669 }
670 }
671
672 return $linkBatch;
673 }
674
675 protected function getAllowedParams() {
676 return array(
677 'titles' => array(
678 ApiBase::PARAM_ISMULTI => true
679 ),
680 'pageids' => array(
681 ApiBase::PARAM_TYPE => 'integer',
682 ApiBase::PARAM_ISMULTI => true
683 ),
684 'revids' => array(
685 ApiBase::PARAM_TYPE => 'integer',
686 ApiBase::PARAM_ISMULTI => true
687 )
688 );
689 }
690
691 protected function getParamDescription() {
692 return array(
693 'titles' => 'A list of titles to work on',
694 'pageids' => 'A list of page IDs to work on',
695 'revids' => 'A list of revision IDs to work on'
696 );
697 }
698
699 public function getPossibleErrors() {
700 return array_merge( parent::getPossibleErrors(), array(
701 array( 'code' => 'multisource', 'info' => "Cannot use 'pageids' at the same time as 'dataSource'" ),
702 array( 'code' => 'multisource', 'info' => "Cannot use 'revids' at the same time as 'dataSource'" ),
703 ) );
704 }
705
706 public function getVersion() {
707 return __CLASS__ . ': $Id$';
708 }
709 }