Merge "Fix variable name and use isset() to shut up a stupid notice"
[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 // Apply change tags
335 if ( count( $params['tags'] ) ) {
336 if ( $user->isAllowed( 'applychangetags' ) ) {
337 $requestArray['wpChangeTags'] = implode( ',', $params['tags'] );
338 } else {
339 $this->dieUsage( 'You don\'t have permission to set change tags.', 'taggingnotallowed' );
340 }
341 }
342
343 // Pass through anything else we might have been given, to support extensions
344 // This is kind of a hack but it's the best we can do to make extensions work
345 $requestArray += $this->getRequest()->getValues();
346
347 global $wgTitle, $wgRequest;
348
349 $req = new DerivativeRequest( $this->getRequest(), $requestArray, true );
350
351 // Some functions depend on $wgTitle == $ep->mTitle
352 // TODO: Make them not or check if they still do
353 $wgTitle = $titleObj;
354
355 $articleContext = new RequestContext;
356 $articleContext->setRequest( $req );
357 $articleContext->setWikiPage( $pageObj );
358 $articleContext->setUser( $this->getUser() );
359
360 /** @var $articleObject Article */
361 $articleObject = Article::newFromWikiPage( $pageObj, $articleContext );
362
363 $ep = new EditPage( $articleObject );
364
365 // allow editing of non-textual content.
366 $ep->allowNonTextContent = true;
367
368 $ep->setContextTitle( $titleObj );
369 $ep->importFormData( $req );
370 $content = $ep->textbox1;
371
372 // The following is needed to give the hook the full content of the
373 // new revision rather than just the current section. (Bug 52077)
374 if ( !is_null( $params['section'] ) &&
375 $contentHandler->supportsSections() && $titleObj->exists()
376 ) {
377 // If sectiontitle is set, use it, otherwise use the summary as the section title (for
378 // backwards compatibility with old forms/bots).
379 if ( $ep->sectiontitle !== '' ) {
380 $sectionTitle = $ep->sectiontitle;
381 } else {
382 $sectionTitle = $ep->summary;
383 }
384
385 $contentObj = $contentHandler->unserializeContent( $content, $contentFormat );
386
387 $fullContentObj = $articleObject->replaceSectionContent(
388 $params['section'],
389 $contentObj,
390 $sectionTitle
391 );
392 if ( $fullContentObj ) {
393 $content = $fullContentObj->serialize( $contentFormat );
394 } else {
395 // This most likely means we have an edit conflict which means that the edit
396 // wont succeed anyway.
397 $this->dieUsageMsg( 'editconflict' );
398 }
399 }
400
401 // Run hooks
402 // Handle APIEditBeforeSave parameters
403 $r = array();
404 if ( !Hooks::run( 'APIEditBeforeSave', array( $ep, $content, &$r ) ) ) {
405 if ( count( $r ) ) {
406 $r['result'] = 'Failure';
407 $apiResult->addValue( null, $this->getModuleName(), $r );
408
409 return;
410 }
411
412 $this->dieUsageMsg( 'hookaborted' );
413 }
414
415 // Do the actual save
416 $oldRevId = $articleObject->getRevIdFetched();
417 $result = null;
418 // Fake $wgRequest for some hooks inside EditPage
419 // @todo FIXME: This interface SUCKS
420 $oldRequest = $wgRequest;
421 $wgRequest = $req;
422
423 $status = $ep->attemptSave( $result );
424 $wgRequest = $oldRequest;
425
426 switch ( $status->value ) {
427 case EditPage::AS_HOOK_ERROR:
428 case EditPage::AS_HOOK_ERROR_EXPECTED:
429 if ( isset( $status->apiHookResult ) ) {
430 $r = $status->apiHookResult;
431 $r['result'] = 'Failure';
432 $apiResult->addValue( null, $this->getModuleName(), $r );
433 return;
434 } else {
435 $this->dieUsageMsg( 'hookaborted' );
436 }
437
438 case EditPage::AS_PARSE_ERROR:
439 $this->dieUsage( $status->getMessage(), 'parseerror' );
440
441 case EditPage::AS_IMAGE_REDIRECT_ANON:
442 $this->dieUsageMsg( 'noimageredirect-anon' );
443
444 case EditPage::AS_IMAGE_REDIRECT_LOGGED:
445 $this->dieUsageMsg( 'noimageredirect-logged' );
446
447 case EditPage::AS_SPAM_ERROR:
448 $this->dieUsageMsg( array( 'spamdetected', $result['spam'] ) );
449
450 case EditPage::AS_BLOCKED_PAGE_FOR_USER:
451 $this->dieUsageMsg( 'blockedtext' );
452
453 case EditPage::AS_MAX_ARTICLE_SIZE_EXCEEDED:
454 case EditPage::AS_CONTENT_TOO_BIG:
455 $this->dieUsageMsg( array( 'contenttoobig', $this->getConfig()->get( 'MaxArticleSize' ) ) );
456
457 case EditPage::AS_READ_ONLY_PAGE_ANON:
458 $this->dieUsageMsg( 'noedit-anon' );
459
460 case EditPage::AS_READ_ONLY_PAGE_LOGGED:
461 $this->dieUsageMsg( 'noedit' );
462
463 case EditPage::AS_READ_ONLY_PAGE:
464 $this->dieReadOnly();
465
466 case EditPage::AS_RATE_LIMITED:
467 $this->dieUsageMsg( 'actionthrottledtext' );
468
469 case EditPage::AS_ARTICLE_WAS_DELETED:
470 $this->dieUsageMsg( 'wasdeleted' );
471
472 case EditPage::AS_NO_CREATE_PERMISSION:
473 $this->dieUsageMsg( 'nocreate-loggedin' );
474
475 case EditPage::AS_NO_CHANGE_CONTENT_MODEL:
476 $this->dieUsageMsg( 'cantchangecontentmodel' );
477
478 case EditPage::AS_BLANK_ARTICLE:
479 $this->dieUsageMsg( 'blankpage' );
480
481 case EditPage::AS_CONFLICT_DETECTED:
482 $this->dieUsageMsg( 'editconflict' );
483
484 case EditPage::AS_TEXTBOX_EMPTY:
485 $this->dieUsageMsg( 'emptynewsection' );
486
487 case EditPage::AS_CHANGE_TAG_ERROR:
488 $this->dieStatus( $status );
489
490 case EditPage::AS_SUCCESS_NEW_ARTICLE:
491 $r['new'] = '';
492 // fall-through
493
494 case EditPage::AS_SUCCESS_UPDATE:
495 $r['result'] = 'Success';
496 $r['pageid'] = intval( $titleObj->getArticleID() );
497 $r['title'] = $titleObj->getPrefixedText();
498 $r['contentmodel'] = $titleObj->getContentModel();
499 $newRevId = $articleObject->getLatest();
500 if ( $newRevId == $oldRevId ) {
501 $r['nochange'] = '';
502 } else {
503 $r['oldrevid'] = intval( $oldRevId );
504 $r['newrevid'] = intval( $newRevId );
505 $r['newtimestamp'] = wfTimestamp( TS_ISO_8601,
506 $pageObj->getTimestamp() );
507 }
508 break;
509
510 case EditPage::AS_SUMMARY_NEEDED:
511 // Shouldn't happen since we set wpIgnoreBlankSummary, but just in case
512 $this->dieUsageMsg( 'summaryrequired' );
513
514 case EditPage::AS_END:
515 default:
516 // $status came from WikiPage::doEdit()
517 $errors = $status->getErrorsArray();
518 $this->dieUsageMsg( $errors[0] ); // TODO: Add new errors to message map
519 break;
520 }
521 $apiResult->addValue( null, $this->getModuleName(), $r );
522 }
523
524 public function mustBePosted() {
525 return true;
526 }
527
528 public function isWriteMode() {
529 return true;
530 }
531
532 public function getAllowedParams() {
533 return array(
534 'title' => array(
535 ApiBase::PARAM_TYPE => 'string',
536 ),
537 'pageid' => array(
538 ApiBase::PARAM_TYPE => 'integer',
539 ),
540 'section' => null,
541 'sectiontitle' => array(
542 ApiBase::PARAM_TYPE => 'string',
543 ),
544 'text' => null,
545 'summary' => null,
546 'tags' => array(
547 ApiBase::PARAM_TYPE => ChangeTags::listExplicitlyDefinedTags(),
548 ApiBase::PARAM_ISMULTI => true,
549 ),
550 'minor' => false,
551 'notminor' => false,
552 'bot' => false,
553 'basetimestamp' => null,
554 'starttimestamp' => null,
555 'recreate' => false,
556 'createonly' => false,
557 'nocreate' => false,
558 'watch' => array(
559 ApiBase::PARAM_DFLT => false,
560 ApiBase::PARAM_DEPRECATED => true,
561 ),
562 'unwatch' => array(
563 ApiBase::PARAM_DFLT => false,
564 ApiBase::PARAM_DEPRECATED => true,
565 ),
566 'watchlist' => array(
567 ApiBase::PARAM_DFLT => 'preferences',
568 ApiBase::PARAM_TYPE => array(
569 'watch',
570 'unwatch',
571 'preferences',
572 'nochange'
573 ),
574 ),
575 'md5' => null,
576 'prependtext' => null,
577 'appendtext' => null,
578 'undo' => array(
579 ApiBase::PARAM_TYPE => 'integer'
580 ),
581 'undoafter' => array(
582 ApiBase::PARAM_TYPE => 'integer'
583 ),
584 'redirect' => array(
585 ApiBase::PARAM_TYPE => 'boolean',
586 ApiBase::PARAM_DFLT => false,
587 ),
588 'contentformat' => array(
589 ApiBase::PARAM_TYPE => ContentHandler::getAllContentFormats(),
590 ),
591 'contentmodel' => array(
592 ApiBase::PARAM_TYPE => ContentHandler::getContentModels(),
593 ),
594 'token' => array(
595 // Standard definition automatically inserted
596 ApiBase::PARAM_HELP_MSG_APPEND => array( 'apihelp-edit-param-token' ),
597 ),
598 );
599 }
600
601 public function needsToken() {
602 return 'csrf';
603 }
604
605 protected function getExamplesMessages() {
606 return array(
607 'action=edit&title=Test&summary=test%20summary&' .
608 'text=article%20content&basetimestamp=2007-08-24T12:34:54Z&token=123ABC'
609 => 'apihelp-edit-example-edit',
610 'action=edit&title=Test&summary=NOTOC&minor=&' .
611 'prependtext=__NOTOC__%0A&basetimestamp=2007-08-24T12:34:54Z&token=123ABC'
612 => 'apihelp-edit-example-prepend',
613 'action=edit&title=Test&undo=13585&undoafter=13579&' .
614 'basetimestamp=2007-08-24T12:34:54Z&token=123ABC'
615 => 'apihelp-edit-example-undo',
616 );
617 }
618
619 public function getHelpUrls() {
620 return 'https://www.mediawiki.org/wiki/API:Edit';
621 }
622 }