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