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