Fix for r99911: don't use getImageArea() to determine the area for comparison against...
[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 = Title::newFromText( $params['title'] );
52 if ( !$titleObj || $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 $reqArr = array(
176 'wpTextbox1' => $params['text'],
177 'wpEditToken' => $params['token'],
178 'wpIgnoreBlankSummary' => ''
179 );
180
181 if ( !is_null( $params['summary'] ) ) {
182 $reqArr['wpSummary'] = $params['summary'];
183 }
184
185 // Watch out for basetimestamp == ''
186 // wfTimestamp() treats it as NOW, almost certainly causing an edit conflict
187 if ( !is_null( $params['basetimestamp'] ) && $params['basetimestamp'] != '' ) {
188 $reqArr['wpEdittime'] = wfTimestamp( TS_MW, $params['basetimestamp'] );
189 } else {
190 $reqArr['wpEdittime'] = $articleObj->getTimestamp();
191 }
192
193 if ( !is_null( $params['starttimestamp'] ) && $params['starttimestamp'] != '' ) {
194 $reqArr['wpStarttime'] = wfTimestamp( TS_MW, $params['starttimestamp'] );
195 } else {
196 $reqArr['wpStarttime'] = wfTimestampNow(); // Fake wpStartime
197 }
198
199 if ( $params['minor'] || ( !$params['notminor'] && $user->getOption( 'minordefault' ) ) ) {
200 $reqArr['wpMinoredit'] = '';
201 }
202
203 if ( $params['recreate'] ) {
204 $reqArr['wpRecreate'] = '';
205 }
206
207 if ( !is_null( $params['section'] ) ) {
208 $section = intval( $params['section'] );
209 if ( $section == 0 && $params['section'] != '0' && $params['section'] != 'new' ) {
210 $this->dieUsage( "The section parameter must be set to an integer or 'new'", "invalidsection" );
211 }
212 $reqArr['wpSection'] = $params['section'];
213 } else {
214 $reqArr['wpSection'] = '';
215 }
216
217 $watch = $this->getWatchlistValue( $params['watchlist'], $titleObj );
218
219 // Deprecated parameters
220 if ( $params['watch'] ) {
221 $watch = true;
222 } elseif ( $params['unwatch'] ) {
223 $watch = false;
224 }
225
226 if ( $watch ) {
227 $reqArr['wpWatchthis'] = '';
228 }
229
230 global $wgTitle, $wgRequest;
231
232 $req = new DerivativeRequest( $this->getRequest(), $reqArr, true );
233
234 // Some functions depend on $wgTitle == $ep->mTitle
235 // TODO: Make them not or check if they still do
236 $wgTitle = $titleObj;
237
238 $ep = new EditPage( $articleObj );
239 $ep->setContextTitle( $titleObj );
240 $ep->importFormData( $req );
241
242 // Run hooks
243 // Handle APIEditBeforeSave parameters
244 $r = array();
245 if ( !wfRunHooks( 'APIEditBeforeSave', array( $ep, $ep->textbox1, &$r ) ) ) {
246 if ( count( $r ) ) {
247 $r['result'] = 'Failure';
248 $apiResult->addValue( null, $this->getModuleName(), $r );
249 return;
250 } else {
251 $this->dieUsageMsg( 'hookaborted' );
252 }
253 }
254
255 // Do the actual save
256 $oldRevId = $articleObj->getRevIdFetched();
257 $result = null;
258 // Fake $wgRequest for some hooks inside EditPage
259 // @todo FIXME: This interface SUCKS
260 $oldRequest = $wgRequest;
261 $wgRequest = $req;
262
263 $status = $ep->internalAttemptSave( $result, $user->isAllowed( 'bot' ) && $params['bot'] );
264 $wgRequest = $oldRequest;
265 global $wgMaxArticleSize;
266
267 switch( $status->value ) {
268 case EditPage::AS_HOOK_ERROR:
269 case EditPage::AS_HOOK_ERROR_EXPECTED:
270 $this->dieUsageMsg( 'hookaborted' );
271
272 case EditPage::AS_IMAGE_REDIRECT_ANON:
273 $this->dieUsageMsg( 'noimageredirect-anon' );
274
275 case EditPage::AS_IMAGE_REDIRECT_LOGGED:
276 $this->dieUsageMsg( 'noimageredirect-logged' );
277
278 case EditPage::AS_SPAM_ERROR:
279 $this->dieUsageMsg( array( 'spamdetected', $result['spam'] ) );
280
281 case EditPage::AS_FILTERING:
282 $this->dieUsageMsg( 'filtered' );
283
284 case EditPage::AS_BLOCKED_PAGE_FOR_USER:
285 $this->dieUsageMsg( 'blockedtext' );
286
287 case EditPage::AS_MAX_ARTICLE_SIZE_EXCEEDED:
288 case EditPage::AS_CONTENT_TOO_BIG:
289 $this->dieUsageMsg( array( 'contenttoobig', $wgMaxArticleSize ) );
290
291 case EditPage::AS_READ_ONLY_PAGE_ANON:
292 $this->dieUsageMsg( 'noedit-anon' );
293
294 case EditPage::AS_READ_ONLY_PAGE_LOGGED:
295 $this->dieUsageMsg( 'noedit' );
296
297 case EditPage::AS_READ_ONLY_PAGE:
298 $this->dieReadOnly();
299
300 case EditPage::AS_RATE_LIMITED:
301 $this->dieUsageMsg( 'actionthrottledtext' );
302
303 case EditPage::AS_ARTICLE_WAS_DELETED:
304 $this->dieUsageMsg( 'wasdeleted' );
305
306 case EditPage::AS_NO_CREATE_PERMISSION:
307 $this->dieUsageMsg( 'nocreate-loggedin' );
308
309 case EditPage::AS_BLANK_ARTICLE:
310 $this->dieUsageMsg( 'blankpage' );
311
312 case EditPage::AS_CONFLICT_DETECTED:
313 $this->dieUsageMsg( 'editconflict' );
314
315 // case EditPage::AS_SUMMARY_NEEDED: Can't happen since we set wpIgnoreBlankSummary
316 case EditPage::AS_TEXTBOX_EMPTY:
317 $this->dieUsageMsg( 'emptynewsection' );
318
319 case EditPage::AS_SUCCESS_NEW_ARTICLE:
320 $r['new'] = '';
321
322 case EditPage::AS_SUCCESS_UPDATE:
323 $r['result'] = 'Success';
324 $r['pageid'] = intval( $titleObj->getArticleID() );
325 $r['title'] = $titleObj->getPrefixedText();
326 $newRevId = $articleObj->getLatest();
327 if ( $newRevId == $oldRevId ) {
328 $r['nochange'] = '';
329 } else {
330 $r['oldrevid'] = intval( $oldRevId );
331 $r['newrevid'] = intval( $newRevId );
332 $r['newtimestamp'] = wfTimestamp( TS_ISO_8601,
333 $articleObj->getTimestamp() );
334 }
335 break;
336
337 case EditPage::AS_SUMMARY_NEEDED:
338 $this->dieUsageMsg( 'summaryrequired' );
339
340 case EditPage::AS_END:
341 // $status came from WikiPage::doEdit()
342 $errors = $status->getErrorsArray();
343 $this->dieUsageMsg( $errors[0] ); // TODO: Add new errors to message map
344 break;
345 default:
346 $this->dieUsageMsg( array( 'unknownerror', $status->value ) );
347 }
348 $apiResult->addValue( null, $this->getModuleName(), $r );
349 }
350
351 public function mustBePosted() {
352 return true;
353 }
354
355 public function isWriteMode() {
356 return true;
357 }
358
359 public function getDescription() {
360 return 'Create and edit pages.';
361 }
362
363 public function getPossibleErrors() {
364 global $wgMaxArticleSize;
365
366 return array_merge( parent::getPossibleErrors(), array(
367 array( 'missingtext' ),
368 array( 'invalidtitle', 'title' ),
369 array( 'createonly-exists' ),
370 array( 'nocreate-missing' ),
371 array( 'nosuchrevid', 'undo' ),
372 array( 'nosuchrevid', 'undoafter' ),
373 array( 'revwrongpage', 'id', 'text' ),
374 array( 'undo-failure' ),
375 array( 'hashcheckfailed' ),
376 array( 'hookaborted' ),
377 array( 'noimageredirect-anon' ),
378 array( 'noimageredirect-logged' ),
379 array( 'spamdetected', 'spam' ),
380 array( 'summaryrequired' ),
381 array( 'filtered' ),
382 array( 'blockedtext' ),
383 array( 'contenttoobig', $wgMaxArticleSize ),
384 array( 'noedit-anon' ),
385 array( 'noedit' ),
386 array( 'actionthrottledtext' ),
387 array( 'wasdeleted' ),
388 array( 'nocreate-loggedin' ),
389 array( 'blankpage' ),
390 array( 'editconflict' ),
391 array( 'emptynewsection' ),
392 array( 'unknownerror', 'retval' ),
393 array( 'code' => 'nosuchsection', 'info' => 'There is no section section.' ),
394 array( 'code' => 'invalidsection', 'info' => 'The section parameter must be set to an integer or \'new\'' ),
395 array( 'customcssprotected' ),
396 array( 'customjsprotected' ),
397 ) );
398 }
399
400 public function getAllowedParams() {
401 return array(
402 'title' => array(
403 ApiBase::PARAM_TYPE => 'string',
404 ApiBase::PARAM_REQUIRED => true
405 ),
406 'section' => null,
407 'text' => null,
408 'token' => null,
409 'summary' => null,
410 'minor' => false,
411 'notminor' => false,
412 'bot' => false,
413 'basetimestamp' => null,
414 'starttimestamp' => null,
415 'recreate' => false,
416 'createonly' => false,
417 'nocreate' => false,
418 'watch' => array(
419 ApiBase::PARAM_DFLT => false,
420 ApiBase::PARAM_DEPRECATED => true,
421 ),
422 'unwatch' => array(
423 ApiBase::PARAM_DFLT => false,
424 ApiBase::PARAM_DEPRECATED => true,
425 ),
426 'watchlist' => array(
427 ApiBase::PARAM_DFLT => 'preferences',
428 ApiBase::PARAM_TYPE => array(
429 'watch',
430 'unwatch',
431 'preferences',
432 'nochange'
433 ),
434 ),
435 'md5' => null,
436 'prependtext' => null,
437 'appendtext' => null,
438 'undo' => array(
439 ApiBase::PARAM_TYPE => 'integer'
440 ),
441 'undoafter' => array(
442 ApiBase::PARAM_TYPE => 'integer'
443 ),
444 'redirect' => array(
445 ApiBase::PARAM_TYPE => 'boolean',
446 ApiBase::PARAM_DFLT => false,
447 ),
448 );
449 }
450
451 public function getParamDescription() {
452 $p = $this->getModulePrefix();
453 return array(
454 'title' => 'Page title',
455 'section' => 'Section number. 0 for the top section, \'new\' for a new section',
456 'text' => 'Page content',
457 'token' => array( 'Edit token. You can get one of these through prop=info.',
458 'The token should always be sent as the last parameter, or at least, after the text parameter'
459 ),
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 (obtained 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 'md5' => array( "The MD5 hash of the {$p}text parameter, or the {$p}prependtext and {$p}appendtext parameters concatenated.",
477 'If set, the edit won\'t be done unless the hash is correct' ),
478 'prependtext' => "Add this text to the beginning of the page. Overrides {$p}text",
479 'appendtext' => "Add this text to the end of the page. Overrides {$p}text",
480 'undo' => "Undo this revision. Overrides {$p}text, {$p}prependtext and {$p}appendtext",
481 'undoafter' => 'Undo all revisions from undo to this one. If not set, just undo one revision',
482 'redirect' => 'Automatically resolve redirects',
483 );
484 }
485
486 public function needsToken() {
487 return true;
488 }
489
490 public function getTokenSalt() {
491 return '';
492 }
493
494 public function getExamples() {
495 return array(
496 'Edit a page (anonymous user):',
497 ' api.php?action=edit&title=Test&summary=test%20summary&text=article%20content&basetimestamp=20070824123454&token=%2B\\',
498 'Prepend __NOTOC__ to a page (anonymous user):',
499 ' api.php?action=edit&title=Test&summary=NOTOC&minor=&prependtext=__NOTOC__%0A&basetimestamp=20070824123454&token=%2B\\',
500 'Undo r13579 through r13585 with autosummary (anonymous user):',
501 ' api.php?action=edit&title=Test&undo=13585&undoafter=13579&basetimestamp=20070824123454&token=%2B\\',
502 );
503 }
504
505 public function getHelpUrls() {
506 return 'http://www.mediawiki.org/wiki/API:Edit';
507 }
508
509 public function getVersion() {
510 return __CLASS__ . ': $Id$';
511 }
512 }