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