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