Kill code duplication & other style tweaks
[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_flags = isset($prop['flags']);
57 $this->fld_timestamp = isset($prop['timestamp']);
58 $this->fld_patrolled = isset($prop['patrolled']);
59
60 // TODO: if the query is going only against the revision table, should this be done?
61 $this->selectNamedDB('contributions', DB_SLAVE, 'contributions');
62 $db = $this->getDB();
63
64 if(isset($this->params['userprefix']))
65 {
66 $this->prefixMode = true;
67 $this->multiUserMode = true;
68 $this->userprefix = $this->params['userprefix'];
69 }
70 else
71 {
72 $this->usernames = array();
73 if(!is_array($this->params['user']))
74 $this->params['user'] = array($this->params['user']);
75 foreach($this->params['user'] as $u)
76 $this->prepareUsername($u);
77 $this->prefixMode = false;
78 $this->multiUserMode = (count($this->params['user']) > 1);
79 }
80 $this->prepareQuery();
81
82 //Do the actual query.
83 $res = $this->select( __METHOD__ );
84
85 //Initialise some variables
86 $data = array ();
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 if ($vals)
103 $data[] = $vals;
104 }
105
106 //Free the database record so the connection can get on with other stuff
107 $db->freeResult($res);
108
109 //And send the whole shebang out as output.
110 $this->getResult()->setIndexedTagName($data, 'item');
111 $this->getResult()->addValue('query', $this->getModuleName(), $data);
112 }
113
114 /**
115 * Validate the 'user' parameter and set the value to compare
116 * against `revision`.`rev_user_text`
117 */
118 private function prepareUsername($user) {
119 if( $user ) {
120 $name = User::isIP( $user )
121 ? $user
122 : User::getCanonicalName( $user, 'valid' );
123 if( $name === false ) {
124 $this->dieUsage( "User name {$user} is not valid", 'param_user' );
125 } else {
126 $this->usernames[] = $name;
127 }
128 } else {
129 $this->dieUsage( 'User parameter may not be empty', 'param_user' );
130 }
131 }
132
133 /**
134 * Prepares the query and returns the limit of rows requested
135 */
136 private function prepareQuery() {
137 // We're after the revision table, and the corresponding page
138 // row for anything we retrieve. We may also need the
139 // recentchanges row.
140 $this->addTables(array('page', 'revision'));
141 $this->addWhere('page_id=rev_page');
142
143 // Handle continue parameter
144 if($this->multiUserMode && !is_null($this->params['continue']))
145 {
146 $continue = explode('|', $this->params['continue']);
147 if(count($continue) != 2)
148 $this->dieUsage("Invalid continue param. You should pass the original " .
149 "value returned by the previous query", "_badcontinue");
150 $encUser = $this->getDB()->strencode($continue[0]);
151 $encTS = wfTimestamp(TS_MW, $continue[1]);
152 $op = ($this->params['dir'] == 'older' ? '<' : '>');
153 $this->addWhere("rev_user_text $op '$encUser' OR " .
154 "(rev_user_text = '$encUser' AND " .
155 "rev_timestamp $op= '$encTS')");
156 }
157
158 $this->addWhereFld('rev_deleted', 0);
159 // We only want pages by the specified users.
160 if($this->prefixMode)
161 $this->addWhere("rev_user_text LIKE '" . $this->getDB()->escapeLike($this->userprefix) . "%'");
162 else
163 $this->addWhereFld('rev_user_text', $this->usernames);
164 // ... and in the specified timeframe.
165 // Ensure the same sort order for rev_user_text and rev_timestamp
166 // so our query is indexed
167 $this->addWhereRange('rev_user_text', $this->params['dir'], null, null);
168 $this->addWhereRange('rev_timestamp',
169 $this->params['dir'], $this->params['start'], $this->params['end'] );
170 $this->addWhereFld('page_namespace', $this->params['namespace']);
171
172 $show = $this->params['show'];
173 if (!is_null($show)) {
174 $show = array_flip($show);
175 if ((isset($show['minor']) && isset($show['!minor']))
176 || (isset($show['patrolled']) && isset($show['!patrolled'])))
177 $this->dieUsage("Incorrect parameter - mutually exclusive values may not be supplied", 'show');
178
179 $this->addWhereIf('rev_minor_edit = 0', isset($show['!minor']));
180 $this->addWhereIf('rev_minor_edit != 0', isset($show['minor']));
181 $this->addWhereIf('rc_patrolled = 0', isset($show['!patrolled']));
182 $this->addWhereIf('rc_patrolled != 0', isset($show['patrolled']));
183 }
184 $this->addOption('LIMIT', $this->params['limit'] + 1);
185 $this->addOption('USE INDEX', array('revision' => 'usertext_timestamp'));
186
187 // Mandatory fields: timestamp allows request continuation
188 // ns+title checks if the user has access rights for this page
189 // user_text is necessary if multiple users were specified
190 $this->addFields(array(
191 'rev_timestamp',
192 'page_namespace',
193 'page_title',
194 'rev_user_text',
195 ));
196
197 if(isset($show['patrolled']) || isset($show['!patrolled']) ||
198 $this->fld_patrolled)
199 {
200 global $wgUser;
201 if(!$wgUser->useRCPatrol() && !$wgUser->useNPPatrol())
202 $this->dieUsage("You need the patrol right to request the patrolled flag", 'permissiondenied');
203 $this->addTables('recentchanges');
204 if(isset($show['patrolled']) || isset($show['!patrolled']))
205 $this->addWhere('rc_this_oldid=rev_id');
206 else
207 $this->addJoinConds(array('recentchanges' => array(
208 'LEFT JOIN',
209 'rc_this_oldid=rev_id')));
210 }
211
212 $this->addFieldsIf('rev_page', $this->fld_ids);
213 $this->addFieldsIf('rev_id', $this->fld_ids || $this->fld_flags);
214 $this->addFieldsIf('page_latest', $this->fld_flags);
215 // $this->addFieldsIf('rev_text_id', $this->fld_ids); // Should this field be exposed?
216 $this->addFieldsIf('rev_comment', $this->fld_comment);
217 $this->addFieldsIf('rev_minor_edit', $this->fld_flags);
218 $this->addFieldsIf('rev_parent_id', $this->fld_flags);
219 $this->addFieldsIf('rc_patrolled', $this->fld_patrolled);
220 }
221
222 /**
223 * Extract fields from the database row and append them to a result array
224 */
225 private function extractRowInfo($row) {
226
227 $vals = array();
228
229 $vals['user'] = $row->rev_user_text;
230 if ($this->fld_ids) {
231 $vals['pageid'] = intval($row->rev_page);
232 $vals['revid'] = intval($row->rev_id);
233 // $vals['textid'] = intval($row->rev_text_id); // todo: Should this field be exposed?
234 }
235
236 if ($this->fld_title)
237 ApiQueryBase :: addTitleInfo($vals,
238 Title :: makeTitle($row->page_namespace, $row->page_title));
239
240 if ($this->fld_timestamp)
241 $vals['timestamp'] = wfTimestamp(TS_ISO_8601, $row->rev_timestamp);
242
243 if ($this->fld_flags) {
244 if ($row->rev_parent_id == 0)
245 $vals['new'] = '';
246 if ($row->rev_minor_edit)
247 $vals['minor'] = '';
248 if ($row->page_latest == $row->rev_id)
249 $vals['top'] = '';
250 }
251
252 if ($this->fld_comment && isset($row->rev_comment))
253 $vals['comment'] = $row->rev_comment;
254
255 if ($this->fld_patrolled && $row->rc_patrolled)
256 $vals['patrolled'] = '';
257
258 return $vals;
259 }
260
261 private function continueStr($row)
262 {
263 return $row->rev_user_text . '|' .
264 wfTimestamp(TS_ISO_8601, $row->rev_timestamp);
265 }
266
267 public function getAllowedParams() {
268 return array (
269 'limit' => array (
270 ApiBase :: PARAM_DFLT => 10,
271 ApiBase :: PARAM_TYPE => 'limit',
272 ApiBase :: PARAM_MIN => 1,
273 ApiBase :: PARAM_MAX => ApiBase :: LIMIT_BIG1,
274 ApiBase :: PARAM_MAX2 => ApiBase :: LIMIT_BIG2
275 ),
276 'start' => array (
277 ApiBase :: PARAM_TYPE => 'timestamp'
278 ),
279 'end' => array (
280 ApiBase :: PARAM_TYPE => 'timestamp'
281 ),
282 'continue' => null,
283 'user' => array (
284 ApiBase :: PARAM_ISMULTI => true
285 ),
286 'userprefix' => null,
287 'dir' => array (
288 ApiBase :: PARAM_DFLT => 'older',
289 ApiBase :: PARAM_TYPE => array (
290 'newer',
291 'older'
292 )
293 ),
294 'namespace' => array (
295 ApiBase :: PARAM_ISMULTI => true,
296 ApiBase :: PARAM_TYPE => 'namespace'
297 ),
298 'prop' => array (
299 ApiBase :: PARAM_ISMULTI => true,
300 ApiBase :: PARAM_DFLT => 'ids|title|timestamp|flags|comment',
301 ApiBase :: PARAM_TYPE => array (
302 'ids',
303 'title',
304 'timestamp',
305 'comment',
306 'flags',
307 'patrolled',
308 )
309 ),
310 'show' => array (
311 ApiBase :: PARAM_ISMULTI => true,
312 ApiBase :: PARAM_TYPE => array (
313 'minor',
314 '!minor',
315 'patrolled',
316 '!patrolled',
317 )
318 ),
319 );
320 }
321
322 public function getParamDescription() {
323 return array (
324 'limit' => 'The maximum number of contributions to return.',
325 'start' => 'The start timestamp to return from.',
326 'end' => 'The end timestamp to return to.',
327 'continue' => 'When more results are available, use this to continue.',
328 'user' => 'The user to retrieve contributions for.',
329 'userprefix' => 'Retrieve contibutions for all users whose names begin with this value. Overrides ucuser.',
330 'dir' => 'The direction to search (older or newer).',
331 'namespace' => 'Only list contributions in these namespaces',
332 'prop' => 'Include additional pieces of information',
333 'show' => array('Show only items that meet this criteria, e.g. non minor edits only: show=!minor',
334 'NOTE: if show=patrolled or show=!patrolled is set, revisions older than $wgRCMaxAge won\'t be shown',),
335 );
336 }
337
338 public function getDescription() {
339 return 'Get all edits by a user';
340 }
341
342 protected function getExamples() {
343 return array (
344 'api.php?action=query&list=usercontribs&ucuser=YurikBot',
345 'api.php?action=query&list=usercontribs&ucuserprefix=217.121.114.',
346 );
347 }
348
349 public function getVersion() {
350 return __CLASS__ . ': $Id$';
351 }
352 }