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