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