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