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