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