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