Merge "Fix description for MessagesBgn.php"
[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 * see T20654 if you're inspired to fix this.
33 *
34 * @ingroup API
35 */
36 class ApiEditPage extends ApiBase {
37 public function execute() {
38 $user = $this->getUser();
39 $params = $this->extractRequestParams();
40
41 if ( is_null( $params['text'] ) && is_null( $params['appendtext'] ) &&
42 is_null( $params['prependtext'] ) &&
43 $params['undo'] == 0
44 ) {
45 $this->dieUsageMsg( 'missingtext' );
46 }
47
48 $pageObj = $this->getTitleOrPageId( $params );
49 $titleObj = $pageObj->getTitle();
50 $apiResult = $this->getResult();
51
52 if ( $params['redirect'] ) {
53 if ( $params['prependtext'] === null && $params['appendtext'] === null
54 && $params['section'] !== 'new'
55 ) {
56 $this->dieUsage( 'You have attempted to edit using the "redirect"-following'
57 . ' mode, which must be used in conjuction with section=new, prependtext'
58 . ', or appendtext.', 'redirect-appendonly' );
59 }
60 if ( $titleObj->isRedirect() ) {
61 $oldTitle = $titleObj;
62
63 $titles = Revision::newFromTitle( $oldTitle, false, Revision::READ_LATEST )
64 ->getContent( Revision::FOR_THIS_USER, $user )
65 ->getRedirectChain();
66 // array_shift( $titles );
67
68 $redirValues = array();
69
70 /** @var $newTitle Title */
71 foreach ( $titles as $id => $newTitle ) {
72
73 if ( !isset( $titles[$id - 1] ) ) {
74 $titles[$id - 1] = $oldTitle;
75 }
76
77 $redirValues[] = array(
78 'from' => $titles[$id - 1]->getPrefixedText(),
79 'to' => $newTitle->getPrefixedText()
80 );
81
82 $titleObj = $newTitle;
83 }
84
85 $apiResult->setIndexedTagName( $redirValues, 'r' );
86 $apiResult->addValue( null, 'redirects', $redirValues );
87
88 // Since the page changed, update $pageObj
89 $pageObj = WikiPage::factory( $titleObj );
90 }
91 }
92
93 if ( !isset( $params['contentmodel'] ) || $params['contentmodel'] == '' ) {
94 $contentHandler = $pageObj->getContentHandler();
95 } else {
96 $contentHandler = ContentHandler::getForModelID( $params['contentmodel'] );
97 }
98
99 // @todo Ask handler whether direct editing is supported at all! make
100 // allowFlatEdit() method or some such
101
102 if ( !isset( $params['contentformat'] ) || $params['contentformat'] == '' ) {
103 $params['contentformat'] = $contentHandler->getDefaultFormat();
104 }
105
106 $contentFormat = $params['contentformat'];
107
108 if ( !$contentHandler->isSupportedFormat( $contentFormat ) ) {
109 $name = $titleObj->getPrefixedDBkey();
110 $model = $contentHandler->getModelID();
111
112 $this->dieUsage( "The requested format $contentFormat is not supported for content model " .
113 " $model used by $name", 'badformat' );
114 }
115
116 if ( $params['createonly'] && $titleObj->exists() ) {
117 $this->dieUsageMsg( 'createonly-exists' );
118 }
119 if ( $params['nocreate'] && !$titleObj->exists() ) {
120 $this->dieUsageMsg( 'nocreate-missing' );
121 }
122
123 // Now let's check whether we're even allowed to do this
124 $errors = $titleObj->getUserPermissionsErrors( 'edit', $user );
125 if ( !$titleObj->exists() ) {
126 $errors = array_merge( $errors, $titleObj->getUserPermissionsErrors( 'create', $user ) );
127 }
128 if ( count( $errors ) ) {
129 $this->dieUsageMsg( $errors[0] );
130 }
131
132 $toMD5 = $params['text'];
133 if ( !is_null( $params['appendtext'] ) || !is_null( $params['prependtext'] ) ) {
134 $content = $pageObj->getContent();
135
136 if ( !$content ) {
137 if ( $titleObj->getNamespace() == NS_MEDIAWIKI ) {
138 # If this is a MediaWiki:x message, then load the messages
139 # and return the message value for x.
140 $text = $titleObj->getDefaultMessageText();
141 if ( $text === false ) {
142 $text = '';
143 }
144
145 try {
146 $content = ContentHandler::makeContent( $text, $this->getTitle() );
147 } catch ( MWContentSerializationException $ex ) {
148 $this->dieUsage( $ex->getMessage(), 'parseerror' );
149
150 return;
151 }
152 } else {
153 # Otherwise, make a new empty content.
154 $content = $contentHandler->makeEmptyContent();
155 }
156 }
157
158 // @todo Add support for appending/prepending to the Content interface
159
160 if ( !( $content instanceof TextContent ) ) {
161 $mode = $contentHandler->getModelID();
162 $this->dieUsage( "Can't append to pages using content model $mode", 'appendnotsupported' );
163 }
164
165 if ( !is_null( $params['section'] ) ) {
166 if ( !$contentHandler->supportsSections() ) {
167 $modelName = $contentHandler->getModelID();
168 $this->dieUsage(
169 "Sections are not supported for this content model: $modelName.",
170 'sectionsnotsupported'
171 );
172 }
173
174 if ( $params['section'] == 'new' ) {
175 // DWIM if they're trying to prepend/append to a new section.
176 $content = null;
177 } else {
178 // Process the content for section edits
179 $section = $params['section'];
180 $content = $content->getSection( $section );
181
182 if ( !$content ) {
183 $this->dieUsage( "There is no section {$section}.", 'nosuchsection' );
184 }
185 }
186 }
187
188 if ( !$content ) {
189 $text = '';
190 } else {
191 $text = $content->serialize( $contentFormat );
192 }
193
194 $params['text'] = $params['prependtext'] . $text . $params['appendtext'];
195 $toMD5 = $params['prependtext'] . $params['appendtext'];
196 }
197
198 if ( $params['undo'] > 0 ) {
199 if ( $params['undoafter'] > 0 ) {
200 if ( $params['undo'] < $params['undoafter'] ) {
201 list( $params['undo'], $params['undoafter'] ) =
202 array( $params['undoafter'], $params['undo'] );
203 }
204 $undoafterRev = Revision::newFromId( $params['undoafter'] );
205 }
206 $undoRev = Revision::newFromId( $params['undo'] );
207 if ( is_null( $undoRev ) || $undoRev->isDeleted( Revision::DELETED_TEXT ) ) {
208 $this->dieUsageMsg( array( 'nosuchrevid', $params['undo'] ) );
209 }
210
211 if ( $params['undoafter'] == 0 ) {
212 $undoafterRev = $undoRev->getPrevious();
213 }
214 if ( is_null( $undoafterRev ) || $undoafterRev->isDeleted( Revision::DELETED_TEXT ) ) {
215 $this->dieUsageMsg( array( 'nosuchrevid', $params['undoafter'] ) );
216 }
217
218 if ( $undoRev->getPage() != $pageObj->getID() ) {
219 $this->dieUsageMsg( array( 'revwrongpage', $undoRev->getID(),
220 $titleObj->getPrefixedText() ) );
221 }
222 if ( $undoafterRev->getPage() != $pageObj->getID() ) {
223 $this->dieUsageMsg( array( 'revwrongpage', $undoafterRev->getID(),
224 $titleObj->getPrefixedText() ) );
225 }
226
227 $newContent = $contentHandler->getUndoContent(
228 $pageObj->getRevision(),
229 $undoRev,
230 $undoafterRev
231 );
232
233 if ( !$newContent ) {
234 $this->dieUsageMsg( 'undo-failure' );
235 }
236
237 $params['text'] = $newContent->serialize( $params['contentformat'] );
238
239 // If no summary was given and we only undid one rev,
240 // use an autosummary
241 if ( is_null( $params['summary'] ) &&
242 $titleObj->getNextRevisionID( $undoafterRev->getID() ) == $params['undo']
243 ) {
244 $params['summary'] = wfMessage( 'undo-summary' )
245 ->params ( $params['undo'], $undoRev->getUserText() )->inContentLanguage()->text();
246 }
247 }
248
249 // See if the MD5 hash checks out
250 if ( !is_null( $params['md5'] ) && md5( $toMD5 ) !== $params['md5'] ) {
251 $this->dieUsageMsg( 'hashcheckfailed' );
252 }
253
254 // EditPage wants to parse its stuff from a WebRequest
255 // That interface kind of sucks, but it's workable
256 $requestArray = array(
257 'wpTextbox1' => $params['text'],
258 'format' => $contentFormat,
259 'model' => $contentHandler->getModelID(),
260 'wpEditToken' => $params['token'],
261 'wpIgnoreBlankSummary' => true,
262 'wpIgnoreBlankArticle' => true,
263 'wpIgnoreSelfRedirect' => true,
264 'bot' => $params['bot'],
265 );
266
267 if ( !is_null( $params['summary'] ) ) {
268 $requestArray['wpSummary'] = $params['summary'];
269 }
270
271 if ( !is_null( $params['sectiontitle'] ) ) {
272 $requestArray['wpSectionTitle'] = $params['sectiontitle'];
273 }
274
275 // TODO: Pass along information from 'undoafter' as well
276 if ( $params['undo'] > 0 ) {
277 $requestArray['wpUndidRevision'] = $params['undo'];
278 }
279
280 // Watch out for basetimestamp == ''
281 // wfTimestamp() treats it as NOW, almost certainly causing an edit conflict
282 if ( !is_null( $params['basetimestamp'] ) && $params['basetimestamp'] != '' ) {
283 $requestArray['wpEdittime'] = wfTimestamp( TS_MW, $params['basetimestamp'] );
284 } else {
285 $requestArray['wpEdittime'] = $pageObj->getTimestamp();
286 }
287
288 if ( !is_null( $params['starttimestamp'] ) && $params['starttimestamp'] != '' ) {
289 $requestArray['wpStarttime'] = wfTimestamp( TS_MW, $params['starttimestamp'] );
290 } else {
291 $requestArray['wpStarttime'] = wfTimestampNow(); // Fake wpStartime
292 }
293
294 if ( $params['minor'] || ( !$params['notminor'] && $user->getOption( 'minordefault' ) ) ) {
295 $requestArray['wpMinoredit'] = '';
296 }
297
298 if ( $params['recreate'] ) {
299 $requestArray['wpRecreate'] = '';
300 }
301
302 if ( !is_null( $params['section'] ) ) {
303 $section = $params['section'];
304 if ( !preg_match( '/^((T-)?\d+|new)$/', $section ) ) {
305 $this->dieUsage( "The section parameter must be a valid section id or 'new'",
306 "invalidsection" );
307 }
308 $content = $pageObj->getContent();
309 if ( $section !== '0' && $section != 'new'
310 && ( !$content || !$content->getSection( $section ) )
311 ) {
312 $this->dieUsage( "There is no section {$section}.", 'nosuchsection' );
313 }
314 $requestArray['wpSection'] = $params['section'];
315 } else {
316 $requestArray['wpSection'] = '';
317 }
318
319 $watch = $this->getWatchlistValue( $params['watchlist'], $titleObj );
320
321 // Deprecated parameters
322 if ( $params['watch'] ) {
323 $this->logFeatureUsage( 'action=edit&watch' );
324 $watch = true;
325 } elseif ( $params['unwatch'] ) {
326 $this->logFeatureUsage( 'action=edit&unwatch' );
327 $watch = false;
328 }
329
330 if ( $watch ) {
331 $requestArray['wpWatchthis'] = '';
332 }
333
334 // Pass through anything else we might have been given, to support extensions
335 // This is kind of a hack but it's the best we can do to make extensions work
336 $requestArray += $this->getRequest()->getValues();
337
338 global $wgTitle, $wgRequest;
339
340 $req = new DerivativeRequest( $this->getRequest(), $requestArray, true );
341
342 // Some functions depend on $wgTitle == $ep->mTitle
343 // TODO: Make them not or check if they still do
344 $wgTitle = $titleObj;
345
346 $articleContext = new RequestContext;
347 $articleContext->setRequest( $req );
348 $articleContext->setWikiPage( $pageObj );
349 $articleContext->setUser( $this->getUser() );
350
351 /** @var $articleObject Article */
352 $articleObject = Article::newFromWikiPage( $pageObj, $articleContext );
353
354 $ep = new EditPage( $articleObject );
355
356 // allow editing of non-textual content.
357 $ep->allowNonTextContent = true;
358
359 $ep->setContextTitle( $titleObj );
360 $ep->importFormData( $req );
361 $content = $ep->textbox1;
362
363 // The following is needed to give the hook the full content of the
364 // new revision rather than just the current section. (Bug 52077)
365 if ( !is_null( $params['section'] ) &&
366 $contentHandler->supportsSections() && $titleObj->exists()
367 ) {
368 // If sectiontitle is set, use it, otherwise use the summary as the section title (for
369 // backwards compatibility with old forms/bots).
370 if ( $ep->sectiontitle !== '' ) {
371 $sectionTitle = $ep->sectiontitle;
372 } else {
373 $sectionTitle = $ep->summary;
374 }
375
376 $contentObj = $contentHandler->unserializeContent( $content, $contentFormat );
377
378 $fullContentObj = $articleObject->replaceSectionContent(
379 $params['section'],
380 $contentObj,
381 $sectionTitle
382 );
383 if ( $fullContentObj ) {
384 $content = $fullContentObj->serialize( $contentFormat );
385 } else {
386 // This most likely means we have an edit conflict which means that the edit
387 // wont succeed anyway.
388 $this->dieUsageMsg( 'editconflict' );
389 }
390 }
391
392 // Run hooks
393 // Handle APIEditBeforeSave parameters
394 $r = array();
395 if ( !Hooks::run( 'APIEditBeforeSave', array( $ep, $content, &$r ) ) ) {
396 if ( count( $r ) ) {
397 $r['result'] = 'Failure';
398 $apiResult->addValue( null, $this->getModuleName(), $r );
399
400 return;
401 }
402
403 $this->dieUsageMsg( 'hookaborted' );
404 }
405
406 // Do the actual save
407 $oldRevId = $articleObject->getRevIdFetched();
408 $result = null;
409 // Fake $wgRequest for some hooks inside EditPage
410 // @todo FIXME: This interface SUCKS
411 $oldRequest = $wgRequest;
412 $wgRequest = $req;
413
414 $status = $ep->attemptSave( $result );
415 $wgRequest = $oldRequest;
416
417 switch ( $status->value ) {
418 case EditPage::AS_HOOK_ERROR:
419 case EditPage::AS_HOOK_ERROR_EXPECTED:
420 if ( isset( $status->apiHookResult ) ) {
421 $r = $status->apiHookResult;
422 $r['result'] = 'Failure';
423 $apiResult->addValue( null, $this->getModuleName(), $r );
424 return;
425 } else {
426 $this->dieUsageMsg( 'hookaborted' );
427 }
428
429 case EditPage::AS_PARSE_ERROR:
430 $this->dieUsage( $status->getMessage(), 'parseerror' );
431
432 case EditPage::AS_IMAGE_REDIRECT_ANON:
433 $this->dieUsageMsg( 'noimageredirect-anon' );
434
435 case EditPage::AS_IMAGE_REDIRECT_LOGGED:
436 $this->dieUsageMsg( 'noimageredirect-logged' );
437
438 case EditPage::AS_SPAM_ERROR:
439 $this->dieUsageMsg( array( 'spamdetected', $result['spam'] ) );
440
441 case EditPage::AS_BLOCKED_PAGE_FOR_USER:
442 $this->dieUsageMsg( 'blockedtext' );
443
444 case EditPage::AS_MAX_ARTICLE_SIZE_EXCEEDED:
445 case EditPage::AS_CONTENT_TOO_BIG:
446 $this->dieUsageMsg( array( 'contenttoobig', $this->getConfig()->get( 'MaxArticleSize' ) ) );
447
448 case EditPage::AS_READ_ONLY_PAGE_ANON:
449 $this->dieUsageMsg( 'noedit-anon' );
450
451 case EditPage::AS_READ_ONLY_PAGE_LOGGED:
452 $this->dieUsageMsg( 'noedit' );
453
454 case EditPage::AS_READ_ONLY_PAGE:
455 $this->dieReadOnly();
456
457 case EditPage::AS_RATE_LIMITED:
458 $this->dieUsageMsg( 'actionthrottledtext' );
459
460 case EditPage::AS_ARTICLE_WAS_DELETED:
461 $this->dieUsageMsg( 'wasdeleted' );
462
463 case EditPage::AS_NO_CREATE_PERMISSION:
464 $this->dieUsageMsg( 'nocreate-loggedin' );
465
466 case EditPage::AS_NO_CHANGE_CONTENT_MODEL:
467 $this->dieUsageMsg( 'cantchangecontentmodel' );
468
469 case EditPage::AS_BLANK_ARTICLE:
470 $this->dieUsageMsg( 'blankpage' );
471
472 case EditPage::AS_CONFLICT_DETECTED:
473 $this->dieUsageMsg( 'editconflict' );
474
475 case EditPage::AS_TEXTBOX_EMPTY:
476 $this->dieUsageMsg( 'emptynewsection' );
477
478 case EditPage::AS_SUCCESS_NEW_ARTICLE:
479 $r['new'] = '';
480 // fall-through
481
482 case EditPage::AS_SUCCESS_UPDATE:
483 $r['result'] = 'Success';
484 $r['pageid'] = intval( $titleObj->getArticleID() );
485 $r['title'] = $titleObj->getPrefixedText();
486 $r['contentmodel'] = $titleObj->getContentModel();
487 $newRevId = $articleObject->getLatest();
488 if ( $newRevId == $oldRevId ) {
489 $r['nochange'] = '';
490 } else {
491 $r['oldrevid'] = intval( $oldRevId );
492 $r['newrevid'] = intval( $newRevId );
493 $r['newtimestamp'] = wfTimestamp( TS_ISO_8601,
494 $pageObj->getTimestamp() );
495 }
496 break;
497
498 case EditPage::AS_SUMMARY_NEEDED:
499 // Shouldn't happen since we set wpIgnoreBlankSummary, but just in case
500 $this->dieUsageMsg( 'summaryrequired' );
501
502 case EditPage::AS_END:
503 default:
504 // $status came from WikiPage::doEdit()
505 $errors = $status->getErrorsArray();
506 $this->dieUsageMsg( $errors[0] ); // TODO: Add new errors to message map
507 break;
508 }
509 $apiResult->addValue( null, $this->getModuleName(), $r );
510 }
511
512 public function mustBePosted() {
513 return true;
514 }
515
516 public function isWriteMode() {
517 return true;
518 }
519
520 public function getAllowedParams() {
521 return array(
522 'title' => array(
523 ApiBase::PARAM_TYPE => 'string',
524 ),
525 'pageid' => array(
526 ApiBase::PARAM_TYPE => 'integer',
527 ),
528 'section' => null,
529 'sectiontitle' => array(
530 ApiBase::PARAM_TYPE => 'string',
531 ),
532 'text' => null,
533 'summary' => null,
534 'minor' => false,
535 'notminor' => false,
536 'bot' => false,
537 'basetimestamp' => null,
538 'starttimestamp' => null,
539 'recreate' => false,
540 'createonly' => false,
541 'nocreate' => false,
542 'watch' => array(
543 ApiBase::PARAM_DFLT => false,
544 ApiBase::PARAM_DEPRECATED => true,
545 ),
546 'unwatch' => array(
547 ApiBase::PARAM_DFLT => false,
548 ApiBase::PARAM_DEPRECATED => true,
549 ),
550 'watchlist' => array(
551 ApiBase::PARAM_DFLT => 'preferences',
552 ApiBase::PARAM_TYPE => array(
553 'watch',
554 'unwatch',
555 'preferences',
556 'nochange'
557 ),
558 ),
559 'md5' => null,
560 'prependtext' => null,
561 'appendtext' => null,
562 'undo' => array(
563 ApiBase::PARAM_TYPE => 'integer'
564 ),
565 'undoafter' => array(
566 ApiBase::PARAM_TYPE => 'integer'
567 ),
568 'redirect' => array(
569 ApiBase::PARAM_TYPE => 'boolean',
570 ApiBase::PARAM_DFLT => false,
571 ),
572 'contentformat' => array(
573 ApiBase::PARAM_TYPE => ContentHandler::getAllContentFormats(),
574 ),
575 'contentmodel' => array(
576 ApiBase::PARAM_TYPE => ContentHandler::getContentModels(),
577 ),
578 'token' => array(
579 // Standard definition automatically inserted
580 ApiBase::PARAM_HELP_MSG_APPEND => array( 'apihelp-edit-param-token' ),
581 ),
582 );
583 }
584
585 public function needsToken() {
586 return 'csrf';
587 }
588
589 protected function getExamplesMessages() {
590 return array(
591 'action=edit&title=Test&summary=test%20summary&' .
592 'text=article%20content&basetimestamp=2007-08-24T12:34:54Z&token=123ABC'
593 => 'apihelp-edit-example-edit',
594 'action=edit&title=Test&summary=NOTOC&minor=&' .
595 'prependtext=__NOTOC__%0A&basetimestamp=2007-08-24T12:34:54Z&token=123ABC'
596 => 'apihelp-edit-example-prepend',
597 'action=edit&title=Test&undo=13585&undoafter=13579&' .
598 'basetimestamp=2007-08-24T12:34:54Z&token=123ABC'
599 => 'apihelp-edit-example-undo',
600 );
601 }
602
603 public function getHelpUrls() {
604 return 'https://www.mediawiki.org/wiki/API:Edit';
605 }
606 }