* Removed inconsistent hard coding of colons
[mediawiki.git] / includes / api / ApiQueryBacklinks.php
blob677ead47802ae982663c690f51213d76deba15be
1 <?php
3 /*
4 * Created on Oct 16, 2006
6 * API for MediaWiki 1.8+
8 * Copyright (C) 2006 Yuri Astrakhan <FirstnameLastname@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");
31 /**
32 * @addtogroup API
34 class ApiQueryBacklinks extends ApiQueryGeneratorBase {
36 private $rootTitle, $contRedirs, $contLevel, $contTitle, $contID;
38 // output element name, database column field prefix, database table
39 private $backlinksSettings = array (
40 'backlinks' => array (
41 'code' => 'bl',
42 'prefix' => 'pl',
43 'linktbl' => 'pagelinks'
45 'embeddedin' => array (
46 'code' => 'ei',
47 'prefix' => 'tl',
48 'linktbl' => 'templatelinks'
50 'imagelinks' => array (
51 'code' => 'il',
52 'prefix' => 'il',
53 'linktbl' => 'imagelinks'
57 public function __construct($query, $moduleName) {
58 $code = $prefix = $linktbl = null;
59 extract($this->backlinksSettings[$moduleName]);
61 parent :: __construct($query, $moduleName, $code);
62 $this->bl_ns = $prefix . '_namespace';
63 $this->bl_from = $prefix . '_from';
64 $this->bl_tables = array (
65 $linktbl,
66 'page'
68 $this->bl_code = $code;
70 $this->hasNS = $moduleName !== 'imagelinks';
71 if ($this->hasNS) {
72 $this->bl_title = $prefix . '_title';
73 $this->bl_sort = "{$this->bl_ns}, {$this->bl_title}, {$this->bl_from}";
74 $this->bl_fields = array (
75 $this->bl_ns,
76 $this->bl_title
78 } else {
79 $this->bl_title = $prefix . '_to';
80 $this->bl_sort = "{$this->bl_title}, {$this->bl_from}";
81 $this->bl_fields = array (
82 $this->bl_title
87 public function execute() {
88 $this->run();
91 public function executeGenerator($resultPageSet) {
92 $this->run($resultPageSet);
95 private function run($resultPageSet = null) {
96 $continue = $namespace = $redirect = $limit = null;
97 extract($this->extractRequestParams());
99 if ($redirect)
100 ApiBase :: dieDebug(__METHOD__, 'Redirect is not yet been implemented', 'notimplemented');
102 $this->processContinue($continue, $redirect);
104 $this->addFields($this->bl_fields);
105 if (is_null($resultPageSet))
106 $this->addFields(array (
107 'page_id',
108 'page_namespace',
109 'page_title'
111 else
112 $this->addFields($resultPageSet->getPageTableFields()); // will include page_id
114 $this->addTables($this->bl_tables);
115 $this->addWhere($this->bl_from . '=page_id');
117 if ($this->hasNS)
118 $this->addWhereFld($this->bl_ns, $this->rootTitle->getNamespace());
119 $this->addWhereFld($this->bl_title, $this->rootTitle->getDBkey());
120 $this->addWhereFld('page_namespace', $namespace);
121 $this->addOption('LIMIT', $limit +1);
122 $this->addOption('ORDER BY', $this->bl_sort);
124 if ($redirect)
125 $this->addWhereFld('page_is_redirect', 0);
127 $db = $this->getDB();
128 if (!is_null($continue)) {
129 $plfrm = intval($this->contID);
130 if ($this->contLevel == 0) {
131 // For the first level, there is only one target title, so no need for complex filtering
132 $this->addWhere($this->bl_from . '>=' . $plfrm);
133 } else {
134 $ns = $this->contTitle->getNamespace();
135 $t = $db->addQuotes($this->contTitle->getDBkey());
136 $whereWithoutNS = "{$this->bl_title}>$t OR ({$this->bl_title}=$t AND {$this->bl_from}>=$plfrm))";
138 if ($this->hasNS)
139 $this->addWhere("{$this->bl_ns}>$ns OR ({$this->bl_ns}=$ns AND ($whereWithoutNS)");
140 else
141 $this->addWhere($whereWithoutNS);
145 $res = $this->select(__METHOD__);
147 $count = 0;
148 $data = array ();
149 while ($row = $db->fetchObject($res)) {
150 if (++ $count > $limit) {
151 // We've reached the one extra which shows that there are additional pages to be had. Stop here...
152 if ($redirect) {
153 $ns = $row-> {
154 $this->bl_ns };
155 $t = $row-> {
156 $this->bl_title };
157 $continue = $this->getContinueRedirStr(false, 0, $ns, $t, $row->page_id);
158 } else
159 $continue = $this->getContinueStr($row->page_id);
160 $this->setContinueEnumParameter('continue', $continue);
161 break;
164 if (is_null($resultPageSet)) {
165 $vals = $this->addRowInfo('page', $row);
166 if ($vals)
167 $data[intval($row->page_id)] = $vals;
168 } else {
169 $resultPageSet->processDbRow($row);
172 $db->freeResult($res);
174 if (is_null($resultPageSet)) {
175 $result = $this->getResult();
176 $result->setIndexedTagName($data, $this->bl_code);
177 $result->addValue('query', $this->getModuleName(), $data);
181 protected function processContinue($continue, $redirect) {
182 $pageSet = $this->getPageSet();
183 $count = $pageSet->getTitleCount();
184 if (!is_null($continue)) {
185 if ($count !== 0)
186 $this->dieUsage("When continuing the {$this->getModuleName()} query, no other titles may be provided", 'titles_on_continue');
187 $this->parseContinueParam($continue, $redirect);
189 // Skip all completed links
191 } else {
192 if ($count !== 1)
193 $this->dieUsage("The {$this->getModuleName()} query requires one title to start", 'bad_title_count');
194 $this->rootTitle = current($pageSet->getTitles()); // only one title there
197 // only image titles are allowed for the root
198 if (!$this->hasNS && $this->rootTitle->getNamespace() !== NS_IMAGE)
199 $this->dieUsage("The title for {$this->getModuleName()} query must be an image", 'bad_image_title');
202 protected function parseContinueParam($continue, $redirect) {
203 $continueList = explode('|', $continue);
204 if ($redirect) {
206 // expected redirect-mode parameter:
207 // ns|db_key|step|level|ns|db_key|id
208 // ns+db_key -- the root title
209 // step = 1 or 2 - which step to continue from - 1-titles, 2-redirects
210 // level -- how many levels to follow before starting enumerating.
211 // if level > 0 -- ns+title to continue from, otherwise skip these
212 // id = last page_id to continue from
214 if (count($continueList) > 4) {
215 $rootNs = intval($continueList[0]);
216 if (($rootNs !== 0 || $continueList[0] === '0') && !empty ($continueList[1])) {
217 $this->rootTitle = Title :: makeTitleSafe($rootNs, $continueList[1]);
218 if ($this->rootTitle && $this->rootTitle->userCanRead()) {
220 $step = intval($continueList[2]);
221 if ($step === 1 || $step === 2) {
222 $this->contRedirs = ($step === 2);
224 $level = intval($continueList[3]);
225 if ($level !== 0 || $continueList[3] === '0') {
226 $this->contLevel = $level;
228 if ($level === 0) {
229 if (count($continueList) === 5) {
230 $contID = intval($continueList[4]);
231 if ($contID !== 0 || $continueList[4] === '0') {
232 $this->contID = $contID;
233 return; // done
236 } else {
237 if (count($continueList) === 7) {
238 $contNs = intval($continueList[4]);
239 if (($contNs !== 0 || $continueList[4] === '0') && !empty ($continueList[5])) {
240 $this->contTitle = Title :: makeTitleSafe($contNs, $continueList[5]);
242 $contID = intval($continueList[6]);
243 if ($contID !== 0 || $continueList[6] === '0') {
244 $this->contID = $contID;
245 return; // done
255 } else {
257 // expected non-redirect-mode parameter:
258 // ns|db_key|id
259 // ns+db_key -- the root title
260 // id = last page_id to continue from
262 if (count($continueList) === 3) {
263 $rootNs = intval($continueList[0]);
264 if (($rootNs !== 0 || $continueList[0] === '0') && !empty ($continueList[1])) {
265 $this->rootTitle = Title :: makeTitleSafe($rootNs, $continueList[1]);
266 if ($this->rootTitle && $this->rootTitle->userCanRead()) {
268 $contID = intval($continueList[2]);
269 if ($contID !== 0) {
270 $this->contID = $contID;
271 return; // done
278 $this->dieUsage("Invalid continue param. You should pass the original value returned by the previous query", "_badcontinue");
281 protected function getContinueStr($lastPageID) {
282 return $this->rootTitle->getNamespace() .
283 '|' . $this->rootTitle->getDBkey() .
284 '|' . $lastPageID;
287 protected function getContinueRedirStr($isRedirPhase, $level, $ns, $title, $lastPageID) {
288 return $this->rootTitle->getNamespace() .
289 '|' . $this->rootTitle->getDBkey() .
290 '|' . ($isRedirPhase ? 1 : 2) .
291 '|' . $level .
292 ($level > 0 ? ('|' . $ns . '|' . $title) : '') .
293 '|' . $lastPageID;
296 protected function getAllowedParams() {
298 return array (
299 'continue' => null,
300 'namespace' => array (
301 ApiBase :: PARAM_ISMULTI => true,
302 ApiBase :: PARAM_TYPE => 'namespace'
304 'redirect' => false,
305 'limit' => array (
306 ApiBase :: PARAM_DFLT => 10,
307 ApiBase :: PARAM_TYPE => 'limit',
308 ApiBase :: PARAM_MIN => 1,
309 ApiBase :: PARAM_MAX1 => ApiBase :: LIMIT_BIG1,
310 ApiBase :: PARAM_MAX2 => ApiBase :: LIMIT_BIG2
315 protected function getParamDescription() {
316 return array (
317 'continue' => 'When more results are available, use this to continue.',
318 'namespace' => 'The namespace to enumerate.',
319 'redirect' => 'If linking page is a redirect, find all pages that link to that redirect (not implemented)',
320 'limit' => 'How many total pages to return.'
324 protected function getDescription() {
325 switch ($this->getModuleName()) {
326 case 'backlinks' :
327 return 'Find all pages that link to the given page';
328 case 'embeddedin' :
329 return 'Find all pages that embed (transclude) the given title';
330 case 'imagelinks' :
331 return 'Find all pages that use the given image title.';
332 default :
333 ApiBase :: dieDebug(__METHOD__, 'Unknown module name');
337 protected function getExamples() {
338 static $examples = array (
339 'backlinks' => array (
340 "api.php?action=query&list=backlinks&titles=Main%20Page",
341 "api.php?action=query&generator=backlinks&titles=Main%20Page&prop=info"
343 'embeddedin' => array (
344 "api.php?action=query&list=embeddedin&titles=Template:Stub",
345 "api.php?action=query&generator=embeddedin&titles=Template:Stub&prop=info"
347 'imagelinks' => array (
348 "api.php?action=query&list=imagelinks&titles=Image:Albert%20Einstein%20Head.jpg",
349 "api.php?action=query&generator=imagelinks&titles=Image:Albert%20Einstein%20Head.jpg&prop=info"
353 return $examples[$this->getModuleName()];
356 public function getVersion() {
357 return __CLASS__ . ': $Id$';