Merge "Add CollationFa"
[lhc/web/wiklou.git] / includes / api / ApiEditPage.php
1 <?php
2 /**
3 *
4 *
5 * Created on August 16, 2007
6 *
7 * Copyright © 2007 Iker Labarga "<Firstname><Lastname>@gmail.com"
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * http://www.gnu.org/copyleft/gpl.html
23 *
24 * @file
25 */
26
27 /**
28 * A module that allows for editing and creating pages.
29 *
30 * Currently, this wraps around the EditPage class in an ugly way,
31 * EditPage.php should be rewritten to provide a cleaner interface,
32 * see T20654 if you're inspired to fix this.
33 *
34 * @ingroup API
35 */
36 class ApiEditPage extends ApiBase {
37 public function execute() {
38 $this->useTransactionalTimeLimit();
39
40 $user = $this->getUser();
41 $params = $this->extractRequestParams();
42
43 $this->requireAtLeastOneParameter( $params, 'text', 'appendtext', 'prependtext', 'undo' );
44
45 $pageObj = $this->getTitleOrPageId( $params );
46 $titleObj = $pageObj->getTitle();
47 $apiResult = $this->getResult();
48
49 if ( $params['redirect'] ) {
50 if ( $params['prependtext'] === null && $params['appendtext'] === null
51 && $params['section'] !== 'new'
52 ) {
53 $this->dieWithError( 'apierror-redirect-appendonly' );
54 }
55 if ( $titleObj->isRedirect() ) {
56 $oldTitle = $titleObj;
57
58 $titles = Revision::newFromTitle( $oldTitle, false, Revision::READ_LATEST )
59 ->getContent( Revision::FOR_THIS_USER, $user )
60 ->getRedirectChain();
61 // array_shift( $titles );
62
63 $redirValues = [];
64
65 /** @var $newTitle Title */
66 foreach ( $titles as $id => $newTitle ) {
67
68 if ( !isset( $titles[$id - 1] ) ) {
69 $titles[$id - 1] = $oldTitle;
70 }
71
72 $redirValues[] = [
73 'from' => $titles[$id - 1]->getPrefixedText(),
74 'to' => $newTitle->getPrefixedText()
75 ];
76
77 $titleObj = $newTitle;
78 }
79
80 ApiResult::setIndexedTagName( $redirValues, 'r' );
81 $apiResult->addValue( null, 'redirects', $redirValues );
82
83 // Since the page changed, update $pageObj
84 $pageObj = WikiPage::factory( $titleObj );
85 }
86 }
87
88 if ( !isset( $params['contentmodel'] ) || $params['contentmodel'] == '' ) {
89 $contentHandler = $pageObj->getContentHandler();
90 } else {
91 $contentHandler = ContentHandler::getForModelID( $params['contentmodel'] );
92 }
93 $contentModel = $contentHandler->getModelID();
94
95 $name = $titleObj->getPrefixedDBkey();
96 $model = $contentHandler->getModelID();
97
98 if ( $params['undo'] > 0 ) {
99 // allow undo via api
100 } elseif ( $contentHandler->supportsDirectApiEditing() === false ) {
101 $this->dieWithError( [ 'apierror-no-direct-editing', $model, $name ] );
102 }
103
104 if ( !isset( $params['contentformat'] ) || $params['contentformat'] == '' ) {
105 $contentFormat = $contentHandler->getDefaultFormat();
106 } else {
107 $contentFormat = $params['contentformat'];
108 }
109
110 if ( !$contentHandler->isSupportedFormat( $contentFormat ) ) {
111 $this->dieWithError( [ 'apierror-badformat', $contentFormat, $model, $name ] );
112 }
113
114 if ( $params['createonly'] && $titleObj->exists() ) {
115 $this->dieWithError( 'apierror-articleexists' );
116 }
117 if ( $params['nocreate'] && !$titleObj->exists() ) {
118 $this->dieWithError( 'apierror-missingtitle' );
119 }
120
121 // Now let's check whether we're even allowed to do this
122 $this->checkTitleUserPermissions(
123 $titleObj,
124 $titleObj->exists() ? 'edit' : [ 'edit', 'create' ]
125 );
126
127 $toMD5 = $params['text'];
128 if ( !is_null( $params['appendtext'] ) || !is_null( $params['prependtext'] ) ) {
129 $content = $pageObj->getContent();
130
131 if ( !$content ) {
132 if ( $titleObj->getNamespace() == NS_MEDIAWIKI ) {
133 # If this is a MediaWiki:x message, then load the messages
134 # and return the message value for x.
135 $text = $titleObj->getDefaultMessageText();
136 if ( $text === false ) {
137 $text = '';
138 }
139
140 try {
141 $content = ContentHandler::makeContent( $text, $this->getTitle() );
142 } catch ( MWContentSerializationException $ex ) {
143 // @todo: Internationalize MWContentSerializationException
144 $this->dieWithError(
145 [ 'apierror-contentserializationexception', wfEscapeWikiText( $ex->getMessage() ) ],
146 'parseerror'
147 );
148 return;
149 }
150 } else {
151 # Otherwise, make a new empty content.
152 $content = $contentHandler->makeEmptyContent();
153 }
154 }
155
156 // @todo Add support for appending/prepending to the Content interface
157
158 if ( !( $content instanceof TextContent ) ) {
159 $modelName = $contentHandler->getModelID();
160 $this->dieWithError( [ 'apierror-appendnotsupported', $modelName ] );
161 }
162
163 if ( !is_null( $params['section'] ) ) {
164 if ( !$contentHandler->supportsSections() ) {
165 $modelName = $contentHandler->getModelID();
166 $this->dieWithError( [ 'apierror-sectionsnotsupported', $modelName ] );
167 }
168
169 if ( $params['section'] == 'new' ) {
170 // DWIM if they're trying to prepend/append to a new section.
171 $content = null;
172 } else {
173 // Process the content for section edits
174 $section = $params['section'];
175 $content = $content->getSection( $section );
176
177 if ( !$content ) {
178 $this->dieWithError( [ 'apierror-nosuchsection', wfEscapeWikiText( $section ) ] );
179 }
180 }
181 }
182
183 if ( !$content ) {
184 $text = '';
185 } else {
186 $text = $content->serialize( $contentFormat );
187 }
188
189 $params['text'] = $params['prependtext'] . $text . $params['appendtext'];
190 $toMD5 = $params['prependtext'] . $params['appendtext'];
191 }
192
193 if ( $params['undo'] > 0 ) {
194 if ( $params['undoafter'] > 0 ) {
195 if ( $params['undo'] < $params['undoafter'] ) {
196 list( $params['undo'], $params['undoafter'] ) =
197 [ $params['undoafter'], $params['undo'] ];
198 }
199 $undoafterRev = Revision::newFromId( $params['undoafter'] );
200 }
201 $undoRev = Revision::newFromId( $params['undo'] );
202 if ( is_null( $undoRev ) || $undoRev->isDeleted( Revision::DELETED_TEXT ) ) {
203 $this->dieWithError( [ 'apierror-nosuchrevid', $params['undo'] ] );
204 }
205
206 if ( $params['undoafter'] == 0 ) {
207 $undoafterRev = $undoRev->getPrevious();
208 }
209 if ( is_null( $undoafterRev ) || $undoafterRev->isDeleted( Revision::DELETED_TEXT ) ) {
210 $this->dieWithError( [ 'apierror-nosuchrevid', $params['undoafter'] ] );
211 }
212
213 if ( $undoRev->getPage() != $pageObj->getId() ) {
214 $this->dieWithError( [ 'apierror-revwrongpage', $undoRev->getId(),
215 $titleObj->getPrefixedText() ] );
216 }
217 if ( $undoafterRev->getPage() != $pageObj->getId() ) {
218 $this->dieWithError( [ 'apierror-revwrongpage', $undoafterRev->getId(),
219 $titleObj->getPrefixedText() ] );
220 }
221
222 $newContent = $contentHandler->getUndoContent(
223 $pageObj->getRevision(),
224 $undoRev,
225 $undoafterRev
226 );
227
228 if ( !$newContent ) {
229 $this->dieWithError( 'undo-failure', 'undofailure' );
230 }
231 if ( empty( $params['contentmodel'] )
232 && empty( $params['contentformat'] )
233 ) {
234 // If we are reverting content model, the new content model
235 // might not support the current serialization format, in
236 // which case go back to the old serialization format,
237 // but only if the user hasn't specified a format/model
238 // parameter.
239 if ( !$newContent->isSupportedFormat( $contentFormat ) ) {
240 $contentFormat = $undoafterRev->getContentFormat();
241 }
242 // Override content model with model of undid revision.
243 $contentModel = $newContent->getModel();
244 }
245 $params['text'] = $newContent->serialize( $contentFormat );
246 // If no summary was given and we only undid one rev,
247 // use an autosummary
248 if ( is_null( $params['summary'] ) &&
249 $titleObj->getNextRevisionID( $undoafterRev->getId() ) == $params['undo']
250 ) {
251 $params['summary'] = wfMessage( 'undo-summary' )
252 ->params( $params['undo'], $undoRev->getUserText() )->inContentLanguage()->text();
253 }
254 }
255
256 // See if the MD5 hash checks out
257 if ( !is_null( $params['md5'] ) && md5( $toMD5 ) !== $params['md5'] ) {
258 $this->dieWithError( 'apierror-badmd5' );
259 }
260
261 // EditPage wants to parse its stuff from a WebRequest
262 // That interface kind of sucks, but it's workable
263 $requestArray = [
264 'wpTextbox1' => $params['text'],
265 'format' => $contentFormat,
266 'model' => $contentModel,
267 'wpEditToken' => $params['token'],
268 'wpIgnoreBlankSummary' => true,
269 'wpIgnoreBlankArticle' => true,
270 'wpIgnoreSelfRedirect' => true,
271 'bot' => $params['bot'],
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 ( count( $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 $articleObject Article */
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 // Run hooks
376 // Handle APIEditBeforeSave parameters
377 $r = [];
378 // Deprecated in favour of EditFilterMergedContent
379 if ( !Hooks::run( 'APIEditBeforeSave', [ $ep, $content, &$r ], '1.28' ) ) {
380 if ( count( $r ) ) {
381 $r['result'] = 'Failure';
382 $apiResult->addValue( null, $this->getModuleName(), $r );
383
384 return;
385 }
386
387 $this->dieWithError( 'hookaborted' );
388 }
389
390 // Do the actual save
391 $oldRevId = $articleObject->getRevIdFetched();
392 $result = null;
393 // Fake $wgRequest for some hooks inside EditPage
394 // @todo FIXME: This interface SUCKS
395 $oldRequest = $wgRequest;
396 $wgRequest = $req;
397
398 $status = $ep->attemptSave( $result );
399 $wgRequest = $oldRequest;
400
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 $status->fatal( 'hookaborted' );
412 }
413 $this->dieStatus( $status );
414
415 case EditPage::AS_BLOCKED_PAGE_FOR_USER:
416 $this->dieWithError(
417 'apierror-blocked',
418 'blocked',
419 [ 'blockinfo' => ApiQueryUserInfo::getBlockInfo( $user->getBlock() ) ]
420 );
421
422 case EditPage::AS_READ_ONLY_PAGE:
423 $this->dieReadOnly();
424
425 case EditPage::AS_SUCCESS_NEW_ARTICLE:
426 $r['new'] = true;
427 // fall-through
428
429 case EditPage::AS_SUCCESS_UPDATE:
430 $r['result'] = 'Success';
431 $r['pageid'] = intval( $titleObj->getArticleID() );
432 $r['title'] = $titleObj->getPrefixedText();
433 $r['contentmodel'] = $articleObject->getContentModel();
434 $newRevId = $articleObject->getLatest();
435 if ( $newRevId == $oldRevId ) {
436 $r['nochange'] = true;
437 } else {
438 $r['oldrevid'] = intval( $oldRevId );
439 $r['newrevid'] = intval( $newRevId );
440 $r['newtimestamp'] = wfTimestamp( TS_ISO_8601,
441 $pageObj->getTimestamp() );
442 }
443 break;
444
445 default:
446 // EditPage sometimes only sets the status code without setting
447 // any actual error messages. Supply defaults for those cases.
448 $maxArticleSize = $this->getConfig()->get( 'MaxArticleSize' );
449 $defaultMessages = [
450 // Currently needed
451 EditPage::AS_IMAGE_REDIRECT_ANON => [ 'apierror-noimageredirect-anon' ],
452 EditPage::AS_IMAGE_REDIRECT_LOGGED => [ 'apierror-noimageredirect-logged' ],
453 EditPage::AS_CONTENT_TOO_BIG => [ 'apierror-contenttoobig', $maxArticleSize ],
454 EditPage::AS_MAX_ARTICLE_SIZE_EXCEEDED => [ 'apierror-contenttoobig', $maxArticleSize ],
455 EditPage::AS_READ_ONLY_PAGE_ANON => [ 'apierror-noedit-anon' ],
456 EditPage::AS_NO_CHANGE_CONTENT_MODEL => [ 'apierror-cantchangecontentmodel' ],
457 EditPage::AS_ARTICLE_WAS_DELETED => [ 'apierror-pagedeleted' ],
458 EditPage::AS_CONFLICT_DETECTED => [ 'editconflict' ],
459
460 // Currently shouldn't be needed
461 EditPage::AS_SPAM_ERROR => [ 'apierror-spamdetected', wfEscapeWikiText( $result['spam'] ) ],
462 EditPage::AS_READ_ONLY_PAGE_LOGGED => [ 'apierror-noedit' ],
463 EditPage::AS_RATE_LIMITED => [ 'apierror-ratelimited' ],
464 EditPage::AS_NO_CREATE_PERMISSION => [ 'nocreate-loggedin' ],
465 EditPage::AS_BLANK_ARTICLE => [ 'apierror-emptypage' ],
466 EditPage::AS_TEXTBOX_EMPTY => [ 'apierror-emptynewsection' ],
467 EditPage::AS_SUMMARY_NEEDED => [ 'apierror-summaryrequired' ],
468 ];
469 if ( !$status->getErrors() ) {
470 if ( isset( $defaultMessages[$status->value] ) ) {
471 call_user_func_array( [ $status, 'fatal' ], $defaultMessages[$status->value] );
472 } else {
473 wfWarn( __METHOD__ . ": Unknown EditPage code {$status->value} with no message" );
474 $status->fatal( 'apierror-unknownerror-editpage', $status->value );
475 }
476 }
477 $this->dieStatus( $status );
478 break;
479 }
480 $apiResult->addValue( null, $this->getModuleName(), $r );
481 }
482
483 public function mustBePosted() {
484 return true;
485 }
486
487 public function isWriteMode() {
488 return true;
489 }
490
491 public function getAllowedParams() {
492 return [
493 'title' => [
494 ApiBase::PARAM_TYPE => 'string',
495 ],
496 'pageid' => [
497 ApiBase::PARAM_TYPE => 'integer',
498 ],
499 'section' => null,
500 'sectiontitle' => [
501 ApiBase::PARAM_TYPE => 'string',
502 ],
503 'text' => [
504 ApiBase::PARAM_TYPE => 'text',
505 ],
506 'summary' => null,
507 'tags' => [
508 ApiBase::PARAM_TYPE => 'tags',
509 ApiBase::PARAM_ISMULTI => true,
510 ],
511 'minor' => false,
512 'notminor' => false,
513 'bot' => false,
514 'basetimestamp' => [
515 ApiBase::PARAM_TYPE => 'timestamp',
516 ],
517 'starttimestamp' => [
518 ApiBase::PARAM_TYPE => 'timestamp',
519 ],
520 'recreate' => false,
521 'createonly' => false,
522 'nocreate' => false,
523 'watch' => [
524 ApiBase::PARAM_DFLT => false,
525 ApiBase::PARAM_DEPRECATED => true,
526 ],
527 'unwatch' => [
528 ApiBase::PARAM_DFLT => false,
529 ApiBase::PARAM_DEPRECATED => true,
530 ],
531 'watchlist' => [
532 ApiBase::PARAM_DFLT => 'preferences',
533 ApiBase::PARAM_TYPE => [
534 'watch',
535 'unwatch',
536 'preferences',
537 'nochange'
538 ],
539 ],
540 'md5' => null,
541 'prependtext' => [
542 ApiBase::PARAM_TYPE => 'text',
543 ],
544 'appendtext' => [
545 ApiBase::PARAM_TYPE => 'text',
546 ],
547 'undo' => [
548 ApiBase::PARAM_TYPE => 'integer'
549 ],
550 'undoafter' => [
551 ApiBase::PARAM_TYPE => 'integer'
552 ],
553 'redirect' => [
554 ApiBase::PARAM_TYPE => 'boolean',
555 ApiBase::PARAM_DFLT => false,
556 ],
557 'contentformat' => [
558 ApiBase::PARAM_TYPE => ContentHandler::getAllContentFormats(),
559 ],
560 'contentmodel' => [
561 ApiBase::PARAM_TYPE => ContentHandler::getContentModels(),
562 ],
563 'token' => [
564 // Standard definition automatically inserted
565 ApiBase::PARAM_HELP_MSG_APPEND => [ 'apihelp-edit-param-token' ],
566 ],
567 ];
568 }
569
570 public function needsToken() {
571 return 'csrf';
572 }
573
574 protected function getExamplesMessages() {
575 return [
576 'action=edit&title=Test&summary=test%20summary&' .
577 'text=article%20content&basetimestamp=2007-08-24T12:34:54Z&token=123ABC'
578 => 'apihelp-edit-example-edit',
579 'action=edit&title=Test&summary=NOTOC&minor=&' .
580 'prependtext=__NOTOC__%0A&basetimestamp=2007-08-24T12:34:54Z&token=123ABC'
581 => 'apihelp-edit-example-prepend',
582 'action=edit&title=Test&undo=13585&undoafter=13579&' .
583 'basetimestamp=2007-08-24T12:34:54Z&token=123ABC'
584 => 'apihelp-edit-example-undo',
585 ];
586 }
587
588 public function getHelpUrls() {
589 return 'https://www.mediawiki.org/wiki/API:Edit';
590 }
591 }