Refactor requiresToken to getTokenSalt - Returns salt if exists, null if no salt...
[lhc/web/wiklou.git] / includes / api / ApiQueryInfo.php
1 <?php
2
3 /*
4 * Created on Sep 25, 2006
5 *
6 * API for MediaWiki 1.8+
7 *
8 * Copyright (C) 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 * A query module to show basic page information.
33 *
34 * @ingroup API
35 */
36 class ApiQueryInfo extends ApiQueryBase {
37
38 private $fld_protection = false, $fld_talkid = false,
39 $fld_subjectid = false, $fld_url = false,
40 $fld_readable = false, $fld_watched = false,
41 $fld_preload = false;
42
43 public function __construct( $query, $moduleName ) {
44 parent :: __construct( $query, $moduleName, 'in' );
45 }
46
47 public function requestExtraData( $pageSet ) {
48 $pageSet->requestField( 'page_restrictions' );
49 $pageSet->requestField( 'page_is_redirect' );
50 $pageSet->requestField( 'page_is_new' );
51 $pageSet->requestField( 'page_counter' );
52 $pageSet->requestField( 'page_touched' );
53 $pageSet->requestField( 'page_latest' );
54 $pageSet->requestField( 'page_len' );
55 }
56
57 /**
58 * Get an array mapping token names to their handler functions.
59 * The prototype for a token function is func($pageid, $title)
60 * it should return a token or false (permission denied)
61 * @return array(tokenname => function)
62 */
63 protected function getTokenFunctions() {
64 // Don't call the hooks twice
65 if ( isset( $this->tokenFunctions ) )
66 return $this->tokenFunctions;
67
68 // If we're in JSON callback mode, no tokens can be obtained
69 if ( !is_null( $this->getMain()->getRequest()->getVal( 'callback' ) ) )
70 return array();
71
72 $this->tokenFunctions = array(
73 'edit' => array( 'ApiQueryInfo', 'getEditToken' ),
74 'delete' => array( 'ApiQueryInfo', 'getDeleteToken' ),
75 'protect' => array( 'ApiQueryInfo', 'getProtectToken' ),
76 'move' => array( 'ApiQueryInfo', 'getMoveToken' ),
77 'block' => array( 'ApiQueryInfo', 'getBlockToken' ),
78 'unblock' => array( 'ApiQueryInfo', 'getUnblockToken' ),
79 'email' => array( 'ApiQueryInfo', 'getEmailToken' ),
80 'import' => array( 'ApiQueryInfo', 'getImportToken' ),
81 );
82 wfRunHooks( 'APIQueryInfoTokens', array( &$this->tokenFunctions ) );
83 return $this->tokenFunctions;
84 }
85
86 public static function getEditToken( $pageid, $title )
87 {
88 // We could check for $title->userCan('edit') here,
89 // but that's too expensive for this purpose
90 // and would break caching
91 global $wgUser;
92 if ( !$wgUser->isAllowed( 'edit' ) )
93 return false;
94
95 // The edit token is always the same, let's exploit that
96 static $cachedEditToken = null;
97 if ( !is_null( $cachedEditToken ) )
98 return $cachedEditToken;
99
100 $cachedEditToken = $wgUser->editToken();
101 return $cachedEditToken;
102 }
103
104 public static function getDeleteToken( $pageid, $title )
105 {
106 global $wgUser;
107 if ( !$wgUser->isAllowed( 'delete' ) )
108 return false;
109
110 static $cachedDeleteToken = null;
111 if ( !is_null( $cachedDeleteToken ) )
112 return $cachedDeleteToken;
113
114 $cachedDeleteToken = $wgUser->editToken();
115 return $cachedDeleteToken;
116 }
117
118 public static function getProtectToken( $pageid, $title )
119 {
120 global $wgUser;
121 if ( !$wgUser->isAllowed( 'protect' ) )
122 return false;
123
124 static $cachedProtectToken = null;
125 if ( !is_null( $cachedProtectToken ) )
126 return $cachedProtectToken;
127
128 $cachedProtectToken = $wgUser->editToken();
129 return $cachedProtectToken;
130 }
131
132 public static function getMoveToken( $pageid, $title )
133 {
134 global $wgUser;
135 if ( !$wgUser->isAllowed( 'move' ) )
136 return false;
137
138 static $cachedMoveToken = null;
139 if ( !is_null( $cachedMoveToken ) )
140 return $cachedMoveToken;
141
142 $cachedMoveToken = $wgUser->editToken();
143 return $cachedMoveToken;
144 }
145
146 public static function getBlockToken( $pageid, $title )
147 {
148 global $wgUser;
149 if ( !$wgUser->isAllowed( 'block' ) )
150 return false;
151
152 static $cachedBlockToken = null;
153 if ( !is_null( $cachedBlockToken ) )
154 return $cachedBlockToken;
155
156 $cachedBlockToken = $wgUser->editToken();
157 return $cachedBlockToken;
158 }
159
160 public static function getUnblockToken( $pageid, $title )
161 {
162 // Currently, this is exactly the same as the block token
163 return self::getBlockToken( $pageid, $title );
164 }
165
166 public static function getEmailToken( $pageid, $title )
167 {
168 global $wgUser;
169 if ( !$wgUser->canSendEmail() || $wgUser->isBlockedFromEmailUser() )
170 return false;
171
172 static $cachedEmailToken = null;
173 if ( !is_null( $cachedEmailToken ) )
174 return $cachedEmailToken;
175
176 $cachedEmailToken = $wgUser->editToken();
177 return $cachedEmailToken;
178 }
179
180 public static function getImportToken( $pageid, $title )
181 {
182 global $wgUser;
183 if ( !$wgUser->isAllowed( 'import' ) )
184 return false;
185
186 static $cachedImportToken = null;
187 if ( !is_null( $cachedImportToken ) )
188 return $cachedImportToken;
189
190 $cachedImportToken = $wgUser->editToken();
191 return $cachedImportToken;
192 }
193
194 public function execute() {
195 $this->params = $this->extractRequestParams();
196 if ( !is_null( $this->params['prop'] ) ) {
197 $prop = array_flip( $this->params['prop'] );
198 $this->fld_protection = isset( $prop['protection'] );
199 $this->fld_watched = isset( $prop['watched'] );
200 $this->fld_talkid = isset( $prop['talkid'] );
201 $this->fld_subjectid = isset( $prop['subjectid'] );
202 $this->fld_url = isset( $prop['url'] );
203 $this->fld_readable = isset( $prop['readable'] );
204 $this->fld_preload = isset ( $prop['preload'] );
205 }
206
207 $pageSet = $this->getPageSet();
208 $this->titles = $pageSet->getGoodTitles();
209 $this->missing = $pageSet->getMissingTitles();
210 $this->everything = $this->titles + $this->missing;
211 $result = $this->getResult();
212
213 uasort( $this->everything, array( 'Title', 'compare' ) );
214 if ( !is_null( $this->params['continue'] ) )
215 {
216 // Throw away any titles we're gonna skip so they don't
217 // clutter queries
218 $cont = explode( '|', $this->params['continue'] );
219 if ( count( $cont ) != 2 )
220 $this->dieUsage( "Invalid continue param. You should pass the original " .
221 "value returned by the previous query", "_badcontinue" );
222 $conttitle = Title::makeTitleSafe( $cont[0], $cont[1] );
223 foreach ( $this->everything as $pageid => $title )
224 {
225 if ( Title::compare( $title, $conttitle ) >= 0 )
226 break;
227 unset( $this->titles[$pageid] );
228 unset( $this->missing[$pageid] );
229 unset( $this->everything[$pageid] );
230 }
231 }
232
233 $this->pageRestrictions = $pageSet->getCustomField( 'page_restrictions' );
234 $this->pageIsRedir = $pageSet->getCustomField( 'page_is_redirect' );
235 $this->pageIsNew = $pageSet->getCustomField( 'page_is_new' );
236 $this->pageCounter = $pageSet->getCustomField( 'page_counter' );
237 $this->pageTouched = $pageSet->getCustomField( 'page_touched' );
238 $this->pageLatest = $pageSet->getCustomField( 'page_latest' );
239 $this->pageLength = $pageSet->getCustomField( 'page_len' );
240
241 $db = $this->getDB();
242 // Get protection info if requested
243 if ( $this->fld_protection )
244 $this->getProtectionInfo();
245
246 if ( $this->fld_watched )
247 $this->getWatchedInfo();
248
249 // Run the talkid/subjectid query if requested
250 if ( $this->fld_talkid || $this->fld_subjectid )
251 $this->getTSIDs();
252
253 foreach ( $this->everything as $pageid => $title ) {
254 $pageInfo = $this->extractPageInfo( $pageid, $title );
255 $fit = $result->addValue( array (
256 'query',
257 'pages'
258 ), $pageid, $pageInfo );
259 if ( !$fit )
260 {
261 $this->setContinueEnumParameter( 'continue',
262 $title->getNamespace() . '|' .
263 $title->getText() );
264 break;
265 }
266 }
267 }
268
269 /**
270 * Get a result array with information about a title
271 * @param $pageid int Page ID (negative for missing titles)
272 * @param $title Title object
273 * @return array
274 */
275 private function extractPageInfo( $pageid, $title )
276 {
277 $pageInfo = array();
278 if ( $title->exists() )
279 {
280 $pageInfo['touched'] = wfTimestamp( TS_ISO_8601, $this->pageTouched[$pageid] );
281 $pageInfo['lastrevid'] = intval( $this->pageLatest[$pageid] );
282 $pageInfo['counter'] = intval( $this->pageCounter[$pageid] );
283 $pageInfo['length'] = intval( $this->pageLength[$pageid] );
284 if ( $this->pageIsRedir[$pageid] )
285 $pageInfo['redirect'] = '';
286 if ( $this->pageIsNew[$pageid] )
287 $pageInfo['new'] = '';
288 }
289
290 if ( !is_null( $this->params['token'] ) ) {
291 $tokenFunctions = $this->getTokenFunctions();
292 $pageInfo['starttimestamp'] = wfTimestamp( TS_ISO_8601, time() );
293 foreach ( $this->params['token'] as $t )
294 {
295 $val = call_user_func( $tokenFunctions[$t], $pageid, $title );
296 if ( $val === false )
297 $this->setWarning( "Action '$t' is not allowed for the current user" );
298 else
299 $pageInfo[$t . 'token'] = $val;
300 }
301 }
302
303 if ( $this->fld_protection ) {
304 $pageInfo['protection'] = array();
305 if ( isset( $this->protections[$title->getNamespace()][$title->getDBkey()] ) )
306 $pageInfo['protection'] =
307 $this->protections[$title->getNamespace()][$title->getDBkey()];
308 $this->getResult()->setIndexedTagName( $pageInfo['protection'], 'pr' );
309 }
310
311 if ( $this->fld_watched && isset( $this->watched[$title->getNamespace()][$title->getDBkey()] ) )
312 $pageInfo['watched'] = '';
313
314 if ( $this->fld_talkid && isset( $this->talkids[$title->getNamespace()][$title->getDBkey()] ) )
315 $pageInfo['talkid'] = $this->talkids[$title->getNamespace()][$title->getDBkey()];
316
317 if ( $this->fld_subjectid && isset( $this->subjectids[$title->getNamespace()][$title->getDBkey()] ) )
318 $pageInfo['subjectid'] = $this->subjectids[$title->getNamespace()][$title->getDBkey()];
319
320 if ( $this->fld_url ) {
321 $pageInfo['fullurl'] = $title->getFullURL();
322 $pageInfo['editurl'] = $title->getFullURL( 'action=edit' );
323 }
324 if ( $this->fld_readable && $title->userCanRead() )
325 $pageInfo['readable'] = '';
326
327 if ( $this->fld_preload ) {
328 if ( $title->exists() )
329 $pageInfo['preload'] = '';
330 else {
331 wfRunHooks( 'EditFormPreloadText', array( &$text, &$title ) );
332
333 $pageInfo['preload'] = $text;
334 }
335 }
336 return $pageInfo;
337 }
338
339 /**
340 * Get information about protections and put it in $protections
341 */
342 private function getProtectionInfo()
343 {
344 $this->protections = array();
345 $db = $this->getDB();
346
347 // Get normal protections for existing titles
348 if ( count( $this->titles ) )
349 {
350 $this->resetQueryParams();
351 $this->addTables( array( 'page_restrictions', 'page' ) );
352 $this->addWhere( 'page_id=pr_page' );
353 $this->addFields( array( 'pr_page', 'pr_type', 'pr_level',
354 'pr_expiry', 'pr_cascade', 'page_namespace',
355 'page_title' ) );
356 $this->addWhereFld( 'pr_page', array_keys( $this->titles ) );
357
358 $res = $this->select( __METHOD__ );
359 while ( $row = $db->fetchObject( $res ) ) {
360 $a = array(
361 'type' => $row->pr_type,
362 'level' => $row->pr_level,
363 'expiry' => Block::decodeExpiry( $row->pr_expiry, TS_ISO_8601 )
364 );
365 if ( $row->pr_cascade )
366 $a['cascade'] = '';
367 $this->protections[$row->page_namespace][$row->page_title][] = $a;
368
369 // Also check old restrictions
370 if ( $this->pageRestrictions[$row->pr_page] ) {
371 $restrictions = explode( ':', trim( $this->pageRestrictions[$row->pr_page] ) );
372 foreach ( $restrictions as $restrict ) {
373 $temp = explode( '=', trim( $restrict ) );
374 if ( count( $temp ) == 1 ) {
375 // old old format should be treated as edit/move restriction
376 $restriction = trim( $temp[0] );
377
378 if ( $restriction == '' )
379 continue;
380 $this->protections[$row->page_namespace][$row->page_title][] = array(
381 'type' => 'edit',
382 'level' => $restriction,
383 'expiry' => 'infinity',
384 );
385 $this->protections[$row->page_namespace][$row->page_title][] = array(
386 'type' => 'move',
387 'level' => $restriction,
388 'expiry' => 'infinity',
389 );
390 } else {
391 $restriction = trim( $temp[1] );
392 if ( $restriction == '' )
393 continue;
394 $this->protections[$row->page_namespace][$row->page_title][] = array(
395 'type' => $temp[0],
396 'level' => $restriction,
397 'expiry' => 'infinity',
398 );
399 }
400 }
401 }
402 }
403 $db->freeResult( $res );
404 }
405
406 // Get protections for missing titles
407 if ( count( $this->missing ) )
408 {
409 $this->resetQueryParams();
410 $lb = new LinkBatch( $this->missing );
411 $this->addTables( 'protected_titles' );
412 $this->addFields( array( 'pt_title', 'pt_namespace', 'pt_create_perm', 'pt_expiry' ) );
413 $this->addWhere( $lb->constructSet( 'pt', $db ) );
414 $res = $this->select( __METHOD__ );
415 while ( $row = $db->fetchObject( $res ) ) {
416 $this->protections[$row->pt_namespace][$row->pt_title][] = array(
417 'type' => 'create',
418 'level' => $row->pt_create_perm,
419 'expiry' => Block::decodeExpiry( $row->pt_expiry, TS_ISO_8601 )
420 );
421 }
422 $db->freeResult( $res );
423 }
424
425 // Cascading protections
426 $images = $others = array();
427 foreach ( $this->everything as $title )
428 if ( $title->getNamespace() == NS_FILE )
429 $images[] = $title->getDBkey();
430 else
431 $others[] = $title;
432
433 if ( count( $others ) ) {
434 // Non-images: check templatelinks
435 $lb = new LinkBatch( $others );
436 $this->resetQueryParams();
437 $this->addTables( array( 'page_restrictions', 'page', 'templatelinks' ) );
438 $this->addFields( array( 'pr_type', 'pr_level', 'pr_expiry',
439 'page_title', 'page_namespace',
440 'tl_title', 'tl_namespace' ) );
441 $this->addWhere( $lb->constructSet( 'tl', $db ) );
442 $this->addWhere( 'pr_page = page_id' );
443 $this->addWhere( 'pr_page = tl_from' );
444 $this->addWhereFld( 'pr_cascade', 1 );
445
446 $res = $this->select( __METHOD__ );
447 while ( $row = $db->fetchObject( $res ) ) {
448 $source = Title::makeTitle( $row->page_namespace, $row->page_title );
449 $this->protections[$row->tl_namespace][$row->tl_title][] = array(
450 'type' => $row->pr_type,
451 'level' => $row->pr_level,
452 'expiry' => Block::decodeExpiry( $row->pr_expiry, TS_ISO_8601 ),
453 'source' => $source->getPrefixedText()
454 );
455 }
456 $db->freeResult( $res );
457 }
458
459 if ( count( $images ) ) {
460 // Images: check imagelinks
461 $this->resetQueryParams();
462 $this->addTables( array( 'page_restrictions', 'page', 'imagelinks' ) );
463 $this->addFields( array( 'pr_type', 'pr_level', 'pr_expiry',
464 'page_title', 'page_namespace', 'il_to' ) );
465 $this->addWhere( 'pr_page = page_id' );
466 $this->addWhere( 'pr_page = il_from' );
467 $this->addWhereFld( 'pr_cascade', 1 );
468 $this->addWhereFld( 'il_to', $images );
469
470 $res = $this->select( __METHOD__ );
471 while ( $row = $db->fetchObject( $res ) ) {
472 $source = Title::makeTitle( $row->page_namespace, $row->page_title );
473 $this->protections[NS_FILE][$row->il_to][] = array(
474 'type' => $row->pr_type,
475 'level' => $row->pr_level,
476 'expiry' => Block::decodeExpiry( $row->pr_expiry, TS_ISO_8601 ),
477 'source' => $source->getPrefixedText()
478 );
479 }
480 $db->freeResult( $res );
481 }
482 }
483
484 /**
485 * Get talk page IDs (if requested) and subject page IDs (if requested)
486 * and put them in $talkids and $subjectids
487 */
488 private function getTSIDs()
489 {
490 $getTitles = $this->talkids = $this->subjectids = array();
491 $db = $this->getDB();
492 foreach ( $this->everything as $t )
493 {
494 if ( MWNamespace::isTalk( $t->getNamespace() ) )
495 {
496 if ( $this->fld_subjectid )
497 $getTitles[] = $t->getSubjectPage();
498 }
499 else if ( $this->fld_talkid )
500 $getTitles[] = $t->getTalkPage();
501 }
502 if ( !count( $getTitles ) )
503 return;
504
505 // Construct a custom WHERE clause that matches
506 // all titles in $getTitles
507 $lb = new LinkBatch( $getTitles );
508 $this->resetQueryParams();
509 $this->addTables( 'page' );
510 $this->addFields( array( 'page_title', 'page_namespace', 'page_id' ) );
511 $this->addWhere( $lb->constructSet( 'page', $db ) );
512 $res = $this->select( __METHOD__ );
513 while ( $row = $db->fetchObject( $res ) )
514 {
515 if ( MWNamespace::isTalk( $row->page_namespace ) )
516 $this->talkids[MWNamespace::getSubject( $row->page_namespace )][$row->page_title] =
517 intval( $row->page_id );
518 else
519 $this->subjectids[MWNamespace::getTalk( $row->page_namespace )][$row->page_title] =
520 intval( $row->page_id );
521 }
522 }
523
524 /**
525 * Get information about watched status and put it in $watched
526 */
527 private function getWatchedInfo()
528 {
529 global $wgUser;
530
531 if ( $wgUser->isAnon() || count( $this->titles ) == 0 )
532 return;
533
534 $this->watched = array();
535 $db = $this->getDB();
536
537 $lb = new LinkBatch( $this->titles );
538
539 $this->resetQueryParams();
540 $this->addTables( array( 'page', 'watchlist' ) );
541 $this->addFields( array( 'page_title', 'page_namespace' ) );
542 $this->addWhere( array(
543 $lb->constructSet( 'page', $db ),
544 'wl_namespace=page_namespace',
545 'wl_title=page_title',
546 'wl_user' => $wgUser->getID()
547 ) );
548
549 $res = $this->select( __METHOD__ );
550
551 while ( $row = $db->fetchObject( $res ) ) {
552 $this->watched[$row->page_namespace][$row->page_title] = true;
553 }
554 }
555
556 public function getAllowedParams() {
557 return array (
558 'prop' => array (
559 ApiBase :: PARAM_DFLT => null,
560 ApiBase :: PARAM_ISMULTI => true,
561 ApiBase :: PARAM_TYPE => array (
562 'protection',
563 'talkid',
564 'watched',
565 'subjectid',
566 'url',
567 'readable',
568 'preload'
569 ) ),
570 'token' => array (
571 ApiBase :: PARAM_DFLT => null,
572 ApiBase :: PARAM_ISMULTI => true,
573 ApiBase :: PARAM_TYPE => array_keys( $this->getTokenFunctions() )
574 ),
575 'continue' => null,
576 );
577 }
578
579 public function getParamDescription() {
580 return array (
581 'prop' => array (
582 'Which additional properties to get:',
583 ' protection - List the protection level of each page',
584 ' talkid - The page ID of the talk page for each non-talk page',
585 ' watched - List the watched status of each page',
586 ' subjectid - The page ID of the parent page for each talk page',
587 ' url - Gives a full URL to the page, and also an edit URL',
588 ' readable - Whether the user can read this page',
589 ' preload - Gives the text returned by EditFormPreloadText'
590 ),
591 'token' => 'Request a token to perform a data-modifying action on a page',
592 'continue' => 'When more results are available, use this to continue',
593 );
594 }
595
596 public function getDescription() {
597 return 'Get basic page information such as namespace, title, last touched date, ...';
598 }
599
600 public function getPossibleErrors() {
601 return array_merge( parent::getPossibleErrors(), array(
602 array( 'code' => '_badcontinue', 'info' => 'Invalid continue param. You should pass the original value returned by the previous query' ),
603 ) );
604 }
605
606 protected function getExamples() {
607 return array (
608 'api.php?action=query&prop=info&titles=Main%20Page',
609 'api.php?action=query&prop=info&inprop=protection&titles=Main%20Page'
610 );
611 }
612
613 public function getVersion() {
614 return __CLASS__ . ': $Id$';
615 }
616 }