(bug 20275) Fixed LIKE queries on SQLite backend
[lhc/web/wiklou.git] / includes / api / ApiQueryUserContributions.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 query action adds a list of a specified user's contributions to the output.
33 *
34 * @ingroup API
35 */
36 class ApiQueryContributions extends ApiQueryBase {
37
38 public function __construct($query, $moduleName) {
39 parent :: __construct($query, $moduleName, 'uc');
40 }
41
42 private $params, $username;
43 private $fld_ids = false, $fld_title = false, $fld_timestamp = false,
44 $fld_comment = false, $fld_flags = false,
45 $fld_patrolled = false;
46
47 public function execute() {
48
49 // Parse some parameters
50 $this->params = $this->extractRequestParams();
51
52 $prop = array_flip($this->params['prop']);
53 $this->fld_ids = isset($prop['ids']);
54 $this->fld_title = isset($prop['title']);
55 $this->fld_comment = isset($prop['comment']);
56 $this->fld_size = isset($prop['size']);
57 $this->fld_flags = isset($prop['flags']);
58 $this->fld_timestamp = isset($prop['timestamp']);
59 $this->fld_patrolled = isset($prop['patrolled']);
60
61 // TODO: if the query is going only against the revision table, should this be done?
62 $this->selectNamedDB('contributions', DB_SLAVE, 'contributions');
63 $db = $this->getDB();
64
65 if(isset($this->params['userprefix']))
66 {
67 $this->prefixMode = true;
68 $this->multiUserMode = true;
69 $this->userprefix = $this->params['userprefix'];
70 }
71 else
72 {
73 $this->usernames = array();
74 if(!is_array($this->params['user']))
75 $this->params['user'] = array($this->params['user']);
76 foreach($this->params['user'] as $u)
77 $this->prepareUsername($u);
78 $this->prefixMode = false;
79 $this->multiUserMode = (count($this->params['user']) > 1);
80 }
81 $this->prepareQuery();
82
83 //Do the actual query.
84 $res = $this->select( __METHOD__ );
85
86 //Initialise some variables
87 $count = 0;
88 $limit = $this->params['limit'];
89
90 //Fetch each row
91 while ( $row = $db->fetchObject( $res ) ) {
92 if (++ $count > $limit) {
93 // We've reached the one extra which shows that there are additional pages to be had. Stop here...
94 if($this->multiUserMode)
95 $this->setContinueEnumParameter('continue', $this->continueStr($row));
96 else
97 $this->setContinueEnumParameter('start', wfTimestamp(TS_ISO_8601, $row->rev_timestamp));
98 break;
99 }
100
101 $vals = $this->extractRowInfo($row);
102 $fit = $this->getResult()->addValue(array('query', $this->getModuleName()), null, $vals);
103 if(!$fit)
104 {
105 if($this->multiUserMode)
106 $this->setContinueEnumParameter('continue', $this->continueStr($row));
107 else
108 $this->setContinueEnumParameter('start', wfTimestamp(TS_ISO_8601, $row->rev_timestamp));
109 break;
110 }
111 }
112
113 //Free the database record so the connection can get on with other stuff
114 $db->freeResult($res);
115
116 $this->getResult()->setIndexedTagName_internal(array('query', $this->getModuleName()), 'item');
117 }
118
119 /**
120 * Validate the 'user' parameter and set the value to compare
121 * against `revision`.`rev_user_text`
122 */
123 private function prepareUsername($user) {
124 if( !is_null( $user ) && $user !== '' ) {
125 $name = User::isIP( $user )
126 ? $user
127 : User::getCanonicalName( $user, 'valid' );
128 if( $name === false ) {
129 $this->dieUsage( "User name {$user} is not valid", 'param_user' );
130 } else {
131 $this->usernames[] = $name;
132 }
133 } else {
134 $this->dieUsage( 'User parameter may not be empty', 'param_user' );
135 }
136 }
137
138 /**
139 * Prepares the query and returns the limit of rows requested
140 */
141 private function prepareQuery() {
142 // We're after the revision table, and the corresponding page
143 // row for anything we retrieve. We may also need the
144 // recentchanges row.
145 global $wgUser;
146 $tables = array('page', 'revision'); // Order may change
147 $this->addWhere('page_id=rev_page');
148
149 // Handle continue parameter
150 if($this->multiUserMode && !is_null($this->params['continue']))
151 {
152 $continue = explode('|', $this->params['continue']);
153 if(count($continue) != 2)
154 $this->dieUsage("Invalid continue param. You should pass the original " .
155 "value returned by the previous query", "_badcontinue");
156 $encUser = $this->getDB()->strencode($continue[0]);
157 $encTS = wfTimestamp(TS_MW, $continue[1]);
158 $op = ($this->params['dir'] == 'older' ? '<' : '>');
159 $this->addWhere("rev_user_text $op '$encUser' OR " .
160 "(rev_user_text = '$encUser' AND " .
161 "rev_timestamp $op= '$encTS')");
162 }
163
164 if(!$wgUser->isAllowed('hideuser'))
165 $this->addWhere($this->getDB()->bitAnd('rev_deleted',Revision::DELETED_USER) . ' = 0');
166 // We only want pages by the specified users.
167 if($this->prefixMode)
168 $this->addWhere('rev_user_text' . $this->getDB()->buildLike($this->userprefix, $this->getDB()->anyString()));
169 else
170 $this->addWhereFld('rev_user_text', $this->usernames);
171 // ... and in the specified timeframe.
172 // Ensure the same sort order for rev_user_text and rev_timestamp
173 // so our query is indexed
174 if($this->multiUserMode)
175 $this->addWhereRange('rev_user_text', $this->params['dir'], null, null);
176 $this->addWhereRange('rev_timestamp',
177 $this->params['dir'], $this->params['start'], $this->params['end'] );
178 $this->addWhereFld('page_namespace', $this->params['namespace']);
179
180 $show = $this->params['show'];
181 if (!is_null($show)) {
182 $show = array_flip($show);
183 if ((isset($show['minor']) && isset($show['!minor']))
184 || (isset($show['patrolled']) && isset($show['!patrolled'])))
185 $this->dieUsage("Incorrect parameter - mutually exclusive values may not be supplied", 'show');
186
187 $this->addWhereIf('rev_minor_edit = 0', isset($show['!minor']));
188 $this->addWhereIf('rev_minor_edit != 0', isset($show['minor']));
189 $this->addWhereIf('rc_patrolled = 0', isset($show['!patrolled']));
190 $this->addWhereIf('rc_patrolled != 0', isset($show['patrolled']));
191 }
192 $this->addOption('LIMIT', $this->params['limit'] + 1);
193 $index['revision'] = 'usertext_timestamp';
194
195 // Mandatory fields: timestamp allows request continuation
196 // ns+title checks if the user has access rights for this page
197 // user_text is necessary if multiple users were specified
198 $this->addFields(array(
199 'rev_timestamp',
200 'page_namespace',
201 'page_title',
202 'rev_user_text',
203 'rev_deleted'
204 ));
205
206 if(isset($show['patrolled']) || isset($show['!patrolled']) ||
207 $this->fld_patrolled)
208 {
209 global $wgUser;
210 if(!$wgUser->useRCPatrol() && !$wgUser->useNPPatrol())
211 $this->dieUsage("You need the patrol right to request the patrolled flag", 'permissiondenied');
212 // Use a redundant join condition on both
213 // timestamp and ID so we can use the timestamp
214 // index
215 $index['recentchanges'] = 'rc_user_text';
216 if(isset($show['patrolled']) || isset($show['!patrolled']))
217 {
218 // Put the tables in the right order for
219 // STRAIGHT_JOIN
220 $tables = array('revision', 'recentchanges', 'page');
221 $this->addOption('STRAIGHT_JOIN');
222 $this->addWhere('rc_user_text=rev_user_text');
223 $this->addWhere('rc_timestamp=rev_timestamp');
224 $this->addWhere('rc_this_oldid=rev_id');
225 }
226 else
227 {
228 $tables[] = 'recentchanges';
229 $this->addJoinConds(array('recentchanges' => array(
230 'LEFT JOIN', array(
231 'rc_user_text=rev_user_text',
232 'rc_timestamp=rev_timestamp',
233 'rc_this_oldid=rev_id'))));
234 }
235 }
236
237 $this->addTables($tables);
238 $this->addOption('USE INDEX', $index);
239 $this->addFieldsIf('rev_page', $this->fld_ids);
240 $this->addFieldsIf('rev_id', $this->fld_ids || $this->fld_flags);
241 $this->addFieldsIf('page_latest', $this->fld_flags);
242 // $this->addFieldsIf('rev_text_id', $this->fld_ids); // Should this field be exposed?
243 $this->addFieldsIf('rev_comment', $this->fld_comment);
244 $this->addFieldsIf('rev_len', $this->fld_size);
245 $this->addFieldsIf('rev_minor_edit', $this->fld_flags);
246 $this->addFieldsIf('rev_parent_id', $this->fld_flags);
247 $this->addFieldsIf('rc_patrolled', $this->fld_patrolled);
248 }
249
250 /**
251 * Extract fields from the database row and append them to a result array
252 */
253 private function extractRowInfo($row) {
254
255 $vals = array();
256
257 $vals['user'] = $row->rev_user_text;
258 if ($row->rev_deleted & Revision::DELETED_USER)
259 $vals['userhidden'] = '';
260 if ($this->fld_ids) {
261 $vals['pageid'] = intval($row->rev_page);
262 $vals['revid'] = intval($row->rev_id);
263 // $vals['textid'] = intval($row->rev_text_id); // todo: Should this field be exposed?
264 }
265
266 if ($this->fld_title)
267 ApiQueryBase :: addTitleInfo($vals,
268 Title :: makeTitle($row->page_namespace, $row->page_title));
269
270 if ($this->fld_timestamp)
271 $vals['timestamp'] = wfTimestamp(TS_ISO_8601, $row->rev_timestamp);
272
273 if ($this->fld_flags) {
274 if ($row->rev_parent_id == 0 && !is_null($row->rev_parent_id))
275 $vals['new'] = '';
276 if ($row->rev_minor_edit)
277 $vals['minor'] = '';
278 if ($row->page_latest == $row->rev_id)
279 $vals['top'] = '';
280 }
281
282 if ($this->fld_comment && isset($row->rev_comment)) {
283 if ($row->rev_deleted & Revision::DELETED_COMMENT)
284 $vals['commenthidden'] = '';
285 else
286 $vals['comment'] = $row->rev_comment;
287 }
288
289 if ($this->fld_patrolled && $row->rc_patrolled)
290 $vals['patrolled'] = '';
291
292 if ($this->fld_size && !is_null($row->rev_len))
293 $vals['size'] = intval($row->rev_len);
294
295 return $vals;
296 }
297
298 private function continueStr($row)
299 {
300 return $row->rev_user_text . '|' .
301 wfTimestamp(TS_ISO_8601, $row->rev_timestamp);
302 }
303
304 public function getAllowedParams() {
305 return array (
306 'limit' => array (
307 ApiBase :: PARAM_DFLT => 10,
308 ApiBase :: PARAM_TYPE => 'limit',
309 ApiBase :: PARAM_MIN => 1,
310 ApiBase :: PARAM_MAX => ApiBase :: LIMIT_BIG1,
311 ApiBase :: PARAM_MAX2 => ApiBase :: LIMIT_BIG2
312 ),
313 'start' => array (
314 ApiBase :: PARAM_TYPE => 'timestamp'
315 ),
316 'end' => array (
317 ApiBase :: PARAM_TYPE => 'timestamp'
318 ),
319 'continue' => null,
320 'user' => array (
321 ApiBase :: PARAM_ISMULTI => true
322 ),
323 'userprefix' => null,
324 'dir' => array (
325 ApiBase :: PARAM_DFLT => 'older',
326 ApiBase :: PARAM_TYPE => array (
327 'newer',
328 'older'
329 )
330 ),
331 'namespace' => array (
332 ApiBase :: PARAM_ISMULTI => true,
333 ApiBase :: PARAM_TYPE => 'namespace'
334 ),
335 'prop' => array (
336 ApiBase :: PARAM_ISMULTI => true,
337 ApiBase :: PARAM_DFLT => 'ids|title|timestamp|comment|size|flags',
338 ApiBase :: PARAM_TYPE => array (
339 'ids',
340 'title',
341 'timestamp',
342 'comment',
343 'size',
344 'flags',
345 'patrolled',
346 )
347 ),
348 'show' => array (
349 ApiBase :: PARAM_ISMULTI => true,
350 ApiBase :: PARAM_TYPE => array (
351 'minor',
352 '!minor',
353 'patrolled',
354 '!patrolled',
355 )
356 ),
357 );
358 }
359
360 public function getParamDescription() {
361 return array (
362 'limit' => 'The maximum number of contributions to return.',
363 'start' => 'The start timestamp to return from.',
364 'end' => 'The end timestamp to return to.',
365 'continue' => 'When more results are available, use this to continue.',
366 'user' => 'The user to retrieve contributions for.',
367 'userprefix' => 'Retrieve contibutions for all users whose names begin with this value. Overrides ucuser.',
368 'dir' => 'The direction to search (older or newer).',
369 'namespace' => 'Only list contributions in these namespaces',
370 'prop' => 'Include additional pieces of information',
371 'show' => array('Show only items that meet this criteria, e.g. non minor edits only: show=!minor',
372 'NOTE: if show=patrolled or show=!patrolled is set, revisions older than $wgRCMaxAge won\'t be shown',),
373 );
374 }
375
376 public function getDescription() {
377 return 'Get all edits by a user';
378 }
379
380 protected function getExamples() {
381 return array (
382 'api.php?action=query&list=usercontribs&ucuser=YurikBot',
383 'api.php?action=query&list=usercontribs&ucuserprefix=217.121.114.',
384 );
385 }
386
387 public function getVersion() {
388 return __CLASS__ . ': $Id$';
389 }
390 }