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