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