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