4 * Created on Oct 16, 2006
6 * API for MediaWiki 1.8+
8 * Copyright (C) 2006 Yuri Astrakhan <Firstname><Lastname>@gmail.com
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.
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.
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
26 if (!defined('MEDIAWIKI')) {
27 // Eclipse helper - will be ignored in production
28 require_once ("ApiQueryBase.php");
32 * This is 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
39 class ApiQueryBacklinks
extends ApiQueryGeneratorBase
{
41 private $params, $rootTitle, $contRedirs, $contLevel, $contTitle, $contID, $redirID;
43 // output element name, database column field prefix, database table
44 private $backlinksSettings = array (
45 'backlinks' => array (
48 'linktbl' => 'pagelinks'
50 'embeddedin' => array (
53 'linktbl' => 'templatelinks'
55 'imageusage' => array (
58 'linktbl' => 'imagelinks'
62 public function __construct($query, $moduleName) {
63 $code = $prefix = $linktbl = null;
64 extract($this->backlinksSettings
[$moduleName]);
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;
72 $this->hasNS
= $moduleName !== 'imageusage';
74 $this->bl_title
= $prefix . '_title';
75 $this->bl_sort
= "{$this->bl_ns}, {$this->bl_title}, {$this->bl_from}";
76 $this->bl_fields
= array (
81 $this->bl_title
= $prefix . '_to';
82 $this->bl_sort
= "{$this->bl_title}, {$this->bl_from}";
83 $this->bl_fields
= array (
89 public function execute() {
93 public function executeGenerator($resultPageSet) {
94 $this->run($resultPageSet);
97 private function prepareFirstQuery($resultPageSet = null) {
98 /* SELECT page_id, page_title, page_namespace, page_is_redirect
99 * FROM pagelinks JOIN page ON pl_from=page_id
100 * WHERE pl_title='Foo' AND pl_namespace=0
101 * LIMIT 11 ORDER BY pl_from
103 $db = $this->getDb();
104 list($tblpage, $tbllinks) = $db->tableNamesN('page', $this->bl_table
);
105 $this->addTables("$tbllinks JOIN $tblpage ON {$this->bl_from}=page_id");
106 if(is_null($resultPageSet))
107 $this->addFields(array('page_id', 'page_title', 'page_namespace', 'page_is_redirect'));
109 $this->addFields($resultPageSet->getPageTableFields());
110 $this->addWhereFld($this->bl_title
, $this->rootTitle
->getDbKey());
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("page_id>={$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
);
124 private function prepareSecondQuery($resultPageSet = null) {
125 /* SELECT page_id, page_title, page_namespace, page_is_redirect, pl_title, pl_namespace
126 * FROM pagelinks JOIN page ON pl_from=page_id
127 * WHERE (pl_title='Foo' AND pl_namespace=0) OR (pl_title='Bar' AND pl_namespace=1)
128 * LIMIT 11 ORDER BY pl_namespace, pl_title, pl_from
130 $db = $this->getDb();
131 list($tblpage, $tbllinks) = $db->tableNamesN('page', $this->bl_table
);
132 $this->addTables("$tbllinks JOIN $tblpage ON {$this->bl_from}=page_id");
133 if(is_null($resultPageSet))
134 $this->addFields(array('page_id', 'page_title', 'page_namespace', 'page_is_redirect'));
136 $this->addFields($resultPageSet->getPageTableFields());
137 $this->addFields($this->bl_title
);
139 $this->addFields($this->bl_ns
);
141 foreach($this->redirTitles
as $t)
142 $titleWhere .= ($titleWhere != '' ?
" OR " : '') .
143 "({$this->bl_title} = '{$t->getDBKey()}'" .
144 ($this->hasNS ?
" AND {$this->bl_ns} = '{$t->getNamespace()}'" : "") .
146 $this->addWhere($titleWhere);
147 $this->addWhereFld('page_namespace', $this->params
['namespace']);
148 if(!is_null($this->redirID
))
149 $this->addWhere("page_id>={$this->redirID}");
150 if($this->params
['filterredir'] == 'redirects')
151 $this->addWhereFld('page_is_redirect', 1);
152 if($this->params
['filterredir'] == 'nonredirects')
153 $this->addWhereFld('page_is_redirect', 0);
154 $this->addOption('LIMIT', $this->params
['limit'] +
1);
155 $this->addOption('ORDER BY', $this->bl_sort
);
158 private function run($resultPageSet = null) {
159 $this->params
= $this->extractRequestParams(false);
160 $userMax = ( $this->params
['redirect'] ? ApiBase
::LIMIT_BIG1
/2 : ApiBase
::LIMIT_BIG1
);
161 $botMax = ( $this->params
['redirect'] ? ApiBase
::LIMIT_BIG2
/2 : ApiBase
::LIMIT_BIG2
);
162 if( $this->params
['limit'] == 'max' ) {
163 $this->params
['limit'] = $this->getMain()->canApiHighLimits() ?
$botMax : $userMax;
164 $this->getResult()->addValue( 'limits', $this->getModuleName(), $this->params
['limit'] );
167 $this->processContinue();
168 $this->prepareFirstQuery($resultPageSet);
170 $db = $this->getDB();
171 $res = $this->select(__METHOD__
);
174 $this->data
= array ();
175 $this->continueStr
= null;
176 $this->redirTitles
= array();
177 while ($row = $db->fetchObject($res)) {
178 if (++
$count > $this->params
['limit']) {
179 // We've reached the one extra which shows that there are additional pages to be had. Stop here...
180 // Continue string preserved in case the redirect query doesn't pass the limit
181 $this->continueStr
= $this->getContinueStr($row->page_id
);
185 if (is_null($resultPageSet))
186 $this->extractRowInfo($row);
188 $resultPageSet->processDbRow($row);
190 $db->freeResult($res);
192 if($this->params
['redirect'] && !empty($this->redirTitles
))
194 $this->resetQueryParams();
195 $this->prepareSecondQuery($resultPageSet);
196 $res = $this->select(__METHOD__
);
198 while($row = $db->fetchObject($res))
200 if(++
$count > $this->params
['limit'])
202 // We've reached the one extra which shows that there are additional pages to be had. Stop here...
203 // We need to keep the parent page of this redir in
205 $contTitle = Title
::makeTitle($row->{$this->bl_ns
}, $row->{$this->bl_title
});
207 $contTitle = Title
::makeTitle(NS_IMAGE
, $row->{$this->bl_title
});
208 $this->continueStr
= $this->getContinueRedirStr($contTitle->getArticleID(), $row->page_id
);
212 if(is_null($resultPageSet))
213 $this->extractRedirRowInfo($row);
215 $resultPageSet->processDbRow($row);
217 $db->freeResult($res);
219 if(!is_null($this->continueStr
))
220 $this->setContinueEnumParameter('continue', $this->continueStr
);
222 if (is_null($resultPageSet)) {
223 $resultData = array();
224 foreach($this->data
as $ns => $a)
225 foreach($a as $title => $arr)
226 $resultData[$arr['pageid']] = $arr;
227 $result = $this->getResult();
228 $result->setIndexedTagName($resultData, $this->bl_code
);
229 $result->addValue('query', $this->getModuleName(), $resultData);
233 private function extractRowInfo($row) {
234 if(!isset($this->data
[$row->page_namespace
][$row->page_title
])) {
235 $this->data
[$row->page_namespace
][$row->page_title
]['pageid'] = $row->page_id
;
236 ApiQueryBase
::addTitleInfo($this->data
[$row->page_namespace
][$row->page_title
], Title
::makeTitle($row->page_namespace
, $row->page_title
));
237 if($row->page_is_redirect
)
239 $this->data
[$row->page_namespace
][$row->page_title
]['redirect'] = '';
240 $this->redirTitles
[] = Title
::makeTitle($row->page_namespace
, $row->page_title
);
245 private function extractRedirRowInfo($row)
247 $a['pageid'] = $row->page_id
;
248 ApiQueryBase
::addTitleInfo($a, Title
::makeTitle($row->page_namespace
, $row->page_title
));
249 if($row->page_is_redirect
)
251 $ns = $this->hasNS ?
$row->{$this->bl_ns
} : NS_IMAGE
;
252 $this->data
[$ns][$row->{$this->bl_title
}]['redirlinks'][] = $a;
253 $this->getResult()->setIndexedTagName($this->data
[$ns][$row->{$this->bl_title
}]['redirlinks'], $this->bl_code
);
256 protected function processContinue() {
257 $pageSet = $this->getPageSet();
258 $count = $pageSet->getTitleCount();
260 if (!is_null($this->params
['continue']))
261 $this->parseContinueParam();
263 $title = $this->params
['title'];
264 if (!is_null($title)) {
265 $this->rootTitle
= Title
:: newFromText($title);
266 } else { // This case is obsolete. Will support this for a while
268 $this->dieUsage("The {$this->getModuleName()} query requires one title to start", 'bad_title_count');
269 $this->rootTitle
= current($pageSet->getTitles()); // only one title there
270 $this->setWarning('Using titles parameter is obsolete for this list. Use ' . $this->encodeParamName('title') . ' instead.');
274 // only image titles are allowed for the root in imageinfo mode
275 if (!$this->hasNS
&& $this->rootTitle
->getNamespace() !== NS_IMAGE
)
276 $this->dieUsage("The title for {$this->getModuleName()} query must be an image", 'bad_image_title');
279 protected function parseContinueParam() {
280 $continueList = explode('|', $this->params
['continue']);
282 // ns | key | id1 [| id2]
283 // ns+key: root title
284 // id1: first-level page ID to continue from
285 // id2: second-level page ID to continue from
287 // null stuff out now so we know what's set and what isn't
288 $this->rootTitle
= $this->contID
= $this->redirID
= null;
289 $rootNs = intval($continueList[0]);
290 if($rootNs === 0 && $continueList[0] !== '0')
291 // Illegal continue parameter
292 $this->dieUsage("Invalid continue param. You should pass the original value returned by the previous query", "_badcontinue");
293 $this->rootTitle
= Title
::makeTitleSafe($rootNs, $continueList[1]);
294 if(!$this->rootTitle
)
295 $this->dieUsage("Invalid continue param. You should pass the original value returned by the previous query", "_badcontinue");
296 $contID = intval($continueList[2]);
297 if($contID === 0 && $continueList[2] !== '0')
298 $this->dieUsage("Invalid continue param. You should pass the original value returned by the previous query", "_badcontinue");
299 $this->contID
= $contID;
300 $redirID = intval(@$continueList[3]);
301 if($redirID === 0 && @$continueList[3] !== '0')
302 // This one isn't required
304 $this->redirID
= $redirID;
308 protected function getContinueStr($lastPageID) {
309 return $this->rootTitle
->getNamespace() .
310 '|' . $this->rootTitle
->getDBkey() .
314 protected function getContinueRedirStr($lastPageID, $lastRedirID) {
315 return $this->getContinueStr($lastPageID) . '|' . $lastRedirID;
318 public function getAllowedParams() {
323 'namespace' => array (
324 ApiBase
:: PARAM_ISMULTI
=> true,
325 ApiBase
:: PARAM_TYPE
=> 'namespace'
327 'filterredir' => array(
328 ApiBase
:: PARAM_DFLT
=> 'all',
329 ApiBase
:: PARAM_TYPE
=> array(
337 ApiBase
:: PARAM_DFLT
=> 10,
338 ApiBase
:: PARAM_TYPE
=> 'limit',
339 ApiBase
:: PARAM_MIN
=> 1,
340 ApiBase
:: PARAM_MAX
=> ApiBase
:: LIMIT_BIG1
,
341 ApiBase
:: PARAM_MAX2
=> ApiBase
:: LIMIT_BIG2
346 public function getParamDescription() {
348 'title' => 'Title to search. If null, titles= parameter will be used instead, but will be obsolete soon.',
349 'continue' => 'When more results are available, use this to continue.',
350 'namespace' => 'The namespace to enumerate.',
351 'filterredir' => 'How to filter for redirects',
352 'redirect' => 'If linking page is a redirect, find all pages that link to that redirect as well. Maximum limit is halved.',
353 'limit' => "How many total pages to return. If {$this->bl_code}redirect is enabled, limit applies to each level separately."
357 public function getDescription() {
358 switch ($this->getModuleName()) {
360 return 'Find all pages that link to the given page';
362 return 'Find all pages that embed (transclude) the given title';
364 return 'Find all pages that use the given image title.';
366 ApiBase
:: dieDebug(__METHOD__
, 'Unknown module name');
370 protected function getExamples() {
371 static $examples = array (
372 'backlinks' => array (
373 "api.php?action=query&list=backlinks&bltitle=Main%20Page",
374 "api.php?action=query&generator=backlinks&gbltitle=Main%20Page&prop=info"
376 'embeddedin' => array (
377 "api.php?action=query&list=embeddedin&eititle=Template:Stub",
378 "api.php?action=query&generator=embeddedin&geititle=Template:Stub&prop=info"
380 'imageusage' => array (
381 "api.php?action=query&list=imageusage&iutitle=Image:Albert%20Einstein%20Head.jpg",
382 "api.php?action=query&generator=imageusage&giutitle=Image:Albert%20Einstein%20Head.jpg&prop=info"
386 return $examples[$this->getModuleName()];
389 public function getVersion() {
390 return __CLASS__
. ': $Id$';