API: Give block details along with errors
[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 * see T20654 if you're inspired to fix this.
33 *
34 * @ingroup API
35 */
36 class ApiEditPage extends ApiBase {
37 public function execute() {
38 $user = $this->getUser();
39 $params = $this->extractRequestParams();
40
41 if ( is_null( $params['text'] ) && is_null( $params['appendtext'] ) &&
42 is_null( $params['prependtext'] ) &&
43 $params['undo'] == 0
44 ) {
45 $this->dieUsageMsg( 'missingtext' );
46 }
47
48 $pageObj = $this->getTitleOrPageId( $params );
49 $titleObj = $pageObj->getTitle();
50 $apiResult = $this->getResult();
51
52 if ( $params['redirect'] ) {
53 if ( $params['prependtext'] === null && $params['appendtext'] === null
54 && $params['section'] !== 'new'
55 ) {
56 $this->dieUsage( 'You have attempted to edit using the "redirect"-following'
57 . ' mode, which must be used in conjuction with section=new, prependtext'
58 . ', or appendtext.', 'redirect-appendonly' );
59 }
60 if ( $titleObj->isRedirect() ) {
61 $oldTitle = $titleObj;
62
63 $titles = Revision::newFromTitle( $oldTitle, false, Revision::READ_LATEST )
64 ->getContent( Revision::FOR_THIS_USER, $user )
65 ->getRedirectChain();
66 // array_shift( $titles );
67
68 $redirValues = array();
69
70 /** @var $newTitle Title */
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 // Since the page changed, update $pageObj
89 $pageObj = WikiPage::factory( $titleObj );
90 }
91 }
92
93 if ( !isset( $params['contentmodel'] ) || $params['contentmodel'] == '' ) {
94 $contentHandler = $pageObj->getContentHandler();
95 } else {
96 $contentHandler = ContentHandler::getForModelID( $params['contentmodel'] );
97 }
98
99 if ( $contentHandler->supportsDirectApiEditing() === false ) {
100 $this->dieUsage(
101 'Direct editing via API is not supported for this content type.',
102 'no-direct-editing'
103 );
104 }
105
106 if ( !isset( $params['contentformat'] ) || $params['contentformat'] == '' ) {
107 $params['contentformat'] = $contentHandler->getDefaultFormat();
108 }
109
110 $contentFormat = $params['contentformat'];
111
112 if ( !$contentHandler->isSupportedFormat( $contentFormat ) ) {
113 $name = $titleObj->getPrefixedDBkey();
114 $model = $contentHandler->getModelID();
115
116 $this->dieUsage( "The requested format $contentFormat is not supported for content model " .
117 " $model used by $name", 'badformat' );
118 }
119
120 if ( $params['createonly'] && $titleObj->exists() ) {
121 $this->dieUsageMsg( 'createonly-exists' );
122 }
123 if ( $params['nocreate'] && !$titleObj->exists() ) {
124 $this->dieUsageMsg( 'nocreate-missing' );
125 }
126
127 // Now let's check whether we're even allowed to do this
128 $errors = $titleObj->getUserPermissionsErrors( 'edit', $user );
129 if ( !$titleObj->exists() ) {
130 $errors = array_merge( $errors, $titleObj->getUserPermissionsErrors( 'create', $user ) );
131 }
132 if ( count( $errors ) ) {
133 if ( is_array( $errors[0] ) ) {
134 switch ( $errors[0][0] ) {
135 case 'blockedtext':
136 $this->dieUsage(
137 'You have been blocked from editing',
138 'blocked',
139 0,
140 array( 'blockinfo' => ApiQueryUserInfo::getBlockInfo( $user->getBlock() ) )
141 );
142 break;
143 case 'autoblockedtext':
144 $this->dieUsage(
145 'Your IP address has been blocked automatically, because it was used by a blocked user',
146 'autoblocked',
147 0,
148 array( 'blockinfo' => ApiQueryUserInfo::getBlockInfo( $user->getBlock() ) )
149 );
150 break;
151 default:
152 $this->dieUsageMsg( $errors[0] );
153 }
154 } else {
155 $this->dieUsageMsg( $errors[0] );
156 }
157 }
158
159 $toMD5 = $params['text'];
160 if ( !is_null( $params['appendtext'] ) || !is_null( $params['prependtext'] ) ) {
161 $content = $pageObj->getContent();
162
163 if ( !$content ) {
164 if ( $titleObj->getNamespace() == NS_MEDIAWIKI ) {
165 # If this is a MediaWiki:x message, then load the messages
166 # and return the message value for x.
167 $text = $titleObj->getDefaultMessageText();
168 if ( $text === false ) {
169 $text = '';
170 }
171
172 try {
173 $content = ContentHandler::makeContent( $text, $this->getTitle() );
174 } catch ( MWContentSerializationException $ex ) {
175 $this->dieUsage( $ex->getMessage(), 'parseerror' );
176
177 return;
178 }
179 } else {
180 # Otherwise, make a new empty content.
181 $content = $contentHandler->makeEmptyContent();
182 }
183 }
184
185 // @todo Add support for appending/prepending to the Content interface
186
187 if ( !( $content instanceof TextContent ) ) {
188 $mode = $contentHandler->getModelID();
189 $this->dieUsage( "Can't append to pages using content model $mode", 'appendnotsupported' );
190 }
191
192 if ( !is_null( $params['section'] ) ) {
193 if ( !$contentHandler->supportsSections() ) {
194 $modelName = $contentHandler->getModelID();
195 $this->dieUsage(
196 "Sections are not supported for this content model: $modelName.",
197 'sectionsnotsupported'
198 );
199 }
200
201 if ( $params['section'] == 'new' ) {
202 // DWIM if they're trying to prepend/append to a new section.
203 $content = null;
204 } else {
205 // Process the content for section edits
206 $section = $params['section'];
207 $content = $content->getSection( $section );
208
209 if ( !$content ) {
210 $this->dieUsage( "There is no section {$section}.", 'nosuchsection' );
211 }
212 }
213 }
214
215 if ( !$content ) {
216 $text = '';
217 } else {
218 $text = $content->serialize( $contentFormat );
219 }
220
221 $params['text'] = $params['prependtext'] . $text . $params['appendtext'];
222 $toMD5 = $params['prependtext'] . $params['appendtext'];
223 }
224
225 if ( $params['undo'] > 0 ) {
226 if ( $params['undoafter'] > 0 ) {
227 if ( $params['undo'] < $params['undoafter'] ) {
228 list( $params['undo'], $params['undoafter'] ) =
229 array( $params['undoafter'], $params['undo'] );
230 }
231 $undoafterRev = Revision::newFromId( $params['undoafter'] );
232 }
233 $undoRev = Revision::newFromId( $params['undo'] );
234 if ( is_null( $undoRev ) || $undoRev->isDeleted( Revision::DELETED_TEXT ) ) {
235 $this->dieUsageMsg( array( 'nosuchrevid', $params['undo'] ) );
236 }
237
238 if ( $params['undoafter'] == 0 ) {
239 $undoafterRev = $undoRev->getPrevious();
240 }
241 if ( is_null( $undoafterRev ) || $undoafterRev->isDeleted( Revision::DELETED_TEXT ) ) {
242 $this->dieUsageMsg( array( 'nosuchrevid', $params['undoafter'] ) );
243 }
244
245 if ( $undoRev->getPage() != $pageObj->getID() ) {
246 $this->dieUsageMsg( array( 'revwrongpage', $undoRev->getID(),
247 $titleObj->getPrefixedText() ) );
248 }
249 if ( $undoafterRev->getPage() != $pageObj->getID() ) {
250 $this->dieUsageMsg( array( 'revwrongpage', $undoafterRev->getID(),
251 $titleObj->getPrefixedText() ) );
252 }
253
254 $newContent = $contentHandler->getUndoContent(
255 $pageObj->getRevision(),
256 $undoRev,
257 $undoafterRev
258 );
259
260 if ( !$newContent ) {
261 $this->dieUsageMsg( 'undo-failure' );
262 }
263
264 $params['text'] = $newContent->serialize( $params['contentformat'] );
265
266 // If no summary was given and we only undid one rev,
267 // use an autosummary
268 if ( is_null( $params['summary'] ) &&
269 $titleObj->getNextRevisionID( $undoafterRev->getID() ) == $params['undo']
270 ) {
271 $params['summary'] = wfMessage( 'undo-summary' )
272 ->params( $params['undo'], $undoRev->getUserText() )->inContentLanguage()->text();
273 }
274 }
275
276 // See if the MD5 hash checks out
277 if ( !is_null( $params['md5'] ) && md5( $toMD5 ) !== $params['md5'] ) {
278 $this->dieUsageMsg( 'hashcheckfailed' );
279 }
280
281 // EditPage wants to parse its stuff from a WebRequest
282 // That interface kind of sucks, but it's workable
283 $requestArray = array(
284 'wpTextbox1' => $params['text'],
285 'format' => $contentFormat,
286 'model' => $contentHandler->getModelID(),
287 'wpEditToken' => $params['token'],
288 'wpIgnoreBlankSummary' => true,
289 'wpIgnoreBlankArticle' => true,
290 'wpIgnoreSelfRedirect' => true,
291 'bot' => $params['bot'],
292 );
293
294 if ( !is_null( $params['summary'] ) ) {
295 $requestArray['wpSummary'] = $params['summary'];
296 }
297
298 if ( !is_null( $params['sectiontitle'] ) ) {
299 $requestArray['wpSectionTitle'] = $params['sectiontitle'];
300 }
301
302 // TODO: Pass along information from 'undoafter' as well
303 if ( $params['undo'] > 0 ) {
304 $requestArray['wpUndidRevision'] = $params['undo'];
305 }
306
307 // Watch out for basetimestamp == '' or '0'
308 // It gets treated as NOW, almost certainly causing an edit conflict
309 if ( $params['basetimestamp'] !== null && (bool)$this->getMain()->getVal( 'basetimestamp' ) ) {
310 $requestArray['wpEdittime'] = $params['basetimestamp'];
311 } else {
312 $requestArray['wpEdittime'] = $pageObj->getTimestamp();
313 }
314
315 if ( $params['starttimestamp'] !== null ) {
316 $requestArray['wpStarttime'] = $params['starttimestamp'];
317 } else {
318 $requestArray['wpStarttime'] = wfTimestampNow(); // Fake wpStartime
319 }
320
321 if ( $params['minor'] || ( !$params['notminor'] && $user->getOption( 'minordefault' ) ) ) {
322 $requestArray['wpMinoredit'] = '';
323 }
324
325 if ( $params['recreate'] ) {
326 $requestArray['wpRecreate'] = '';
327 }
328
329 if ( !is_null( $params['section'] ) ) {
330 $section = $params['section'];
331 if ( !preg_match( '/^((T-)?\d+|new)$/', $section ) ) {
332 $this->dieUsage( "The section parameter must be a valid section id or 'new'",
333 "invalidsection" );
334 }
335 $content = $pageObj->getContent();
336 if ( $section !== '0' && $section != 'new'
337 && ( !$content || !$content->getSection( $section ) )
338 ) {
339 $this->dieUsage( "There is no section {$section}.", 'nosuchsection' );
340 }
341 $requestArray['wpSection'] = $params['section'];
342 } else {
343 $requestArray['wpSection'] = '';
344 }
345
346 $watch = $this->getWatchlistValue( $params['watchlist'], $titleObj );
347
348 // Deprecated parameters
349 if ( $params['watch'] ) {
350 $this->logFeatureUsage( 'action=edit&watch' );
351 $watch = true;
352 } elseif ( $params['unwatch'] ) {
353 $this->logFeatureUsage( 'action=edit&unwatch' );
354 $watch = false;
355 }
356
357 if ( $watch ) {
358 $requestArray['wpWatchthis'] = '';
359 }
360
361 // Apply change tags
362 if ( count( $params['tags'] ) ) {
363 if ( $user->isAllowed( 'applychangetags' ) ) {
364 $requestArray['wpChangeTags'] = implode( ',', $params['tags'] );
365 } else {
366 $this->dieUsage( 'You don\'t have permission to set change tags.', 'taggingnotallowed' );
367 }
368 }
369
370 // Pass through anything else we might have been given, to support extensions
371 // This is kind of a hack but it's the best we can do to make extensions work
372 $requestArray += $this->getRequest()->getValues();
373
374 global $wgTitle, $wgRequest;
375
376 $req = new DerivativeRequest( $this->getRequest(), $requestArray, true );
377
378 // Some functions depend on $wgTitle == $ep->mTitle
379 // TODO: Make them not or check if they still do
380 $wgTitle = $titleObj;
381
382 $articleContext = new RequestContext;
383 $articleContext->setRequest( $req );
384 $articleContext->setWikiPage( $pageObj );
385 $articleContext->setUser( $this->getUser() );
386
387 /** @var $articleObject Article */
388 $articleObject = Article::newFromWikiPage( $pageObj, $articleContext );
389
390 $ep = new EditPage( $articleObject );
391
392 $ep->setApiEditOverride( true );
393 $ep->setContextTitle( $titleObj );
394 $ep->importFormData( $req );
395 $content = $ep->textbox1;
396
397 // The following is needed to give the hook the full content of the
398 // new revision rather than just the current section. (Bug 52077)
399 if ( !is_null( $params['section'] ) &&
400 $contentHandler->supportsSections() && $titleObj->exists()
401 ) {
402 // If sectiontitle is set, use it, otherwise use the summary as the section title (for
403 // backwards compatibility with old forms/bots).
404 if ( $ep->sectiontitle !== '' ) {
405 $sectionTitle = $ep->sectiontitle;
406 } else {
407 $sectionTitle = $ep->summary;
408 }
409
410 $contentObj = $contentHandler->unserializeContent( $content, $contentFormat );
411
412 $fullContentObj = $articleObject->replaceSectionContent(
413 $params['section'],
414 $contentObj,
415 $sectionTitle
416 );
417 if ( $fullContentObj ) {
418 $content = $fullContentObj->serialize( $contentFormat );
419 } else {
420 // This most likely means we have an edit conflict which means that the edit
421 // wont succeed anyway.
422 $this->dieUsageMsg( 'editconflict' );
423 }
424 }
425
426 // Run hooks
427 // Handle APIEditBeforeSave parameters
428 $r = array();
429 if ( !Hooks::run( 'APIEditBeforeSave', array( $ep, $content, &$r ) ) ) {
430 if ( count( $r ) ) {
431 $r['result'] = 'Failure';
432 $apiResult->addValue( null, $this->getModuleName(), $r );
433
434 return;
435 }
436
437 $this->dieUsageMsg( 'hookaborted' );
438 }
439
440 // Do the actual save
441 $oldRevId = $articleObject->getRevIdFetched();
442 $result = null;
443 // Fake $wgRequest for some hooks inside EditPage
444 // @todo FIXME: This interface SUCKS
445 $oldRequest = $wgRequest;
446 $wgRequest = $req;
447
448 $status = $ep->attemptSave( $result );
449 $wgRequest = $oldRequest;
450
451 switch ( $status->value ) {
452 case EditPage::AS_HOOK_ERROR:
453 case EditPage::AS_HOOK_ERROR_EXPECTED:
454 if ( isset( $status->apiHookResult ) ) {
455 $r = $status->apiHookResult;
456 $r['result'] = 'Failure';
457 $apiResult->addValue( null, $this->getModuleName(), $r );
458 return;
459 } else {
460 $this->dieUsageMsg( 'hookaborted' );
461 }
462
463 case EditPage::AS_PARSE_ERROR:
464 $this->dieUsage( $status->getMessage(), 'parseerror' );
465
466 case EditPage::AS_IMAGE_REDIRECT_ANON:
467 $this->dieUsageMsg( 'noimageredirect-anon' );
468
469 case EditPage::AS_IMAGE_REDIRECT_LOGGED:
470 $this->dieUsageMsg( 'noimageredirect-logged' );
471
472 case EditPage::AS_SPAM_ERROR:
473 $this->dieUsageMsg( array( 'spamdetected', $result['spam'] ) );
474
475 case EditPage::AS_BLOCKED_PAGE_FOR_USER:
476 $this->dieUsage(
477 'You have been blocked from editing',
478 'blocked',
479 0,
480 array( 'blockinfo' => ApiQueryUserInfo::getBlockInfo( $user->getBlock() ) )
481 );
482
483 case EditPage::AS_MAX_ARTICLE_SIZE_EXCEEDED:
484 case EditPage::AS_CONTENT_TOO_BIG:
485 $this->dieUsageMsg( array( 'contenttoobig', $this->getConfig()->get( 'MaxArticleSize' ) ) );
486
487 case EditPage::AS_READ_ONLY_PAGE_ANON:
488 $this->dieUsageMsg( 'noedit-anon' );
489
490 case EditPage::AS_READ_ONLY_PAGE_LOGGED:
491 $this->dieUsageMsg( 'noedit' );
492
493 case EditPage::AS_READ_ONLY_PAGE:
494 $this->dieReadOnly();
495
496 case EditPage::AS_RATE_LIMITED:
497 $this->dieUsageMsg( 'actionthrottledtext' );
498
499 case EditPage::AS_ARTICLE_WAS_DELETED:
500 $this->dieUsageMsg( 'wasdeleted' );
501
502 case EditPage::AS_NO_CREATE_PERMISSION:
503 $this->dieUsageMsg( 'nocreate-loggedin' );
504
505 case EditPage::AS_NO_CHANGE_CONTENT_MODEL:
506 $this->dieUsageMsg( 'cantchangecontentmodel' );
507
508 case EditPage::AS_BLANK_ARTICLE:
509 $this->dieUsageMsg( 'blankpage' );
510
511 case EditPage::AS_CONFLICT_DETECTED:
512 $this->dieUsageMsg( 'editconflict' );
513
514 case EditPage::AS_TEXTBOX_EMPTY:
515 $this->dieUsageMsg( 'emptynewsection' );
516
517 case EditPage::AS_CHANGE_TAG_ERROR:
518 $this->dieStatus( $status );
519
520 case EditPage::AS_SUCCESS_NEW_ARTICLE:
521 $r['new'] = true;
522 // fall-through
523
524 case EditPage::AS_SUCCESS_UPDATE:
525 $r['result'] = 'Success';
526 $r['pageid'] = intval( $titleObj->getArticleID() );
527 $r['title'] = $titleObj->getPrefixedText();
528 $r['contentmodel'] = $articleObject->getContentModel();
529 $newRevId = $articleObject->getLatest();
530 if ( $newRevId == $oldRevId ) {
531 $r['nochange'] = true;
532 } else {
533 $r['oldrevid'] = intval( $oldRevId );
534 $r['newrevid'] = intval( $newRevId );
535 $r['newtimestamp'] = wfTimestamp( TS_ISO_8601,
536 $pageObj->getTimestamp() );
537 }
538 break;
539
540 case EditPage::AS_SUMMARY_NEEDED:
541 // Shouldn't happen since we set wpIgnoreBlankSummary, but just in case
542 $this->dieUsageMsg( 'summaryrequired' );
543
544 case EditPage::AS_END:
545 default:
546 // $status came from WikiPage::doEdit()
547 $errors = $status->getErrorsArray();
548 $this->dieUsageMsg( $errors[0] ); // TODO: Add new errors to message map
549 break;
550 }
551 $apiResult->addValue( null, $this->getModuleName(), $r );
552 }
553
554 public function mustBePosted() {
555 return true;
556 }
557
558 public function isWriteMode() {
559 return true;
560 }
561
562 public function getAllowedParams() {
563 return array(
564 'title' => array(
565 ApiBase::PARAM_TYPE => 'string',
566 ),
567 'pageid' => array(
568 ApiBase::PARAM_TYPE => 'integer',
569 ),
570 'section' => null,
571 'sectiontitle' => array(
572 ApiBase::PARAM_TYPE => 'string',
573 ),
574 'text' => array(
575 ApiBase::PARAM_TYPE => 'text',
576 ),
577 'summary' => null,
578 'tags' => array(
579 ApiBase::PARAM_TYPE => ChangeTags::listExplicitlyDefinedTags(),
580 ApiBase::PARAM_ISMULTI => true,
581 ),
582 'minor' => false,
583 'notminor' => false,
584 'bot' => false,
585 'basetimestamp' => array(
586 ApiBase::PARAM_TYPE => 'timestamp',
587 ),
588 'starttimestamp' => array(
589 ApiBase::PARAM_TYPE => 'timestamp',
590 ),
591 'recreate' => false,
592 'createonly' => false,
593 'nocreate' => false,
594 'watch' => array(
595 ApiBase::PARAM_DFLT => false,
596 ApiBase::PARAM_DEPRECATED => true,
597 ),
598 'unwatch' => array(
599 ApiBase::PARAM_DFLT => false,
600 ApiBase::PARAM_DEPRECATED => true,
601 ),
602 'watchlist' => array(
603 ApiBase::PARAM_DFLT => 'preferences',
604 ApiBase::PARAM_TYPE => array(
605 'watch',
606 'unwatch',
607 'preferences',
608 'nochange'
609 ),
610 ),
611 'md5' => null,
612 'prependtext' => array(
613 ApiBase::PARAM_TYPE => 'text',
614 ),
615 'appendtext' => array(
616 ApiBase::PARAM_TYPE => 'text',
617 ),
618 'undo' => array(
619 ApiBase::PARAM_TYPE => 'integer'
620 ),
621 'undoafter' => array(
622 ApiBase::PARAM_TYPE => 'integer'
623 ),
624 'redirect' => array(
625 ApiBase::PARAM_TYPE => 'boolean',
626 ApiBase::PARAM_DFLT => false,
627 ),
628 'contentformat' => array(
629 ApiBase::PARAM_TYPE => ContentHandler::getAllContentFormats(),
630 ),
631 'contentmodel' => array(
632 ApiBase::PARAM_TYPE => ContentHandler::getContentModels(),
633 ),
634 'token' => array(
635 // Standard definition automatically inserted
636 ApiBase::PARAM_HELP_MSG_APPEND => array( 'apihelp-edit-param-token' ),
637 ),
638 );
639 }
640
641 public function needsToken() {
642 return 'csrf';
643 }
644
645 protected function getExamplesMessages() {
646 return array(
647 'action=edit&title=Test&summary=test%20summary&' .
648 'text=article%20content&basetimestamp=2007-08-24T12:34:54Z&token=123ABC'
649 => 'apihelp-edit-example-edit',
650 'action=edit&title=Test&summary=NOTOC&minor=&' .
651 'prependtext=__NOTOC__%0A&basetimestamp=2007-08-24T12:34:54Z&token=123ABC'
652 => 'apihelp-edit-example-prepend',
653 'action=edit&title=Test&undo=13585&undoafter=13579&' .
654 'basetimestamp=2007-08-24T12:34:54Z&token=123ABC'
655 => 'apihelp-edit-example-undo',
656 );
657 }
658
659 public function getHelpUrls() {
660 return 'https://www.mediawiki.org/wiki/API:Edit';
661 }
662 }