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