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