d46b1f0f442ab4e0a50a5abc08b8c914bd4bb78d
[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 if($params['watch'])
173 $watch = true;
174 else if($params['unwatch'])
175 $watch = false;
176 else if($titleObj->userIsWatching())
177 $watch = true;
178 else if($wgUser->getOption('watchdefault'))
179 $watch = true;
180 else if($wgUser->getOption('watchcreations') && !$titleObj->exists())
181 $watch = true;
182 else
183 $watch = false;
184 if($watch)
185 $reqArr['wpWatchthis'] = '';
186
187 $req = new FauxRequest($reqArr, true);
188 $ep->importFormData($req);
189
190 # Run hooks
191 # Handle CAPTCHA parameters
192 global $wgRequest;
193 if(!is_null($params['captchaid']))
194 $wgRequest->setVal( 'wpCaptchaId', $params['captchaid'] );
195 if(!is_null($params['captchaword']))
196 $wgRequest->setVal( 'wpCaptchaWord', $params['captchaword'] );
197 $r = array();
198 if(!wfRunHooks('APIEditBeforeSave', array(&$ep, $ep->textbox1, &$r)))
199 {
200 if(count($r))
201 {
202 $r['result'] = "Failure";
203 $this->getResult()->addValue(null, $this->getModuleName(), $r);
204 return;
205 }
206 else
207 $this->dieUsageMsg(array('hookaborted'));
208 }
209
210 # Do the actual save
211 $oldRevId = $articleObj->getRevIdFetched();
212 $result = null;
213 # Fake $wgRequest for some hooks inside EditPage
214 # FIXME: This interface SUCKS
215 $oldRequest = $wgRequest;
216 $wgRequest = $req;
217
218 $retval = $ep->internalAttemptSave($result, $wgUser->isAllowed('bot') && $params['bot']);
219 $wgRequest = $oldRequest;
220 switch($retval)
221 {
222 case EditPage::AS_HOOK_ERROR:
223 case EditPage::AS_HOOK_ERROR_EXPECTED:
224 $this->dieUsageMsg(array('hookaborted'));
225 case EditPage::AS_IMAGE_REDIRECT_ANON:
226 $this->dieUsageMsg(array('noimageredirect-anon'));
227 case EditPage::AS_IMAGE_REDIRECT_LOGGED:
228 $this->dieUsageMsg(array('noimageredirect-logged'));
229 case EditPage::AS_SPAM_ERROR:
230 $this->dieUsageMsg(array('spamdetected', $result['spam']));
231 case EditPage::AS_FILTERING:
232 $this->dieUsageMsg(array('filtered'));
233 case EditPage::AS_BLOCKED_PAGE_FOR_USER:
234 $this->dieUsageMsg(array('blockedtext'));
235 case EditPage::AS_MAX_ARTICLE_SIZE_EXCEEDED:
236 case EditPage::AS_CONTENT_TOO_BIG:
237 global $wgMaxArticleSize;
238 $this->dieUsageMsg(array('contenttoobig', $wgMaxArticleSize));
239 case EditPage::AS_READ_ONLY_PAGE_ANON:
240 $this->dieUsageMsg(array('noedit-anon'));
241 case EditPage::AS_READ_ONLY_PAGE_LOGGED:
242 $this->dieUsageMsg(array('noedit'));
243 case EditPage::AS_READ_ONLY_PAGE:
244 $this->dieReadOnly();
245 case EditPage::AS_RATE_LIMITED:
246 $this->dieUsageMsg(array('actionthrottledtext'));
247 case EditPage::AS_ARTICLE_WAS_DELETED:
248 $this->dieUsageMsg(array('wasdeleted'));
249 case EditPage::AS_NO_CREATE_PERMISSION:
250 $this->dieUsageMsg(array('nocreate-loggedin'));
251 case EditPage::AS_BLANK_ARTICLE:
252 $this->dieUsageMsg(array('blankpage'));
253 case EditPage::AS_CONFLICT_DETECTED:
254 $this->dieUsageMsg(array('editconflict'));
255 #case EditPage::AS_SUMMARY_NEEDED: Can't happen since we set wpIgnoreBlankSummary
256 case EditPage::AS_TEXTBOX_EMPTY:
257 $this->dieUsageMsg(array('emptynewsection'));
258 case EditPage::AS_END:
259 # This usually means some kind of race condition
260 # or DB weirdness occurred. Throw an unknown error here.
261 $this->dieUsageMsg(array('unknownerror'));
262 case EditPage::AS_SUCCESS_NEW_ARTICLE:
263 $r['new'] = '';
264 case EditPage::AS_SUCCESS_UPDATE:
265 $r['result'] = "Success";
266 $r['pageid'] = intval($titleObj->getArticleID());
267 $r['title'] = $titleObj->getPrefixedText();
268 # HACK: We create a new Article object here because getRevIdFetched()
269 # refuses to be run twice, and because Title::getLatestRevId()
270 # won't fetch from the master unless we select for update, which we
271 # don't want to do.
272 $newArticle = new Article($titleObj);
273 $newRevId = $newArticle->getRevIdFetched();
274 if($newRevId == $oldRevId)
275 $r['nochange'] = '';
276 else
277 {
278 $r['oldrevid'] = intval($oldRevId);
279 $r['newrevid'] = intval($newRevId);
280 $r['newtimestamp'] = wfTimestamp(TS_ISO_8601,
281 $newArticle->getTimestamp());
282 }
283 break;
284 default:
285 $this->dieUsageMsg(array('unknownerror', $retval));
286 }
287 $this->getResult()->addValue(null, $this->getModuleName(), $r);
288 }
289
290 public function mustBePosted() {
291 return true;
292 }
293
294 public function isWriteMode() {
295 return true;
296 }
297
298 protected function getDescription() {
299 return 'Create and edit pages.';
300 }
301
302 protected function getAllowedParams() {
303 return array (
304 'title' => null,
305 'section' => null,
306 'text' => null,
307 'token' => null,
308 'summary' => null,
309 'minor' => false,
310 'notminor' => false,
311 'bot' => false,
312 'basetimestamp' => null,
313 'starttimestamp' => null,
314 'recreate' => false,
315 'createonly' => false,
316 'nocreate' => false,
317 'captchaword' => null,
318 'captchaid' => null,
319 'watch' => false,
320 'unwatch' => false,
321 'md5' => null,
322 'prependtext' => null,
323 'appendtext' => null,
324 'undo' => array(
325 ApiBase :: PARAM_TYPE => 'integer'
326 ),
327 'undoafter' => array(
328 ApiBase :: PARAM_TYPE => 'integer'
329 ),
330 );
331 }
332
333 protected function getParamDescription() {
334 return array (
335 'title' => 'Page title',
336 'section' => 'Section number. 0 for the top section, \'new\' for a new section',
337 'text' => 'Page content',
338 'token' => 'Edit token. You can get one of these through prop=info',
339 'summary' => 'Edit summary. Also section title when section=new',
340 'minor' => 'Minor edit',
341 'notminor' => 'Non-minor edit',
342 'bot' => 'Mark this edit as bot',
343 'basetimestamp' => array('Timestamp of the base revision (gotten through prop=revisions&rvprop=timestamp).',
344 'Used to detect edit conflicts; leave unset to ignore conflicts.'
345 ),
346 'starttimestamp' => array('Timestamp when you obtained the edit token.',
347 'Used to detect edit conflicts; leave unset to ignore conflicts.'
348 ),
349 'recreate' => 'Override any errors about the article having been deleted in the meantime',
350 'createonly' => 'Don\'t edit the page if it exists already',
351 'nocreate' => 'Throw an error if the page doesn\'t exist',
352 'watch' => 'Add the page to your watchlist',
353 'unwatch' => 'Remove the page from your watchlist',
354 'captchaid' => 'CAPTCHA ID from previous request',
355 'captchaword' => 'Answer to the CAPTCHA',
356 'md5' => array( 'The MD5 hash of the text parameter, or the prependtext and appendtext parameters concatenated.',
357 'If set, the edit won\'t be done unless the hash is correct'),
358 'prependtext' => 'Add this text to the beginning of the page. Overrides text.',
359 'appendtext' => 'Add this text to the end of the page. Overrides text',
360 'undo' => 'Undo this revision. Overrides text, prependtext and appendtext',
361 'undoafter' => 'Undo all revisions from undo to this one. If not set, just undo one revision',
362 );
363 }
364
365 protected function getExamples() {
366 return array (
367 "Edit a page (anonymous user):",
368 " api.php?action=edit&title=Test&summary=test%20summary&text=article%20content&basetimestamp=20070824123454&token=%2B\\",
369 "Prepend __NOTOC__ to a page (anonymous user):",
370 " api.php?action=edit&title=Test&summary=NOTOC&minor&prependtext=__NOTOC__%0A&basetimestamp=20070824123454&token=%2B\\",
371 "Undo r13579 through r13585 with autosummary(anonymous user):",
372 " api.php?action=edit&title=Test&undo=13585&undoafter=13579&basetimestamp=20070824123454&token=%2B\\",
373 );
374 }
375
376 public function getVersion() {
377 return __CLASS__ . ': $Id$';
378 }
379 }