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