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