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