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