4 * Created on August 16, 2007
6 * API for MediaWiki 1.8+
8 * Copyright (C) 2007 Iker Labarga <Firstname><Lastname>@gmail.com
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.
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.
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
26 if (!defined('MEDIAWIKI')) {
27 // Eclipse helper - will be ignored in production
28 require_once ("ApiBase.php");
32 * A module that allows for editing and creating pages.
34 * Currently, this wraps around the EditPage class in an ugly way,
35 * EditPage.php should be rewritten to provide a cleaner interface
38 class ApiEditPage
extends ApiBase
{
40 public function __construct($query, $moduleName) {
41 parent
:: __construct($query, $moduleName);
44 public function execute() {
46 $this->getMain()->requestWriteMode();
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'));
58 $titleObj = Title
::newFromText($params['title']);
60 $this->dieUsageMsg(array('invalidtitle', $params['title']));
62 if($params['createonly'] && $titleObj->exists())
63 $this->dieUsageMsg(array('createonly-exists'));
64 if($params['nocreate'] && !$titleObj->exists())
65 $this->dieUsageMsg(array('nocreate-missing'));
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));
72 $this->dieUsageMsg($errors[0]);
74 $articleObj = new Article($titleObj);
75 $toMD5 = $params['text'];
76 if(!is_null($params['appendtext']) ||
!is_null($params['prependtext']))
78 $content = $articleObj->getContent();
79 $params['text'] = $params['prependtext'] . $content . $params['appendtext'];
80 $toMD5 = $params['prependtext'] . $params['appendtext'];
83 # See if the MD5 hash checks out
84 if(isset($params['md5']))
85 if(md5($toMD5) !== $params['md5'])
86 $this->dieUsageMsg(array('hashcheckfailed'));
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' => ''
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']);
102 $reqArr['wpEdittime'] = $articleObj->getTimestamp();
103 if(!is_null($params['starttimestamp']) && $params['starttimestamp'] != '')
104 $reqArr['wpStarttime'] = wfTimestamp(TS_MW
, $params['starttimestamp']);
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']))
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'];
122 else if($params['unwatch'])
124 else if($titleObj->userIsWatching())
126 else if($wgUser->getOption('watchdefault'))
128 else if($wgUser->getOption('watchcreations') && !$titleObj->exists())
133 $reqArr['wpWatchthis'] = '';
135 $req = new FauxRequest($reqArr, true);
136 $ep->importFormData($req);
139 # Handle CAPTCHA parameters
141 if(isset($params['captchaid']))
142 $wgRequest->setVal( 'wpCaptchaId', $params['captchaid'] );
143 if(isset($params['captchaword']))
144 $wgRequest->setVal( 'wpCaptchaWord', $params['captchaword'] );
146 if(!wfRunHooks('APIEditBeforeSave', array(&$ep, $ep->textbox1
, &$r)))
150 $r['result'] = "Failure";
151 $this->getResult()->addValue(null, $this->getModuleName(), $r);
155 $this->dieUsageMsg(array('hookaborted'));
159 $oldRevId = $articleObj->getRevIdFetched();
161 # *Something* is setting $wgTitle to a title corresponding to "Msg",
162 # but that breaks API mode detection through is_null($wgTitle)
165 # Fake $wgRequest for some hooks inside EditPage
166 # FIXME: This interface SUCKS
167 $oldRequest = $wgRequest;
170 $retval = $ep->internalAttemptSave($result, $wgUser->isAllowed('bot') && $params['bot']);
171 $wgRequest = $oldRequest;
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
:
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
224 $newArticle = new Article($titleObj);
225 $newRevId = $newArticle->getRevIdFetched();
226 if($newRevId == $oldRevId)
230 $r['oldrevid'] = $oldRevId;
231 $r['newrevid'] = $newRevId;
235 $this->dieUsageMsg(array('unknownerror', $retval));
237 $this->getResult()->addValue(null, $this->getModuleName(), $r);
240 public function mustBePosted() {
244 protected function getDescription() {
245 return 'Create and edit pages.';
248 protected function getAllowedParams() {
258 'basetimestamp' => null,
259 'starttimestamp' => null,
261 'createonly' => false,
263 'captchaword' => null,
268 'prependtext' => null,
269 'appendtext' => null,
273 protected function getParamDescription() {
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.'
286 'starttimestamp' => array('Timestamp when you obtained the edit token.',
287 'Used to detect edit conflicts; leave unset to ignore conflicts.'
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',
304 protected function getExamples() {
306 "Edit a page (anonymous user):",
307 " api.php?action=edit&title=Test&summary=test%20summary&text=article%20content&basetimestamp=20070824123454&token=%2B\\"
311 public function getVersion() {
312 return __CLASS__
. ': $Id$';