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