Remove ?>'s from files. They're pointless, and just asking for people to mess with...
[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 $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 $continue = $namespace = $redirect = $limit = null;
102 extract($this->extractRequestParams());
103
104 if ($redirect)
105 ApiBase :: dieDebug(__METHOD__, 'Redirect has not been implemented', 'notimplemented');
106
107 $this->processContinue($continue, $redirect);
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', $namespace);
126 $this->addOption('LIMIT', $limit +1);
127 $this->addOption('ORDER BY', $this->bl_sort);
128
129 if ($redirect)
130 $this->addWhereFld('page_is_redirect', 0);
131
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);
138 } else {
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))";
142
143 if ($this->hasNS)
144 $this->addWhere("{$this->bl_ns}>$ns OR ({$this->bl_ns}=$ns AND ($whereWithoutNS)");
145 else
146 $this->addWhere($whereWithoutNS);
147 }
148 }
149
150 $res = $this->select(__METHOD__);
151
152 $count = 0;
153 $data = array ();
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...
157 if ($redirect) {
158 $ns = $row-> { $this->bl_ns };
159 $t = $row-> { $this->bl_title };
160 $continue = $this->getContinueRedirStr(false, 0, $ns, $t, $row->page_id);
161 } else
162 $continue = $this->getContinueStr($row->page_id);
163 $this->setContinueEnumParameter('continue', $continue);
164 break;
165 }
166
167 if (is_null($resultPageSet)) {
168 $vals = $this->extractRowInfo($row);
169 if ($vals)
170 $data[] = $vals;
171 } else {
172 $resultPageSet->processDbRow($row);
173 }
174 }
175 $db->freeResult($res);
176
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);
181 }
182 }
183
184 private function extractRowInfo($row) {
185
186 $title = Title :: makeTitle($row->page_namespace, $row->page_title);
187 if (!$title->userCanRead())
188 return false;
189
190 $vals = array();
191 $vals['pageid'] = intval($row->page_id);
192 ApiQueryBase :: addTitleInfo($vals, $title);
193
194 return $vals;
195 }
196
197 protected function processContinue($continue, $redirect) {
198 $pageSet = $this->getPageSet();
199 $count = $pageSet->getTitleCount();
200 if (!is_null($continue)) {
201 if ($count !== 0)
202 $this->dieUsage("When continuing the {$this->getModuleName()} query, no other titles may be provided", 'titles_on_continue');
203 $this->parseContinueParam($continue, $redirect);
204
205 // Skip all completed links
206
207 } else {
208 if ($count !== 1)
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
211 }
212
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');
216 }
217
218 protected function parseContinueParam($continue, $redirect) {
219 $continueList = explode('|', $continue);
220 if ($redirect) {
221 //
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
229 //
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()) {
235
236 $step = intval($continueList[2]);
237 if ($step === 1 || $step === 2) {
238 $this->contRedirs = ($step === 2);
239
240 $level = intval($continueList[3]);
241 if ($level !== 0 || $continueList[3] === '0') {
242 $this->contLevel = $level;
243
244 if ($level === 0) {
245 if (count($continueList) === 5) {
246 $contID = intval($continueList[4]);
247 if ($contID !== 0 || $continueList[4] === '0') {
248 $this->contID = $contID;
249 return; // done
250 }
251 }
252 } else {
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]);
257
258 $contID = intval($continueList[6]);
259 if ($contID !== 0 || $continueList[6] === '0') {
260 $this->contID = $contID;
261 return; // done
262 }
263 }
264 }
265 }
266 }
267 }
268 }
269 }
270 }
271 } else {
272 //
273 // expected non-redirect-mode parameter:
274 // ns|db_key|id
275 // ns+db_key -- the root title
276 // id = last page_id to continue from
277 //
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()) {
283
284 $contID = intval($continueList[2]);
285 if ($contID !== 0) {
286 $this->contID = $contID;
287 return; // done
288 }
289 }
290 }
291 }
292 }
293
294 $this->dieUsage("Invalid continue param. You should pass the original value returned by the previous query", "_badcontinue");
295 }
296
297 protected function getContinueStr($lastPageID) {
298 return $this->rootTitle->getNamespace() .
299 '|' . $this->rootTitle->getDBkey() .
300 '|' . $lastPageID;
301 }
302
303 protected function getContinueRedirStr($isRedirPhase, $level, $ns, $title, $lastPageID) {
304 return $this->rootTitle->getNamespace() .
305 '|' . $this->rootTitle->getDBkey() .
306 '|' . ($isRedirPhase ? 1 : 2) .
307 '|' . $level .
308 ($level > 0 ? ('|' . $ns . '|' . $title) : '') .
309 '|' . $lastPageID;
310 }
311
312 protected function getAllowedParams() {
313
314 return array (
315 'continue' => null,
316 'namespace' => array (
317 ApiBase :: PARAM_ISMULTI => true,
318 ApiBase :: PARAM_TYPE => 'namespace'
319 ),
320 'redirect' => false,
321 'limit' => array (
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
327 )
328 );
329 }
330
331 protected function getParamDescription() {
332 return array (
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.'
337 );
338 }
339
340 protected function getDescription() {
341 switch ($this->getModuleName()) {
342 case 'backlinks' :
343 return 'Find all pages that link to the given page';
344 case 'embeddedin' :
345 return 'Find all pages that embed (transclude) the given title';
346 case 'imageusage' :
347 return 'Find all pages that use the given image title.';
348 default :
349 ApiBase :: dieDebug(__METHOD__, 'Unknown module name');
350 }
351 }
352
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"
358 ),
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"
362 ),
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"
366 )
367 );
368
369 return $examples[$this->getModuleName()];
370 }
371
372 public function getVersion() {
373 return __CLASS__ . ': $Id$';
374 }
375 }
376