API: Added meta=userinfo module to get data about the currently logged-in user.
[lhc/web/wiklou.git] / includes / api / ApiQueryBacklinks.php
1 <?php
2
3 /*
4 * Created on Oct 16, 2006
5 *
6 * API for MediaWiki 1.8+
7 *
8 * Copyright (C) 2006 Yuri Astrakhan <Firstname><Lastname>@gmail.com
9 *
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.
14 *
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.
19 *
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
24 */
25
26 if (!defined('MEDIAWIKI')) {
27 // Eclipse helper - will be ignored in production
28 require_once ("ApiQueryBase.php");
29 }
30
31 /**
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
36 *
37 * @addtogroup API
38 */
39 class ApiQueryBacklinks extends ApiQueryGeneratorBase {
40
41 private $params, $rootTitle, $contRedirs, $contLevel, $contTitle, $contID;
42
43 // output element name, database column field prefix, database table
44 private $backlinksSettings = array (
45 'backlinks' => array (
46 'code' => 'bl',
47 'prefix' => 'pl',
48 'linktbl' => 'pagelinks'
49 ),
50 'embeddedin' => array (
51 'code' => 'ei',
52 'prefix' => 'tl',
53 'linktbl' => 'templatelinks'
54 ),
55 'imageusage' => array (
56 'code' => 'iu',
57 'prefix' => 'il',
58 'linktbl' => 'imagelinks'
59 )
60 );
61
62 public function __construct($query, $moduleName) {
63 $code = $prefix = $linktbl = null;
64 extract($this->backlinksSettings[$moduleName]);
65
66 parent :: __construct($query, $moduleName, $code);
67 $this->bl_ns = $prefix . '_namespace';
68 $this->bl_from = $prefix . '_from';
69 $this->bl_tables = array (
70 $linktbl,
71 'page'
72 );
73 $this->bl_code = $code;
74
75 $this->hasNS = $moduleName !== 'imageusage';
76 if ($this->hasNS) {
77 $this->bl_title = $prefix . '_title';
78 $this->bl_sort = "{$this->bl_ns}, {$this->bl_title}, {$this->bl_from}";
79 $this->bl_fields = array (
80 $this->bl_ns,
81 $this->bl_title
82 );
83 } else {
84 $this->bl_title = $prefix . '_to';
85 $this->bl_sort = "{$this->bl_title}, {$this->bl_from}";
86 $this->bl_fields = array (
87 $this->bl_title
88 );
89 }
90 }
91
92 public function execute() {
93 $this->run();
94 }
95
96 public function executeGenerator($resultPageSet) {
97 $this->run($resultPageSet);
98 }
99
100 private function run($resultPageSet = null) {
101 $this->params = $this->extractRequestParams();
102
103 $redirect = $this->params['redirect'];
104 if ($redirect)
105 ApiBase :: dieDebug(__METHOD__, 'Redirect has not been implemented', 'notimplemented');
106
107 $this->processContinue();
108
109 $this->addFields($this->bl_fields);
110 if (is_null($resultPageSet))
111 $this->addFields(array (
112 'page_id',
113 'page_namespace',
114 'page_title'
115 ));
116 else
117 $this->addFields($resultPageSet->getPageTableFields()); // will include page_id
118
119 $this->addTables($this->bl_tables);
120 $this->addWhere($this->bl_from . '=page_id');
121
122 if ($this->hasNS)
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']);
126
127 $limit = $this->params['limit'];
128 $this->addOption('LIMIT', $limit +1);
129 $this->addOption('ORDER BY', $this->bl_sort);
130
131 if ($redirect)
132 $this->addWhereFld('page_is_redirect', 0);
133
134 $db = $this->getDB();
135 if (!is_null($this->params['continue'])) {
136 $plfrm = intval($this->contID);
137 if ($this->contLevel == 0) {
138 // For the first level, there is only one target title, so no need for complex filtering
139 $this->addWhere($this->bl_from . '>=' . $plfrm);
140 } else {
141 $ns = $this->contTitle->getNamespace();
142 $t = $db->addQuotes($this->contTitle->getDBkey());
143 $whereWithoutNS = "{$this->bl_title}>$t OR ({$this->bl_title}=$t AND {$this->bl_from}>=$plfrm))";
144
145 if ($this->hasNS)
146 $this->addWhere("{$this->bl_ns}>$ns OR ({$this->bl_ns}=$ns AND ($whereWithoutNS)");
147 else
148 $this->addWhere($whereWithoutNS);
149 }
150 }
151
152 $res = $this->select(__METHOD__);
153
154 $count = 0;
155 $data = array ();
156 while ($row = $db->fetchObject($res)) {
157 if (++ $count > $limit) {
158 // We've reached the one extra which shows that there are additional pages to be had. Stop here...
159 if ($redirect) {
160 $ns = $row-> { $this->bl_ns };
161 $t = $row-> { $this->bl_title };
162 $continue = $this->getContinueRedirStr(false, 0, $ns, $t, $row->page_id);
163 } else
164 $continue = $this->getContinueStr($row->page_id);
165 // TODO: Security issue - if the user has no right to view next title, it will still be shown
166 $this->setContinueEnumParameter('continue', $continue);
167 break;
168 }
169
170 if (is_null($resultPageSet)) {
171 $vals = $this->extractRowInfo($row);
172 if ($vals)
173 $data[] = $vals;
174 } else {
175 $resultPageSet->processDbRow($row);
176 }
177 }
178 $db->freeResult($res);
179
180 if (is_null($resultPageSet) && !empty($data)) {
181 $result = $this->getResult();
182 $result->setIndexedTagName($data, $this->bl_code);
183 $result->addValue('query', $this->getModuleName(), $data);
184 }
185 }
186
187 private function extractRowInfo($row) {
188
189 $vals = array();
190 $vals['pageid'] = intval($row->page_id);
191 ApiQueryBase :: addTitleInfo($vals, Title :: makeTitle($row->page_namespace, $row->page_title));
192
193 return $vals;
194 }
195
196 protected function processContinue() {
197 $pageSet = $this->getPageSet();
198 $count = $pageSet->getTitleCount();
199
200 if (!is_null($this->params['continue'])) {
201 $this->parseContinueParam();
202
203 // Skip all completed links
204
205 } else {
206 $title = $this->params['title'];
207 if (!is_null($title)) {
208 $this->rootTitle = Title :: newFromText($title);
209 } else { // This case is obsolete. Will support this for a while
210 if ($count !== 1)
211 $this->dieUsage("The {$this->getModuleName()} query requires one title to start", 'bad_title_count');
212 $this->rootTitle = current($pageSet->getTitles()); // only one title there
213 $this->setWarning('Using titles parameter is obsolete for this list. Use ' . $this->encodeParamName('title') . ' instead.');
214 }
215 }
216
217 // only image titles are allowed for the root
218 if (!$this->hasNS && $this->rootTitle->getNamespace() !== NS_IMAGE)
219 $this->dieUsage("The title for {$this->getModuleName()} query must be an image", 'bad_image_title');
220 }
221
222 protected function parseContinueParam() {
223 $continueList = explode('|', $this->params['continue']);
224 if ($this->params['redirect']) {
225 //
226 // expected redirect-mode parameter:
227 // ns|db_key|step|level|ns|db_key|id
228 // ns+db_key -- the root title
229 // step = 1 or 2 - which step to continue from - 1-titles, 2-redirects
230 // level -- how many levels to follow before starting enumerating.
231 // if level > 0 -- ns+title to continue from, otherwise skip these
232 // id = last page_id to continue from
233 //
234 if (count($continueList) > 4) {
235 $rootNs = intval($continueList[0]);
236 if (($rootNs !== 0 || $continueList[0] === '0') && !empty ($continueList[1])) {
237 $this->rootTitle = Title :: makeTitleSafe($rootNs, $continueList[1]);
238 if ($this->rootTitle) {
239
240 $step = intval($continueList[2]);
241 if ($step === 1 || $step === 2) {
242 $this->contRedirs = ($step === 2);
243
244 $level = intval($continueList[3]);
245 if ($level !== 0 || $continueList[3] === '0') {
246 $this->contLevel = $level;
247
248 if ($level === 0) {
249 if (count($continueList) === 5) {
250 $contID = intval($continueList[4]);
251 if ($contID !== 0 || $continueList[4] === '0') {
252 $this->contID = $contID;
253 return; // done
254 }
255 }
256 } else {
257 if (count($continueList) === 7) {
258 $contNs = intval($continueList[4]);
259 if (($contNs !== 0 || $continueList[4] === '0') && !empty ($continueList[5])) {
260 $this->contTitle = Title :: makeTitleSafe($contNs, $continueList[5]);
261
262 $contID = intval($continueList[6]);
263 if ($contID !== 0 || $continueList[6] === '0') {
264 $this->contID = $contID;
265 return; // done
266 }
267 }
268 }
269 }
270 }
271 }
272 }
273 }
274 }
275 } else {
276 //
277 // expected non-redirect-mode parameter:
278 // ns|db_key|id
279 // ns+db_key -- the root title
280 // id = last page_id to continue from
281 //
282 if (count($continueList) === 3) {
283 $rootNs = intval($continueList[0]);
284 if (($rootNs !== 0 || $continueList[0] === '0') && !empty ($continueList[1])) {
285 $this->rootTitle = Title :: makeTitleSafe($rootNs, $continueList[1]);
286 if ($this->rootTitle) {
287
288 $contID = intval($continueList[2]);
289 if ($contID !== 0) {
290 $this->contID = $contID;
291 return; // done
292 }
293 }
294 }
295 }
296 }
297
298 $this->dieUsage("Invalid continue param. You should pass the original value returned by the previous query", "_badcontinue");
299 }
300
301 protected function getContinueStr($lastPageID) {
302 return $this->rootTitle->getNamespace() .
303 '|' . $this->rootTitle->getDBkey() .
304 '|' . $lastPageID;
305 }
306
307 protected function getContinueRedirStr($isRedirPhase, $level, $ns, $title, $lastPageID) {
308 return $this->rootTitle->getNamespace() .
309 '|' . $this->rootTitle->getDBkey() .
310 '|' . ($isRedirPhase ? 1 : 2) .
311 '|' . $level .
312 ($level > 0 ? ('|' . $ns . '|' . $title) : '') .
313 '|' . $lastPageID;
314 }
315
316 protected function getAllowedParams() {
317
318 return array (
319 'title' => null,
320 'continue' => null,
321 'namespace' => array (
322 ApiBase :: PARAM_ISMULTI => true,
323 ApiBase :: PARAM_TYPE => 'namespace'
324 ),
325 'redirect' => false,
326 'limit' => array (
327 ApiBase :: PARAM_DFLT => 10,
328 ApiBase :: PARAM_TYPE => 'limit',
329 ApiBase :: PARAM_MIN => 1,
330 ApiBase :: PARAM_MAX => ApiBase :: LIMIT_BIG1,
331 ApiBase :: PARAM_MAX2 => ApiBase :: LIMIT_BIG2
332 )
333 );
334 }
335
336 protected function getParamDescription() {
337 return array (
338 'title' => 'Title to search. If null, titles= parameter will be used instead, but will be obsolete soon.',
339 'continue' => 'When more results are available, use this to continue.',
340 'namespace' => 'The namespace to enumerate.',
341 'redirect' => 'If linking page is a redirect, find all pages that link to that redirect (not implemented)',
342 'limit' => 'How many total pages to return.'
343 );
344 }
345
346 protected function getDescription() {
347 switch ($this->getModuleName()) {
348 case 'backlinks' :
349 return 'Find all pages that link to the given page';
350 case 'embeddedin' :
351 return 'Find all pages that embed (transclude) the given title';
352 case 'imageusage' :
353 return 'Find all pages that use the given image title.';
354 default :
355 ApiBase :: dieDebug(__METHOD__, 'Unknown module name');
356 }
357 }
358
359 protected function getExamples() {
360 static $examples = array (
361 'backlinks' => array (
362 "api.php?action=query&list=backlinks&bltitle=Main%20Page",
363 "api.php?action=query&generator=backlinks&gbltitle=Main%20Page&prop=info"
364 ),
365 'embeddedin' => array (
366 "api.php?action=query&list=embeddedin&eititle=Template:Stub",
367 "api.php?action=query&generator=embeddedin&geititle=Template:Stub&prop=info"
368 ),
369 'imageusage' => array (
370 "api.php?action=query&list=imageusage&iutitle=Image:Albert%20Einstein%20Head.jpg",
371 "api.php?action=query&generator=imageusage&giutitle=Image:Albert%20Einstein%20Head.jpg&prop=info"
372 )
373 );
374
375 return $examples[$this->getModuleName()];
376 }
377
378 public function getVersion() {
379 return __CLASS__ . ': $Id$';
380 }
381 }
382