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