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