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