Use consistent notation for "@todo FIXME". Should update http://svn.wikimedia.org...
[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( 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 if ( $params['redirect'] ) {
62 if ( $titleObj->isRedirect() ) {
63 $oldTitle = $titleObj;
64
65 $titles = Title::newFromRedirectArray( Revision::newFromTitle( $oldTitle )->getText( Revision::FOR_THIS_USER ) );
66 // array_shift( $titles );
67
68 $this->getResult()->addValue( null, 'foo', $titles );
69
70 $redirValues = array();
71 foreach ( $titles as $id => $newTitle ) {
72
73 if ( !isset( $titles[ $id - 1 ] ) ) {
74 $titles[ $id - 1 ] = $oldTitle;
75 }
76
77 $redirValues[] = array(
78 'from' => $titles[ $id - 1 ]->getPrefixedText(),
79 'to' => $newTitle->getPrefixedText()
80 );
81
82 $titleObj = $newTitle;
83 }
84
85 $this->getResult()->setIndexedTagName( $redirValues, 'r' );
86 $this->getResult()->addValue( null, 'redirects', $redirValues );
87
88 }
89 }
90
91 // Some functions depend on $wgTitle == $ep->mTitle
92 global $wgTitle;
93 $wgTitle = $titleObj;
94
95 if ( $params['createonly'] && $titleObj->exists() ) {
96 $this->dieUsageMsg( array( 'createonly-exists' ) );
97 }
98 if ( $params['nocreate'] && !$titleObj->exists() ) {
99 $this->dieUsageMsg( array( 'nocreate-missing' ) );
100 }
101
102 // Now let's check whether we're even allowed to do this
103 $errors = $titleObj->getUserPermissionsErrors( 'edit', $wgUser );
104 if ( !$titleObj->exists() ) {
105 $errors = array_merge( $errors, $titleObj->getUserPermissionsErrors( 'create', $wgUser ) );
106 }
107 if ( count( $errors ) ) {
108 $this->dieUsageMsg( $errors[0] );
109 }
110
111 $articleObj = new Article( $titleObj );
112 $toMD5 = $params['text'];
113 if ( !is_null( $params['appendtext'] ) || !is_null( $params['prependtext'] ) )
114 {
115 // For non-existent pages, Article::getContent()
116 // returns an interface message rather than ''
117 // We do want getContent()'s behavior for non-existent
118 // MediaWiki: pages, though
119 if ( $articleObj->getID() == 0 && $titleObj->getNamespace() != NS_MEDIAWIKI ) {
120 $content = '';
121 } else {
122 $content = $articleObj->getContent();
123 }
124
125 if ( !is_null( $params['section'] ) ) {
126 // Process the content for section edits
127 global $wgParser;
128 $section = intval( $params['section'] );
129 $content = $wgParser->getSection( $content, $section, false );
130 if ( $content === false ) {
131 $this->dieUsage( "There is no section {$section}.", 'nosuchsection' );
132 }
133 }
134 $params['text'] = $params['prependtext'] . $content . $params['appendtext'];
135 $toMD5 = $params['prependtext'] . $params['appendtext'];
136 }
137
138 if ( $params['undo'] > 0 ) {
139 if ( $params['undoafter'] > 0 ) {
140 if ( $params['undo'] < $params['undoafter'] ) {
141 list( $params['undo'], $params['undoafter'] ) =
142 array( $params['undoafter'], $params['undo'] );
143 }
144 $undoafterRev = Revision::newFromID( $params['undoafter'] );
145 }
146 $undoRev = Revision::newFromID( $params['undo'] );
147 if ( is_null( $undoRev ) || $undoRev->isDeleted( Revision::DELETED_TEXT ) ) {
148 $this->dieUsageMsg( array( 'nosuchrevid', $params['undo'] ) );
149 }
150
151 if ( $params['undoafter'] == 0 ) {
152 $undoafterRev = $undoRev->getPrevious();
153 }
154 if ( is_null( $undoafterRev ) || $undoafterRev->isDeleted( Revision::DELETED_TEXT ) ) {
155 $this->dieUsageMsg( array( 'nosuchrevid', $params['undoafter'] ) );
156 }
157
158 if ( $undoRev->getPage() != $articleObj->getID() ) {
159 $this->dieUsageMsg( array( 'revwrongpage', $undoRev->getID(), $titleObj->getPrefixedText() ) );
160 }
161 if ( $undoafterRev->getPage() != $articleObj->getID() ) {
162 $this->dieUsageMsg( array( 'revwrongpage', $undoafterRev->getID(), $titleObj->getPrefixedText() ) );
163 }
164
165 $newtext = $articleObj->getUndoText( $undoRev, $undoafterRev );
166 if ( $newtext === false ) {
167 $this->dieUsageMsg( array( 'undo-failure' ) );
168 }
169 $params['text'] = $newtext;
170 // If no summary was given and we only undid one rev,
171 // use an autosummary
172 if ( is_null( $params['summary'] ) && $titleObj->getNextRevisionID( $undoafterRev->getID() ) == $params['undo'] ) {
173 $params['summary'] = wfMsgForContent( 'undo-summary', $params['undo'], $undoRev->getUserText() );
174 }
175 }
176
177 // See if the MD5 hash checks out
178 if ( !is_null( $params['md5'] ) && md5( $toMD5 ) !== $params['md5'] ) {
179 $this->dieUsageMsg( array( 'hashcheckfailed' ) );
180 }
181
182 $ep = new EditPage( $articleObj );
183 $ep->setContextTitle( $titleObj );
184
185 // EditPage wants to parse its stuff from a WebRequest
186 // That interface kind of sucks, but it's workable
187 $reqArr = array(
188 'wpTextbox1' => $params['text'],
189 'wpEditToken' => $params['token'],
190 'wpIgnoreBlankSummary' => ''
191 );
192
193 if ( !is_null( $params['summary'] ) ) {
194 $reqArr['wpSummary'] = $params['summary'];
195 }
196
197 // Watch out for basetimestamp == ''
198 // wfTimestamp() treats it as NOW, almost certainly causing an edit conflict
199 if ( !is_null( $params['basetimestamp'] ) && $params['basetimestamp'] != '' ) {
200 $reqArr['wpEdittime'] = wfTimestamp( TS_MW, $params['basetimestamp'] );
201 } else {
202 $reqArr['wpEdittime'] = $articleObj->getTimestamp();
203 }
204
205 if ( !is_null( $params['starttimestamp'] ) && $params['starttimestamp'] != '' ) {
206 $reqArr['wpStarttime'] = wfTimestamp( TS_MW, $params['starttimestamp'] );
207 } else {
208 $reqArr['wpStarttime'] = wfTimestampNow(); // Fake wpStartime
209 }
210
211 if ( $params['minor'] || ( !$params['notminor'] && $wgUser->getOption( 'minordefault' ) ) ) {
212 $reqArr['wpMinoredit'] = '';
213 }
214
215 if ( $params['recreate'] ) {
216 $reqArr['wpRecreate'] = '';
217 }
218
219 if ( !is_null( $params['section'] ) ) {
220 $section = intval( $params['section'] );
221 if ( $section == 0 && $params['section'] != '0' && $params['section'] != 'new' ) {
222 $this->dieUsage( "The section parameter must be set to an integer or 'new'", "invalidsection" );
223 }
224 $reqArr['wpSection'] = $params['section'];
225 } else {
226 $reqArr['wpSection'] = '';
227 }
228
229 $watch = $this->getWatchlistValue( $params['watchlist'], $titleObj );
230
231 // Deprecated parameters
232 if ( $params['watch'] ) {
233 $watch = true;
234 } elseif ( $params['unwatch'] ) {
235 $watch = false;
236 }
237
238 if ( $watch ) {
239 $reqArr['wpWatchthis'] = '';
240 }
241
242 $req = new FauxRequest( $reqArr, true );
243 $ep->importFormData( $req );
244
245 // Run hooks
246 // Handle CAPTCHA parameters
247 global $wgRequest;
248 if ( !is_null( $params['captchaid'] ) ) {
249 $wgRequest->setVal( 'wpCaptchaId', $params['captchaid'] );
250 }
251 if ( !is_null( $params['captchaword'] ) ) {
252 $wgRequest->setVal( 'wpCaptchaWord', $params['captchaword'] );
253 }
254
255 $r = array();
256 if ( !wfRunHooks( 'APIEditBeforeSave', array( $ep, $ep->textbox1, &$r ) ) ) {
257 if ( count( $r ) ) {
258 $r['result'] = 'Failure';
259 $this->getResult()->addValue( null, $this->getModuleName(), $r );
260 return;
261 } else {
262 $this->dieUsageMsg( array( 'hookaborted' ) );
263 }
264 }
265
266 // Do the actual save
267 $oldRevId = $articleObj->getRevIdFetched();
268 $result = null;
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( array( 'hookaborted' ) );
282
283 case EditPage::AS_IMAGE_REDIRECT_ANON:
284 $this->dieUsageMsg( array( 'noimageredirect-anon' ) );
285
286 case EditPage::AS_IMAGE_REDIRECT_LOGGED:
287 $this->dieUsageMsg( array( '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( array( 'filtered' ) );
294
295 case EditPage::AS_BLOCKED_PAGE_FOR_USER:
296 $this->dieUsageMsg( array( '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( array( 'noedit-anon' ) );
304
305 case EditPage::AS_READ_ONLY_PAGE_LOGGED:
306 $this->dieUsageMsg( array( 'noedit' ) );
307
308 case EditPage::AS_READ_ONLY_PAGE:
309 $this->dieReadOnly();
310
311 case EditPage::AS_RATE_LIMITED:
312 $this->dieUsageMsg( array( 'actionthrottledtext' ) );
313
314 case EditPage::AS_ARTICLE_WAS_DELETED:
315 $this->dieUsageMsg( array( 'wasdeleted' ) );
316
317 case EditPage::AS_NO_CREATE_PERMISSION:
318 $this->dieUsageMsg( array( 'nocreate-loggedin' ) );
319
320 case EditPage::AS_BLANK_ARTICLE:
321 $this->dieUsageMsg( array( 'blankpage' ) );
322
323 case EditPage::AS_CONFLICT_DETECTED:
324 $this->dieUsageMsg( array( 'editconflict' ) );
325
326 // case EditPage::AS_SUMMARY_NEEDED: Can't happen since we set wpIgnoreBlankSummary
327 case EditPage::AS_TEXTBOX_EMPTY:
328 $this->dieUsageMsg( array( '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( array( '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 $this->getResult()->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 ) );
415 }
416
417 protected function getAllowedParams() {
418 return array(
419 'title' => array(
420 ApiBase::PARAM_TYPE => 'string',
421 ApiBase::PARAM_REQUIRED => true
422 ),
423 'section' => null,
424 'text' => null,
425 'token' => null,
426 'summary' => null,
427 'minor' => false,
428 'notminor' => false,
429 'bot' => false,
430 'basetimestamp' => null,
431 'starttimestamp' => null,
432 'recreate' => false,
433 'createonly' => false,
434 'nocreate' => false,
435 'captchaword' => null,
436 'captchaid' => null,
437 'watch' => array(
438 ApiBase::PARAM_DFLT => false,
439 ApiBase::PARAM_DEPRECATED => true,
440 ),
441 'unwatch' => array(
442 ApiBase::PARAM_DFLT => false,
443 ApiBase::PARAM_DEPRECATED => true,
444 ),
445 'watchlist' => array(
446 ApiBase::PARAM_DFLT => 'preferences',
447 ApiBase::PARAM_TYPE => array(
448 'watch',
449 'unwatch',
450 'preferences',
451 'nochange'
452 ),
453 ),
454 'md5' => null,
455 'prependtext' => null,
456 'appendtext' => null,
457 'undo' => array(
458 ApiBase::PARAM_TYPE => 'integer'
459 ),
460 'undoafter' => array(
461 ApiBase::PARAM_TYPE => 'integer'
462 ),
463 'redirect' => array(
464 ApiBase::PARAM_TYPE => 'boolean',
465 ApiBase::PARAM_DFLT => false,
466 ),
467 );
468 }
469
470 protected function getParamDescription() {
471 $p = $this->getModulePrefix();
472 return array(
473 'title' => 'Page title',
474 'section' => 'Section number. 0 for the top section, \'new\' for a new section',
475 'text' => 'Page content',
476 'token' => 'Edit token. You can get one of these through prop=info',
477 'summary' => 'Edit summary. Also section title when section=new',
478 'minor' => 'Minor edit',
479 'notminor' => 'Non-minor edit',
480 'bot' => 'Mark this edit as bot',
481 'basetimestamp' => array( 'Timestamp of the base revision (gotten through prop=revisions&rvprop=timestamp).',
482 'Used to detect edit conflicts; leave unset to ignore conflicts.'
483 ),
484 'starttimestamp' => array( 'Timestamp when you obtained the edit token.',
485 'Used to detect edit conflicts; leave unset to ignore conflicts'
486 ),
487 'recreate' => 'Override any errors about the article having been deleted in the meantime',
488 'createonly' => 'Don\'t edit the page if it exists already',
489 'nocreate' => 'Throw an error if the page doesn\'t exist',
490 'watch' => 'Add the page to your watchlist',
491 'unwatch' => 'Remove the page from your watchlist',
492 'watchlist' => 'Unconditionally add or remove the page from your watchlist, use preferences or do not change watch',
493 'captchaid' => 'CAPTCHA ID from previous request',
494 'captchaword' => 'Answer to the CAPTCHA',
495 'md5' => array( "The MD5 hash of the {$p}text parameter, or the {$p}prependtext and {$p}appendtext parameters concatenated.",
496 'If set, the edit won\'t be done unless the hash is correct' ),
497 'prependtext' => "Add this text to the beginning of the page. Overrides {$p}text",
498 'appendtext' => "Add this text to the end of the page. Overrides {$p}text",
499 'undo' => "Undo this revision. Overrides {$p}text, {$p}prependtext and {$p}appendtext",
500 'undoafter' => 'Undo all revisions from undo to this one. If not set, just undo one revision',
501 'redirect' => 'Automatically resolve redirects',
502 );
503 }
504
505 public function needsToken() {
506 return true;
507 }
508
509 public function getTokenSalt() {
510 return '';
511 }
512
513 protected function getExamples() {
514 return array(
515 'Edit a page (anonymous user):',
516 ' api.php?action=edit&title=Test&summary=test%20summary&text=article%20content&basetimestamp=20070824123454&token=%2B\\',
517 'Prepend __NOTOC__ to a page (anonymous user):',
518 ' api.php?action=edit&title=Test&summary=NOTOC&minor=&prependtext=__NOTOC__%0A&basetimestamp=20070824123454&token=%2B\\',
519 'Undo r13579 through r13585 with autosummary (anonymous user):',
520 ' api.php?action=edit&title=Test&undo=13585&undoafter=13579&basetimestamp=20070824123454&token=%2B\\',
521 );
522 }
523
524 public function getVersion() {
525 return __CLASS__ . ': $Id$';
526 }
527 }