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