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