Kill the error suppression operator in the Api
[lhc/web/wiklou.git] / includes / api / ApiQueryBacklinks.php
1 <?php
2 /**
3 *
4 *
5 * Created on Oct 16, 2006
6 *
7 * Copyright © 2006 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 if ( !defined( 'MEDIAWIKI' ) ) {
28 // Eclipse helper - will be ignored in production
29 require_once( "ApiQueryBase.php" );
30 }
31
32 /**
33 * This is a three-in-one module to query:
34 * * backlinks - links pointing to the given page,
35 * * embeddedin - what pages transclude the given page within themselves,
36 * * imageusage - what pages use the given image
37 *
38 * @ingroup API
39 */
40 class ApiQueryBacklinks extends ApiQueryGeneratorBase {
41
42 /**
43 * @var Title
44 */
45 private $rootTitle;
46
47 private $params, $contID, $redirID, $redirect;
48 private $bl_ns, $bl_from, $bl_table, $bl_code, $bl_title, $bl_sort, $bl_fields, $hasNS;
49
50 /**
51 * Maps ns and title to pageid
52 *
53 * @var array
54 */
55 private $pageMap = array();
56 private $resultArr;
57
58 private $redirTitles = array();
59 private $continueStr = null;
60
61 // output element name, database column field prefix, database table
62 private $backlinksSettings = array(
63 'backlinks' => array(
64 'code' => 'bl',
65 'prefix' => 'pl',
66 'linktbl' => 'pagelinks'
67 ),
68 'embeddedin' => array(
69 'code' => 'ei',
70 'prefix' => 'tl',
71 'linktbl' => 'templatelinks'
72 ),
73 'imageusage' => array(
74 'code' => 'iu',
75 'prefix' => 'il',
76 'linktbl' => 'imagelinks'
77 )
78 );
79
80 public function __construct( $query, $moduleName ) {
81 $settings = $this->backlinksSettings[$moduleName];
82 $prefix = $settings['prefix'];
83 $code = $settings['code'];
84 $this->resultArr = array();
85
86 parent::__construct( $query, $moduleName, $code );
87 $this->bl_ns = $prefix . '_namespace';
88 $this->bl_from = $prefix . '_from';
89 $this->bl_table = $settings['linktbl'];
90 $this->bl_code = $code;
91
92 $this->hasNS = $moduleName !== 'imageusage';
93 if ( $this->hasNS ) {
94 $this->bl_title = $prefix . '_title';
95 $this->bl_sort = "{$this->bl_ns}, {$this->bl_title}, {$this->bl_from}";
96 $this->bl_fields = array(
97 $this->bl_ns,
98 $this->bl_title
99 );
100 } else {
101 $this->bl_title = $prefix . '_to';
102 $this->bl_sort = "{$this->bl_title}, {$this->bl_from}";
103 $this->bl_fields = array(
104 $this->bl_title
105 );
106 }
107 }
108
109 public function execute() {
110 $this->run();
111 }
112
113 public function getCacheMode( $params ) {
114 return 'public';
115 }
116
117 public function executeGenerator( $resultPageSet ) {
118 $this->run( $resultPageSet );
119 }
120
121 /**
122 * @param $resultPageSet ApiPageSet
123 * @return void
124 */
125 private function prepareFirstQuery( $resultPageSet = null ) {
126 /* SELECT page_id, page_title, page_namespace, page_is_redirect
127 * FROM pagelinks, page WHERE pl_from=page_id
128 * AND pl_title='Foo' AND pl_namespace=0
129 * LIMIT 11 ORDER BY pl_from
130 */
131 $this->addTables( array( $this->bl_table, 'page' ) );
132 $this->addWhere( "{$this->bl_from}=page_id" );
133 if ( is_null( $resultPageSet ) ) {
134 $this->addFields( array( 'page_id', 'page_title', 'page_namespace' ) );
135 } else {
136 $this->addFields( $resultPageSet->getPageTableFields() );
137 }
138
139 $this->addFields( 'page_is_redirect' );
140 $this->addWhereFld( $this->bl_title, $this->rootTitle->getDBkey() );
141
142 if ( $this->hasNS ) {
143 $this->addWhereFld( $this->bl_ns, $this->rootTitle->getNamespace() );
144 }
145 $this->addWhereFld( 'page_namespace', $this->params['namespace'] );
146
147 if ( !is_null( $this->contID ) ) {
148 $this->addWhere( "{$this->bl_from}>={$this->contID}" );
149 }
150
151 if ( $this->params['filterredir'] == 'redirects' ) {
152 $this->addWhereFld( 'page_is_redirect', 1 );
153 } elseif ( $this->params['filterredir'] == 'nonredirects' && !$this->redirect ) {
154 // bug 22245 - Check for !redirect, as filtering nonredirects, when getting what links to them is contradictory
155 $this->addWhereFld( 'page_is_redirect', 0 );
156 }
157
158 $this->addOption( 'LIMIT', $this->params['limit'] + 1 );
159 $this->addOption( 'ORDER BY', $this->bl_from );
160 $this->addOption( 'STRAIGHT_JOIN' );
161 }
162
163 /**
164 * @param $resultPageSet ApiPageSet
165 * @return void
166 */
167 private function prepareSecondQuery( $resultPageSet = null ) {
168 /* SELECT page_id, page_title, page_namespace, page_is_redirect, pl_title, pl_namespace
169 FROM pagelinks, page WHERE pl_from=page_id
170 AND (pl_title='Foo' AND pl_namespace=0) OR (pl_title='Bar' AND pl_namespace=1)
171 ORDER BY pl_namespace, pl_title, pl_from LIMIT 11
172 */
173 $db = $this->getDB();
174 $this->addTables( array( 'page', $this->bl_table ) );
175 $this->addWhere( "{$this->bl_from}=page_id" );
176
177 if ( is_null( $resultPageSet ) ) {
178 $this->addFields( array( 'page_id', 'page_title', 'page_namespace', 'page_is_redirect' ) );
179 } else {
180 $this->addFields( $resultPageSet->getPageTableFields() );
181 }
182
183 $this->addFields( $this->bl_title );
184 if ( $this->hasNS ) {
185 $this->addFields( $this->bl_ns );
186 }
187
188 // We can't use LinkBatch here because $this->hasNS may be false
189 $titleWhere = array();
190 foreach ( $this->redirTitles as $t ) {
191 $titleWhere[] = "{$this->bl_title} = " . $db->addQuotes( $t->getDBkey() ) .
192 ( $this->hasNS ? " AND {$this->bl_ns} = '{$t->getNamespace()}'" : '' );
193 }
194 $this->addWhere( $db->makeList( $titleWhere, LIST_OR ) );
195 $this->addWhereFld( 'page_namespace', $this->params['namespace'] );
196
197 if ( !is_null( $this->redirID ) ) {
198 $first = $this->redirTitles[0];
199 $title = $db->strencode( $first->getDBkey() );
200 $ns = $first->getNamespace();
201 $from = $this->redirID;
202 if ( $this->hasNS ) {
203 $this->addWhere( "{$this->bl_ns} > $ns OR " .
204 "({$this->bl_ns} = $ns AND " .
205 "({$this->bl_title} > '$title' OR " .
206 "({$this->bl_title} = '$title' AND " .
207 "{$this->bl_from} >= $from)))" );
208 } else {
209 $this->addWhere( "{$this->bl_title} > '$title' OR " .
210 "({$this->bl_title} = '$title' AND " .
211 "{$this->bl_from} >= $from)" );
212 }
213 }
214 if ( $this->params['filterredir'] == 'redirects' ) {
215 $this->addWhereFld( 'page_is_redirect', 1 );
216 } elseif ( $this->params['filterredir'] == 'nonredirects' ) {
217 $this->addWhereFld( 'page_is_redirect', 0 );
218 }
219
220 $this->addOption( 'LIMIT', $this->params['limit'] + 1 );
221 $this->addOption( 'ORDER BY', $this->bl_sort );
222 $this->addOption( 'USE INDEX', array( 'page' => 'PRIMARY' ) );
223 }
224
225 /**
226 * @param $resultPageSet ApiPageSet
227 * @return void
228 */
229 private function run( $resultPageSet = null ) {
230 $this->params = $this->extractRequestParams( false );
231 $this->redirect = isset( $this->params['redirect'] ) && $this->params['redirect'];
232 $userMax = ( $this->redirect ? ApiBase::LIMIT_BIG1 / 2 : ApiBase::LIMIT_BIG1 );
233 $botMax = ( $this->redirect ? ApiBase::LIMIT_BIG2 / 2 : ApiBase::LIMIT_BIG2 );
234 if ( $this->params['limit'] == 'max' ) {
235 $this->params['limit'] = $this->getMain()->canApiHighLimits() ? $botMax : $userMax;
236 $this->getResult()->setParsedLimit( $this->getModuleName(), $this->params['limit'] );
237 }
238
239 $this->processContinue();
240 $this->prepareFirstQuery( $resultPageSet );
241
242 $res = $this->select( __METHOD__ . '::firstQuery' );
243
244 $count = 0;
245
246 foreach ( $res as $row ) {
247 if ( ++ $count > $this->params['limit'] ) {
248 // We've reached the one extra which shows that there are additional pages to be had. Stop here...
249 // Continue string preserved in case the redirect query doesn't pass the limit
250 $this->continueStr = $this->getContinueStr( $row->page_id );
251 break;
252 }
253
254 if ( is_null( $resultPageSet ) ) {
255 $this->extractRowInfo( $row );
256 } else {
257 $this->pageMap[$row->page_namespace][$row->page_title] = $row->page_id;
258 if ( $row->page_is_redirect ) {
259 $this->redirTitles[] = Title::makeTitle( $row->page_namespace, $row->page_title );
260 }
261
262 $resultPageSet->processDbRow( $row );
263 }
264 }
265
266 if ( $this->redirect && count( $this->redirTitles ) ) {
267 $this->resetQueryParams();
268 $this->prepareSecondQuery( $resultPageSet );
269 $res = $this->select( __METHOD__ . '::secondQuery' );
270 $count = 0;
271 foreach ( $res as $row ) {
272 if ( ++$count > $this->params['limit'] ) {
273 // We've reached the one extra which shows that there are additional pages to be had. Stop here...
274 // We need to keep the parent page of this redir in
275 if ( $this->hasNS ) {
276 $parentID = $this->pageMap[$row-> { $this->bl_ns } ][$row-> { $this->bl_title } ];
277 } else {
278 $parentID = $this->pageMap[NS_IMAGE][$row-> { $this->bl_title } ];
279 }
280 $this->continueStr = $this->getContinueRedirStr( $parentID, $row->page_id );
281 break;
282 }
283
284 if ( is_null( $resultPageSet ) ) {
285 $this->extractRedirRowInfo( $row );
286 } else {
287 $resultPageSet->processDbRow( $row );
288 }
289 }
290 }
291 if ( is_null( $resultPageSet ) ) {
292 // Try to add the result data in one go and pray that it fits
293 $fit = $this->getResult()->addValue( 'query', $this->getModuleName(), array_values( $this->resultArr ) );
294 if ( !$fit ) {
295 // It didn't fit. Add elements one by one until the
296 // result is full.
297 foreach ( $this->resultArr as $pageID => $arr ) {
298 // Add the basic entry without redirlinks first
299 $fit = $this->getResult()->addValue(
300 array( 'query', $this->getModuleName() ),
301 null, array_diff_key( $arr, array( 'redirlinks' => '' ) ) );
302 if ( !$fit ) {
303 $this->continueStr = $this->getContinueStr( $pageID );
304 break;
305 }
306
307 $hasRedirs = false;
308 $redirLinks = isset( $arr['redirlinks'] ) ? $arr['redirlinks'] : array();
309 foreach ( (array)$redirLinks as $key => $redir ) {
310 $fit = $this->getResult()->addValue(
311 array( 'query', $this->getModuleName(), $pageID, 'redirlinks' ),
312 $key, $redir );
313 if ( !$fit ) {
314 $this->continueStr = $this->getContinueRedirStr( $pageID, $redir['pageid'] );
315 break;
316 }
317 $hasRedirs = true;
318 }
319 if ( $hasRedirs ) {
320 $this->getResult()->setIndexedTagName_internal(
321 array( 'query', $this->getModuleName(), $pageID, 'redirlinks' ),
322 $this->bl_code );
323 }
324 if ( !$fit ) {
325 break;
326 }
327 }
328 }
329
330 $this->getResult()->setIndexedTagName_internal(
331 array( 'query', $this->getModuleName() ),
332 $this->bl_code
333 );
334 }
335 if ( !is_null( $this->continueStr ) ) {
336 $this->setContinueEnumParameter( 'continue', $this->continueStr );
337 }
338 }
339
340 private function extractRowInfo( $row ) {
341 $this->pageMap[$row->page_namespace][$row->page_title] = $row->page_id;
342 $t = Title::makeTitle( $row->page_namespace, $row->page_title );
343 $a = array( 'pageid' => intval( $row->page_id ) );
344 ApiQueryBase::addTitleInfo( $a, $t );
345 if ( $row->page_is_redirect ) {
346 $a['redirect'] = '';
347 $this->redirTitles[] = $t;
348 }
349 // Put all the results in an array first
350 $this->resultArr[$a['pageid']] = $a;
351 }
352
353 private function extractRedirRowInfo( $row ) {
354 $a['pageid'] = intval( $row->page_id );
355 ApiQueryBase::addTitleInfo( $a, Title::makeTitle( $row->page_namespace, $row->page_title ) );
356 if ( $row->page_is_redirect ) {
357 $a['redirect'] = '';
358 }
359 $ns = $this->hasNS ? $row-> { $this->bl_ns } : NS_FILE;
360 $parentID = $this->pageMap[$ns][$row-> { $this->bl_title } ];
361 // Put all the results in an array first
362 $this->resultArr[$parentID]['redirlinks'][] = $a;
363 $this->getResult()->setIndexedTagName( $this->resultArr[$parentID]['redirlinks'], $this->bl_code );
364 }
365
366 protected function processContinue() {
367 if ( !is_null( $this->params['continue'] ) ) {
368 $this->parseContinueParam();
369 } else {
370 if ( $this->params['title'] !== '' ) {
371 $title = Title::newFromText( $this->params['title'] );
372 if ( !$title ) {
373 $this->dieUsageMsg( array( 'invalidtitle', $this->params['title'] ) );
374 } else {
375 $this->rootTitle = $title;
376 }
377 }
378 }
379
380 // only image titles are allowed for the root in imageinfo mode
381 if ( !$this->hasNS && $this->rootTitle->getNamespace() !== NS_FILE ) {
382 $this->dieUsage( "The title for {$this->getModuleName()} query must be an image", 'bad_image_title' );
383 }
384 }
385
386 protected function parseContinueParam() {
387 $continueList = explode( '|', $this->params['continue'] );
388 // expected format:
389 // ns | key | id1 [| id2]
390 // ns+key: root title
391 // id1: first-level page ID to continue from
392 // id2: second-level page ID to continue from
393
394 // null stuff out now so we know what's set and what isn't
395 $this->rootTitle = $this->contID = $this->redirID = null;
396 $rootNs = intval( $continueList[0] );
397 if ( $rootNs === 0 && $continueList[0] !== '0' ) {
398 // Illegal continue parameter
399 $this->dieUsage( 'Invalid continue param. You should pass the original value returned by the previous query', '_badcontinue' );
400 }
401 $this->rootTitle = Title::makeTitleSafe( $rootNs, $continueList[1] );
402
403 if ( !$this->rootTitle ) {
404 $this->dieUsage( 'Invalid continue param. You should pass the original value returned by the previous query', '_badcontinue' );
405 }
406 $contID = intval( $continueList[2] );
407
408 if ( $contID === 0 && $continueList[2] !== '0' ) {
409 $this->dieUsage( 'Invalid continue param. You should pass the original value returned by the previous query', '_badcontinue' );
410 }
411 $this->contID = $contID;
412 $redirID = intval( @$continueList[3] );
413
414 if ( $redirID === 0 && @$continueList[3] !== '0' ) {
415 // This one isn't required
416 return;
417 }
418 $this->redirID = $redirID;
419
420 }
421
422 protected function getContinueStr( $lastPageID ) {
423 return $this->rootTitle->getNamespace() .
424 '|' . $this->rootTitle->getDBkey() .
425 '|' . $lastPageID;
426 }
427
428 protected function getContinueRedirStr( $lastPageID, $lastRedirID ) {
429 return $this->getContinueStr( $lastPageID ) . '|' . $lastRedirID;
430 }
431
432 public function getAllowedParams() {
433 $retval = array(
434 'title' => array(
435 ApiBase::PARAM_TYPE => 'string',
436 ApiBase::PARAM_REQUIRED => true
437 ),
438 'continue' => null,
439 'namespace' => array(
440 ApiBase::PARAM_ISMULTI => true,
441 ApiBase::PARAM_TYPE => 'namespace'
442 ),
443 'filterredir' => array(
444 ApiBase::PARAM_DFLT => 'all',
445 ApiBase::PARAM_TYPE => array(
446 'all',
447 'redirects',
448 'nonredirects'
449 )
450 ),
451 'limit' => array(
452 ApiBase::PARAM_DFLT => 10,
453 ApiBase::PARAM_TYPE => 'limit',
454 ApiBase::PARAM_MIN => 1,
455 ApiBase::PARAM_MAX => ApiBase::LIMIT_BIG1,
456 ApiBase::PARAM_MAX2 => ApiBase::LIMIT_BIG2
457 )
458 );
459 if ( $this->getModuleName() == 'embeddedin' ) {
460 return $retval;
461 }
462 $retval['redirect'] = false;
463 return $retval;
464 }
465
466 public function getParamDescription() {
467 $retval = array(
468 'title' => 'Title to search',
469 'continue' => 'When more results are available, use this to continue',
470 'namespace' => 'The namespace to enumerate',
471 );
472 if ( $this->getModuleName() != 'embeddedin' ) {
473 return array_merge( $retval, array(
474 'redirect' => 'If linking page is a redirect, find all pages that link to that redirect as well. Maximum limit is halved.',
475 'filterredir' => "How to filter for redirects. If set to nonredirects when {$this->bl_code}redirect is enabled, this is only applied to the second level",
476 'limit' => "How many total pages to return. If {$this->bl_code}redirect is enabled, limit applies to each level separately (which means you may get up to 2 * limit results)."
477 ) );
478 }
479 return array_merge( $retval, array(
480 'filterredir' => 'How to filter for redirects',
481 'limit' => 'How many total pages to return'
482 ) );
483 }
484
485 public function getDescription() {
486 switch ( $this->getModuleName() ) {
487 case 'backlinks':
488 return 'Find all pages that link to the given page';
489 case 'embeddedin':
490 return 'Find all pages that embed (transclude) the given title';
491 case 'imageusage':
492 return 'Find all pages that use the given image title.';
493 default:
494 ApiBase::dieDebug( __METHOD__, 'Unknown module name' );
495 }
496 }
497
498 public function getPossibleErrors() {
499 return array_merge( parent::getPossibleErrors(), array(
500 array( 'invalidtitle', 'title' ),
501 array( 'code' => 'bad_image_title', 'info' => "The title for {$this->getModuleName()} query must be an image" ),
502 array( 'code' => '_badcontinue', 'info' => 'Invalid continue param. You should pass the original value returned by the previous query' ),
503 ) );
504 }
505
506 protected function getExamples() {
507 static $examples = array(
508 'backlinks' => array(
509 'api.php?action=query&list=backlinks&bltitle=Main%20Page',
510 'api.php?action=query&generator=backlinks&gbltitle=Main%20Page&prop=info'
511 ),
512 'embeddedin' => array(
513 'api.php?action=query&list=embeddedin&eititle=Template:Stub',
514 'api.php?action=query&generator=embeddedin&geititle=Template:Stub&prop=info'
515 ),
516 'imageusage' => array(
517 'api.php?action=query&list=imageusage&iutitle=File:Albert%20Einstein%20Head.jpg',
518 'api.php?action=query&generator=imageusage&giutitle=File:Albert%20Einstein%20Head.jpg&prop=info'
519 )
520 );
521
522 return $examples[$this->getModuleName()];
523 }
524
525 public function getVersion() {
526 return __CLASS__ . ': $Id$';
527 }
528 }