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;
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_tables
= array (
73 $this->bl_code
= $code;
75 $this->hasNS
= $moduleName !== 'imageusage';
77 $this->bl_title
= $prefix . '_title';
78 $this->bl_sort
= "{$this->bl_ns}, {$this->bl_title}, {$this->bl_from}";
79 $this->bl_fields
= array (
84 $this->bl_title
= $prefix . '_to';
85 $this->bl_sort
= "{$this->bl_title}, {$this->bl_from}";
86 $this->bl_fields
= array (
92 public function execute() {
96 public function executeGenerator($resultPageSet) {
97 $this->run($resultPageSet);
100 private function run($resultPageSet = null) {
101 $this->params
= $this->extractRequestParams();
103 $redirect = $this->params
['redirect'];
105 $this->dieDebug('Redirect has not been implemented', 'notimplemented');
107 $this->processContinue();
109 $this->addFields($this->bl_fields
);
110 if (is_null($resultPageSet))
111 $this->addFields(array (
117 $this->addFields($resultPageSet->getPageTableFields()); // will include page_id
119 $this->addTables($this->bl_tables
);
120 $this->addWhere($this->bl_from
. '=page_id');
123 $this->addWhereFld($this->bl_ns
, $this->rootTitle
->getNamespace());
124 $this->addWhereFld($this->bl_title
, $this->rootTitle
->getDBkey());
125 $this->addWhereFld('page_namespace', $this->params
['namespace']);
127 if($this->params
['filterredir'] == 'redirects')
128 $this->addWhereFld('page_is_redirect', 1);
129 if($this->params
['filterredir'] == 'nonredirects')
130 $this->addWhereFld('page_is_redirect', 0);
132 $limit = $this->params
['limit'];
133 $this->addOption('LIMIT', $limit +
1);
134 $this->addOption('ORDER BY', $this->bl_sort
);
136 $db = $this->getDB();
137 if (!is_null($this->params
['continue'])) {
138 $plfrm = intval($this->contID
);
139 if ($this->contLevel
== 0) {
140 // For the first level, there is only one target title, so no need for complex filtering
141 $this->addWhere($this->bl_from
. '>=' . $plfrm);
143 $ns = $this->contTitle
->getNamespace();
144 $t = $db->addQuotes($this->contTitle
->getDBkey());
145 $whereWithoutNS = "{$this->bl_title}>$t OR ({$this->bl_title}=$t AND {$this->bl_from}>=$plfrm))";
148 $this->addWhere("{$this->bl_ns}>$ns OR ({$this->bl_ns}=$ns AND ($whereWithoutNS)");
150 $this->addWhere($whereWithoutNS);
154 $res = $this->select(__METHOD__
);
158 while ($row = $db->fetchObject($res)) {
159 if (++
$count > $limit) {
160 // We've reached the one extra which shows that there are additional pages to be had. Stop here...
162 $ns = $row-> { $this->bl_ns
};
163 $t = $row-> { $this->bl_title
};
164 $continue = $this->getContinueRedirStr(false, 0, $ns, $t, $row->page_id
);
166 $continue = $this->getContinueStr($row->page_id
);
167 // TODO: Security issue - if the user has no right to view next title, it will still be shown
168 $this->setContinueEnumParameter('continue', $continue);
172 if (is_null($resultPageSet)) {
173 $vals = $this->extractRowInfo($row);
177 $resultPageSet->processDbRow($row);
180 $db->freeResult($res);
182 if (is_null($resultPageSet)) {
183 $result = $this->getResult();
184 $result->setIndexedTagName($data, $this->bl_code
);
185 $result->addValue('query', $this->getModuleName(), $data);
189 private function extractRowInfo($row) {
192 $vals['pageid'] = intval($row->page_id
);
193 ApiQueryBase
:: addTitleInfo($vals, Title
:: makeTitle($row->page_namespace
, $row->page_title
));
198 protected function processContinue() {
199 $pageSet = $this->getPageSet();
200 $count = $pageSet->getTitleCount();
202 if (!is_null($this->params
['continue'])) {
203 $this->parseContinueParam();
205 // Skip all completed links
208 $title = $this->params
['title'];
209 if (!is_null($title)) {
210 $this->rootTitle
= Title
:: newFromText($title);
211 } else { // This case is obsolete. Will support this for a while
213 $this->dieUsage("The {$this->getModuleName()} query requires one title to start", 'bad_title_count');
214 $this->rootTitle
= current($pageSet->getTitles()); // only one title there
215 $this->setWarning('Using titles parameter is obsolete for this list. Use ' . $this->encodeParamName('title') . ' instead.');
219 // only image titles are allowed for the root
220 if (!$this->hasNS
&& $this->rootTitle
->getNamespace() !== NS_IMAGE
)
221 $this->dieUsage("The title for {$this->getModuleName()} query must be an image", 'bad_image_title');
224 protected function parseContinueParam() {
225 $continueList = explode('|', $this->params
['continue']);
226 if ($this->params
['redirect']) {
228 // expected redirect-mode parameter:
229 // ns|db_key|step|level|ns|db_key|id
230 // ns+db_key -- the root title
231 // step = 1 or 2 - which step to continue from - 1-titles, 2-redirects
232 // level -- how many levels to follow before starting enumerating.
233 // if level > 0 -- ns+title to continue from, otherwise skip these
234 // id = last page_id to continue from
236 if (count($continueList) > 4) {
237 $rootNs = intval($continueList[0]);
238 if (($rootNs !== 0 ||
$continueList[0] === '0') && !empty ($continueList[1])) {
239 $this->rootTitle
= Title
:: makeTitleSafe($rootNs, $continueList[1]);
240 if ($this->rootTitle
) {
242 $step = intval($continueList[2]);
243 if ($step === 1 ||
$step === 2) {
244 $this->contRedirs
= ($step === 2);
246 $level = intval($continueList[3]);
247 if ($level !== 0 ||
$continueList[3] === '0') {
248 $this->contLevel
= $level;
251 if (count($continueList) === 5) {
252 $contID = intval($continueList[4]);
253 if ($contID !== 0 ||
$continueList[4] === '0') {
254 $this->contID
= $contID;
259 if (count($continueList) === 7) {
260 $contNs = intval($continueList[4]);
261 if (($contNs !== 0 ||
$continueList[4] === '0') && !empty ($continueList[5])) {
262 $this->contTitle
= Title
:: makeTitleSafe($contNs, $continueList[5]);
264 $contID = intval($continueList[6]);
265 if ($contID !== 0 ||
$continueList[6] === '0') {
266 $this->contID
= $contID;
279 // expected non-redirect-mode parameter:
281 // ns+db_key -- the root title
282 // id = last page_id to continue from
284 if (count($continueList) === 3) {
285 $rootNs = intval($continueList[0]);
286 if (($rootNs !== 0 ||
$continueList[0] === '0') && !empty ($continueList[1])) {
287 $this->rootTitle
= Title
:: makeTitleSafe($rootNs, $continueList[1]);
288 if ($this->rootTitle
) {
290 $contID = intval($continueList[2]);
292 $this->contID
= $contID;
300 $this->dieUsage("Invalid continue param. You should pass the original value returned by the previous query", "_badcontinue");
303 protected function getContinueStr($lastPageID) {
304 return $this->rootTitle
->getNamespace() .
305 '|' . $this->rootTitle
->getDBkey() .
309 protected function getContinueRedirStr($isRedirPhase, $level, $ns, $title, $lastPageID) {
310 return $this->rootTitle
->getNamespace() .
311 '|' . $this->rootTitle
->getDBkey() .
312 '|' . ($isRedirPhase ?
1 : 2) .
314 ($level > 0 ?
('|' . $ns . '|' . $title) : '') .
318 protected 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 protected 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 (not implemented)',
353 'limit' => 'How many total pages to return.'
357 protected 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$';