Use (int) rather than intval()
[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 // Run hooks
371 // Handle APIEditBeforeSave parameters
372 $r = [];
373 // Deprecated in favour of EditFilterMergedContent
374 if ( !Hooks::run( 'APIEditBeforeSave', [ $ep, $content, &$r ], '1.28' ) ) {
375 if ( count( $r ) ) {
376 $r['result'] = 'Failure';
377 $apiResult->addValue( null, $this->getModuleName(), $r );
378
379 return;
380 }
381
382 $this->dieWithError( 'hookaborted' );
383 }
384
385 // Do the actual save
386 $oldRevId = $articleObject->getRevIdFetched();
387 $result = null;
388 // Fake $wgRequest for some hooks inside EditPage
389 // @todo FIXME: This interface SUCKS
390 $oldRequest = $wgRequest;
391 $wgRequest = $req;
392
393 $status = $ep->attemptSave( $result );
394 $wgRequest = $oldRequest;
395
396 switch ( $status->value ) {
397 case EditPage::AS_HOOK_ERROR:
398 case EditPage::AS_HOOK_ERROR_EXPECTED:
399 if ( isset( $status->apiHookResult ) ) {
400 $r = $status->apiHookResult;
401 $r['result'] = 'Failure';
402 $apiResult->addValue( null, $this->getModuleName(), $r );
403 return;
404 }
405 if ( !$status->getErrors() ) {
406 // This appears to be unreachable right now, because all
407 // code paths will set an error. Could change, though.
408 $status->fatal( 'hookaborted' ); //@codeCoverageIgnore
409 }
410 $this->dieStatus( $status );
411
412 // These two cases will normally have been caught earlier, and will
413 // only occur if something blocks the user between the earlier
414 // check and the check in EditPage (presumably a hook). It's not
415 // obvious that this is even possible.
416 // @codeCoverageIgnoreStart
417 case EditPage::AS_BLOCKED_PAGE_FOR_USER:
418 $this->dieBlocked( $user->getBlock() );
419
420 case EditPage::AS_READ_ONLY_PAGE:
421 $this->dieReadOnly();
422 // @codeCoverageIgnoreEnd
423
424 case EditPage::AS_SUCCESS_NEW_ARTICLE:
425 $r['new'] = true;
426 // fall-through
427
428 case EditPage::AS_SUCCESS_UPDATE:
429 $r['result'] = 'Success';
430 $r['pageid'] = (int)$titleObj->getArticleID();
431 $r['title'] = $titleObj->getPrefixedText();
432 $r['contentmodel'] = $articleObject->getContentModel();
433 $newRevId = $articleObject->getLatest();
434 if ( $newRevId == $oldRevId ) {
435 $r['nochange'] = true;
436 } else {
437 $r['oldrevid'] = (int)$oldRevId;
438 $r['newrevid'] = (int)$newRevId;
439 $r['newtimestamp'] = wfTimestamp( TS_ISO_8601,
440 $pageObj->getTimestamp() );
441 }
442 break;
443
444 default:
445 if ( !$status->getErrors() ) {
446 // EditPage sometimes only sets the status code without setting
447 // any actual error messages. Supply defaults for those cases.
448 switch ( $status->value ) {
449 // Currently needed
450 case EditPage::AS_IMAGE_REDIRECT_ANON:
451 $status->fatal( 'apierror-noimageredirect-anon' );
452 break;
453 case EditPage::AS_IMAGE_REDIRECT_LOGGED:
454 $status->fatal( 'apierror-noimageredirect' );
455 break;
456 case EditPage::AS_CONTENT_TOO_BIG:
457 case EditPage::AS_MAX_ARTICLE_SIZE_EXCEEDED:
458 $status->fatal( 'apierror-contenttoobig', $this->getConfig()->get( 'MaxArticleSize' ) );
459 break;
460 case EditPage::AS_READ_ONLY_PAGE_ANON:
461 $status->fatal( 'apierror-noedit-anon' );
462 break;
463 case EditPage::AS_NO_CHANGE_CONTENT_MODEL:
464 $status->fatal( 'apierror-cantchangecontentmodel' );
465 break;
466 case EditPage::AS_ARTICLE_WAS_DELETED:
467 $status->fatal( 'apierror-pagedeleted' );
468 break;
469 case EditPage::AS_CONFLICT_DETECTED:
470 $status->fatal( 'editconflict' );
471 break;
472
473 // Currently shouldn't be needed, but here in case
474 // hooks use them without setting appropriate
475 // errors on the status.
476 // @codeCoverageIgnoreStart
477 case EditPage::AS_SPAM_ERROR:
478 $status->fatal( 'apierror-spamdetected', $result['spam'] );
479 break;
480 case EditPage::AS_READ_ONLY_PAGE_LOGGED:
481 $status->fatal( 'apierror-noedit' );
482 break;
483 case EditPage::AS_RATE_LIMITED:
484 $status->fatal( 'apierror-ratelimited' );
485 break;
486 case EditPage::AS_NO_CREATE_PERMISSION:
487 $status->fatal( 'nocreate-loggedin' );
488 break;
489 case EditPage::AS_BLANK_ARTICLE:
490 $status->fatal( 'apierror-emptypage' );
491 break;
492 case EditPage::AS_TEXTBOX_EMPTY:
493 $status->fatal( 'apierror-emptynewsection' );
494 break;
495 case EditPage::AS_SUMMARY_NEEDED:
496 $status->fatal( 'apierror-summaryrequired' );
497 break;
498 default:
499 wfWarn( __METHOD__ . ": Unknown EditPage code {$status->value} with no message" );
500 $status->fatal( 'apierror-unknownerror-editpage', $status->value );
501 break;
502 // @codeCoverageIgnoreEnd
503 }
504 }
505 $this->dieStatus( $status );
506 }
507 $apiResult->addValue( null, $this->getModuleName(), $r );
508 }
509
510 public function mustBePosted() {
511 return true;
512 }
513
514 public function isWriteMode() {
515 return true;
516 }
517
518 public function getAllowedParams() {
519 return [
520 'title' => [
521 ApiBase::PARAM_TYPE => 'string',
522 ],
523 'pageid' => [
524 ApiBase::PARAM_TYPE => 'integer',
525 ],
526 'section' => null,
527 'sectiontitle' => [
528 ApiBase::PARAM_TYPE => 'string',
529 ],
530 'text' => [
531 ApiBase::PARAM_TYPE => 'text',
532 ],
533 'summary' => null,
534 'tags' => [
535 ApiBase::PARAM_TYPE => 'tags',
536 ApiBase::PARAM_ISMULTI => true,
537 ],
538 'minor' => false,
539 'notminor' => false,
540 'bot' => false,
541 'basetimestamp' => [
542 ApiBase::PARAM_TYPE => 'timestamp',
543 ],
544 'starttimestamp' => [
545 ApiBase::PARAM_TYPE => 'timestamp',
546 ],
547 'recreate' => false,
548 'createonly' => false,
549 'nocreate' => false,
550 'watch' => [
551 ApiBase::PARAM_DFLT => false,
552 ApiBase::PARAM_DEPRECATED => true,
553 ],
554 'unwatch' => [
555 ApiBase::PARAM_DFLT => false,
556 ApiBase::PARAM_DEPRECATED => true,
557 ],
558 'watchlist' => [
559 ApiBase::PARAM_DFLT => 'preferences',
560 ApiBase::PARAM_TYPE => [
561 'watch',
562 'unwatch',
563 'preferences',
564 'nochange'
565 ],
566 ],
567 'md5' => null,
568 'prependtext' => [
569 ApiBase::PARAM_TYPE => 'text',
570 ],
571 'appendtext' => [
572 ApiBase::PARAM_TYPE => 'text',
573 ],
574 'undo' => [
575 ApiBase::PARAM_TYPE => 'integer',
576 ApiBase::PARAM_MIN => 0,
577 ApiBase::PARAM_RANGE_ENFORCE => true,
578 ],
579 'undoafter' => [
580 ApiBase::PARAM_TYPE => 'integer',
581 ApiBase::PARAM_MIN => 0,
582 ApiBase::PARAM_RANGE_ENFORCE => true,
583 ],
584 'redirect' => [
585 ApiBase::PARAM_TYPE => 'boolean',
586 ApiBase::PARAM_DFLT => false,
587 ],
588 'contentformat' => [
589 ApiBase::PARAM_TYPE => ContentHandler::getAllContentFormats(),
590 ],
591 'contentmodel' => [
592 ApiBase::PARAM_TYPE => ContentHandler::getContentModels(),
593 ],
594 'token' => [
595 // Standard definition automatically inserted
596 ApiBase::PARAM_HELP_MSG_APPEND => [ 'apihelp-edit-param-token' ],
597 ],
598 ];
599 }
600
601 public function needsToken() {
602 return 'csrf';
603 }
604
605 protected function getExamplesMessages() {
606 return [
607 'action=edit&title=Test&summary=test%20summary&' .
608 'text=article%20content&basetimestamp=2007-08-24T12:34:54Z&token=123ABC'
609 => 'apihelp-edit-example-edit',
610 'action=edit&title=Test&summary=NOTOC&minor=&' .
611 'prependtext=__NOTOC__%0A&basetimestamp=2007-08-24T12:34:54Z&token=123ABC'
612 => 'apihelp-edit-example-prepend',
613 'action=edit&title=Test&undo=13585&undoafter=13579&' .
614 'basetimestamp=2007-08-24T12:34:54Z&token=123ABC'
615 => 'apihelp-edit-example-undo',
616 ];
617 }
618
619 public function getHelpUrls() {
620 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Edit';
621 }
622 }