93da4a67adb31c1db94c3e630cc5560684f20e29
[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 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, 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 $this->dieUsageMsg( array( 'nosuchrevid', $params['undo'] ) );
122 }
123
124 if ( $params['undoafter'] == 0 ) {
125 $undoafterRev = $undoRev->getPrevious();
126 }
127 if ( is_null( $undoafterRev ) || $undoafterRev->isDeleted( Revision::DELETED_TEXT ) ) {
128 $this->dieUsageMsg( array( 'nosuchrevid', $params['undoafter'] ) );
129 }
130
131 if ( $undoRev->getPage() != $articleObj->getID() ) {
132 $this->dieUsageMsg( array( 'revwrongpage', $undoRev->getID(), $titleObj->getPrefixedText() ) );
133 }
134 if ( $undoafterRev->getPage() != $articleObj->getID() ) {
135 $this->dieUsageMsg( array( 'revwrongpage', $undoafterRev->getID(), $titleObj->getPrefixedText() ) );
136 }
137
138 $newtext = $articleObj->getUndoText( $undoRev, $undoafterRev );
139 if ( $newtext === false ) {
140 $this->dieUsageMsg( array( 'undo-failure' ) );
141 }
142 $params['text'] = $newtext;
143 // If no summary was given and we only undid one rev,
144 // use an autosummary
145 if ( is_null( $params['summary'] ) && $titleObj->getNextRevisionID( $undoafterRev->getID() ) == $params['undo'] ) {
146 $params['summary'] = wfMsgForContent( 'undo-summary', $params['undo'], $undoRev->getUserText() );
147 }
148 }
149
150 // See if the MD5 hash checks out
151 if ( !is_null( $params['md5'] ) && md5( $toMD5 ) !== $params['md5'] ) {
152 $this->dieUsageMsg( array( 'hashcheckfailed' ) );
153 }
154
155 $ep = new EditPage( $articleObj );
156 // EditPage wants to parse its stuff from a WebRequest
157 // That interface kind of sucks, but it's workable
158 $reqArr = array(
159 'wpTextbox1' => $params['text'],
160 'wpEditToken' => $params['token'],
161 'wpIgnoreBlankSummary' => ''
162 );
163
164 if ( !is_null( $params['summary'] ) ) {
165 $reqArr['wpSummary'] = $params['summary'];
166 }
167
168 // Watch out for basetimestamp == ''
169 // wfTimestamp() treats it as NOW, almost certainly causing an edit conflict
170 if ( !is_null( $params['basetimestamp'] ) && $params['basetimestamp'] != '' ) {
171 $reqArr['wpEdittime'] = wfTimestamp( TS_MW, $params['basetimestamp'] );
172 } else {
173 $reqArr['wpEdittime'] = $articleObj->getTimestamp();
174 }
175
176 if ( !is_null( $params['starttimestamp'] ) && $params['starttimestamp'] != '' ) {
177 $reqArr['wpStarttime'] = wfTimestamp( TS_MW, $params['starttimestamp'] );
178 } else {
179 $reqArr['wpStarttime'] = $reqArr['wpEdittime']; // Fake wpStartime
180 }
181
182 if ( $params['minor'] || ( !$params['notminor'] && $wgUser->getOption( 'minordefault' ) ) ) {
183 $reqArr['wpMinoredit'] = '';
184 }
185
186 if ( $params['recreate'] ) {
187 $reqArr['wpRecreate'] = '';
188 }
189
190 if ( !is_null( $params['section'] ) ) {
191 $section = intval( $params['section'] );
192 if ( $section == 0 && $params['section'] != '0' && $params['section'] != 'new' ) {
193 $this->dieUsage( "The section parameter must be set to an integer or 'new'", "invalidsection" );
194 }
195 $reqArr['wpSection'] = $params['section'];
196 } else {
197 $reqArr['wpSection'] = '';
198 }
199
200 $watch = $this->getWatchlistValue( $params['watchlist'], $titleObj );
201
202 // Deprecated parameters
203 if ( $params['watch'] ) {
204 $watch = true;
205 } elseif ( $params['unwatch'] ) {
206 $watch = false;
207 }
208
209 if ( $watch ) {
210 $reqArr['wpWatchthis'] = '';
211 }
212
213 $req = new FauxRequest( $reqArr, true );
214 $ep->importFormData( $req );
215
216 // Run hooks
217 // Handle CAPTCHA parameters
218 global $wgRequest;
219 if ( !is_null( $params['captchaid'] ) ) {
220 $wgRequest->setVal( 'wpCaptchaId', $params['captchaid'] );
221 }
222 if ( !is_null( $params['captchaword'] ) ) {
223 $wgRequest->setVal( 'wpCaptchaWord', $params['captchaword'] );
224 }
225
226 $r = array();
227 if ( !wfRunHooks( 'APIEditBeforeSave', array( $ep, $ep->textbox1, &$r ) ) ) {
228 if ( count( $r ) ) {
229 $r['result'] = 'Failure';
230 $this->getResult()->addValue( null, $this->getModuleName(), $r );
231 return;
232 } else {
233 $this->dieUsageMsg( array( 'hookaborted' ) );
234 }
235 }
236
237 // Do the actual save
238 $oldRevId = $articleObj->getRevIdFetched();
239 $result = null;
240 // Fake $wgRequest for some hooks inside EditPage
241 // FIXME: This interface SUCKS
242 $oldRequest = $wgRequest;
243 $wgRequest = $req;
244
245 $retval = $ep->internalAttemptSave( $result, $wgUser->isAllowed( 'bot' ) && $params['bot'] );
246 $wgRequest = $oldRequest;
247 switch( $retval ) {
248 case EditPage::AS_HOOK_ERROR:
249 case EditPage::AS_HOOK_ERROR_EXPECTED:
250 $this->dieUsageMsg( array( 'hookaborted' ) );
251
252 case EditPage::AS_IMAGE_REDIRECT_ANON:
253 $this->dieUsageMsg( array( 'noimageredirect-anon' ) );
254
255 case EditPage::AS_IMAGE_REDIRECT_LOGGED:
256 $this->dieUsageMsg( array( 'noimageredirect-logged' ) );
257
258 case EditPage::AS_SPAM_ERROR:
259 $this->dieUsageMsg( array( 'spamdetected', $result['spam'] ) );
260
261 case EditPage::AS_FILTERING:
262 $this->dieUsageMsg( array( 'filtered' ) );
263
264 case EditPage::AS_BLOCKED_PAGE_FOR_USER:
265 $this->dieUsageMsg( array( 'blockedtext' ) );
266
267 case EditPage::AS_MAX_ARTICLE_SIZE_EXCEEDED:
268 case EditPage::AS_CONTENT_TOO_BIG:
269 global $wgMaxArticleSize;
270 $this->dieUsageMsg( array( 'contenttoobig', $wgMaxArticleSize ) );
271
272 case EditPage::AS_READ_ONLY_PAGE_ANON:
273 $this->dieUsageMsg( array( 'noedit-anon' ) );
274
275 case EditPage::AS_READ_ONLY_PAGE_LOGGED:
276 $this->dieUsageMsg( array( 'noedit' ) );
277
278 case EditPage::AS_READ_ONLY_PAGE:
279 $this->dieReadOnly();
280
281 case EditPage::AS_RATE_LIMITED:
282 $this->dieUsageMsg( array( 'actionthrottledtext' ) );
283
284 case EditPage::AS_ARTICLE_WAS_DELETED:
285 $this->dieUsageMsg( array( 'wasdeleted' ) );
286
287 case EditPage::AS_NO_CREATE_PERMISSION:
288 $this->dieUsageMsg( array( 'nocreate-loggedin' ) );
289
290 case EditPage::AS_BLANK_ARTICLE:
291 $this->dieUsageMsg( array( 'blankpage' ) );
292
293 case EditPage::AS_CONFLICT_DETECTED:
294 $this->dieUsageMsg( array( 'editconflict' ) );
295
296 // case EditPage::AS_SUMMARY_NEEDED: Can't happen since we set wpIgnoreBlankSummary
297 case EditPage::AS_TEXTBOX_EMPTY:
298 $this->dieUsageMsg( array( 'emptynewsection' ) );
299
300 case EditPage::AS_SUCCESS_NEW_ARTICLE:
301 $r['new'] = '';
302
303 case EditPage::AS_SUCCESS_UPDATE:
304 $r['result'] = 'Success';
305 $r['pageid'] = intval( $titleObj->getArticleID() );
306 $r['title'] = $titleObj->getPrefixedText();
307 // HACK: We create a new Article object here because getRevIdFetched()
308 // refuses to be run twice, and because Title::getLatestRevId()
309 // won't fetch from the master unless we select for update, which we
310 // don't want to do.
311 $newArticle = new Article( $titleObj );
312 $newRevId = $newArticle->getRevIdFetched();
313 if ( $newRevId == $oldRevId ) {
314 $r['nochange'] = '';
315 } else {
316 $r['oldrevid'] = intval( $oldRevId );
317 $r['newrevid'] = intval( $newRevId );
318 $r['newtimestamp'] = wfTimestamp( TS_ISO_8601,
319 $newArticle->getTimestamp() );
320 }
321 break;
322
323 case EditPage::AS_SUMMARY_NEEDED:
324 $this->dieUsageMsg( array( 'summaryrequired' ) );
325
326 case EditPage::AS_END:
327 // This usually means some kind of race condition
328 // or DB weirdness occurred.
329 if ( is_array( $result ) && count( $result ) > 0 ) {
330 $this->dieUsageMsg( array( 'unknownerror', $result[0][0] ) );
331 }
332
333 // Unknown error, but no specific error message
334 // Fall through
335 default:
336 $this->dieUsageMsg( array( 'unknownerror', $retval ) );
337 }
338 $this->getResult()->addValue( null, $this->getModuleName(), $r );
339 }
340
341 public function mustBePosted() {
342 return true;
343 }
344
345 public function isWriteMode() {
346 return true;
347 }
348
349 protected function getDescription() {
350 return 'Create and edit pages.';
351 }
352
353 public function getPossibleErrors() {
354 global $wgMaxArticleSize;
355
356 return array_merge( parent::getPossibleErrors(), array(
357 array( 'missingparam', 'title' ),
358 array( 'missingtext' ),
359 array( 'invalidtitle', 'title' ),
360 array( 'createonly-exists' ),
361 array( 'nocreate-missing' ),
362 array( 'nosuchrevid', 'undo' ),
363 array( 'nosuchrevid', 'undoafter' ),
364 array( 'revwrongpage', 'id', 'text' ),
365 array( 'undo-failure' ),
366 array( 'hashcheckfailed' ),
367 array( 'hookaborted' ),
368 array( 'noimageredirect-anon' ),
369 array( 'noimageredirect-logged' ),
370 array( 'spamdetected', 'spam' ),
371 array( 'summaryrequired' ),
372 array( 'filtered' ),
373 array( 'blockedtext' ),
374 array( 'contenttoobig', $wgMaxArticleSize ),
375 array( 'noedit-anon' ),
376 array( 'noedit' ),
377 array( 'actionthrottledtext' ),
378 array( 'wasdeleted' ),
379 array( 'nocreate-loggedin' ),
380 array( 'blankpage' ),
381 array( 'editconflict' ),
382 array( 'emptynewsection' ),
383 array( 'unknownerror', 'retval' ),
384 array( 'code' => 'nosuchsection', 'info' => 'There is no section section.' ),
385 array( 'code' => 'invalidsection', 'info' => 'The section parameter must be set to an integer or \'new\'' ),
386 ) );
387 }
388
389 protected function getAllowedParams() {
390 return array(
391 'title' => null,
392 'section' => null,
393 'text' => null,
394 'token' => null,
395 'summary' => null,
396 'minor' => false,
397 'notminor' => false,
398 'bot' => false,
399 'basetimestamp' => null,
400 'starttimestamp' => null,
401 'recreate' => false,
402 'createonly' => false,
403 'nocreate' => false,
404 'captchaword' => null,
405 'captchaid' => null,
406 'watch' => array(
407 ApiBase::PARAM_DFLT => false,
408 ApiBase::PARAM_DEPRECATED => true,
409 ),
410 'unwatch' => array(
411 ApiBase::PARAM_DFLT => false,
412 ApiBase::PARAM_DEPRECATED => true,
413 ),
414 'watchlist' => array(
415 ApiBase::PARAM_DFLT => 'preferences',
416 ApiBase::PARAM_TYPE => array(
417 'watch',
418 'unwatch',
419 'preferences',
420 'nochange'
421 ),
422 ),
423 'md5' => null,
424 'prependtext' => null,
425 'appendtext' => null,
426 'undo' => array(
427 ApiBase::PARAM_TYPE => 'integer'
428 ),
429 'undoafter' => array(
430 ApiBase::PARAM_TYPE => 'integer'
431 ),
432 );
433 }
434
435 protected function getParamDescription() {
436 $p = $this->getModulePrefix();
437 return array(
438 'title' => 'Page title',
439 'section' => 'Section number. 0 for the top section, \'new\' for a new section',
440 'text' => 'Page content',
441 'token' => 'Edit token. You can get one of these through prop=info',
442 'summary' => 'Edit summary. Also section title when section=new',
443 'minor' => 'Minor edit',
444 'notminor' => 'Non-minor edit',
445 'bot' => 'Mark this edit as bot',
446 'basetimestamp' => array( 'Timestamp of the base revision (gotten through prop=revisions&rvprop=timestamp).',
447 'Used to detect edit conflicts; leave unset to ignore conflicts.'
448 ),
449 'starttimestamp' => array( 'Timestamp when you obtained the edit token.',
450 'Used to detect edit conflicts; leave unset to ignore conflicts'
451 ),
452 'recreate' => 'Override any errors about the article having been deleted in the meantime',
453 'createonly' => 'Don\'t edit the page if it exists already',
454 'nocreate' => 'Throw an error if the page doesn\'t exist',
455 'watch' => 'Add the page to your watchlist',
456 'unwatch' => 'Remove the page from your watchlist',
457 'watchlist' => 'Unconditionally add or remove the page from your watchlist, use preferences or do not change watch',
458 'captchaid' => 'CAPTCHA ID from previous request',
459 'captchaword' => 'Answer to the CAPTCHA',
460 'md5' => array( "The MD5 hash of the {$p}text parameter, or the {$p}prependtext and {$p}appendtext parameters concatenated.",
461 'If set, the edit won\'t be done unless the hash is correct' ),
462 'prependtext' => "Add this text to the beginning of the page. Overrides {$p}text",
463 'appendtext' => "Add this text to the end of the page. Overrides {$p}text",
464 'undo' => "Undo this revision. Overrides {$p}text, {$p}prependtext and {$p}appendtext",
465 'undoafter' => 'Undo all revisions from undo to this one. If not set, just undo one revision',
466 );
467 }
468
469 public function getTokenSalt() {
470 return '';
471 }
472
473 protected function getExamples() {
474 return array(
475 'Edit a page (anonymous user):',
476 ' api.php?action=edit&title=Test&summary=test%20summary&text=article%20content&basetimestamp=20070824123454&token=%2B\\',
477 'Prepend __NOTOC__ to a page (anonymous user):',
478 ' api.php?action=edit&title=Test&summary=NOTOC&minor&prependtext=__NOTOC__%0A&basetimestamp=20070824123454&token=%2B\\',
479 'Undo r13579 through r13585 with autosummary (anonymous user):',
480 ' api.php?action=edit&title=Test&undo=13585&undoafter=13579&basetimestamp=20070824123454&token=%2B\\',
481 );
482 }
483
484 public function getVersion() {
485 return __CLASS__ . ': $Id$';
486 }
487 }