stylize.php on API code
[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 $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'] ) &&
50 is_null( $params['prependtext'] ) &&
51 $params['undo'] == 0 )
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 || $titleObj->isExternal() )
60 $this->dieUsageMsg( array( 'invalidtitle', $params['title'] ) );
61
62 // Some functions depend on $wgTitle == $ep->mTitle
63 global $wgTitle;
64 $wgTitle = $titleObj;
65
66 if ( $params['createonly'] && $titleObj->exists() )
67 $this->dieUsageMsg( array( 'createonly-exists' ) );
68 if ( $params['nocreate'] && !$titleObj->exists() )
69 $this->dieUsageMsg( array( 'nocreate-missing' ) );
70
71 // Now let's check whether we're even allowed to do this
72 $errors = $titleObj->getUserPermissionsErrors( 'edit', $wgUser );
73 if ( !$titleObj->exists() )
74 $errors = array_merge( $errors, $titleObj->getUserPermissionsErrors( 'create', $wgUser ) );
75 if ( count( $errors ) )
76 $this->dieUsageMsg( $errors[0] );
77
78 $articleObj = new Article( $titleObj );
79 $toMD5 = $params['text'];
80 if ( !is_null( $params['appendtext'] ) || !is_null( $params['prependtext'] ) )
81 {
82 // For non-existent pages, Article::getContent()
83 // returns an interface message rather than ''
84 // We do want getContent()'s behavior for non-existent
85 // MediaWiki: pages, though
86 if ( $articleObj->getID() == 0 && $titleObj->getNamespace() != NS_MEDIAWIKI )
87 $content = '';
88 else
89 $content = $articleObj->getContent();
90
91 if ( !is_null( $params['section'] ) )
92 {
93 // Process the content for section edits
94 global $wgParser;
95 $section = intval( $params['section'] );
96 $content = $wgParser->getSection( $content, $section, false );
97 if ( $content === false )
98 $this->dieUsage( "There is no section {$section}.", 'nosuchsection' );
99 }
100 $params['text'] = $params['prependtext'] . $content . $params['appendtext'];
101 $toMD5 = $params['prependtext'] . $params['appendtext'];
102 }
103
104 if ( $params['undo'] > 0 )
105 {
106 if ( $params['undoafter'] > 0 )
107 {
108 if ( $params['undo'] < $params['undoafter'] )
109 list( $params['undo'], $params['undoafter'] ) =
110 array( $params['undoafter'], $params['undo'] );
111 $undoafterRev = Revision::newFromID( $params['undoafter'] );
112 }
113 $undoRev = Revision::newFromID( $params['undo'] );
114 if ( is_null( $undoRev ) || $undoRev->isDeleted( Revision::DELETED_TEXT ) )
115 $this->dieUsageMsg( array( 'nosuchrevid', $params['undo'] ) );
116 if ( $params['undoafter'] == 0 )
117 $undoafterRev = $undoRev->getPrevious();
118 if ( is_null( $undoafterRev ) || $undoafterRev->isDeleted( Revision::DELETED_TEXT ) )
119 $this->dieUsageMsg( array( 'nosuchrevid', $params['undoafter'] ) );
120 if ( $undoRev->getPage() != $articleObj->getID() )
121 $this->dieUsageMsg( array( 'revwrongpage', $undoRev->getID(), $titleObj->getPrefixedText() ) );
122 if ( $undoafterRev->getPage() != $articleObj->getID() )
123 $this->dieUsageMsg( array( 'revwrongpage', $undoafterRev->getID(), $titleObj->getPrefixedText() ) );
124 $newtext = $articleObj->getUndoText( $undoRev, $undoafterRev );
125 if ( $newtext === false )
126 $this->dieUsageMsg( array( 'undo-failure' ) );
127 $params['text'] = $newtext;
128 // If no summary was given and we only undid one rev,
129 // use an autosummary
130 if ( is_null( $params['summary'] ) && $titleObj->getNextRevisionID( $undoafterRev->getID() ) == $params['undo'] )
131 $params['summary'] = wfMsgForContent( 'undo-summary', $params['undo'], $undoRev->getUserText() );
132 }
133
134 # See if the MD5 hash checks out
135 if ( !is_null( $params['md5'] ) )
136 if ( md5( $toMD5 ) !== $params['md5'] )
137 $this->dieUsageMsg( array( 'hashcheckfailed' ) );
138
139 $ep = new EditPage( $articleObj );
140 // EditPage wants to parse its stuff from a WebRequest
141 // That interface kind of sucks, but it's workable
142 $reqArr = array( 'wpTextbox1' => $params['text'],
143 'wpEdittoken' => $params['token'],
144 'wpIgnoreBlankSummary' => ''
145 );
146 if ( !is_null( $params['summary'] ) )
147 $reqArr['wpSummary'] = $params['summary'];
148 # Watch out for basetimestamp == ''
149 # wfTimestamp() treats it as NOW, almost certainly causing an edit conflict
150 if ( !is_null( $params['basetimestamp'] ) && $params['basetimestamp'] != '' )
151 $reqArr['wpEdittime'] = wfTimestamp( TS_MW, $params['basetimestamp'] );
152 else
153 $reqArr['wpEdittime'] = $articleObj->getTimestamp();
154 if ( !is_null( $params['starttimestamp'] ) && $params['starttimestamp'] != '' )
155 $reqArr['wpStarttime'] = wfTimestamp( TS_MW, $params['starttimestamp'] );
156 else
157 # Fake wpStartime
158 $reqArr['wpStarttime'] = $reqArr['wpEdittime'];
159 if ( $params['minor'] || ( !$params['notminor'] && $wgUser->getOption( 'minordefault' ) ) )
160 $reqArr['wpMinoredit'] = '';
161 if ( $params['recreate'] )
162 $reqArr['wpRecreate'] = '';
163 if ( !is_null( $params['section'] ) )
164 {
165 $section = intval( $params['section'] );
166 if ( $section == 0 && $params['section'] != '0' && $params['section'] != 'new' )
167 $this->dieUsage( "The section parameter must be set to an integer or 'new'", "invalidsection" );
168 $reqArr['wpSection'] = $params['section'];
169 }
170 else
171 $reqArr['wpSection'] = '';
172
173 // Handle watchlist settings
174 switch ( $params['watchlist'] )
175 {
176 case 'watch':
177 $watch = true;
178 break;
179 case 'unwatch':
180 $watch = false;
181 break;
182 case 'preferences':
183 if ( $titleObj->exists() )
184 $watch = $wgUser->getOption( 'watchdefault' ) || $titleObj->userIsWatching();
185 else
186 $watch = $wgUser->getOption( 'watchcreations' );
187 break;
188 case 'nochange':
189 default:
190 $watch = $titleObj->userIsWatching();
191 }
192 // Deprecated parameters
193 if ( $params['watch'] )
194 $watch = true;
195 elseif ( $params['unwatch'] )
196 $watch = false;
197
198 if ( $watch )
199 $reqArr['wpWatchthis'] = '';
200
201 $req = new FauxRequest( $reqArr, true );
202 $ep->importFormData( $req );
203
204 # Run hooks
205 # Handle CAPTCHA parameters
206 global $wgRequest;
207 if ( !is_null( $params['captchaid'] ) )
208 $wgRequest->setVal( 'wpCaptchaId', $params['captchaid'] );
209 if ( !is_null( $params['captchaword'] ) )
210 $wgRequest->setVal( 'wpCaptchaWord', $params['captchaword'] );
211 $r = array();
212 if ( !wfRunHooks( 'APIEditBeforeSave', array( $ep, $ep->textbox1, &$r ) ) )
213 {
214 if ( count( $r ) )
215 {
216 $r['result'] = "Failure";
217 $this->getResult()->addValue( null, $this->getModuleName(), $r );
218 return;
219 }
220 else
221 $this->dieUsageMsg( array( 'hookaborted' ) );
222 }
223
224 # Do the actual save
225 $oldRevId = $articleObj->getRevIdFetched();
226 $result = null;
227 # Fake $wgRequest for some hooks inside EditPage
228 # FIXME: This interface SUCKS
229 $oldRequest = $wgRequest;
230 $wgRequest = $req;
231
232 $retval = $ep->internalAttemptSave( $result, $wgUser->isAllowed( 'bot' ) && $params['bot'] );
233 $wgRequest = $oldRequest;
234 switch( $retval )
235 {
236 case EditPage::AS_HOOK_ERROR:
237 case EditPage::AS_HOOK_ERROR_EXPECTED:
238 $this->dieUsageMsg( array( 'hookaborted' ) );
239 case EditPage::AS_IMAGE_REDIRECT_ANON:
240 $this->dieUsageMsg( array( 'noimageredirect-anon' ) );
241 case EditPage::AS_IMAGE_REDIRECT_LOGGED:
242 $this->dieUsageMsg( array( 'noimageredirect-logged' ) );
243 case EditPage::AS_SPAM_ERROR:
244 $this->dieUsageMsg( array( 'spamdetected', $result['spam'] ) );
245 case EditPage::AS_FILTERING:
246 $this->dieUsageMsg( array( 'filtered' ) );
247 case EditPage::AS_BLOCKED_PAGE_FOR_USER:
248 $this->dieUsageMsg( array( 'blockedtext' ) );
249 case EditPage::AS_MAX_ARTICLE_SIZE_EXCEEDED:
250 case EditPage::AS_CONTENT_TOO_BIG:
251 global $wgMaxArticleSize;
252 $this->dieUsageMsg( array( 'contenttoobig', $wgMaxArticleSize ) );
253 case EditPage::AS_READ_ONLY_PAGE_ANON:
254 $this->dieUsageMsg( array( 'noedit-anon' ) );
255 case EditPage::AS_READ_ONLY_PAGE_LOGGED:
256 $this->dieUsageMsg( array( 'noedit' ) );
257 case EditPage::AS_READ_ONLY_PAGE:
258 $this->dieReadOnly();
259 case EditPage::AS_RATE_LIMITED:
260 $this->dieUsageMsg( array( 'actionthrottledtext' ) );
261 case EditPage::AS_ARTICLE_WAS_DELETED:
262 $this->dieUsageMsg( array( 'wasdeleted' ) );
263 case EditPage::AS_NO_CREATE_PERMISSION:
264 $this->dieUsageMsg( array( 'nocreate-loggedin' ) );
265 case EditPage::AS_BLANK_ARTICLE:
266 $this->dieUsageMsg( array( 'blankpage' ) );
267 case EditPage::AS_CONFLICT_DETECTED:
268 $this->dieUsageMsg( array( 'editconflict' ) );
269 # case EditPage::AS_SUMMARY_NEEDED: Can't happen since we set wpIgnoreBlankSummary
270 case EditPage::AS_TEXTBOX_EMPTY:
271 $this->dieUsageMsg( array( 'emptynewsection' ) );
272 case EditPage::AS_SUCCESS_NEW_ARTICLE:
273 $r['new'] = '';
274 case EditPage::AS_SUCCESS_UPDATE:
275 $r['result'] = "Success";
276 $r['pageid'] = intval( $titleObj->getArticleID() );
277 $r['title'] = $titleObj->getPrefixedText();
278 # HACK: We create a new Article object here because getRevIdFetched()
279 # refuses to be run twice, and because Title::getLatestRevId()
280 # won't fetch from the master unless we select for update, which we
281 # don't want to do.
282 $newArticle = new Article( $titleObj );
283 $newRevId = $newArticle->getRevIdFetched();
284 if ( $newRevId == $oldRevId )
285 $r['nochange'] = '';
286 else
287 {
288 $r['oldrevid'] = intval( $oldRevId );
289 $r['newrevid'] = intval( $newRevId );
290 $r['newtimestamp'] = wfTimestamp( TS_ISO_8601,
291 $newArticle->getTimestamp() );
292 }
293 break;
294 case EditPage::AS_END:
295 # This usually means some kind of race condition
296 # or DB weirdness occurred. Fall through to throw an unknown
297 # error.
298
299 # This needs fixing higher up, as Article::doEdit should be
300 # used rather than Article::updateArticle, so that specific
301 # error conditions can be returned
302 default:
303 $this->dieUsageMsg( array( 'unknownerror', $retval ) );
304 }
305 $this->getResult()->addValue( null, $this->getModuleName(), $r );
306 }
307
308 public function mustBePosted() {
309 return true;
310 }
311
312 public function isWriteMode() {
313 return true;
314 }
315
316 protected function getDescription() {
317 return 'Create and edit pages.';
318 }
319
320 protected function getAllowedParams() {
321 return array (
322 'title' => null,
323 'section' => null,
324 'text' => null,
325 'token' => null,
326 'summary' => null,
327 'minor' => false,
328 'notminor' => false,
329 'bot' => false,
330 'basetimestamp' => null,
331 'starttimestamp' => null,
332 'recreate' => false,
333 'createonly' => false,
334 'nocreate' => false,
335 'captchaword' => null,
336 'captchaid' => null,
337 'watch' => array(
338 ApiBase :: PARAM_DFLT => false,
339 ApiBase :: PARAM_DEPRECATED => true,
340 ),
341 'unwatch' => array(
342 ApiBase :: PARAM_DFLT => false,
343 ApiBase :: PARAM_DEPRECATED => true,
344 ),
345 'watchlist' => array(
346 ApiBase :: PARAM_DFLT => 'preferences',
347 ApiBase :: PARAM_TYPE => array(
348 'watch',
349 'unwatch',
350 'preferences',
351 'nochange'
352 ),
353 ),
354 'md5' => null,
355 'prependtext' => null,
356 'appendtext' => null,
357 'undo' => array(
358 ApiBase :: PARAM_TYPE => 'integer'
359 ),
360 'undoafter' => array(
361 ApiBase :: PARAM_TYPE => 'integer'
362 ),
363 );
364 }
365
366 protected function getParamDescription() {
367 return array (
368 'title' => 'Page title',
369 'section' => 'Section number. 0 for the top section, \'new\' for a new section',
370 'text' => 'Page content',
371 'token' => 'Edit token. You can get one of these through prop=info',
372 'summary' => 'Edit summary. Also section title when section=new',
373 'minor' => 'Minor edit',
374 'notminor' => 'Non-minor edit',
375 'bot' => 'Mark this edit as bot',
376 'basetimestamp' => array( 'Timestamp of the base revision (gotten through prop=revisions&rvprop=timestamp).',
377 'Used to detect edit conflicts; leave unset to ignore conflicts.'
378 ),
379 'starttimestamp' => array( 'Timestamp when you obtained the edit token.',
380 'Used to detect edit conflicts; leave unset to ignore conflicts.'
381 ),
382 'recreate' => 'Override any errors about the article having been deleted in the meantime',
383 'createonly' => 'Don\'t edit the page if it exists already',
384 'nocreate' => 'Throw an error if the page doesn\'t exist',
385 'watch' => 'Add the page to your watchlist',
386 'unwatch' => 'Remove the page from your watchlist',
387 'watchlist' => 'Unconditionally add or remove the page from your watchlist, use preferences or do not change watch',
388 'captchaid' => 'CAPTCHA ID from previous request',
389 'captchaword' => 'Answer to the CAPTCHA',
390 'md5' => array( 'The MD5 hash of the text parameter, or the prependtext and appendtext parameters concatenated.',
391 'If set, the edit won\'t be done unless the hash is correct' ),
392 'prependtext' => 'Add this text to the beginning of the page. Overrides text.',
393 'appendtext' => 'Add this text to the end of the page. Overrides text',
394 'undo' => 'Undo this revision. Overrides text, prependtext and appendtext',
395 'undoafter' => 'Undo all revisions from undo to this one. If not set, just undo one revision',
396 );
397 }
398
399 protected function getExamples() {
400 return array (
401 "Edit a page (anonymous user):",
402 " api.php?action=edit&title=Test&summary=test%20summary&text=article%20content&basetimestamp=20070824123454&token=%2B\\",
403 "Prepend __NOTOC__ to a page (anonymous user):",
404 " api.php?action=edit&title=Test&summary=NOTOC&minor&prependtext=__NOTOC__%0A&basetimestamp=20070824123454&token=%2B\\",
405 "Undo r13579 through r13585 with autosummary(anonymous user):",
406 " api.php?action=edit&title=Test&undo=13585&undoafter=13579&basetimestamp=20070824123454&token=%2B\\",
407 );
408 }
409
410 public function getVersion() {
411 return __CLASS__ . ': $Id$';
412 }
413 }