90d976a53ed58c8ecc819914e3a71a847d733b39
[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 if ( is_null( $params['text'] ) && is_null( $params['appendtext'] ) &&
44 is_null( $params['prependtext'] ) &&
45 $params['undo'] == 0
46 ) {
47 $this->dieUsageMsg( 'missingtext' );
48 }
49
50 $pageObj = $this->getTitleOrPageId( $params );
51 $titleObj = $pageObj->getTitle();
52 $apiResult = $this->getResult();
53
54 if ( $params['redirect'] ) {
55 if ( $params['prependtext'] === null && $params['appendtext'] === null
56 && $params['section'] !== 'new'
57 ) {
58 $this->dieUsage( 'You have attempted to edit using the "redirect"-following'
59 . ' mode, which must be used in conjuction with section=new, prependtext'
60 . ', or appendtext.', 'redirect-appendonly' );
61 }
62 if ( $titleObj->isRedirect() ) {
63 $oldTitle = $titleObj;
64
65 $titles = Revision::newFromTitle( $oldTitle, false, Revision::READ_LATEST )
66 ->getContent( Revision::FOR_THIS_USER, $user )
67 ->getRedirectChain();
68 // array_shift( $titles );
69
70 $redirValues = array();
71
72 /** @var $newTitle Title */
73 foreach ( $titles as $id => $newTitle ) {
74
75 if ( !isset( $titles[$id - 1] ) ) {
76 $titles[$id - 1] = $oldTitle;
77 }
78
79 $redirValues[] = array(
80 'from' => $titles[$id - 1]->getPrefixedText(),
81 'to' => $newTitle->getPrefixedText()
82 );
83
84 $titleObj = $newTitle;
85 }
86
87 ApiResult::setIndexedTagName( $redirValues, 'r' );
88 $apiResult->addValue( null, 'redirects', $redirValues );
89
90 // Since the page changed, update $pageObj
91 $pageObj = WikiPage::factory( $titleObj );
92 }
93 }
94
95 if ( !isset( $params['contentmodel'] ) || $params['contentmodel'] == '' ) {
96 $contentHandler = $pageObj->getContentHandler();
97 } else {
98 $contentHandler = ContentHandler::getForModelID( $params['contentmodel'] );
99 }
100
101 $name = $titleObj->getPrefixedDBkey();
102 $model = $contentHandler->getModelID();
103 if ( $contentHandler->supportsDirectApiEditing() === false ) {
104 $this->dieUsage(
105 "Direct editing via API is not supported for content model $model used by $name",
106 'no-direct-editing'
107 );
108 }
109
110 if ( !isset( $params['contentformat'] ) || $params['contentformat'] == '' ) {
111 $params['contentformat'] = $contentHandler->getDefaultFormat();
112 }
113
114 $contentFormat = $params['contentformat'];
115
116 if ( !$contentHandler->isSupportedFormat( $contentFormat ) ) {
117
118 $this->dieUsage( "The requested format $contentFormat is not supported for content model " .
119 " $model used by $name", 'badformat' );
120 }
121
122 if ( $params['createonly'] && $titleObj->exists() ) {
123 $this->dieUsageMsg( 'createonly-exists' );
124 }
125 if ( $params['nocreate'] && !$titleObj->exists() ) {
126 $this->dieUsageMsg( 'nocreate-missing' );
127 }
128
129 // Now let's check whether we're even allowed to do this
130 $errors = $titleObj->getUserPermissionsErrors( 'edit', $user );
131 if ( !$titleObj->exists() ) {
132 $errors = array_merge( $errors, $titleObj->getUserPermissionsErrors( 'create', $user ) );
133 }
134 if ( count( $errors ) ) {
135 if ( is_array( $errors[0] ) ) {
136 switch ( $errors[0][0] ) {
137 case 'blockedtext':
138 $this->dieUsage(
139 'You have been blocked from editing',
140 'blocked',
141 0,
142 array( 'blockinfo' => ApiQueryUserInfo::getBlockInfo( $user->getBlock() ) )
143 );
144 break;
145 case 'autoblockedtext':
146 $this->dieUsage(
147 'Your IP address has been blocked automatically, because it was used by a blocked user',
148 'autoblocked',
149 0,
150 array( 'blockinfo' => ApiQueryUserInfo::getBlockInfo( $user->getBlock() ) )
151 );
152 break;
153 default:
154 $this->dieUsageMsg( $errors[0] );
155 }
156 } else {
157 $this->dieUsageMsg( $errors[0] );
158 }
159 }
160
161 $toMD5 = $params['text'];
162 if ( !is_null( $params['appendtext'] ) || !is_null( $params['prependtext'] ) ) {
163 $content = $pageObj->getContent();
164
165 if ( !$content ) {
166 if ( $titleObj->getNamespace() == NS_MEDIAWIKI ) {
167 # If this is a MediaWiki:x message, then load the messages
168 # and return the message value for x.
169 $text = $titleObj->getDefaultMessageText();
170 if ( $text === false ) {
171 $text = '';
172 }
173
174 try {
175 $content = ContentHandler::makeContent( $text, $this->getTitle() );
176 } catch ( MWContentSerializationException $ex ) {
177 $this->dieUsage( $ex->getMessage(), 'parseerror' );
178
179 return;
180 }
181 } else {
182 # Otherwise, make a new empty content.
183 $content = $contentHandler->makeEmptyContent();
184 }
185 }
186
187 // @todo Add support for appending/prepending to the Content interface
188
189 if ( !( $content instanceof TextContent ) ) {
190 $mode = $contentHandler->getModelID();
191 $this->dieUsage( "Can't append to pages using content model $mode", 'appendnotsupported' );
192 }
193
194 if ( !is_null( $params['section'] ) ) {
195 if ( !$contentHandler->supportsSections() ) {
196 $modelName = $contentHandler->getModelID();
197 $this->dieUsage(
198 "Sections are not supported for this content model: $modelName.",
199 'sectionsnotsupported'
200 );
201 }
202
203 if ( $params['section'] == 'new' ) {
204 // DWIM if they're trying to prepend/append to a new section.
205 $content = null;
206 } else {
207 // Process the content for section edits
208 $section = $params['section'];
209 $content = $content->getSection( $section );
210
211 if ( !$content ) {
212 $this->dieUsage( "There is no section {$section}.", 'nosuchsection' );
213 }
214 }
215 }
216
217 if ( !$content ) {
218 $text = '';
219 } else {
220 $text = $content->serialize( $contentFormat );
221 }
222
223 $params['text'] = $params['prependtext'] . $text . $params['appendtext'];
224 $toMD5 = $params['prependtext'] . $params['appendtext'];
225 }
226
227 if ( $params['undo'] > 0 ) {
228 if ( $params['undoafter'] > 0 ) {
229 if ( $params['undo'] < $params['undoafter'] ) {
230 list( $params['undo'], $params['undoafter'] ) =
231 array( $params['undoafter'], $params['undo'] );
232 }
233 $undoafterRev = Revision::newFromId( $params['undoafter'] );
234 }
235 $undoRev = Revision::newFromId( $params['undo'] );
236 if ( is_null( $undoRev ) || $undoRev->isDeleted( Revision::DELETED_TEXT ) ) {
237 $this->dieUsageMsg( array( 'nosuchrevid', $params['undo'] ) );
238 }
239
240 if ( $params['undoafter'] == 0 ) {
241 $undoafterRev = $undoRev->getPrevious();
242 }
243 if ( is_null( $undoafterRev ) || $undoafterRev->isDeleted( Revision::DELETED_TEXT ) ) {
244 $this->dieUsageMsg( array( 'nosuchrevid', $params['undoafter'] ) );
245 }
246
247 if ( $undoRev->getPage() != $pageObj->getID() ) {
248 $this->dieUsageMsg( array( 'revwrongpage', $undoRev->getID(),
249 $titleObj->getPrefixedText() ) );
250 }
251 if ( $undoafterRev->getPage() != $pageObj->getID() ) {
252 $this->dieUsageMsg( array( 'revwrongpage', $undoafterRev->getID(),
253 $titleObj->getPrefixedText() ) );
254 }
255
256 $newContent = $contentHandler->getUndoContent(
257 $pageObj->getRevision(),
258 $undoRev,
259 $undoafterRev
260 );
261
262 if ( !$newContent ) {
263 $this->dieUsageMsg( 'undo-failure' );
264 }
265
266 $params['text'] = $newContent->serialize( $params['contentformat'] );
267
268 // If no summary was given and we only undid one rev,
269 // use an autosummary
270 if ( is_null( $params['summary'] ) &&
271 $titleObj->getNextRevisionID( $undoafterRev->getID() ) == $params['undo']
272 ) {
273 $params['summary'] = wfMessage( 'undo-summary' )
274 ->params( $params['undo'], $undoRev->getUserText() )->inContentLanguage()->text();
275 }
276 }
277
278 // See if the MD5 hash checks out
279 if ( !is_null( $params['md5'] ) && md5( $toMD5 ) !== $params['md5'] ) {
280 $this->dieUsageMsg( 'hashcheckfailed' );
281 }
282
283 // EditPage wants to parse its stuff from a WebRequest
284 // That interface kind of sucks, but it's workable
285 $requestArray = array(
286 'wpTextbox1' => $params['text'],
287 'format' => $contentFormat,
288 'model' => $contentHandler->getModelID(),
289 'wpEditToken' => $params['token'],
290 'wpIgnoreBlankSummary' => true,
291 'wpIgnoreBlankArticle' => true,
292 'wpIgnoreSelfRedirect' => true,
293 'bot' => $params['bot'],
294 );
295
296 if ( !is_null( $params['summary'] ) ) {
297 $requestArray['wpSummary'] = $params['summary'];
298 }
299
300 if ( !is_null( $params['sectiontitle'] ) ) {
301 $requestArray['wpSectionTitle'] = $params['sectiontitle'];
302 }
303
304 // TODO: Pass along information from 'undoafter' as well
305 if ( $params['undo'] > 0 ) {
306 $requestArray['wpUndidRevision'] = $params['undo'];
307 }
308
309 // Watch out for basetimestamp == '' or '0'
310 // It gets treated as NOW, almost certainly causing an edit conflict
311 if ( $params['basetimestamp'] !== null && (bool)$this->getMain()->getVal( 'basetimestamp' ) ) {
312 $requestArray['wpEdittime'] = $params['basetimestamp'];
313 } else {
314 $requestArray['wpEdittime'] = $pageObj->getTimestamp();
315 }
316
317 if ( $params['starttimestamp'] !== null ) {
318 $requestArray['wpStarttime'] = $params['starttimestamp'];
319 } else {
320 $requestArray['wpStarttime'] = wfTimestampNow(); // Fake wpStartime
321 }
322
323 if ( $params['minor'] || ( !$params['notminor'] && $user->getOption( 'minordefault' ) ) ) {
324 $requestArray['wpMinoredit'] = '';
325 }
326
327 if ( $params['recreate'] ) {
328 $requestArray['wpRecreate'] = '';
329 }
330
331 if ( !is_null( $params['section'] ) ) {
332 $section = $params['section'];
333 if ( !preg_match( '/^((T-)?\d+|new)$/', $section ) ) {
334 $this->dieUsage( "The section parameter must be a valid section id or 'new'",
335 "invalidsection" );
336 }
337 $content = $pageObj->getContent();
338 if ( $section !== '0' && $section != 'new'
339 && ( !$content || !$content->getSection( $section ) )
340 ) {
341 $this->dieUsage( "There is no section {$section}.", 'nosuchsection' );
342 }
343 $requestArray['wpSection'] = $params['section'];
344 } else {
345 $requestArray['wpSection'] = '';
346 }
347
348 $watch = $this->getWatchlistValue( $params['watchlist'], $titleObj );
349
350 // Deprecated parameters
351 if ( $params['watch'] ) {
352 $watch = true;
353 } elseif ( $params['unwatch'] ) {
354 $watch = false;
355 }
356
357 if ( $watch ) {
358 $requestArray['wpWatchthis'] = '';
359 }
360
361 // Apply change tags
362 if ( count( $params['tags'] ) ) {
363 if ( $user->isAllowed( 'applychangetags' ) ) {
364 $requestArray['wpChangeTags'] = implode( ',', $params['tags'] );
365 } else {
366 $this->dieUsage( 'You don\'t have permission to set change tags.', 'taggingnotallowed' );
367 }
368 }
369
370 // Pass through anything else we might have been given, to support extensions
371 // This is kind of a hack but it's the best we can do to make extensions work
372 $requestArray += $this->getRequest()->getValues();
373
374 global $wgTitle, $wgRequest;
375
376 $req = new DerivativeRequest( $this->getRequest(), $requestArray, true );
377
378 // Some functions depend on $wgTitle == $ep->mTitle
379 // TODO: Make them not or check if they still do
380 $wgTitle = $titleObj;
381
382 $articleContext = new RequestContext;
383 $articleContext->setRequest( $req );
384 $articleContext->setWikiPage( $pageObj );
385 $articleContext->setUser( $this->getUser() );
386
387 /** @var $articleObject Article */
388 $articleObject = Article::newFromWikiPage( $pageObj, $articleContext );
389
390 $ep = new EditPage( $articleObject );
391
392 $ep->setApiEditOverride( true );
393 $ep->setContextTitle( $titleObj );
394 $ep->importFormData( $req );
395 $content = $ep->textbox1;
396
397 // The following is needed to give the hook the full content of the
398 // new revision rather than just the current section. (Bug 52077)
399 if ( !is_null( $params['section'] ) &&
400 $contentHandler->supportsSections() && $titleObj->exists()
401 ) {
402 // If sectiontitle is set, use it, otherwise use the summary as the section title (for
403 // backwards compatibility with old forms/bots).
404 if ( $ep->sectiontitle !== '' ) {
405 $sectionTitle = $ep->sectiontitle;
406 } else {
407 $sectionTitle = $ep->summary;
408 }
409
410 $contentObj = $contentHandler->unserializeContent( $content, $contentFormat );
411
412 $fullContentObj = $articleObject->replaceSectionContent(
413 $params['section'],
414 $contentObj,
415 $sectionTitle
416 );
417 if ( $fullContentObj ) {
418 $content = $fullContentObj->serialize( $contentFormat );
419 } else {
420 // This most likely means we have an edit conflict which means that the edit
421 // wont succeed anyway.
422 $this->dieUsageMsg( 'editconflict' );
423 }
424 }
425
426 // Run hooks
427 // Handle APIEditBeforeSave parameters
428 $r = array();
429 if ( !Hooks::run( 'APIEditBeforeSave', array( $ep, $content, &$r ) ) ) {
430 if ( count( $r ) ) {
431 $r['result'] = 'Failure';
432 $apiResult->addValue( null, $this->getModuleName(), $r );
433
434 return;
435 }
436
437 $this->dieUsageMsg( 'hookaborted' );
438 }
439
440 // Do the actual save
441 $oldRevId = $articleObject->getRevIdFetched();
442 $result = null;
443 // Fake $wgRequest for some hooks inside EditPage
444 // @todo FIXME: This interface SUCKS
445 $oldRequest = $wgRequest;
446 $wgRequest = $req;
447
448 $status = $ep->attemptSave( $result );
449 $wgRequest = $oldRequest;
450
451 switch ( $status->value ) {
452 case EditPage::AS_HOOK_ERROR:
453 case EditPage::AS_HOOK_ERROR_EXPECTED:
454 if ( isset( $status->apiHookResult ) ) {
455 $r = $status->apiHookResult;
456 $r['result'] = 'Failure';
457 $apiResult->addValue( null, $this->getModuleName(), $r );
458 return;
459 } else {
460 $this->dieUsageMsg( 'hookaborted' );
461 }
462
463 case EditPage::AS_PARSE_ERROR:
464 $this->dieUsage( $status->getMessage(), 'parseerror' );
465
466 case EditPage::AS_IMAGE_REDIRECT_ANON:
467 $this->dieUsageMsg( 'noimageredirect-anon' );
468
469 case EditPage::AS_IMAGE_REDIRECT_LOGGED:
470 $this->dieUsageMsg( 'noimageredirect-logged' );
471
472 case EditPage::AS_SPAM_ERROR:
473 $this->dieUsageMsg( array( 'spamdetected', $result['spam'] ) );
474
475 case EditPage::AS_BLOCKED_PAGE_FOR_USER:
476 $this->dieUsage(
477 'You have been blocked from editing',
478 'blocked',
479 0,
480 array( 'blockinfo' => ApiQueryUserInfo::getBlockInfo( $user->getBlock() ) )
481 );
482
483 case EditPage::AS_MAX_ARTICLE_SIZE_EXCEEDED:
484 case EditPage::AS_CONTENT_TOO_BIG:
485 $this->dieUsageMsg( array( 'contenttoobig', $this->getConfig()->get( 'MaxArticleSize' ) ) );
486
487 case EditPage::AS_READ_ONLY_PAGE_ANON:
488 $this->dieUsageMsg( 'noedit-anon' );
489
490 case EditPage::AS_READ_ONLY_PAGE_LOGGED:
491 $this->dieUsageMsg( 'noedit' );
492
493 case EditPage::AS_READ_ONLY_PAGE:
494 $this->dieReadOnly();
495
496 case EditPage::AS_RATE_LIMITED:
497 $this->dieUsageMsg( 'actionthrottledtext' );
498
499 case EditPage::AS_ARTICLE_WAS_DELETED:
500 $this->dieUsageMsg( 'wasdeleted' );
501
502 case EditPage::AS_NO_CREATE_PERMISSION:
503 $this->dieUsageMsg( 'nocreate-loggedin' );
504
505 case EditPage::AS_NO_CHANGE_CONTENT_MODEL:
506 $this->dieUsageMsg( 'cantchangecontentmodel' );
507
508 case EditPage::AS_BLANK_ARTICLE:
509 $this->dieUsageMsg( 'blankpage' );
510
511 case EditPage::AS_CONFLICT_DETECTED:
512 $this->dieUsageMsg( 'editconflict' );
513
514 case EditPage::AS_TEXTBOX_EMPTY:
515 $this->dieUsageMsg( 'emptynewsection' );
516
517 case EditPage::AS_CHANGE_TAG_ERROR:
518 $this->dieStatus( $status );
519
520 case EditPage::AS_SUCCESS_NEW_ARTICLE:
521 $r['new'] = true;
522 // fall-through
523
524 case EditPage::AS_SUCCESS_UPDATE:
525 $r['result'] = 'Success';
526 $r['pageid'] = intval( $titleObj->getArticleID() );
527 $r['title'] = $titleObj->getPrefixedText();
528 $r['contentmodel'] = $articleObject->getContentModel();
529 $newRevId = $articleObject->getLatest();
530 if ( $newRevId == $oldRevId ) {
531 $r['nochange'] = true;
532 } else {
533 $r['oldrevid'] = intval( $oldRevId );
534 $r['newrevid'] = intval( $newRevId );
535 $r['newtimestamp'] = wfTimestamp( TS_ISO_8601,
536 $pageObj->getTimestamp() );
537 }
538 break;
539
540 case EditPage::AS_SUMMARY_NEEDED:
541 // Shouldn't happen since we set wpIgnoreBlankSummary, but just in case
542 $this->dieUsageMsg( 'summaryrequired' );
543
544 case EditPage::AS_END:
545 default:
546 // $status came from WikiPage::doEdit()
547 $errors = $status->getErrorsArray();
548 $this->dieUsageMsg( $errors[0] ); // TODO: Add new errors to message map
549 break;
550 }
551 $apiResult->addValue( null, $this->getModuleName(), $r );
552 }
553
554 public function mustBePosted() {
555 return true;
556 }
557
558 public function isWriteMode() {
559 return true;
560 }
561
562 public function getAllowedParams() {
563 return array(
564 'title' => array(
565 ApiBase::PARAM_TYPE => 'string',
566 ),
567 'pageid' => array(
568 ApiBase::PARAM_TYPE => 'integer',
569 ),
570 'section' => null,
571 'sectiontitle' => array(
572 ApiBase::PARAM_TYPE => 'string',
573 ),
574 'text' => array(
575 ApiBase::PARAM_TYPE => 'text',
576 ),
577 'summary' => null,
578 'tags' => array(
579 ApiBase::PARAM_TYPE => ChangeTags::listExplicitlyDefinedTags(),
580 ApiBase::PARAM_ISMULTI => true,
581 ),
582 'minor' => false,
583 'notminor' => false,
584 'bot' => false,
585 'basetimestamp' => array(
586 ApiBase::PARAM_TYPE => 'timestamp',
587 ),
588 'starttimestamp' => array(
589 ApiBase::PARAM_TYPE => 'timestamp',
590 ),
591 'recreate' => false,
592 'createonly' => false,
593 'nocreate' => false,
594 'watch' => array(
595 ApiBase::PARAM_DFLT => false,
596 ApiBase::PARAM_DEPRECATED => true,
597 ),
598 'unwatch' => array(
599 ApiBase::PARAM_DFLT => false,
600 ApiBase::PARAM_DEPRECATED => true,
601 ),
602 'watchlist' => array(
603 ApiBase::PARAM_DFLT => 'preferences',
604 ApiBase::PARAM_TYPE => array(
605 'watch',
606 'unwatch',
607 'preferences',
608 'nochange'
609 ),
610 ),
611 'md5' => null,
612 'prependtext' => array(
613 ApiBase::PARAM_TYPE => 'text',
614 ),
615 'appendtext' => array(
616 ApiBase::PARAM_TYPE => 'text',
617 ),
618 'undo' => array(
619 ApiBase::PARAM_TYPE => 'integer'
620 ),
621 'undoafter' => array(
622 ApiBase::PARAM_TYPE => 'integer'
623 ),
624 'redirect' => array(
625 ApiBase::PARAM_TYPE => 'boolean',
626 ApiBase::PARAM_DFLT => false,
627 ),
628 'contentformat' => array(
629 ApiBase::PARAM_TYPE => ContentHandler::getAllContentFormats(),
630 ),
631 'contentmodel' => array(
632 ApiBase::PARAM_TYPE => ContentHandler::getContentModels(),
633 ),
634 'token' => array(
635 // Standard definition automatically inserted
636 ApiBase::PARAM_HELP_MSG_APPEND => array( 'apihelp-edit-param-token' ),
637 ),
638 );
639 }
640
641 public function needsToken() {
642 return 'csrf';
643 }
644
645 protected function getExamplesMessages() {
646 return array(
647 'action=edit&title=Test&summary=test%20summary&' .
648 'text=article%20content&basetimestamp=2007-08-24T12:34:54Z&token=123ABC'
649 => 'apihelp-edit-example-edit',
650 'action=edit&title=Test&summary=NOTOC&minor=&' .
651 'prependtext=__NOTOC__%0A&basetimestamp=2007-08-24T12:34:54Z&token=123ABC'
652 => 'apihelp-edit-example-prepend',
653 'action=edit&title=Test&undo=13585&undoafter=13579&' .
654 'basetimestamp=2007-08-24T12:34:54Z&token=123ABC'
655 => 'apihelp-edit-example-undo',
656 );
657 }
658
659 public function getHelpUrls() {
660 return 'https://www.mediawiki.org/wiki/API:Edit';
661 }
662 }