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