The war on redundant ampersand usage!
[lhc/web/wiklou.git] / includes / api / ApiQueryBacklinks.php
1 <?php
2
3
4 /*
5 * Created on Oct 16, 2006
6 *
7 * API for MediaWiki 1.8+
8 *
9 * Copyright (C) 2006 Yuri Astrakhan <FirstnameLastname@gmail.com>
10 *
11 * This program is free software; you can redistribute it and/or modify
12 * it under the terms of the GNU General Public License as published by
13 * the Free Software Foundation; either version 2 of the License, or
14 * (at your option) any later version.
15 *
16 * This program is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 * GNU General Public License for more details.
20 *
21 * You should have received a copy of the GNU General Public License along
22 * with this program; if not, write to the Free Software Foundation, Inc.,
23 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
24 * http://www.gnu.org/copyleft/gpl.html
25 */
26
27 if (!defined('MEDIAWIKI')) {
28 // Eclipse helper - will be ignored in production
29 require_once ("ApiQueryBase.php");
30 }
31
32 class ApiQueryBacklinks extends ApiQueryGeneratorBase {
33
34 private $rootTitle, $contRedirs, $contLevel, $contTitle, $contID;
35
36 // output element name, database column field prefix, database table
37 private $backlinksSettings = array (
38 'backlinks' => array (
39 'code' => 'bl',
40 'prefix' => 'pl',
41 'linktbl' => 'pagelinks'
42 ),
43 'embeddedin' => array (
44 'code' => 'ei',
45 'prefix' => 'tl',
46 'linktbl' => 'templatelinks'
47 ),
48 'imagelinks' => array (
49 'code' => 'il',
50 'prefix' => 'il',
51 'linktbl' => 'imagelinks'
52 )
53 );
54
55 public function __construct($query, $moduleName) {
56 $code = $prefix = $linktbl = null;
57 extract($this->backlinksSettings[$moduleName]);
58
59 parent :: __construct($query, $moduleName, $code);
60 $this->bl_ns = $prefix . '_namespace';
61 $this->bl_from = $prefix . '_from';
62 $this->bl_tables = array (
63 $linktbl,
64 'page'
65 );
66 $this->bl_code = $code;
67
68 $this->hasNS = $moduleName !== 'imagelinks';
69 if ($this->hasNS) {
70 $this->bl_title = $prefix . '_title';
71 $this->bl_sort = "{$this->bl_ns}, {$this->bl_title}, {$this->bl_from}";
72 $this->bl_fields = array (
73 $this->bl_ns,
74 $this->bl_title
75 );
76 } else {
77 $this->bl_title = $prefix . '_to';
78 $this->bl_sort = "{$this->bl_title}, {$this->bl_from}";
79 $this->bl_fields = array (
80 $this->bl_title
81 );
82 }
83 }
84
85 public function execute() {
86 $this->run();
87 }
88
89 public function executeGenerator($resultPageSet) {
90 $this->run($resultPageSet);
91 }
92
93 private function run($resultPageSet = null) {
94 $continue = $namespace = $redirect = $limit = null;
95 extract($this->extractRequestParams());
96
97 if ($redirect)
98 ApiBase :: dieDebug(__METHOD__, 'Redirect is not yet been implemented', 'notimplemented');
99
100 $this->processContinue($continue, $redirect);
101
102 $this->addFields($this->bl_fields);
103 if (is_null($resultPageSet))
104 $this->addFields(array (
105 'page_id',
106 'page_namespace',
107 'page_title'
108 ));
109 else
110 $this->addFields($resultPageSet->getPageTableFields()); // will include page_id
111
112 $this->addTables($this->bl_tables);
113 $this->addWhere($this->bl_from . '=page_id');
114
115 if ($this->hasNS)
116 $this->addWhereFld($this->bl_ns, $this->rootTitle->getNamespace());
117 $this->addWhereFld($this->bl_title, $this->rootTitle->getDBkey());
118 $this->addWhereFld('page_namespace', $namespace);
119 $this->addOption('LIMIT', $limit +1);
120 $this->addOption('ORDER BY', $this->bl_sort);
121
122 if ($redirect)
123 $this->addWhereFld('page_is_redirect', 0);
124
125 $db = $this->getDB();
126 if (!is_null($continue)) {
127 $plfrm = intval($this->contID);
128 if ($this->contLevel == 0) {
129 // For the first level, there is only one target title, so no need for complex filtering
130 $this->addWhere($this->bl_from . '>=' . $plfrm);
131 } else {
132 $ns = $this->contTitle->getNamespace();
133 $t = $db->addQuotes($this->contTitle->getDBkey());
134 $whereWithoutNS = "{$this->bl_title}>$t OR ({$this->bl_title}=$t AND {$this->bl_from}>=$plfrm))";
135
136 if ($this->hasNS)
137 $this->addWhere("{$this->bl_ns}>$ns OR ({$this->bl_ns}=$ns AND ($whereWithoutNS)");
138 else
139 $this->addWhere($whereWithoutNS);
140 }
141 }
142
143 $res = $this->select(__METHOD__);
144
145 $count = 0;
146 $data = array ();
147 while ($row = $db->fetchObject($res)) {
148 if (++ $count > $limit) {
149 // We've reached the one extra which shows that there are additional pages to be had. Stop here...
150 if ($redirect) {
151 $ns = $row-> {
152 $this->bl_ns };
153 $t = $row-> {
154 $this->bl_title };
155 $continue = $this->getContinueRedirStr(false, 0, $ns, $t, $row->page_id);
156 } else
157 $continue = $this->getContinueStr($row->page_id);
158 $this->setContinueEnumParameter('continue', $continue);
159 break;
160 }
161
162 if (is_null($resultPageSet)) {
163 $vals = $this->addRowInfo('page', $row);
164 if ($vals)
165 $data[intval($row->page_id)] = $vals;
166 } else {
167 $resultPageSet->processDbRow($row);
168 }
169 }
170 $db->freeResult($res);
171
172 if (is_null($resultPageSet)) {
173 $result = $this->getResult();
174 $result->setIndexedTagName($data, $this->bl_code);
175 $result->addValue('query', $this->getModuleName(), $data);
176 }
177 }
178
179 protected function processContinue($continue, $redirect) {
180 $pageSet = $this->getPageSet();
181 $count = $pageSet->getTitleCount();
182 if (!is_null($continue)) {
183 if ($count !== 0)
184 $this->dieUsage("When continuing the {$this->getModuleName()} query, no other titles may be provided", 'titles_on_continue');
185 $this->parseContinueParam($continue, $redirect);
186
187 // Skip all completed links
188
189 } else {
190 if ($count !== 1)
191 $this->dieUsage("The {$this->getModuleName()} query requires one title to start", 'bad_title_count');
192 $this->rootTitle = current($pageSet->getTitles()); // only one title there
193 }
194
195 // only image titles are allowed for the root
196 if (!$this->hasNS && $this->rootTitle->getNamespace() !== NS_IMAGE)
197 $this->dieUsage("The title for {$this->getModuleName()} query must be an image", 'bad_image_title');
198 }
199
200 protected function parseContinueParam($continue, $redirect) {
201 $continueList = explode('|', $continue);
202 if ($redirect) {
203 //
204 // expected redirect-mode parameter:
205 // ns|db_key|step|level|ns|db_key|id
206 // ns+db_key -- the root title
207 // step = 1 or 2 - which step to continue from - 1-titles, 2-redirects
208 // level -- how many levels to follow before starting enumerating.
209 // if level > 0 -- ns+title to continue from, otherwise skip these
210 // id = last page_id to continue from
211 //
212 if (count($continueList) > 4) {
213 $rootNs = intval($continueList[0]);
214 if (($rootNs !== 0 || $continueList[0] === '0') && !empty ($continueList[1])) {
215 $this->rootTitle = Title :: makeTitleSafe($rootNs, $continueList[1]);
216 if ($this->rootTitle && $this->rootTitle->userCanRead()) {
217
218 $step = intval($continueList[2]);
219 if ($step === 1 || $step === 2) {
220 $this->contRedirs = ($step === 2);
221
222 $level = intval($continueList[3]);
223 if ($level !== 0 || $continueList[3] === '0') {
224 $this->contLevel = $level;
225
226 if ($level === 0) {
227 if (count($continueList) === 5) {
228 $contID = intval($continueList[4]);
229 if ($contID !== 0 || $continueList[4] === '0') {
230 $this->contID = $contID;
231 return; // done
232 }
233 }
234 } else {
235 if (count($continueList) === 7) {
236 $contNs = intval($continueList[4]);
237 if (($contNs !== 0 || $continueList[4] === '0') && !empty ($continueList[5])) {
238 $this->contTitle = Title :: makeTitleSafe($contNs, $continueList[5]);
239
240 $contID = intval($continueList[6]);
241 if ($contID !== 0 || $continueList[6] === '0') {
242 $this->contID = $contID;
243 return; // done
244 }
245 }
246 }
247 }
248 }
249 }
250 }
251 }
252 }
253 } else {
254 //
255 // expected non-redirect-mode parameter:
256 // ns|db_key|id
257 // ns+db_key -- the root title
258 // id = last page_id to continue from
259 //
260 if (count($continueList) === 3) {
261 $rootNs = intval($continueList[0]);
262 if (($rootNs !== 0 || $continueList[0] === '0') && !empty ($continueList[1])) {
263 $this->rootTitle = Title :: makeTitleSafe($rootNs, $continueList[1]);
264 if ($this->rootTitle && $this->rootTitle->userCanRead()) {
265
266 $contID = intval($continueList[2]);
267 if ($contID !== 0) {
268 $this->contID = $contID;
269 return; // done
270 }
271 }
272 }
273 }
274 }
275
276 $this->dieUsage("Invalid continue param. You should pass the original value returned by the previous query", "_badcontinue");
277 }
278
279 protected function getContinueStr($lastPageID) {
280 return $this->rootTitle->getNamespace() .
281 '|' . $this->rootTitle->getDBkey() .
282 '|' . $lastPageID;
283 }
284
285 protected function getContinueRedirStr($isRedirPhase, $level, $ns, $title, $lastPageID) {
286 return $this->rootTitle->getNamespace() .
287 '|' . $this->rootTitle->getDBkey() .
288 '|' . ($isRedirPhase ? 1 : 2) .
289 '|' . $level .
290 ($level > 0 ? ('|' . $ns . '|' . $title) : '') .
291 '|' . $lastPageID;
292 }
293
294 protected function getAllowedParams() {
295
296 return array (
297 'continue' => null,
298 'namespace' => array (
299 ApiBase :: PARAM_ISMULTI => true,
300 ApiBase :: PARAM_TYPE => 'namespace'
301 ),
302 'redirect' => false,
303 'limit' => array (
304 ApiBase :: PARAM_DFLT => 10,
305 ApiBase :: PARAM_TYPE => 'limit',
306 ApiBase :: PARAM_MIN => 1,
307 ApiBase :: PARAM_MAX1 => ApiBase :: LIMIT_BIG1,
308 ApiBase :: PARAM_MAX2 => ApiBase :: LIMIT_BIG2
309 )
310 );
311 }
312
313 protected function getParamDescription() {
314 return array (
315 'continue' => 'When more results are available, use this to continue.',
316 'namespace' => 'The namespace to enumerate.',
317 'redirect' => 'If linking page is a redirect, find all pages that link to that redirect (not implemented)',
318 'limit' => 'How many total pages to return.'
319 );
320 }
321
322 protected function getDescription() {
323 switch ($this->getModuleName()) {
324 case 'backlinks' :
325 return 'Find all pages that link to the given page';
326 case 'embeddedin' :
327 return 'Find all pages that embed (transclude) the given title';
328 case 'imagelinks' :
329 return 'Find all pages that use the given image title.';
330 default :
331 ApiBase :: dieDebug(__METHOD__, 'Unknown module name');
332 }
333 }
334
335 protected function getExamples() {
336 static $examples = array (
337 'backlinks' => array (
338 "api.php?action=query&list=backlinks&titles=Main%20Page",
339 "api.php?action=query&generator=backlinks&titles=Main%20Page&prop=info"
340 ),
341 'embeddedin' => array (
342 "api.php?action=query&list=embeddedin&titles=Template:Stub",
343 "api.php?action=query&generator=embeddedin&titles=Template:Stub&prop=info"
344 ),
345 'imagelinks' => array (
346 "api.php?action=query&list=imagelinks&titles=Image:Albert%20Einstein%20Head.jpg",
347 "api.php?action=query&generator=imagelinks&titles=Image:Albert%20Einstein%20Head.jpg&prop=info"
348 )
349 );
350
351 return $examples[$this->getModuleName()];
352 }
353
354 public function getVersion() {
355 return __CLASS__ . ': $Id$';
356 }
357 }
358 ?>