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