API: Improvements to action=emailuser:
[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("page_id>={$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 * LIMIT 11 ORDER BY pl_namespace, pl_title, pl_from
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 $this->addWhere("page_id>={$this->redirID}");
151 if($this->params['filterredir'] == 'redirects')
152 $this->addWhereFld('page_is_redirect', 1);
153 if($this->params['filterredir'] == 'nonredirects')
154 $this->addWhereFld('page_is_redirect', 0);
155 $this->addOption('LIMIT', $this->params['limit'] + 1);
156 $this->addOption('ORDER BY', $this->bl_sort);
157 }
158
159 private function run($resultPageSet = null) {
160 $this->params = $this->extractRequestParams(false);
161 $this->redirect = isset($this->params['redirect']) && $this->params['redirect'];
162 $userMax = ( $this->redirect ? ApiBase::LIMIT_BIG1/2 : ApiBase::LIMIT_BIG1 );
163 $botMax = ( $this->redirect ? ApiBase::LIMIT_BIG2/2 : ApiBase::LIMIT_BIG2 );
164 if( $this->params['limit'] == 'max' ) {
165 $this->params['limit'] = $this->getMain()->canApiHighLimits() ? $botMax : $userMax;
166 $this->getResult()->addValue( 'limits', $this->getModuleName(), $this->params['limit'] );
167 }
168
169 $this->processContinue();
170 $this->prepareFirstQuery($resultPageSet);
171
172 $db = $this->getDB();
173 $res = $this->select(__METHOD__);
174
175 $count = 0;
176 $this->data = array ();
177 $this->continueStr = null;
178 $this->redirTitles = array();
179 while ($row = $db->fetchObject($res)) {
180 if (++ $count > $this->params['limit']) {
181 // We've reached the one extra which shows that there are additional pages to be had. Stop here...
182 // Continue string preserved in case the redirect query doesn't pass the limit
183 $this->continueStr = $this->getContinueStr($row->page_id);
184 break;
185 }
186
187 if (is_null($resultPageSet))
188 $this->extractRowInfo($row);
189 else
190 {
191 if($row->page_is_redirect)
192 $this->redirTitles[] = Title::makeTitle($row->page_namespace, $row->page_title);
193 $resultPageSet->processDbRow($row);
194 }
195 }
196 $db->freeResult($res);
197
198 if($this->redirect && !empty($this->redirTitles))
199 {
200 $this->resetQueryParams();
201 $this->prepareSecondQuery($resultPageSet);
202 $res = $this->select(__METHOD__);
203 $count = 0;
204 while($row = $db->fetchObject($res))
205 {
206 if(++$count > $this->params['limit'])
207 {
208 // We've reached the one extra which shows that there are additional pages to be had. Stop here...
209 // We need to keep the parent page of this redir in
210 if($this->hasNS)
211 $contTitle = Title::makeTitle($row->{$this->bl_ns}, $row->{$this->bl_title});
212 else
213 $contTitle = Title::makeTitle(NS_IMAGE, $row->{$this->bl_title});
214 $this->continueStr = $this->getContinueRedirStr($contTitle->getArticleID(), $row->page_id);
215 break;
216 }
217
218 if(is_null($resultPageSet))
219 $this->extractRedirRowInfo($row);
220 else
221 $resultPageSet->processDbRow($row);
222 }
223 $db->freeResult($res);
224 }
225 if(!is_null($this->continueStr))
226 $this->setContinueEnumParameter('continue', $this->continueStr);
227
228 if (is_null($resultPageSet)) {
229 $resultData = array();
230 foreach($this->data as $ns => $a)
231 foreach($a as $title => $arr)
232 $resultData[] = $arr;
233 $result = $this->getResult();
234 $result->setIndexedTagName($resultData, $this->bl_code);
235 $result->addValue('query', $this->getModuleName(), $resultData);
236 }
237 }
238
239 private function extractRowInfo($row) {
240 if(!isset($this->data[$row->page_namespace][$row->page_title])) {
241 $this->data[$row->page_namespace][$row->page_title]['pageid'] = $row->page_id;
242 ApiQueryBase::addTitleInfo($this->data[$row->page_namespace][$row->page_title], Title::makeTitle($row->page_namespace, $row->page_title));
243 if($row->page_is_redirect)
244 {
245 $this->data[$row->page_namespace][$row->page_title]['redirect'] = '';
246 $this->redirTitles[] = Title::makeTitle($row->page_namespace, $row->page_title);
247 }
248 }
249 }
250
251 private function extractRedirRowInfo($row)
252 {
253 $a['pageid'] = $row->page_id;
254 ApiQueryBase::addTitleInfo($a, Title::makeTitle($row->page_namespace, $row->page_title));
255 if($row->page_is_redirect)
256 $a['redirect'] = '';
257 $ns = $this->hasNS ? $row->{$this->bl_ns} : NS_IMAGE;
258 $this->data[$ns][$row->{$this->bl_title}]['redirlinks'][] = $a;
259 $this->getResult()->setIndexedTagName($this->data[$ns][$row->{$this->bl_title}]['redirlinks'], $this->bl_code);
260 }
261
262 protected function processContinue() {
263 if (!is_null($this->params['continue']))
264 $this->parseContinueParam();
265 else {
266 if ( $this->params['title'] !== "" ) {
267 $title = Title::newFromText( $this->params['title'] );
268 if ( !$title ) {
269 $this->dieUsageMsg(array('invalidtitle', $this->params['title']));
270 } else {
271 $this->rootTitle = $title;
272 }
273 } else {
274 $this->dieUsageMsg(array('missingparam', 'title'));
275 }
276 }
277
278 // only image titles are allowed for the root in imageinfo mode
279 if (!$this->hasNS && $this->rootTitle->getNamespace() !== NS_IMAGE)
280 $this->dieUsage("The title for {$this->getModuleName()} query must be an image", 'bad_image_title');
281 }
282
283 protected function parseContinueParam() {
284 $continueList = explode('|', $this->params['continue']);
285 // expected format:
286 // ns | key | id1 [| id2]
287 // ns+key: root title
288 // id1: first-level page ID to continue from
289 // id2: second-level page ID to continue from
290
291 // null stuff out now so we know what's set and what isn't
292 $this->rootTitle = $this->contID = $this->redirID = null;
293 $rootNs = intval($continueList[0]);
294 if($rootNs === 0 && $continueList[0] !== '0')
295 // Illegal continue parameter
296 $this->dieUsage("Invalid continue param. You should pass the original value returned by the previous query", "_badcontinue");
297 $this->rootTitle = Title::makeTitleSafe($rootNs, $continueList[1]);
298 if(!$this->rootTitle)
299 $this->dieUsage("Invalid continue param. You should pass the original value returned by the previous query", "_badcontinue");
300 $contID = intval($continueList[2]);
301 if($contID === 0 && $continueList[2] !== '0')
302 $this->dieUsage("Invalid continue param. You should pass the original value returned by the previous query", "_badcontinue");
303 $this->contID = $contID;
304 $redirID = intval(@$continueList[3]);
305 if($redirID === 0 && @$continueList[3] !== '0')
306 // This one isn't required
307 return;
308 $this->redirID = $redirID;
309
310 }
311
312 protected function getContinueStr($lastPageID) {
313 return $this->rootTitle->getNamespace() .
314 '|' . $this->rootTitle->getDBkey() .
315 '|' . $lastPageID;
316 }
317
318 protected function getContinueRedirStr($lastPageID, $lastRedirID) {
319 return $this->getContinueStr($lastPageID) . '|' . $lastRedirID;
320 }
321
322 public function getAllowedParams() {
323 $retval = array (
324 'title' => null,
325 'continue' => null,
326 'namespace' => array (
327 ApiBase :: PARAM_ISMULTI => true,
328 ApiBase :: PARAM_TYPE => 'namespace'
329 ),
330 'filterredir' => array(
331 ApiBase :: PARAM_DFLT => 'all',
332 ApiBase :: PARAM_TYPE => array(
333 'all',
334 'redirects',
335 'nonredirects'
336 )
337 ),
338 'limit' => array (
339 ApiBase :: PARAM_DFLT => 10,
340 ApiBase :: PARAM_TYPE => 'limit',
341 ApiBase :: PARAM_MIN => 1,
342 ApiBase :: PARAM_MAX => ApiBase :: LIMIT_BIG1,
343 ApiBase :: PARAM_MAX2 => ApiBase :: LIMIT_BIG2
344 )
345 );
346 if($this->getModuleName() == 'embeddedin')
347 return $retval;
348 $retval['redirect'] = false;
349 return $retval;
350 }
351
352 public function getParamDescription() {
353 $retval = array (
354 'title' => 'Title to search. If null, titles= parameter will be used instead, but will be obsolete soon.',
355 'continue' => 'When more results are available, use this to continue.',
356 'namespace' => 'The namespace to enumerate.',
357 'filterredir' => 'How to filter for redirects'
358 );
359 if($this->getModuleName() != 'embeddedin')
360 return array_merge($retval, array(
361 'redirect' => 'If linking page is a redirect, find all pages that link to that redirect as well. Maximum limit is halved.',
362 'limit' => "How many total pages to return. If {$this->bl_code}redirect is enabled, limit applies to each level separately."
363 ));
364 return array_merge($retval, array(
365 'limit' => "How many total pages to return."
366 ));
367 }
368
369 public function getDescription() {
370 switch ($this->getModuleName()) {
371 case 'backlinks' :
372 return 'Find all pages that link to the given page';
373 case 'embeddedin' :
374 return 'Find all pages that embed (transclude) the given title';
375 case 'imageusage' :
376 return 'Find all pages that use the given image title.';
377 default :
378 ApiBase :: dieDebug(__METHOD__, 'Unknown module name');
379 }
380 }
381
382 protected function getExamples() {
383 static $examples = array (
384 'backlinks' => array (
385 "api.php?action=query&list=backlinks&bltitle=Main%20Page",
386 "api.php?action=query&generator=backlinks&gbltitle=Main%20Page&prop=info"
387 ),
388 'embeddedin' => array (
389 "api.php?action=query&list=embeddedin&eititle=Template:Stub",
390 "api.php?action=query&generator=embeddedin&geititle=Template:Stub&prop=info"
391 ),
392 'imageusage' => array (
393 "api.php?action=query&list=imageusage&iutitle=Image:Albert%20Einstein%20Head.jpg",
394 "api.php?action=query&generator=imageusage&giutitle=Image:Albert%20Einstein%20Head.jpg&prop=info"
395 )
396 );
397
398 return $examples[$this->getModuleName()];
399 }
400
401 public function getVersion() {
402 return __CLASS__ . ': $Id$';
403 }
404 }