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