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