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