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