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