ApiEditPage: Test for bad redirect targets
[lhc/web/wiklou.git] / includes / api / ApiEditPage.php
1 <?php
2 /**
3 * Copyright © 2007 Iker Labarga "<Firstname><Lastname>@gmail.com"
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 */
22
23 use MediaWiki\MediaWikiServices;
24 use MediaWiki\Revision\RevisionRecord;
25
26 /**
27 * A module that allows for editing and creating pages.
28 *
29 * Currently, this wraps around the EditPage class in an ugly way,
30 * EditPage.php should be rewritten to provide a cleaner interface,
31 * see T20654 if you're inspired to fix this.
32 *
33 * @ingroup API
34 */
35 class ApiEditPage extends ApiBase {
36 public function execute() {
37 $this->useTransactionalTimeLimit();
38
39 $user = $this->getUser();
40 $params = $this->extractRequestParams();
41
42 $this->requireAtLeastOneParameter( $params, 'text', 'appendtext', 'prependtext', 'undo' );
43
44 $pageObj = $this->getTitleOrPageId( $params );
45 $titleObj = $pageObj->getTitle();
46 $apiResult = $this->getResult();
47
48 if ( $params['redirect'] ) {
49 if ( $params['prependtext'] === null && $params['appendtext'] === null
50 && $params['section'] !== 'new'
51 ) {
52 $this->dieWithError( 'apierror-redirect-appendonly' );
53 }
54 if ( $titleObj->isRedirect() ) {
55 $oldTitle = $titleObj;
56
57 $titles = Revision::newFromTitle( $oldTitle, false, Revision::READ_LATEST )
58 ->getContent( RevisionRecord::FOR_THIS_USER, $user )
59 ->getRedirectChain();
60 // array_shift( $titles );
61
62 $redirValues = [];
63
64 /** @var Title $newTitle */
65 foreach ( $titles as $id => $newTitle ) {
66 $titles[$id - 1] = $titles[$id - 1] ?? $oldTitle;
67
68 $redirValues[] = [
69 'from' => $titles[$id - 1]->getPrefixedText(),
70 'to' => $newTitle->getPrefixedText()
71 ];
72
73 $titleObj = $newTitle;
74
75 // T239428: Check whether the new title is valid
76 if ( $titleObj->isExternal() || !$titleObj->canExist() ) {
77 $redirValues[count( $redirValues ) - 1]['to'] = $titleObj->getFullText();
78 $this->dieWithError(
79 [
80 'apierror-edit-invalidredirect',
81 Message::plaintextParam( $oldTitle->getPrefixedText() ),
82 Message::plaintextParam( $titleObj->getFullText() ),
83 ],
84 'edit-invalidredirect',
85 [ 'redirects' => $redirValues ]
86 );
87 }
88 }
89
90 ApiResult::setIndexedTagName( $redirValues, 'r' );
91 $apiResult->addValue( null, 'redirects', $redirValues );
92
93 // Since the page changed, update $pageObj
94 $pageObj = WikiPage::factory( $titleObj );
95 }
96 }
97
98 if ( !isset( $params['contentmodel'] ) || $params['contentmodel'] == '' ) {
99 $contentHandler = $pageObj->getContentHandler();
100 } else {
101 $contentHandler = ContentHandler::getForModelID( $params['contentmodel'] );
102 }
103 $contentModel = $contentHandler->getModelID();
104
105 $name = $titleObj->getPrefixedDBkey();
106 $model = $contentHandler->getModelID();
107
108 if ( $params['undo'] > 0 ) {
109 // allow undo via api
110 } elseif ( $contentHandler->supportsDirectApiEditing() === false ) {
111 $this->dieWithError( [ 'apierror-no-direct-editing', $model, $name ] );
112 }
113
114 if ( !isset( $params['contentformat'] ) || $params['contentformat'] == '' ) {
115 $contentFormat = $contentHandler->getDefaultFormat();
116 } else {
117 $contentFormat = $params['contentformat'];
118 }
119
120 if ( !$contentHandler->isSupportedFormat( $contentFormat ) ) {
121 $this->dieWithError( [ 'apierror-badformat', $contentFormat, $model, $name ] );
122 }
123
124 if ( $params['createonly'] && $titleObj->exists() ) {
125 $this->dieWithError( 'apierror-articleexists' );
126 }
127 if ( $params['nocreate'] && !$titleObj->exists() ) {
128 $this->dieWithError( 'apierror-missingtitle' );
129 }
130
131 // Now let's check whether we're even allowed to do this
132 $this->checkTitleUserPermissions(
133 $titleObj,
134 $titleObj->exists() ? 'edit' : [ 'edit', 'create' ],
135 [ 'autoblock' => true ]
136 );
137
138 $toMD5 = $params['text'];
139 if ( !is_null( $params['appendtext'] ) || !is_null( $params['prependtext'] ) ) {
140 $content = $pageObj->getContent();
141
142 if ( !$content ) {
143 if ( $titleObj->getNamespace() == NS_MEDIAWIKI ) {
144 # If this is a MediaWiki:x message, then load the messages
145 # and return the message value for x.
146 $text = $titleObj->getDefaultMessageText();
147 if ( $text === false ) {
148 $text = '';
149 }
150
151 try {
152 $content = ContentHandler::makeContent( $text, $titleObj );
153 } catch ( MWContentSerializationException $ex ) {
154 $this->dieWithException( $ex, [
155 'wrap' => ApiMessage::create( 'apierror-contentserializationexception', 'parseerror' )
156 ] );
157 return;
158 }
159 } else {
160 # Otherwise, make a new empty content.
161 $content = $contentHandler->makeEmptyContent();
162 }
163 }
164
165 // @todo Add support for appending/prepending to the Content interface
166
167 if ( !( $content instanceof TextContent ) ) {
168 $modelName = $contentHandler->getModelID();
169 $this->dieWithError( [ 'apierror-appendnotsupported', $modelName ] );
170 }
171
172 if ( !is_null( $params['section'] ) ) {
173 if ( !$contentHandler->supportsSections() ) {
174 $modelName = $contentHandler->getModelID();
175 $this->dieWithError( [ 'apierror-sectionsnotsupported', $modelName ] );
176 }
177
178 if ( $params['section'] == 'new' ) {
179 // DWIM if they're trying to prepend/append to a new section.
180 $content = null;
181 } else {
182 // Process the content for section edits
183 $section = $params['section'];
184 $content = $content->getSection( $section );
185
186 if ( !$content ) {
187 $this->dieWithError( [ 'apierror-nosuchsection', wfEscapeWikiText( $section ) ] );
188 }
189 }
190 }
191
192 if ( !$content ) {
193 $text = '';
194 } else {
195 $text = $content->serialize( $contentFormat );
196 }
197
198 $params['text'] = $params['prependtext'] . $text . $params['appendtext'];
199 $toMD5 = $params['prependtext'] . $params['appendtext'];
200 }
201
202 if ( $params['undo'] > 0 ) {
203 if ( $params['undoafter'] > 0 ) {
204 if ( $params['undo'] < $params['undoafter'] ) {
205 list( $params['undo'], $params['undoafter'] ) =
206 [ $params['undoafter'], $params['undo'] ];
207 }
208 $undoafterRev = Revision::newFromId( $params['undoafter'] );
209 }
210 $undoRev = Revision::newFromId( $params['undo'] );
211 if ( is_null( $undoRev ) || $undoRev->isDeleted( RevisionRecord::DELETED_TEXT ) ) {
212 $this->dieWithError( [ 'apierror-nosuchrevid', $params['undo'] ] );
213 }
214
215 if ( $params['undoafter'] == 0 ) {
216 $undoafterRev = $undoRev->getPrevious();
217 }
218 if ( is_null( $undoafterRev ) || $undoafterRev->isDeleted( RevisionRecord::DELETED_TEXT ) ) {
219 $this->dieWithError( [ 'apierror-nosuchrevid', $params['undoafter'] ] );
220 }
221
222 if ( $undoRev->getPage() != $pageObj->getId() ) {
223 $this->dieWithError( [ 'apierror-revwrongpage', $undoRev->getId(),
224 $titleObj->getPrefixedText() ] );
225 }
226 if ( $undoafterRev->getPage() != $pageObj->getId() ) {
227 $this->dieWithError( [ 'apierror-revwrongpage', $undoafterRev->getId(),
228 $titleObj->getPrefixedText() ] );
229 }
230
231 $newContent = $contentHandler->getUndoContent(
232 $pageObj->getRevision(),
233 $undoRev,
234 $undoafterRev
235 );
236
237 if ( !$newContent ) {
238 $this->dieWithError( 'undo-failure', 'undofailure' );
239 }
240 if ( empty( $params['contentmodel'] )
241 && empty( $params['contentformat'] )
242 ) {
243 // If we are reverting content model, the new content model
244 // might not support the current serialization format, in
245 // which case go back to the old serialization format,
246 // but only if the user hasn't specified a format/model
247 // parameter.
248 if ( !$newContent->isSupportedFormat( $contentFormat ) ) {
249 $contentFormat = $undoafterRev->getContentFormat();
250 }
251 // Override content model with model of undid revision.
252 $contentModel = $newContent->getModel();
253 }
254 $params['text'] = $newContent->serialize( $contentFormat );
255 // If no summary was given and we only undid one rev,
256 // use an autosummary
257
258 if ( is_null( $params['summary'] ) ) {
259 $nextRev = MediaWikiServices::getInstance()->getRevisionLookup()
260 ->getNextRevision( $undoafterRev->getRevisionRecord() );
261 if ( $nextRev && $nextRev->getId() == $params['undo'] ) {
262 $params['summary'] = wfMessage( 'undo-summary' )
263 ->params( $params['undo'], $undoRev->getUserText() )
264 ->inContentLanguage()->text();
265 }
266 }
267 }
268
269 // See if the MD5 hash checks out
270 if ( !is_null( $params['md5'] ) && md5( $toMD5 ) !== $params['md5'] ) {
271 $this->dieWithError( 'apierror-badmd5' );
272 }
273
274 // EditPage wants to parse its stuff from a WebRequest
275 // That interface kind of sucks, but it's workable
276 $requestArray = [
277 'wpTextbox1' => $params['text'],
278 'format' => $contentFormat,
279 'model' => $contentModel,
280 'wpEditToken' => $params['token'],
281 'wpIgnoreBlankSummary' => true,
282 'wpIgnoreBlankArticle' => true,
283 'wpIgnoreSelfRedirect' => true,
284 'bot' => $params['bot'],
285 'wpUnicodeCheck' => EditPage::UNICODE_CHECK,
286 ];
287
288 if ( !is_null( $params['summary'] ) ) {
289 $requestArray['wpSummary'] = $params['summary'];
290 }
291
292 if ( !is_null( $params['sectiontitle'] ) ) {
293 $requestArray['wpSectionTitle'] = $params['sectiontitle'];
294 }
295
296 // TODO: Pass along information from 'undoafter' as well
297 if ( $params['undo'] > 0 ) {
298 $requestArray['wpUndidRevision'] = $params['undo'];
299 }
300
301 // Watch out for basetimestamp == '' or '0'
302 // It gets treated as NOW, almost certainly causing an edit conflict
303 if ( $params['basetimestamp'] !== null && (bool)$this->getMain()->getVal( 'basetimestamp' ) ) {
304 $requestArray['wpEdittime'] = $params['basetimestamp'];
305 } else {
306 $requestArray['wpEdittime'] = $pageObj->getTimestamp();
307 }
308
309 if ( $params['starttimestamp'] !== null ) {
310 $requestArray['wpStarttime'] = $params['starttimestamp'];
311 } else {
312 $requestArray['wpStarttime'] = wfTimestampNow(); // Fake wpStartime
313 }
314
315 if ( $params['minor'] || ( !$params['notminor'] && $user->getOption( 'minordefault' ) ) ) {
316 $requestArray['wpMinoredit'] = '';
317 }
318
319 if ( $params['recreate'] ) {
320 $requestArray['wpRecreate'] = '';
321 }
322
323 if ( !is_null( $params['section'] ) ) {
324 $section = $params['section'];
325 if ( !preg_match( '/^((T-)?\d+|new)$/', $section ) ) {
326 $this->dieWithError( 'apierror-invalidsection' );
327 }
328 $content = $pageObj->getContent();
329 if ( $section !== '0' && $section != 'new'
330 && ( !$content || !$content->getSection( $section ) )
331 ) {
332 $this->dieWithError( [ 'apierror-nosuchsection', $section ] );
333 }
334 $requestArray['wpSection'] = $params['section'];
335 } else {
336 $requestArray['wpSection'] = '';
337 }
338
339 $watch = $this->getWatchlistValue( $params['watchlist'], $titleObj );
340
341 // Deprecated parameters
342 if ( $params['watch'] ) {
343 $watch = true;
344 } elseif ( $params['unwatch'] ) {
345 $watch = false;
346 }
347
348 if ( $watch ) {
349 $requestArray['wpWatchthis'] = '';
350 }
351
352 // Apply change tags
353 if ( $params['tags'] ) {
354 $tagStatus = ChangeTags::canAddTagsAccompanyingChange( $params['tags'], $user );
355 if ( $tagStatus->isOK() ) {
356 $requestArray['wpChangeTags'] = implode( ',', $params['tags'] );
357 } else {
358 $this->dieStatus( $tagStatus );
359 }
360 }
361
362 // Pass through anything else we might have been given, to support extensions
363 // This is kind of a hack but it's the best we can do to make extensions work
364 $requestArray += $this->getRequest()->getValues();
365
366 global $wgTitle, $wgRequest;
367
368 $req = new DerivativeRequest( $this->getRequest(), $requestArray, true );
369
370 // Some functions depend on $wgTitle == $ep->mTitle
371 // TODO: Make them not or check if they still do
372 $wgTitle = $titleObj;
373
374 $articleContext = new RequestContext;
375 $articleContext->setRequest( $req );
376 $articleContext->setWikiPage( $pageObj );
377 $articleContext->setUser( $this->getUser() );
378
379 /** @var Article $articleObject */
380 $articleObject = Article::newFromWikiPage( $pageObj, $articleContext );
381
382 $ep = new EditPage( $articleObject );
383
384 $ep->setApiEditOverride( true );
385 $ep->setContextTitle( $titleObj );
386 $ep->importFormData( $req );
387 $content = $ep->textbox1;
388
389 // Do the actual save
390 $oldRevId = $articleObject->getRevIdFetched();
391 $result = null;
392 // Fake $wgRequest for some hooks inside EditPage
393 // @todo FIXME: This interface SUCKS
394 $oldRequest = $wgRequest;
395 $wgRequest = $req;
396
397 $status = $ep->attemptSave( $result );
398 $wgRequest = $oldRequest;
399
400 $r = [];
401 switch ( $status->value ) {
402 case EditPage::AS_HOOK_ERROR:
403 case EditPage::AS_HOOK_ERROR_EXPECTED:
404 if ( isset( $status->apiHookResult ) ) {
405 $r = $status->apiHookResult;
406 $r['result'] = 'Failure';
407 $apiResult->addValue( null, $this->getModuleName(), $r );
408 return;
409 }
410 if ( !$status->getErrors() ) {
411 // This appears to be unreachable right now, because all
412 // code paths will set an error. Could change, though.
413 $status->fatal( 'hookaborted' ); //@codeCoverageIgnore
414 }
415 $this->dieStatus( $status );
416
417 // These two cases will normally have been caught earlier, and will
418 // only occur if something blocks the user between the earlier
419 // check and the check in EditPage (presumably a hook). It's not
420 // obvious that this is even possible.
421 // @codeCoverageIgnoreStart
422 case EditPage::AS_BLOCKED_PAGE_FOR_USER:
423 $this->dieBlocked( $user->getBlock() );
424
425 case EditPage::AS_READ_ONLY_PAGE:
426 $this->dieReadOnly();
427 // @codeCoverageIgnoreEnd
428
429 case EditPage::AS_SUCCESS_NEW_ARTICLE:
430 $r['new'] = true;
431 // fall-through
432
433 case EditPage::AS_SUCCESS_UPDATE:
434 $r['result'] = 'Success';
435 $r['pageid'] = (int)$titleObj->getArticleID();
436 $r['title'] = $titleObj->getPrefixedText();
437 $r['contentmodel'] = $articleObject->getContentModel();
438 $newRevId = $articleObject->getLatest();
439 if ( $newRevId == $oldRevId ) {
440 $r['nochange'] = true;
441 } else {
442 $r['oldrevid'] = (int)$oldRevId;
443 $r['newrevid'] = (int)$newRevId;
444 $r['newtimestamp'] = wfTimestamp( TS_ISO_8601,
445 $pageObj->getTimestamp() );
446 }
447 break;
448
449 default:
450 if ( !$status->getErrors() ) {
451 // EditPage sometimes only sets the status code without setting
452 // any actual error messages. Supply defaults for those cases.
453 switch ( $status->value ) {
454 // Currently needed
455 case EditPage::AS_IMAGE_REDIRECT_ANON:
456 $status->fatal( 'apierror-noimageredirect-anon' );
457 break;
458 case EditPage::AS_IMAGE_REDIRECT_LOGGED:
459 $status->fatal( 'apierror-noimageredirect' );
460 break;
461 case EditPage::AS_CONTENT_TOO_BIG:
462 case EditPage::AS_MAX_ARTICLE_SIZE_EXCEEDED:
463 $status->fatal( 'apierror-contenttoobig', $this->getConfig()->get( 'MaxArticleSize' ) );
464 break;
465 case EditPage::AS_READ_ONLY_PAGE_ANON:
466 $status->fatal( 'apierror-noedit-anon' );
467 break;
468 case EditPage::AS_NO_CHANGE_CONTENT_MODEL:
469 $status->fatal( 'apierror-cantchangecontentmodel' );
470 break;
471 case EditPage::AS_ARTICLE_WAS_DELETED:
472 $status->fatal( 'apierror-pagedeleted' );
473 break;
474 case EditPage::AS_CONFLICT_DETECTED:
475 $status->fatal( 'editconflict' );
476 break;
477
478 // Currently shouldn't be needed, but here in case
479 // hooks use them without setting appropriate
480 // errors on the status.
481 // @codeCoverageIgnoreStart
482 case EditPage::AS_SPAM_ERROR:
483 $status->fatal( 'apierror-spamdetected', $result['spam'] );
484 break;
485 case EditPage::AS_READ_ONLY_PAGE_LOGGED:
486 $status->fatal( 'apierror-noedit' );
487 break;
488 case EditPage::AS_RATE_LIMITED:
489 $status->fatal( 'apierror-ratelimited' );
490 break;
491 case EditPage::AS_NO_CREATE_PERMISSION:
492 $status->fatal( 'nocreate-loggedin' );
493 break;
494 case EditPage::AS_BLANK_ARTICLE:
495 $status->fatal( 'apierror-emptypage' );
496 break;
497 case EditPage::AS_TEXTBOX_EMPTY:
498 $status->fatal( 'apierror-emptynewsection' );
499 break;
500 case EditPage::AS_SUMMARY_NEEDED:
501 $status->fatal( 'apierror-summaryrequired' );
502 break;
503 default:
504 wfWarn( __METHOD__ . ": Unknown EditPage code {$status->value} with no message" );
505 $status->fatal( 'apierror-unknownerror-editpage', $status->value );
506 break;
507 // @codeCoverageIgnoreEnd
508 }
509 }
510 $this->dieStatus( $status );
511 }
512 $apiResult->addValue( null, $this->getModuleName(), $r );
513 }
514
515 public function mustBePosted() {
516 return true;
517 }
518
519 public function isWriteMode() {
520 return true;
521 }
522
523 public function getAllowedParams() {
524 return [
525 'title' => [
526 ApiBase::PARAM_TYPE => 'string',
527 ],
528 'pageid' => [
529 ApiBase::PARAM_TYPE => 'integer',
530 ],
531 'section' => null,
532 'sectiontitle' => [
533 ApiBase::PARAM_TYPE => 'string',
534 ],
535 'text' => [
536 ApiBase::PARAM_TYPE => 'text',
537 ],
538 'summary' => null,
539 'tags' => [
540 ApiBase::PARAM_TYPE => 'tags',
541 ApiBase::PARAM_ISMULTI => true,
542 ],
543 'minor' => false,
544 'notminor' => false,
545 'bot' => false,
546 'basetimestamp' => [
547 ApiBase::PARAM_TYPE => 'timestamp',
548 ],
549 'starttimestamp' => [
550 ApiBase::PARAM_TYPE => 'timestamp',
551 ],
552 'recreate' => false,
553 'createonly' => false,
554 'nocreate' => false,
555 'watch' => [
556 ApiBase::PARAM_DFLT => false,
557 ApiBase::PARAM_DEPRECATED => true,
558 ],
559 'unwatch' => [
560 ApiBase::PARAM_DFLT => false,
561 ApiBase::PARAM_DEPRECATED => true,
562 ],
563 'watchlist' => [
564 ApiBase::PARAM_DFLT => 'preferences',
565 ApiBase::PARAM_TYPE => [
566 'watch',
567 'unwatch',
568 'preferences',
569 'nochange'
570 ],
571 ],
572 'md5' => null,
573 'prependtext' => [
574 ApiBase::PARAM_TYPE => 'text',
575 ],
576 'appendtext' => [
577 ApiBase::PARAM_TYPE => 'text',
578 ],
579 'undo' => [
580 ApiBase::PARAM_TYPE => 'integer',
581 ApiBase::PARAM_MIN => 0,
582 ApiBase::PARAM_RANGE_ENFORCE => true,
583 ],
584 'undoafter' => [
585 ApiBase::PARAM_TYPE => 'integer',
586 ApiBase::PARAM_MIN => 0,
587 ApiBase::PARAM_RANGE_ENFORCE => true,
588 ],
589 'redirect' => [
590 ApiBase::PARAM_TYPE => 'boolean',
591 ApiBase::PARAM_DFLT => false,
592 ],
593 'contentformat' => [
594 ApiBase::PARAM_TYPE => ContentHandler::getAllContentFormats(),
595 ],
596 'contentmodel' => [
597 ApiBase::PARAM_TYPE => ContentHandler::getContentModels(),
598 ],
599 'token' => [
600 // Standard definition automatically inserted
601 ApiBase::PARAM_HELP_MSG_APPEND => [ 'apihelp-edit-param-token' ],
602 ],
603 ];
604 }
605
606 public function needsToken() {
607 return 'csrf';
608 }
609
610 protected function getExamplesMessages() {
611 return [
612 'action=edit&title=Test&summary=test%20summary&' .
613 'text=article%20content&basetimestamp=2007-08-24T12:34:54Z&token=123ABC'
614 => 'apihelp-edit-example-edit',
615 'action=edit&title=Test&summary=NOTOC&minor=&' .
616 'prependtext=__NOTOC__%0A&basetimestamp=2007-08-24T12:34:54Z&token=123ABC'
617 => 'apihelp-edit-example-prepend',
618 'action=edit&title=Test&undo=13585&undoafter=13579&' .
619 'basetimestamp=2007-08-24T12:34:54Z&token=123ABC'
620 => 'apihelp-edit-example-undo',
621 ];
622 }
623
624 public function getHelpUrls() {
625 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Edit';
626 }
627 }