make ApiEditPage aware of content model and format.
[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
36 public function __construct( $query, $moduleName ) {
37 parent::__construct( $query, $moduleName );
38 }
39
40 public function execute() {
41 $user = $this->getUser();
42 $params = $this->extractRequestParams();
43
44 if ( is_null( $params['text'] ) && is_null( $params['appendtext'] ) &&
45 is_null( $params['prependtext'] ) &&
46 $params['undo'] == 0 )
47 {
48 $this->dieUsageMsg( 'missingtext' );
49 }
50
51 $pageObj = $this->getTitleOrPageId( $params );
52 $titleObj = $pageObj->getTitle();
53 if ( $titleObj->isExternal() ) {
54 $this->dieUsageMsg( array( 'invalidtitle', $params['title'] ) );
55 }
56
57 $contentHandler = $pageObj->getContentHandler();
58
59 // @todo ask handler whether direct editing is supported at all! make allowFlatEdit() method or some such
60
61 if ( !isset( $params['contentformat'] ) || $params['contentformat'] == '' ) {
62 $contentFormat = $contentHandler->getDefaultFormat();
63 $params['contentformat'] = ContentHandler::getContentFormatMimeType( $contentFormat );
64 } else {
65 $contentFormat = ContentHandler::getContentFormatID( $params['contentformat'] );
66
67 if ( !is_int( $contentFormat ) ) {
68 $this->dieUsage( "Unknown format " . $params['contentformat'], 'badformat' );
69 }
70 }
71
72 if ( !$contentHandler->isSupportedFormat( $contentFormat ) ) {
73 $formatName = ContentHandler::getContentFormatMimeType( $contentFormat );
74 $modelName = $contentHandler->getModelName();
75 $name = $titleObj->getPrefixedDBkey();
76 $model = $contentHandler->getModelID();
77
78 $this->dieUsage( "The requested format #$contentFormat ($formatName) is not supported for content model #$model ($modelName) used by $name", 'badformat' );
79 }
80
81 $apiResult = $this->getResult();
82
83 if ( $params['redirect'] ) {
84 if ( $titleObj->isRedirect() ) {
85 $oldTitle = $titleObj;
86
87 $titles = Revision::newFromTitle( $oldTitle )->getContent( Revision::FOR_THIS_USER )->getRedirectChain();
88 // array_shift( $titles );
89
90 $redirValues = array();
91 foreach ( $titles as $id => $newTitle ) {
92
93 if ( !isset( $titles[ $id - 1 ] ) ) {
94 $titles[ $id - 1 ] = $oldTitle;
95 }
96
97 $redirValues[] = array(
98 'from' => $titles[ $id - 1 ]->getPrefixedText(),
99 'to' => $newTitle->getPrefixedText()
100 );
101
102 $titleObj = $newTitle;
103 }
104
105 $apiResult->setIndexedTagName( $redirValues, 'r' );
106 $apiResult->addValue( null, 'redirects', $redirValues );
107 }
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 {
129 $content = $pageObj->getContent();
130
131 if ( !( $content instanceof TextContent ) ) {
132 // @todo: ContentHandler should have an isFlat() method or some such
133 // @todo: XXX: or perhaps there should be Content::append(), Content::prepend() and Content::supportsConcatenation()
134 $mode = $contentHandler->getModelName();
135 $this->dieUsage( "Can't append to pages using content model $mode", 'appendnotsupported' );
136 }
137
138 if ( !$content ) {
139 # If this is a MediaWiki:x message, then load the messages
140 # and return the message value for x.
141 if ( $titleObj->getNamespace() == NS_MEDIAWIKI ) {
142 $text = $titleObj->getDefaultMessageText();
143 if ( $text === false ) {
144 $text = '';
145 }
146
147 $content = ContentHandler::makeContent( $text, $this->getTitle() );
148 }
149 }
150
151 if ( !is_null( $params['section'] ) ) {
152 if ( !$contentHandler->supportsSections() ) {
153 $modelName = $contentHandler->getModelName();
154 $this->dieUsage( "Sections are not supported for this content model: $modelName.", 'sectionsnotsupported' );
155 }
156
157 // Process the content for section edits
158 $section = intval( $params['section'] );
159 $content = $content->getSection( $section );
160
161 if ( !$content ) {
162 $this->dieUsage( "There is no section {$section}.", 'nosuchsection' );
163 }
164 }
165
166 if ( !$content ) {
167 $text = '';
168 } else {
169 $text = $content->serialize( $contentFormat );
170 }
171
172 $params['text'] = $params['prependtext'] . $text . $params['appendtext'];
173 $toMD5 = $params['prependtext'] . $params['appendtext'];
174 }
175
176 if ( $params['undo'] > 0 ) {
177 if ( $params['undoafter'] > 0 ) {
178 if ( $params['undo'] < $params['undoafter'] ) {
179 list( $params['undo'], $params['undoafter'] ) =
180 array( $params['undoafter'], $params['undo'] );
181 }
182 $undoafterRev = Revision::newFromID( $params['undoafter'] );
183 }
184 $undoRev = Revision::newFromID( $params['undo'] );
185 if ( is_null( $undoRev ) || $undoRev->isDeleted( Revision::DELETED_TEXT ) ) {
186 $this->dieUsageMsg( array( 'nosuchrevid', $params['undo'] ) );
187 }
188
189 if ( $params['undoafter'] == 0 ) {
190 $undoafterRev = $undoRev->getPrevious();
191 }
192 if ( is_null( $undoafterRev ) || $undoafterRev->isDeleted( Revision::DELETED_TEXT ) ) {
193 $this->dieUsageMsg( array( 'nosuchrevid', $params['undoafter'] ) );
194 }
195
196 if ( $undoRev->getPage() != $pageObj->getID() ) {
197 $this->dieUsageMsg( array( 'revwrongpage', $undoRev->getID(), $titleObj->getPrefixedText() ) );
198 }
199 if ( $undoafterRev->getPage() != $pageObj->getID() ) {
200 $this->dieUsageMsg( array( 'revwrongpage', $undoafterRev->getID(), $titleObj->getPrefixedText() ) );
201 }
202
203 $newContent = $contentHandler->getUndoContent( $undoRev, $undoafterRev );
204 if ( !$newContent ) {
205 $this->dieUsageMsg( 'undo-failure' );
206 }
207
208 $params['contentformat'] = $contentHandler->getDefaultFormat();
209 $params['text'] = $newContent->serialize( $params['contentformat'] );
210
211 // If no summary was given and we only undid one rev,
212 // use an autosummary
213 if ( is_null( $params['summary'] ) && $titleObj->getNextRevisionID( $undoafterRev->getID() ) == $params['undo'] ) {
214 $params['summary'] = wfMsgForContent( 'undo-summary', $params['undo'], $undoRev->getUserText() );
215 }
216 }
217
218 // See if the MD5 hash checks out
219 if ( !is_null( $params['md5'] ) && md5( $toMD5 ) !== $params['md5'] ) {
220 $this->dieUsageMsg( 'hashcheckfailed' );
221 }
222
223 // EditPage wants to parse its stuff from a WebRequest
224 // That interface kind of sucks, but it's workable
225 $requestArray = array(
226 'wpTextbox1' => $params['text'],
227 'format' => $contentFormat,
228 'model' => $contentHandler->getModelID(),
229 'wpEditToken' => $params['token'],
230 'wpIgnoreBlankSummary' => ''
231 );
232
233 if ( !is_null( $params['summary'] ) ) {
234 $requestArray['wpSummary'] = $params['summary'];
235 }
236
237 if ( !is_null( $params['sectiontitle'] ) ) {
238 $requestArray['wpSectionTitle'] = $params['sectiontitle'];
239 }
240
241 // Watch out for basetimestamp == ''
242 // wfTimestamp() treats it as NOW, almost certainly causing an edit conflict
243 if ( !is_null( $params['basetimestamp'] ) && $params['basetimestamp'] != '' ) {
244 $requestArray['wpEdittime'] = wfTimestamp( TS_MW, $params['basetimestamp'] );
245 } else {
246 $requestArray['wpEdittime'] = $pageObj->getTimestamp();
247 }
248
249 if ( !is_null( $params['starttimestamp'] ) && $params['starttimestamp'] != '' ) {
250 $requestArray['wpStarttime'] = wfTimestamp( TS_MW, $params['starttimestamp'] );
251 } else {
252 $requestArray['wpStarttime'] = wfTimestampNow(); // Fake wpStartime
253 }
254
255 if ( $params['minor'] || ( !$params['notminor'] && $user->getOption( 'minordefault' ) ) ) {
256 $requestArray['wpMinoredit'] = '';
257 }
258
259 if ( $params['recreate'] ) {
260 $requestArray['wpRecreate'] = '';
261 }
262
263 if ( !is_null( $params['section'] ) ) {
264 $section = intval( $params['section'] );
265 if ( $section == 0 && $params['section'] != '0' && $params['section'] != 'new' ) {
266 $this->dieUsage( "The section parameter must be set to an integer or 'new'", "invalidsection" );
267 }
268 $requestArray['wpSection'] = $params['section'];
269 } else {
270 $requestArray['wpSection'] = '';
271 }
272
273 $watch = $this->getWatchlistValue( $params['watchlist'], $titleObj );
274
275 // Deprecated parameters
276 if ( $params['watch'] ) {
277 $watch = true;
278 } elseif ( $params['unwatch'] ) {
279 $watch = false;
280 }
281
282 if ( $watch ) {
283 $requestArray['wpWatchthis'] = '';
284 }
285
286 global $wgTitle, $wgRequest;
287
288 $req = new DerivativeRequest( $this->getRequest(), $requestArray, true );
289
290 // Some functions depend on $wgTitle == $ep->mTitle
291 // TODO: Make them not or check if they still do
292 $wgTitle = $titleObj;
293
294 $articleObject = new Article( $titleObj );
295 $ep = new EditPage( $articleObject );
296
297 $ep->setContextTitle( $titleObj );
298 $ep->importFormData( $req );
299
300 // Run hooks
301 // Handle APIEditBeforeSave parameters
302 $r = array();
303 if ( !wfRunHooks( 'APIEditBeforeSave', array( $ep, $ep->textbox1, &$r ) ) ) {
304 if ( count( $r ) ) {
305 $r['result'] = 'Failure';
306 $apiResult->addValue( null, $this->getModuleName(), $r );
307 return;
308 } else {
309 $this->dieUsageMsg( 'hookaborted' );
310 }
311 }
312
313 // Do the actual save
314 $oldRevId = $articleObject->getRevIdFetched();
315 $result = null;
316 // Fake $wgRequest for some hooks inside EditPage
317 // @todo FIXME: This interface SUCKS
318 $oldRequest = $wgRequest;
319 $wgRequest = $req;
320
321 $status = $ep->internalAttemptSave( $result, $user->isAllowed( 'bot' ) && $params['bot'] );
322 $wgRequest = $oldRequest;
323 global $wgMaxArticleSize;
324
325 switch( $status->value ) {
326 case EditPage::AS_HOOK_ERROR:
327 case EditPage::AS_HOOK_ERROR_EXPECTED:
328 $this->dieUsageMsg( 'hookaborted' );
329
330 case EditPage::AS_IMAGE_REDIRECT_ANON:
331 $this->dieUsageMsg( 'noimageredirect-anon' );
332
333 case EditPage::AS_IMAGE_REDIRECT_LOGGED:
334 $this->dieUsageMsg( 'noimageredirect-logged' );
335
336 case EditPage::AS_SPAM_ERROR:
337 $this->dieUsageMsg( array( 'spamdetected', $result['spam'] ) );
338
339 case EditPage::AS_BLOCKED_PAGE_FOR_USER:
340 $this->dieUsageMsg( 'blockedtext' );
341
342 case EditPage::AS_MAX_ARTICLE_SIZE_EXCEEDED:
343 case EditPage::AS_CONTENT_TOO_BIG:
344 $this->dieUsageMsg( array( 'contenttoobig', $wgMaxArticleSize ) );
345
346 case EditPage::AS_READ_ONLY_PAGE_ANON:
347 $this->dieUsageMsg( 'noedit-anon' );
348
349 case EditPage::AS_READ_ONLY_PAGE_LOGGED:
350 $this->dieUsageMsg( 'noedit' );
351
352 case EditPage::AS_READ_ONLY_PAGE:
353 $this->dieReadOnly();
354
355 case EditPage::AS_RATE_LIMITED:
356 $this->dieUsageMsg( 'actionthrottledtext' );
357
358 case EditPage::AS_ARTICLE_WAS_DELETED:
359 $this->dieUsageMsg( 'wasdeleted' );
360
361 case EditPage::AS_NO_CREATE_PERMISSION:
362 $this->dieUsageMsg( 'nocreate-loggedin' );
363
364 case EditPage::AS_BLANK_ARTICLE:
365 $this->dieUsageMsg( 'blankpage' );
366
367 case EditPage::AS_CONFLICT_DETECTED:
368 $this->dieUsageMsg( 'editconflict' );
369
370 // case EditPage::AS_SUMMARY_NEEDED: Can't happen since we set wpIgnoreBlankSummary
371 case EditPage::AS_TEXTBOX_EMPTY:
372 $this->dieUsageMsg( 'emptynewsection' );
373
374 case EditPage::AS_SUCCESS_NEW_ARTICLE:
375 $r['new'] = '';
376
377 case EditPage::AS_SUCCESS_UPDATE:
378 $r['result'] = 'Success';
379 $r['pageid'] = intval( $titleObj->getArticleID() );
380 $r['title'] = $titleObj->getPrefixedText();
381 $r['contentmodel'] = $titleObj->getContentModel();
382 $newRevId = $articleObject->getLatest();
383 if ( $newRevId == $oldRevId ) {
384 $r['nochange'] = '';
385 } else {
386 $r['oldrevid'] = intval( $oldRevId );
387 $r['newrevid'] = intval( $newRevId );
388 $r['newtimestamp'] = wfTimestamp( TS_ISO_8601,
389 $pageObj->getTimestamp() );
390 }
391 break;
392
393 case EditPage::AS_SUMMARY_NEEDED:
394 $this->dieUsageMsg( 'summaryrequired' );
395
396 case EditPage::AS_END:
397 default:
398 // $status came from WikiPage::doEdit()
399 $errors = $status->getErrorsArray();
400 $this->dieUsageMsg( $errors[0] ); // TODO: Add new errors to message map
401 break;
402 }
403 $apiResult->addValue( null, $this->getModuleName(), $r );
404 }
405
406 public function mustBePosted() {
407 return true;
408 }
409
410 public function isWriteMode() {
411 return true;
412 }
413
414 public function getDescription() {
415 return 'Create and edit pages.';
416 }
417
418 public function getPossibleErrors() {
419 global $wgMaxArticleSize;
420
421 return array_merge( parent::getPossibleErrors(),
422 $this->getTitleOrPageIdErrorMessage(),
423 array(
424 array( 'missingtext' ),
425 array( 'createonly-exists' ),
426 array( 'nocreate-missing' ),
427 array( 'nosuchrevid', 'undo' ),
428 array( 'nosuchrevid', 'undoafter' ),
429 array( 'revwrongpage', 'id', 'text' ),
430 array( 'undo-failure' ),
431 array( 'hashcheckfailed' ),
432 array( 'hookaborted' ),
433 array( 'noimageredirect-anon' ),
434 array( 'noimageredirect-logged' ),
435 array( 'spamdetected', 'spam' ),
436 array( 'summaryrequired' ),
437 array( 'blockedtext' ),
438 array( 'contenttoobig', $wgMaxArticleSize ),
439 array( 'noedit-anon' ),
440 array( 'noedit' ),
441 array( 'actionthrottledtext' ),
442 array( 'wasdeleted' ),
443 array( 'nocreate-loggedin' ),
444 array( 'blankpage' ),
445 array( 'editconflict' ),
446 array( 'emptynewsection' ),
447 array( 'unknownerror', 'retval' ),
448 array( 'code' => 'nosuchsection', 'info' => 'There is no section section.' ),
449 array( 'code' => 'invalidsection', 'info' => 'The section parameter must be set to an integer or \'new\'' ),
450 array( 'code' => 'sectionsnotsupported', 'info' => 'Sections are not supported for this type of page.' ),
451 array( 'code' => 'editnotsupported', 'info' => 'Editing of this type of page is not supported using the text based edit API.' ),
452 array( 'code' => 'appendnotsupported', 'info' => 'This type of page can not be edited by appending or prepending text.' ),
453 array( 'code' => 'badformat', 'info' => 'The requested serialization format can not be applied to the page\'s content model' ),
454 array( 'customcssprotected' ),
455 array( 'customjsprotected' ),
456 )
457 );
458 }
459
460 public function getAllowedParams() {
461 return array(
462 'title' => array(
463 ApiBase::PARAM_TYPE => 'string',
464 ),
465 'pageid' => array(
466 ApiBase::PARAM_TYPE => 'integer',
467 ),
468 'section' => null,
469 'sectiontitle' => array(
470 ApiBase::PARAM_TYPE => 'string',
471 ApiBase::PARAM_REQUIRED => false,
472 ),
473 'text' => null,
474 'token' => null,
475 'summary' => null,
476 'minor' => false,
477 'notminor' => false,
478 'bot' => false,
479 'basetimestamp' => null,
480 'starttimestamp' => null,
481 'recreate' => false,
482 'createonly' => false,
483 'nocreate' => false,
484 'watch' => array(
485 ApiBase::PARAM_DFLT => false,
486 ApiBase::PARAM_DEPRECATED => true,
487 ),
488 'unwatch' => array(
489 ApiBase::PARAM_DFLT => false,
490 ApiBase::PARAM_DEPRECATED => true,
491 ),
492 'watchlist' => array(
493 ApiBase::PARAM_DFLT => 'preferences',
494 ApiBase::PARAM_TYPE => array(
495 'watch',
496 'unwatch',
497 'preferences',
498 'nochange'
499 ),
500 ),
501 'md5' => null,
502 'prependtext' => null,
503 'appendtext' => null,
504 'undo' => array(
505 ApiBase::PARAM_TYPE => 'integer'
506 ),
507 'undoafter' => array(
508 ApiBase::PARAM_TYPE => 'integer'
509 ),
510 'redirect' => array(
511 ApiBase::PARAM_TYPE => 'boolean',
512 ApiBase::PARAM_DFLT => false,
513 ),
514 );
515 }
516
517 public function getParamDescription() {
518 $p = $this->getModulePrefix();
519 return array(
520 'title' => "Title of the page you want to edit. Cannot be used together with {$p}pageid",
521 'pageid' => "Page ID of the page you want to edit. Cannot be used together with {$p}title",
522 'section' => 'Section number. 0 for the top section, \'new\' for a new section',
523 'sectiontitle' => 'The title for a new section',
524 'text' => 'Page content',
525 'token' => array( 'Edit token. You can get one of these through prop=info.',
526 "The token should always be sent as the last parameter, or at least, after the {$p}text parameter"
527 ),
528 'summary' => "Edit summary. Also section title when {$p}section=new and {$p}sectiontitle is not set",
529 'minor' => 'Minor edit',
530 'notminor' => 'Non-minor edit',
531 'bot' => 'Mark this edit as bot',
532 'basetimestamp' => array( 'Timestamp of the base revision (obtained through prop=revisions&rvprop=timestamp).',
533 'Used to detect edit conflicts; leave unset to ignore conflicts'
534 ),
535 'starttimestamp' => array( 'Timestamp when you obtained the edit token.',
536 'Used to detect edit conflicts; leave unset to ignore conflicts'
537 ),
538 'recreate' => 'Override any errors about the article having been deleted in the meantime',
539 'createonly' => 'Don\'t edit the page if it exists already',
540 'nocreate' => 'Throw an error if the page doesn\'t exist',
541 'watch' => 'Add the page to your watchlist',
542 'unwatch' => 'Remove the page from your watchlist',
543 'watchlist' => 'Unconditionally add or remove the page from your watchlist, use preferences or do not change watch',
544 'md5' => array( "The MD5 hash of the {$p}text parameter, or the {$p}prependtext and {$p}appendtext parameters concatenated.",
545 'If set, the edit won\'t be done unless the hash is correct' ),
546 'prependtext' => "Add this text to the beginning of the page. Overrides {$p}text",
547 'appendtext' => array( "Add this text to the end of the page. Overrides {$p}text.",
548 "Use {$p}section=new to append a new section" ),
549 'undo' => "Undo this revision. Overrides {$p}text, {$p}prependtext and {$p}appendtext",
550 'undoafter' => 'Undo all revisions from undo to this one. If not set, just undo one revision',
551 'redirect' => 'Automatically resolve redirects',
552 );
553 }
554
555 public function getResultProperties() {
556 return array(
557 '' => array(
558 'new' => 'boolean',
559 'result' => array(
560 ApiBase::PROP_TYPE => array(
561 'Success',
562 'Failure'
563 ),
564 ),
565 'pageid' => array(
566 ApiBase::PROP_TYPE => 'integer',
567 ApiBase::PROP_NULLABLE => true
568 ),
569 'title' => array(
570 ApiBase::PROP_TYPE => 'string',
571 ApiBase::PROP_NULLABLE => true
572 ),
573 'nochange' => 'boolean',
574 'oldrevid' => array(
575 ApiBase::PROP_TYPE => 'integer',
576 ApiBase::PROP_NULLABLE => true
577 ),
578 'newrevid' => array(
579 ApiBase::PROP_TYPE => 'integer',
580 ApiBase::PROP_NULLABLE => true
581 ),
582 'newtimestamp' => array(
583 ApiBase::PROP_TYPE => 'string',
584 ApiBase::PROP_NULLABLE => true
585 )
586 )
587 );
588 }
589
590 public function needsToken() {
591 return true;
592 }
593
594 public function getTokenSalt() {
595 return '';
596 }
597
598 public function getExamples() {
599 return array(
600
601 'api.php?action=edit&title=Test&summary=test%20summary&text=article%20content&basetimestamp=20070824123454&token=%2B\\'
602 => 'Edit a page (anonymous user)',
603
604 'api.php?action=edit&title=Test&summary=NOTOC&minor=&prependtext=__NOTOC__%0A&basetimestamp=20070824123454&token=%2B\\'
605 => 'Prepend __NOTOC__ to a page (anonymous user)',
606 'api.php?action=edit&title=Test&undo=13585&undoafter=13579&basetimestamp=20070824123454&token=%2B\\'
607 => 'Undo r13579 through r13585 with autosummary (anonymous user)',
608 );
609 }
610
611 public function getHelpUrls() {
612 return 'https://www.mediawiki.org/wiki/API:Edit';
613 }
614
615 public function getVersion() {
616 return __CLASS__ . ': $Id$';
617 }
618 }