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 $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 $continue = $namespace = $redirect = $limit = null;
102 extract($this->extractRequestParams());
105 ApiBase
:: dieDebug(__METHOD__
, 'Redirect has not been implemented', 'notimplemented');
107 $this->processContinue($continue, $redirect);
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', $namespace);
126 $this->addOption('LIMIT', $limit +
1);
127 $this->addOption('ORDER BY', $this->bl_sort
);
130 $this->addWhereFld('page_is_redirect', 0);
132 $db = $this->getDB();
133 if (!is_null($continue)) {
134 $plfrm = intval($this->contID
);
135 if ($this->contLevel
== 0) {
136 // For the first level, there is only one target title, so no need for complex filtering
137 $this->addWhere($this->bl_from
. '>=' . $plfrm);
139 $ns = $this->contTitle
->getNamespace();
140 $t = $db->addQuotes($this->contTitle
->getDBkey());
141 $whereWithoutNS = "{$this->bl_title}>$t OR ({$this->bl_title}=$t AND {$this->bl_from}>=$plfrm))";
144 $this->addWhere("{$this->bl_ns}>$ns OR ({$this->bl_ns}=$ns AND ($whereWithoutNS)");
146 $this->addWhere($whereWithoutNS);
150 $res = $this->select(__METHOD__
);
154 while ($row = $db->fetchObject($res)) {
155 if (++
$count > $limit) {
156 // We've reached the one extra which shows that there are additional pages to be had. Stop here...
158 $ns = $row-> { $this->bl_ns
};
159 $t = $row-> { $this->bl_title
};
160 $continue = $this->getContinueRedirStr(false, 0, $ns, $t, $row->page_id
);
162 $continue = $this->getContinueStr($row->page_id
);
163 $this->setContinueEnumParameter('continue', $continue);
167 if (is_null($resultPageSet)) {
168 $vals = $this->extractRowInfo($row);
172 $resultPageSet->processDbRow($row);
175 $db->freeResult($res);
177 if (is_null($resultPageSet) && !empty($data)) {
178 $result = $this->getResult();
179 $result->setIndexedTagName($data, $this->bl_code
);
180 $result->addValue('query', $this->getModuleName(), $data);
184 private function extractRowInfo($row) {
186 $title = Title
:: makeTitle($row->page_namespace
, $row->page_title
);
187 if (!$title->userCanRead())
191 $vals['pageid'] = intval($row->page_id
);
192 ApiQueryBase
:: addTitleInfo($vals, $title);
197 protected function processContinue($continue, $redirect) {
198 $pageSet = $this->getPageSet();
199 $count = $pageSet->getTitleCount();
200 if (!is_null($continue)) {
202 $this->dieUsage("When continuing the {$this->getModuleName()} query, no other titles may be provided", 'titles_on_continue');
203 $this->parseContinueParam($continue, $redirect);
205 // Skip all completed links
209 $this->dieUsage("The {$this->getModuleName()} query requires one title to start", 'bad_title_count');
210 $this->rootTitle
= current($pageSet->getTitles()); // only one title there
213 // only image titles are allowed for the root
214 if (!$this->hasNS
&& $this->rootTitle
->getNamespace() !== NS_IMAGE
)
215 $this->dieUsage("The title for {$this->getModuleName()} query must be an image", 'bad_image_title');
218 protected function parseContinueParam($continue, $redirect) {
219 $continueList = explode('|', $continue);
222 // expected redirect-mode parameter:
223 // ns|db_key|step|level|ns|db_key|id
224 // ns+db_key -- the root title
225 // step = 1 or 2 - which step to continue from - 1-titles, 2-redirects
226 // level -- how many levels to follow before starting enumerating.
227 // if level > 0 -- ns+title to continue from, otherwise skip these
228 // id = last page_id to continue from
230 if (count($continueList) > 4) {
231 $rootNs = intval($continueList[0]);
232 if (($rootNs !== 0 ||
$continueList[0] === '0') && !empty ($continueList[1])) {
233 $this->rootTitle
= Title
:: makeTitleSafe($rootNs, $continueList[1]);
234 if ($this->rootTitle
&& $this->rootTitle
->userCanRead()) {
236 $step = intval($continueList[2]);
237 if ($step === 1 ||
$step === 2) {
238 $this->contRedirs
= ($step === 2);
240 $level = intval($continueList[3]);
241 if ($level !== 0 ||
$continueList[3] === '0') {
242 $this->contLevel
= $level;
245 if (count($continueList) === 5) {
246 $contID = intval($continueList[4]);
247 if ($contID !== 0 ||
$continueList[4] === '0') {
248 $this->contID
= $contID;
253 if (count($continueList) === 7) {
254 $contNs = intval($continueList[4]);
255 if (($contNs !== 0 ||
$continueList[4] === '0') && !empty ($continueList[5])) {
256 $this->contTitle
= Title
:: makeTitleSafe($contNs, $continueList[5]);
258 $contID = intval($continueList[6]);
259 if ($contID !== 0 ||
$continueList[6] === '0') {
260 $this->contID
= $contID;
273 // expected non-redirect-mode parameter:
275 // ns+db_key -- the root title
276 // id = last page_id to continue from
278 if (count($continueList) === 3) {
279 $rootNs = intval($continueList[0]);
280 if (($rootNs !== 0 ||
$continueList[0] === '0') && !empty ($continueList[1])) {
281 $this->rootTitle
= Title
:: makeTitleSafe($rootNs, $continueList[1]);
282 if ($this->rootTitle
&& $this->rootTitle
->userCanRead()) {
284 $contID = intval($continueList[2]);
286 $this->contID
= $contID;
294 $this->dieUsage("Invalid continue param. You should pass the original value returned by the previous query", "_badcontinue");
297 protected function getContinueStr($lastPageID) {
298 return $this->rootTitle
->getNamespace() .
299 '|' . $this->rootTitle
->getDBkey() .
303 protected function getContinueRedirStr($isRedirPhase, $level, $ns, $title, $lastPageID) {
304 return $this->rootTitle
->getNamespace() .
305 '|' . $this->rootTitle
->getDBkey() .
306 '|' . ($isRedirPhase ?
1 : 2) .
308 ($level > 0 ?
('|' . $ns . '|' . $title) : '') .
312 protected function getAllowedParams() {
316 'namespace' => array (
317 ApiBase
:: PARAM_ISMULTI
=> true,
318 ApiBase
:: PARAM_TYPE
=> 'namespace'
322 ApiBase
:: PARAM_DFLT
=> 10,
323 ApiBase
:: PARAM_TYPE
=> 'limit',
324 ApiBase
:: PARAM_MIN
=> 1,
325 ApiBase
:: PARAM_MAX
=> ApiBase
:: LIMIT_BIG1
,
326 ApiBase
:: PARAM_MAX2
=> ApiBase
:: LIMIT_BIG2
331 protected function getParamDescription() {
333 'continue' => 'When more results are available, use this to continue.',
334 'namespace' => 'The namespace to enumerate.',
335 'redirect' => 'If linking page is a redirect, find all pages that link to that redirect (not implemented)',
336 'limit' => 'How many total pages to return.'
340 protected function getDescription() {
341 switch ($this->getModuleName()) {
343 return 'Find all pages that link to the given page';
345 return 'Find all pages that embed (transclude) the given title';
347 return 'Find all pages that use the given image title.';
349 ApiBase
:: dieDebug(__METHOD__
, 'Unknown module name');
353 protected function getExamples() {
354 static $examples = array (
355 'backlinks' => array (
356 "api.php?action=query&list=backlinks&titles=Main%20Page",
357 "api.php?action=query&generator=backlinks&titles=Main%20Page&prop=info"
359 'embeddedin' => array (
360 "api.php?action=query&list=embeddedin&titles=Template:Stub",
361 "api.php?action=query&generator=embeddedin&titles=Template:Stub&prop=info"
363 'imageusage' => array (
364 "api.php?action=query&list=imageusage&titles=Image:Albert%20Einstein%20Head.jpg",
365 "api.php?action=query&generator=imageusage&titles=Image:Albert%20Einstein%20Head.jpg&prop=info"
369 return $examples[$this->getModuleName()];
372 public function getVersion() {
373 return __CLASS__
. ': $Id$';