(bug 19090) Added watchlist parameter, deprecated watch and unwatch parameter in...
[lhc/web/wiklou.git] / includes / api / ApiEditPage.php
1 <?php
2
3 /*
4 * Created on August 16, 2007
5 *
6 * API for MediaWiki 1.8+
7 *
8 * Copyright (C) 2007 Iker Labarga <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 ("ApiBase.php");
29 }
30
31 /**
32 * A module that allows for editing and creating pages.
33 *
34 * Currently, this wraps around the EditPage class in an ugly way,
35 * EditPage.php should be rewritten to provide a cleaner interface
36 * @ingroup API
37 */
38 class ApiEditPage extends ApiBase {
39
40 public function __construct($query, $moduleName) {
41 parent :: __construct($query, $moduleName);
42 }
43
44 public function execute() {
45 global $wgUser;
46 $params = $this->extractRequestParams();
47 if(is_null($params['title']))
48 $this->dieUsageMsg(array('missingparam', 'title'));
49 if(is_null($params['text']) && is_null($params['appendtext']) &&
50 is_null($params['prependtext']) &&
51 $params['undo'] == 0)
52 $this->dieUsageMsg(array('missingtext'));
53 if(is_null($params['token']))
54 $this->dieUsageMsg(array('missingparam', 'token'));
55 if(!$wgUser->matchEditToken($params['token']))
56 $this->dieUsageMsg(array('sessionfailure'));
57
58 $titleObj = Title::newFromText($params['title']);
59 if(!$titleObj)
60 $this->dieUsageMsg(array('invalidtitle', $params['title']));
61 // Some functions depend on $wgTitle == $ep->mTitle
62 global $wgTitle;
63 $wgTitle = $titleObj;
64
65 if($params['createonly'] && $titleObj->exists())
66 $this->dieUsageMsg(array('createonly-exists'));
67 if($params['nocreate'] && !$titleObj->exists())
68 $this->dieUsageMsg(array('nocreate-missing'));
69
70 // Now let's check whether we're even allowed to do this
71 $errors = $titleObj->getUserPermissionsErrors('edit', $wgUser);
72 if(!$titleObj->exists())
73 $errors = array_merge($errors, $titleObj->getUserPermissionsErrors('create', $wgUser));
74 if(count($errors))
75 $this->dieUsageMsg($errors[0]);
76
77 $articleObj = new Article($titleObj);
78 $toMD5 = $params['text'];
79 if(!is_null($params['appendtext']) || !is_null($params['prependtext']))
80 {
81 // For non-existent pages, Article::getContent()
82 // returns an interface message rather than ''
83 // We do want getContent()'s behavior for non-existent
84 // MediaWiki: pages, though
85 if($articleObj->getID() == 0 && $titleObj->getNamespace() != NS_MEDIAWIKI)
86 $content = '';
87 else
88 $content = $articleObj->getContent();
89
90 if (!is_null($params['section']))
91 {
92 // Process the content for section edits
93 global $wgParser;
94 $section = intval($params['section']);
95 $content = $wgParser->getSection($content, $section, false);
96 if ($content === false)
97 $this->dieUsage("There is no section {$section}.", 'nosuchsection');
98 }
99 $params['text'] = $params['prependtext'] . $content . $params['appendtext'];
100 $toMD5 = $params['prependtext'] . $params['appendtext'];
101 }
102
103 if($params['undo'] > 0)
104 {
105 if($params['undoafter'] > 0)
106 {
107 if($params['undo'] < $params['undoafter'])
108 list($params['undo'], $params['undoafter']) =
109 array($params['undoafter'], $params['undo']);
110 $undoafterRev = Revision::newFromID($params['undoafter']);
111 }
112 $undoRev = Revision::newFromID($params['undo']);
113 if(is_null($undoRev) || $undoRev->isDeleted(Revision::DELETED_TEXT))
114 $this->dieUsageMsg(array('nosuchrevid', $params['undo']));
115 if($params['undoafter'] == 0)
116 $undoafterRev = $undoRev->getPrevious();
117 if(is_null($undoafterRev) || $undoafterRev->isDeleted(Revision::DELETED_TEXT))
118 $this->dieUsageMsg(array('nosuchrevid', $params['undoafter']));
119 if($undoRev->getPage() != $articleObj->getID())
120 $this->dieUsageMsg(array('revwrongpage', $undoRev->getID(), $titleObj->getPrefixedText()));
121 if($undoafterRev->getPage() != $articleObj->getID())
122 $this->dieUsageMsg(array('revwrongpage', $undoafterRev->getID(), $titleObj->getPrefixedText()));
123 $newtext = $articleObj->getUndoText($undoRev, $undoafterRev);
124 if($newtext === false)
125 $this->dieUsageMsg(array('undo-failure'));
126 $params['text'] = $newtext;
127 // If no summary was given and we only undid one rev,
128 // use an autosummary
129 if(is_null($params['summary']) && $titleObj->getNextRevisionID($undoafterRev->getID()) == $params['undo'])
130 $params['summary'] = wfMsgForContent('undo-summary', $params['undo'], $undoRev->getUserText());
131 }
132
133 # See if the MD5 hash checks out
134 if(!is_null($params['md5']))
135 if(md5($toMD5) !== $params['md5'])
136 $this->dieUsageMsg(array('hashcheckfailed'));
137
138 $ep = new EditPage($articleObj);
139 // EditPage wants to parse its stuff from a WebRequest
140 // That interface kind of sucks, but it's workable
141 $reqArr = array('wpTextbox1' => $params['text'],
142 'wpEdittoken' => $params['token'],
143 'wpIgnoreBlankSummary' => ''
144 );
145 if(!is_null($params['summary']))
146 $reqArr['wpSummary'] = $params['summary'];
147 # Watch out for basetimestamp == ''
148 # wfTimestamp() treats it as NOW, almost certainly causing an edit conflict
149 if(!is_null($params['basetimestamp']) && $params['basetimestamp'] != '')
150 $reqArr['wpEdittime'] = wfTimestamp(TS_MW, $params['basetimestamp']);
151 else
152 $reqArr['wpEdittime'] = $articleObj->getTimestamp();
153 if(!is_null($params['starttimestamp']) && $params['starttimestamp'] != '')
154 $reqArr['wpStarttime'] = wfTimestamp(TS_MW, $params['starttimestamp']);
155 else
156 # Fake wpStartime
157 $reqArr['wpStarttime'] = $reqArr['wpEdittime'];
158 if($params['minor'] || (!$params['notminor'] && $wgUser->getOption('minordefault')))
159 $reqArr['wpMinoredit'] = '';
160 if($params['recreate'])
161 $reqArr['wpRecreate'] = '';
162 if(!is_null($params['section']))
163 {
164 $section = intval($params['section']);
165 if($section == 0 && $params['section'] != '0' && $params['section'] != 'new')
166 $this->dieUsage("The section parameter must be set to an integer or 'new'", "invalidsection");
167 $reqArr['wpSection'] = $params['section'];
168 }
169 else
170 $reqArr['wpSection'] = '';
171
172 // Handle watchlist settings
173 switch ($params['watchlist'])
174 {
175 case 'watch':
176 $watch = true;
177 break;
178 case 'unwatch':
179 $watch = false;
180 break;
181 case 'preferences':
182 if ($titleObj->exists())
183 $watch = $wgUser->getOption('watchdefault');
184 else
185 $watch = $wgUser->getOption('watchcreations');
186 break;
187 case 'nochange':
188 default:
189 $watch = $titleObj->userIsWatching();
190 }
191 // Deprecated parameters
192 if ($params['watch'])
193 {
194 $watch = true;
195 $this->setWarning('The watch parameter has been deprecated.');
196 }
197 elseif ($params['unwatch'])
198 {
199 $watch = false;
200 $this->setWarning('The unwatch parameter has been deprecated.');
201 }
202
203 if($watch)
204 $reqArr['wpWatchthis'] = '';
205
206 $req = new FauxRequest($reqArr, true);
207 $ep->importFormData($req);
208
209 # Run hooks
210 # Handle CAPTCHA parameters
211 global $wgRequest;
212 if(!is_null($params['captchaid']))
213 $wgRequest->setVal( 'wpCaptchaId', $params['captchaid'] );
214 if(!is_null($params['captchaword']))
215 $wgRequest->setVal( 'wpCaptchaWord', $params['captchaword'] );
216 $r = array();
217 if(!wfRunHooks('APIEditBeforeSave', array(&$ep, $ep->textbox1, &$r)))
218 {
219 if(count($r))
220 {
221 $r['result'] = "Failure";
222 $this->getResult()->addValue(null, $this->getModuleName(), $r);
223 return;
224 }
225 else
226 $this->dieUsageMsg(array('hookaborted'));
227 }
228
229 # Do the actual save
230 $oldRevId = $articleObj->getRevIdFetched();
231 $result = null;
232 # Fake $wgRequest for some hooks inside EditPage
233 # FIXME: This interface SUCKS
234 $oldRequest = $wgRequest;
235 $wgRequest = $req;
236
237 $retval = $ep->internalAttemptSave($result, $wgUser->isAllowed('bot') && $params['bot']);
238 $wgRequest = $oldRequest;
239 switch($retval)
240 {
241 case EditPage::AS_HOOK_ERROR:
242 case EditPage::AS_HOOK_ERROR_EXPECTED:
243 $this->dieUsageMsg(array('hookaborted'));
244 case EditPage::AS_IMAGE_REDIRECT_ANON:
245 $this->dieUsageMsg(array('noimageredirect-anon'));
246 case EditPage::AS_IMAGE_REDIRECT_LOGGED:
247 $this->dieUsageMsg(array('noimageredirect-logged'));
248 case EditPage::AS_SPAM_ERROR:
249 $this->dieUsageMsg(array('spamdetected', $result['spam']));
250 case EditPage::AS_FILTERING:
251 $this->dieUsageMsg(array('filtered'));
252 case EditPage::AS_BLOCKED_PAGE_FOR_USER:
253 $this->dieUsageMsg(array('blockedtext'));
254 case EditPage::AS_MAX_ARTICLE_SIZE_EXCEEDED:
255 case EditPage::AS_CONTENT_TOO_BIG:
256 global $wgMaxArticleSize;
257 $this->dieUsageMsg(array('contenttoobig', $wgMaxArticleSize));
258 case EditPage::AS_READ_ONLY_PAGE_ANON:
259 $this->dieUsageMsg(array('noedit-anon'));
260 case EditPage::AS_READ_ONLY_PAGE_LOGGED:
261 $this->dieUsageMsg(array('noedit'));
262 case EditPage::AS_READ_ONLY_PAGE:
263 $this->dieReadOnly();
264 case EditPage::AS_RATE_LIMITED:
265 $this->dieUsageMsg(array('actionthrottledtext'));
266 case EditPage::AS_ARTICLE_WAS_DELETED:
267 $this->dieUsageMsg(array('wasdeleted'));
268 case EditPage::AS_NO_CREATE_PERMISSION:
269 $this->dieUsageMsg(array('nocreate-loggedin'));
270 case EditPage::AS_BLANK_ARTICLE:
271 $this->dieUsageMsg(array('blankpage'));
272 case EditPage::AS_CONFLICT_DETECTED:
273 $this->dieUsageMsg(array('editconflict'));
274 #case EditPage::AS_SUMMARY_NEEDED: Can't happen since we set wpIgnoreBlankSummary
275 case EditPage::AS_TEXTBOX_EMPTY:
276 $this->dieUsageMsg(array('emptynewsection'));
277 case EditPage::AS_END:
278 # This usually means some kind of race condition
279 # or DB weirdness occurred. Throw an unknown error here.
280 $this->dieUsageMsg(array('unknownerror'));
281 case EditPage::AS_SUCCESS_NEW_ARTICLE:
282 $r['new'] = '';
283 case EditPage::AS_SUCCESS_UPDATE:
284 $r['result'] = "Success";
285 $r['pageid'] = intval($titleObj->getArticleID());
286 $r['title'] = $titleObj->getPrefixedText();
287 # HACK: We create a new Article object here because getRevIdFetched()
288 # refuses to be run twice, and because Title::getLatestRevId()
289 # won't fetch from the master unless we select for update, which we
290 # don't want to do.
291 $newArticle = new Article($titleObj);
292 $newRevId = $newArticle->getRevIdFetched();
293 if($newRevId == $oldRevId)
294 $r['nochange'] = '';
295 else
296 {
297 $r['oldrevid'] = intval($oldRevId);
298 $r['newrevid'] = intval($newRevId);
299 $r['newtimestamp'] = wfTimestamp(TS_ISO_8601,
300 $newArticle->getTimestamp());
301 }
302 break;
303 default:
304 $this->dieUsageMsg(array('unknownerror', $retval));
305 }
306 $this->getResult()->addValue(null, $this->getModuleName(), $r);
307 }
308
309 public function mustBePosted() {
310 return true;
311 }
312
313 public function isWriteMode() {
314 return true;
315 }
316
317 protected function getDescription() {
318 return 'Create and edit pages.';
319 }
320
321 protected function getAllowedParams() {
322 return array (
323 'title' => null,
324 'section' => null,
325 'text' => null,
326 'token' => null,
327 'summary' => null,
328 'minor' => false,
329 'notminor' => false,
330 'bot' => false,
331 'basetimestamp' => null,
332 'starttimestamp' => null,
333 'recreate' => false,
334 'createonly' => false,
335 'nocreate' => false,
336 'captchaword' => null,
337 'captchaid' => null,
338 'watch' => false,
339 'unwatch' => false,
340 'watchlist' => array(
341 ApiBase :: PARAM_DFLT => 'preferences',
342 ApiBase :: PARAM_TYPE => array(
343 'watch',
344 'unwatch',
345 'preferences',
346 'nochange'
347 ),
348 ),
349 'md5' => null,
350 'prependtext' => null,
351 'appendtext' => null,
352 'undo' => array(
353 ApiBase :: PARAM_TYPE => 'integer'
354 ),
355 'undoafter' => array(
356 ApiBase :: PARAM_TYPE => 'integer'
357 ),
358 );
359 }
360
361 protected function getParamDescription() {
362 return array (
363 'title' => 'Page title',
364 'section' => 'Section number. 0 for the top section, \'new\' for a new section',
365 'text' => 'Page content',
366 'token' => 'Edit token. You can get one of these through prop=info',
367 'summary' => 'Edit summary. Also section title when section=new',
368 'minor' => 'Minor edit',
369 'notminor' => 'Non-minor edit',
370 'bot' => 'Mark this edit as bot',
371 'basetimestamp' => array('Timestamp of the base revision (gotten through prop=revisions&rvprop=timestamp).',
372 'Used to detect edit conflicts; leave unset to ignore conflicts.'
373 ),
374 'starttimestamp' => array('Timestamp when you obtained the edit token.',
375 'Used to detect edit conflicts; leave unset to ignore conflicts.'
376 ),
377 'recreate' => 'Override any errors about the article having been deleted in the meantime',
378 'createonly' => 'Don\'t edit the page if it exists already',
379 'nocreate' => 'Throw an error if the page doesn\'t exist',
380 'watch' => 'DEPRECATED! Add the page to your watchlist',
381 'unwatch' => 'DEPRECATED! Remove the page from your watchlist',
382 'watchlist' => 'Unconditionally add or remove the page from your watchlist, use preferences or do not change watch',
383 'captchaid' => 'CAPTCHA ID from previous request',
384 'captchaword' => 'Answer to the CAPTCHA',
385 'md5' => array( 'The MD5 hash of the text parameter, or the prependtext and appendtext parameters concatenated.',
386 'If set, the edit won\'t be done unless the hash is correct'),
387 'prependtext' => 'Add this text to the beginning of the page. Overrides text.',
388 'appendtext' => 'Add this text to the end of the page. Overrides text',
389 'undo' => 'Undo this revision. Overrides text, prependtext and appendtext',
390 'undoafter' => 'Undo all revisions from undo to this one. If not set, just undo one revision',
391 );
392 }
393
394 protected function getExamples() {
395 return array (
396 "Edit a page (anonymous user):",
397 " api.php?action=edit&title=Test&summary=test%20summary&text=article%20content&basetimestamp=20070824123454&token=%2B\\",
398 "Prepend __NOTOC__ to a page (anonymous user):",
399 " api.php?action=edit&title=Test&summary=NOTOC&minor&prependtext=__NOTOC__%0A&basetimestamp=20070824123454&token=%2B\\",
400 "Undo r13579 through r13585 with autosummary(anonymous user):",
401 " api.php?action=edit&title=Test&undo=13585&undoafter=13579&basetimestamp=20070824123454&token=%2B\\",
402 );
403 }
404
405 public function getVersion() {
406 return __CLASS__ . ': $Id$';
407 }
408 }