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