API: Crusade against extract(). Left one extract() call alone in ApiQueryBacklinks...
[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;
42
43 // output element name, database column field prefix, database table
44 private $backlinksSettings = array (
45 'backlinks' => array (
46 'code' => 'bl',
47 'prefix' => 'pl',
48 'linktbl' => 'pagelinks'
49 ),
50 'embeddedin' => array (
51 'code' => 'ei',
52 'prefix' => 'tl',
53 'linktbl' => 'templatelinks'
54 ),
55 'imageusage' => array (
56 'code' => 'iu',
57 'prefix' => 'il',
58 'linktbl' => 'imagelinks'
59 )
60 );
61
62 public function __construct($query, $moduleName) {
63 extract($this->backlinksSettings[$moduleName]);
64
65 parent :: __construct($query, $moduleName, $code);
66 $this->bl_ns = $prefix . '_namespace';
67 $this->bl_from = $prefix . '_from';
68 $this->bl_table = $linktbl;
69 $this->bl_code = $code;
70
71 $this->hasNS = $moduleName !== 'imageusage';
72 if ($this->hasNS) {
73 $this->bl_title = $prefix . '_title';
74 $this->bl_sort = "{$this->bl_ns}, {$this->bl_title}, {$this->bl_from}";
75 $this->bl_fields = array (
76 $this->bl_ns,
77 $this->bl_title
78 );
79 } else {
80 $this->bl_title = $prefix . '_to';
81 $this->bl_sort = "{$this->bl_title}, {$this->bl_from}";
82 $this->bl_fields = array (
83 $this->bl_title
84 );
85 }
86 }
87
88 public function execute() {
89 $this->run();
90 }
91
92 public function executeGenerator($resultPageSet) {
93 $this->run($resultPageSet);
94 }
95
96 private function prepareFirstQuery($resultPageSet = null) {
97 /* SELECT page_id, page_title, page_namespace, page_is_redirect
98 * FROM pagelinks, page WHERE pl_from=page_id
99 * AND pl_title='Foo' AND pl_namespace=0
100 * LIMIT 11 ORDER BY pl_from
101 */
102 $db = $this->getDB();
103 $this->addTables(array('page', $this->bl_table));
104 $this->addWhere("{$this->bl_from}=page_id");
105 if(is_null($resultPageSet))
106 $this->addFields(array('page_id', 'page_title', 'page_namespace'));
107 else
108 $this->addFields($resultPageSet->getPageTableFields());
109 $this->addFields('page_is_redirect');
110 $this->addWhereFld($this->bl_title, $this->rootTitle->getDBKey());
111 if($this->hasNS)
112 $this->addWhereFld($this->bl_ns, $this->rootTitle->getNamespace());
113 $this->addWhereFld('page_namespace', $this->params['namespace']);
114 if(!is_null($this->contID))
115 $this->addWhere("{$this->bl_from}>={$this->contID}");
116 if($this->params['filterredir'] == 'redirects')
117 $this->addWhereFld('page_is_redirect', 1);
118 if($this->params['filterredir'] == 'nonredirects')
119 $this->addWhereFld('page_is_redirect', 0);
120 $this->addOption('LIMIT', $this->params['limit'] + 1);
121 $this->addOption('ORDER BY', $this->bl_from);
122 }
123
124 private function prepareSecondQuery($resultPageSet = null) {
125 /* SELECT page_id, page_title, page_namespace, page_is_redirect, pl_title, pl_namespace
126 FROM pagelinks, page WHERE pl_from=page_id
127 AND (pl_title='Foo' AND pl_namespace=0) OR (pl_title='Bar' AND pl_namespace=1)
128 ORDER BY pl_namespace, pl_title, pl_from LIMIT 11
129 */
130 $db = $this->getDB();
131 $this->addTables(array('page', $this->bl_table));
132 $this->addWhere("{$this->bl_from}=page_id");
133 if(is_null($resultPageSet))
134 $this->addFields(array('page_id', 'page_title', 'page_namespace', 'page_is_redirect'));
135 else
136 $this->addFields($resultPageSet->getPageTableFields());
137 $this->addFields($this->bl_title);
138 if($this->hasNS)
139 $this->addFields($this->bl_ns);
140 $titleWhere = '';
141 foreach($this->redirTitles as $t)
142 $titleWhere .= ($titleWhere != '' ? " OR " : '') .
143 "({$this->bl_title} = ".$db->addQuotes($t->getDBKey()).
144 ($this->hasNS ? " AND {$this->bl_ns} = '{$t->getNamespace()}'" : "") .
145 ")";
146 $this->addWhere($titleWhere);
147 $this->addWhereFld('page_namespace', $this->params['namespace']);
148 if(!is_null($this->redirID))
149 {
150 $first = $this->redirTitles[0];
151 $title = $db->strencode($first->getDBKey());
152 $ns = $first->getNamespace();
153 $from = $this->redirID;
154 if($this->hasNS)
155 $this->addWhere("{$this->bl_ns} > $ns OR ".
156 "({$this->bl_ns} = $ns AND ".
157 "({$this->bl_title} > '$title' OR ".
158 "({$this->bl_title} = '$title' AND ".
159 "{$this->bl_from} >= $from)))");
160 else
161 $this->addWhere("{$this->bl_title} > '$title' OR ".
162 "({$this->bl_title} = '$title' AND ".
163 "{$this->bl_from} >= $from)");
164
165 }
166 if($this->params['filterredir'] == 'redirects')
167 $this->addWhereFld('page_is_redirect', 1);
168 if($this->params['filterredir'] == 'nonredirects')
169 $this->addWhereFld('page_is_redirect', 0);
170 $this->addOption('LIMIT', $this->params['limit'] + 1);
171 $this->addOption('ORDER BY', $this->bl_sort);
172 }
173
174 private function run($resultPageSet = null) {
175 $this->params = $this->extractRequestParams(false);
176 $this->redirect = isset($this->params['redirect']) && $this->params['redirect'];
177 $userMax = ( $this->redirect ? ApiBase::LIMIT_BIG1/2 : ApiBase::LIMIT_BIG1 );
178 $botMax = ( $this->redirect ? ApiBase::LIMIT_BIG2/2 : ApiBase::LIMIT_BIG2 );
179 if( $this->params['limit'] == 'max' ) {
180 $this->params['limit'] = $this->getMain()->canApiHighLimits() ? $botMax : $userMax;
181 $this->getResult()->addValue( 'limits', $this->getModuleName(), $this->params['limit'] );
182 }
183
184 $this->processContinue();
185 $this->prepareFirstQuery($resultPageSet);
186
187 $db = $this->getDB();
188 $res = $this->select(__METHOD__.'::firstQuery');
189
190 $count = 0;
191 $this->data = array ();
192 $this->continueStr = null;
193 $this->redirTitles = array();
194 while ($row = $db->fetchObject($res)) {
195 if (++ $count > $this->params['limit']) {
196 // We've reached the one extra which shows that there are additional pages to be had. Stop here...
197 // Continue string preserved in case the redirect query doesn't pass the limit
198 $this->continueStr = $this->getContinueStr($row->page_id);
199 break;
200 }
201
202 if (is_null($resultPageSet))
203 $this->extractRowInfo($row);
204 else
205 {
206 if($row->page_is_redirect)
207 $this->redirTitles[] = Title::makeTitle($row->page_namespace, $row->page_title);
208 $resultPageSet->processDbRow($row);
209 }
210 }
211 $db->freeResult($res);
212
213 if($this->redirect && count($this->redirTitles))
214 {
215 $this->resetQueryParams();
216 $this->prepareSecondQuery($resultPageSet);
217 $res = $this->select(__METHOD__.'::secondQuery');
218 $count = 0;
219 while($row = $db->fetchObject($res))
220 {
221 if(++$count > $this->params['limit'])
222 {
223 // We've reached the one extra which shows that there are additional pages to be had. Stop here...
224 // We need to keep the parent page of this redir in
225 if($this->hasNS)
226 $contTitle = Title::makeTitle($row->{$this->bl_ns}, $row->{$this->bl_title});
227 else
228 $contTitle = Title::makeTitle(NS_FILE, $row->{$this->bl_title});
229 $this->continueStr = $this->getContinueRedirStr($contTitle->getArticleID(), $row->page_id);
230 break;
231 }
232
233 if(is_null($resultPageSet))
234 $this->extractRedirRowInfo($row);
235 else
236 $resultPageSet->processDbRow($row);
237 }
238 $db->freeResult($res);
239 }
240 if(!is_null($this->continueStr))
241 $this->setContinueEnumParameter('continue', $this->continueStr);
242
243 if (is_null($resultPageSet)) {
244 $resultData = array();
245 foreach($this->data as $ns => $a)
246 foreach($a as $title => $arr)
247 $resultData[] = $arr;
248 $result = $this->getResult();
249 $result->setIndexedTagName($resultData, $this->bl_code);
250 $result->addValue('query', $this->getModuleName(), $resultData);
251 }
252 }
253
254 private function extractRowInfo($row) {
255 if(!isset($this->data[$row->page_namespace][$row->page_title])) {
256 $this->data[$row->page_namespace][$row->page_title]['pageid'] = $row->page_id;
257 ApiQueryBase::addTitleInfo($this->data[$row->page_namespace][$row->page_title], Title::makeTitle($row->page_namespace, $row->page_title));
258 if($row->page_is_redirect)
259 {
260 $this->data[$row->page_namespace][$row->page_title]['redirect'] = '';
261 $this->redirTitles[] = Title::makeTitle($row->page_namespace, $row->page_title);
262 }
263 }
264 }
265
266 private function extractRedirRowInfo($row)
267 {
268 $a['pageid'] = $row->page_id;
269 ApiQueryBase::addTitleInfo($a, Title::makeTitle($row->page_namespace, $row->page_title));
270 if($row->page_is_redirect)
271 $a['redirect'] = '';
272 $ns = $this->hasNS ? $row->{$this->bl_ns} : NS_FILE;
273 $this->data[$ns][$row->{$this->bl_title}]['redirlinks'][] = $a;
274 $this->getResult()->setIndexedTagName($this->data[$ns][$row->{$this->bl_title}]['redirlinks'], $this->bl_code);
275 }
276
277 protected function processContinue() {
278 if (!is_null($this->params['continue']))
279 $this->parseContinueParam();
280 else {
281 if ( $this->params['title'] !== "" ) {
282 $title = Title::newFromText( $this->params['title'] );
283 if ( !$title ) {
284 $this->dieUsageMsg(array('invalidtitle', $this->params['title']));
285 } else {
286 $this->rootTitle = $title;
287 }
288 } else {
289 $this->dieUsageMsg(array('missingparam', 'title'));
290 }
291 }
292
293 // only image titles are allowed for the root in imageinfo mode
294 if (!$this->hasNS && $this->rootTitle->getNamespace() !== NS_FILE)
295 $this->dieUsage("The title for {$this->getModuleName()} query must be an image", 'bad_image_title');
296 }
297
298 protected function parseContinueParam() {
299 $continueList = explode('|', $this->params['continue']);
300 // expected format:
301 // ns | key | id1 [| id2]
302 // ns+key: root title
303 // id1: first-level page ID to continue from
304 // id2: second-level page ID to continue from
305
306 // null stuff out now so we know what's set and what isn't
307 $this->rootTitle = $this->contID = $this->redirID = null;
308 $rootNs = intval($continueList[0]);
309 if($rootNs === 0 && $continueList[0] !== '0')
310 // Illegal continue parameter
311 $this->dieUsage("Invalid continue param. You should pass the original value returned by the previous query", "_badcontinue");
312 $this->rootTitle = Title::makeTitleSafe($rootNs, $continueList[1]);
313 if(!$this->rootTitle)
314 $this->dieUsage("Invalid continue param. You should pass the original value returned by the previous query", "_badcontinue");
315 $contID = intval($continueList[2]);
316 if($contID === 0 && $continueList[2] !== '0')
317 $this->dieUsage("Invalid continue param. You should pass the original value returned by the previous query", "_badcontinue");
318 $this->contID = $contID;
319 $redirID = intval(@$continueList[3]);
320 if($redirID === 0 && @$continueList[3] !== '0')
321 // This one isn't required
322 return;
323 $this->redirID = $redirID;
324
325 }
326
327 protected function getContinueStr($lastPageID) {
328 return $this->rootTitle->getNamespace() .
329 '|' . $this->rootTitle->getDBkey() .
330 '|' . $lastPageID;
331 }
332
333 protected function getContinueRedirStr($lastPageID, $lastRedirID) {
334 return $this->getContinueStr($lastPageID) . '|' . $lastRedirID;
335 }
336
337 public function getAllowedParams() {
338 $retval = array (
339 'title' => null,
340 'continue' => null,
341 'namespace' => array (
342 ApiBase :: PARAM_ISMULTI => true,
343 ApiBase :: PARAM_TYPE => 'namespace'
344 ),
345 'filterredir' => array(
346 ApiBase :: PARAM_DFLT => 'all',
347 ApiBase :: PARAM_TYPE => array(
348 'all',
349 'redirects',
350 'nonredirects'
351 )
352 ),
353 'limit' => array (
354 ApiBase :: PARAM_DFLT => 10,
355 ApiBase :: PARAM_TYPE => 'limit',
356 ApiBase :: PARAM_MIN => 1,
357 ApiBase :: PARAM_MAX => ApiBase :: LIMIT_BIG1,
358 ApiBase :: PARAM_MAX2 => ApiBase :: LIMIT_BIG2
359 )
360 );
361 if($this->getModuleName() == 'embeddedin')
362 return $retval;
363 $retval['redirect'] = false;
364 return $retval;
365 }
366
367 public function getParamDescription() {
368 $retval = array (
369 'title' => 'Title to search. If null, titles= parameter will be used instead, but will be obsolete soon.',
370 'continue' => 'When more results are available, use this to continue.',
371 'namespace' => 'The namespace to enumerate.',
372 'filterredir' => 'How to filter for redirects'
373 );
374 if($this->getModuleName() != 'embeddedin')
375 return array_merge($retval, array(
376 'redirect' => 'If linking page is a redirect, find all pages that link to that redirect as well. Maximum limit is halved.',
377 'limit' => "How many total pages to return. If {$this->bl_code}redirect is enabled, limit applies to each level separately."
378 ));
379 return array_merge($retval, array(
380 'limit' => "How many total pages to return."
381 ));
382 }
383
384 public function getDescription() {
385 switch ($this->getModuleName()) {
386 case 'backlinks' :
387 return 'Find all pages that link to the given page';
388 case 'embeddedin' :
389 return 'Find all pages that embed (transclude) the given title';
390 case 'imageusage' :
391 return 'Find all pages that use the given image title.';
392 default :
393 ApiBase :: dieDebug(__METHOD__, 'Unknown module name');
394 }
395 }
396
397 protected function getExamples() {
398 static $examples = array (
399 'backlinks' => array (
400 "api.php?action=query&list=backlinks&bltitle=Main%20Page",
401 "api.php?action=query&generator=backlinks&gbltitle=Main%20Page&prop=info"
402 ),
403 'embeddedin' => array (
404 "api.php?action=query&list=embeddedin&eititle=Template:Stub",
405 "api.php?action=query&generator=embeddedin&geititle=Template:Stub&prop=info"
406 ),
407 'imageusage' => array (
408 "api.php?action=query&list=imageusage&iutitle=Image:Albert%20Einstein%20Head.jpg",
409 "api.php?action=query&generator=imageusage&giutitle=Image:Albert%20Einstein%20Head.jpg&prop=info"
410 )
411 );
412
413 return $examples[$this->getModuleName()];
414 }
415
416 public function getVersion() {
417 return __CLASS__ . ': $Id$';
418 }
419 }