fixing long lines
[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 $pageObj = $this->getTitleOrPageId( $params );
52 $titleObj = $pageObj->getTitle();
53 if ( $titleObj->isExternal() ) {
54 $this->dieUsageMsg( array( 'invalidtitle', $params['title'] ) );
55 }
56
57 $contentHandler = $pageObj->getContentHandler();
58
59 // @todo ask handler whether direct editing is supported at all! make allowFlatEdit() method or some such
60
61 if ( !isset( $params['contentformat'] ) || $params['contentformat'] == '' ) {
62 $params['contentformat'] = $contentHandler->getDefaultFormat();
63 }
64
65 $contentFormat = $params['contentformat'];
66
67 if ( !$contentHandler->isSupportedFormat( $contentFormat ) ) {
68 $name = $titleObj->getPrefixedDBkey();
69 $model = $contentHandler->getModelID();
70
71 $this->dieUsage( "The requested format $contentFormat is not supported for content model ".
72 " $model used by $name", 'badformat' );
73 }
74
75 $apiResult = $this->getResult();
76
77 if ( $params['redirect'] ) {
78 if ( $titleObj->isRedirect() ) {
79 $oldTitle = $titleObj;
80
81 $titles = Revision::newFromTitle( $oldTitle )->getContent( Revision::FOR_THIS_USER )->getRedirectChain();
82 // array_shift( $titles );
83
84 $redirValues = array();
85 foreach ( $titles as $id => $newTitle ) {
86
87 if ( !isset( $titles[ $id - 1 ] ) ) {
88 $titles[ $id - 1 ] = $oldTitle;
89 }
90
91 $redirValues[] = array(
92 'from' => $titles[ $id - 1 ]->getPrefixedText(),
93 'to' => $newTitle->getPrefixedText()
94 );
95
96 $titleObj = $newTitle;
97 }
98
99 $apiResult->setIndexedTagName( $redirValues, 'r' );
100 $apiResult->addValue( null, 'redirects', $redirValues );
101 }
102 }
103
104 if ( $params['createonly'] && $titleObj->exists() ) {
105 $this->dieUsageMsg( 'createonly-exists' );
106 }
107 if ( $params['nocreate'] && !$titleObj->exists() ) {
108 $this->dieUsageMsg( 'nocreate-missing' );
109 }
110
111 // Now let's check whether we're even allowed to do this
112 $errors = $titleObj->getUserPermissionsErrors( 'edit', $user );
113 if ( !$titleObj->exists() ) {
114 $errors = array_merge( $errors, $titleObj->getUserPermissionsErrors( 'create', $user ) );
115 }
116 if ( count( $errors ) ) {
117 $this->dieUsageMsg( $errors[0] );
118 }
119
120 $toMD5 = $params['text'];
121 if ( !is_null( $params['appendtext'] ) || !is_null( $params['prependtext'] ) )
122 {
123 $content = $pageObj->getContent();
124
125 if ( !( $content instanceof TextContent ) ) {
126 // @todo: ContentHandler should have an isFlat() method or some such
127 // @todo: XXX: or perhaps there should be Content::append(), Content::prepend()
128 // @todo: ...and Content::supportsConcatenation()
129 $mode = $contentHandler->getModelID();
130 $this->dieUsage( "Can't append to pages using content model $mode", 'appendnotsupported' );
131 }
132
133 if ( !$content ) {
134 # If this is a MediaWiki:x message, then load the messages
135 # and return the message value for x.
136 if ( $titleObj->getNamespace() == NS_MEDIAWIKI ) {
137 $text = $titleObj->getDefaultMessageText();
138 if ( $text === false ) {
139 $text = '';
140 }
141
142 $content = ContentHandler::makeContent( $text, $this->getTitle() );
143 }
144 }
145
146 if ( !is_null( $params['section'] ) ) {
147 if ( !$contentHandler->supportsSections() ) {
148 $modelName = $contentHandler->getModelID();
149 $this->dieUsage( "Sections are not supported for this content model: $modelName.", 'sectionsnotsupported' );
150 }
151
152 // Process the content for section edits
153 $section = intval( $params['section'] );
154 $content = $content->getSection( $section );
155
156 if ( !$content ) {
157 $this->dieUsage( "There is no section {$section}.", 'nosuchsection' );
158 }
159 }
160
161 if ( !$content ) {
162 $text = '';
163 } else {
164 $text = $content->serialize( $contentFormat );
165 }
166
167 $params['text'] = $params['prependtext'] . $text . $params['appendtext'];
168 $toMD5 = $params['prependtext'] . $params['appendtext'];
169 }
170
171 if ( $params['undo'] > 0 ) {
172 if ( $params['undoafter'] > 0 ) {
173 if ( $params['undo'] < $params['undoafter'] ) {
174 list( $params['undo'], $params['undoafter'] ) =
175 array( $params['undoafter'], $params['undo'] );
176 }
177 $undoafterRev = Revision::newFromID( $params['undoafter'] );
178 }
179 $undoRev = Revision::newFromID( $params['undo'] );
180 if ( is_null( $undoRev ) || $undoRev->isDeleted( Revision::DELETED_TEXT ) ) {
181 $this->dieUsageMsg( array( 'nosuchrevid', $params['undo'] ) );
182 }
183
184 if ( $params['undoafter'] == 0 ) {
185 $undoafterRev = $undoRev->getPrevious();
186 }
187 if ( is_null( $undoafterRev ) || $undoafterRev->isDeleted( Revision::DELETED_TEXT ) ) {
188 $this->dieUsageMsg( array( 'nosuchrevid', $params['undoafter'] ) );
189 }
190
191 if ( $undoRev->getPage() != $pageObj->getID() ) {
192 $this->dieUsageMsg( array( 'revwrongpage', $undoRev->getID(), $titleObj->getPrefixedText() ) );
193 }
194 if ( $undoafterRev->getPage() != $pageObj->getID() ) {
195 $this->dieUsageMsg( array( 'revwrongpage', $undoafterRev->getID(), $titleObj->getPrefixedText() ) );
196 }
197
198 $newContent = $contentHandler->getUndoContent( $undoRev, $undoafterRev );
199 if ( !$newContent ) {
200 $this->dieUsageMsg( 'undo-failure' );
201 }
202
203 $params['contentformat'] = $contentHandler->getDefaultFormat();
204 $params['text'] = $newContent->serialize( $params['contentformat'] );
205
206 // If no summary was given and we only undid one rev,
207 // use an autosummary
208 if ( is_null( $params['summary'] ) && $titleObj->getNextRevisionID( $undoafterRev->getID() ) == $params['undo'] ) {
209 $params['summary'] = wfMessage( 'undo-summary', $params['undo'], $undoRev->getUserText() )->inContentLanguage()->text();
210 }
211 }
212
213 // See if the MD5 hash checks out
214 if ( !is_null( $params['md5'] ) && md5( $toMD5 ) !== $params['md5'] ) {
215 $this->dieUsageMsg( 'hashcheckfailed' );
216 }
217
218 // EditPage wants to parse its stuff from a WebRequest
219 // That interface kind of sucks, but it's workable
220 $requestArray = array(
221 'wpTextbox1' => $params['text'],
222 'format' => $contentFormat,
223 'model' => $contentHandler->getModelID(),
224 'wpEditToken' => $params['token'],
225 'wpIgnoreBlankSummary' => ''
226 );
227
228 if ( !is_null( $params['summary'] ) ) {
229 $requestArray['wpSummary'] = $params['summary'];
230 }
231
232 if ( !is_null( $params['sectiontitle'] ) ) {
233 $requestArray['wpSectionTitle'] = $params['sectiontitle'];
234 }
235
236 // Watch out for basetimestamp == ''
237 // wfTimestamp() treats it as NOW, almost certainly causing an edit conflict
238 if ( !is_null( $params['basetimestamp'] ) && $params['basetimestamp'] != '' ) {
239 $requestArray['wpEdittime'] = wfTimestamp( TS_MW, $params['basetimestamp'] );
240 } else {
241 $requestArray['wpEdittime'] = $pageObj->getTimestamp();
242 }
243
244 if ( !is_null( $params['starttimestamp'] ) && $params['starttimestamp'] != '' ) {
245 $requestArray['wpStarttime'] = wfTimestamp( TS_MW, $params['starttimestamp'] );
246 } else {
247 $requestArray['wpStarttime'] = wfTimestampNow(); // Fake wpStartime
248 }
249
250 if ( $params['minor'] || ( !$params['notminor'] && $user->getOption( 'minordefault' ) ) ) {
251 $requestArray['wpMinoredit'] = '';
252 }
253
254 if ( $params['recreate'] ) {
255 $requestArray['wpRecreate'] = '';
256 }
257
258 if ( !is_null( $params['section'] ) ) {
259 $section = intval( $params['section'] );
260 if ( $section == 0 && $params['section'] != '0' && $params['section'] != 'new' ) {
261 $this->dieUsage( "The section parameter must be set to an integer or 'new'", "invalidsection" );
262 }
263 $requestArray['wpSection'] = $params['section'];
264 } else {
265 $requestArray['wpSection'] = '';
266 }
267
268 $watch = $this->getWatchlistValue( $params['watchlist'], $titleObj );
269
270 // Deprecated parameters
271 if ( $params['watch'] ) {
272 $watch = true;
273 } elseif ( $params['unwatch'] ) {
274 $watch = false;
275 }
276
277 if ( $watch ) {
278 $requestArray['wpWatchthis'] = '';
279 }
280
281 global $wgTitle, $wgRequest;
282
283 $req = new DerivativeRequest( $this->getRequest(), $requestArray, true );
284
285 // Some functions depend on $wgTitle == $ep->mTitle
286 // TODO: Make them not or check if they still do
287 $wgTitle = $titleObj;
288
289 $articleObject = new Article( $titleObj );
290 $ep = new EditPage( $articleObject );
291
292 $ep->setContextTitle( $titleObj );
293 $ep->importFormData( $req );
294
295 // Run hooks
296 // Handle APIEditBeforeSave parameters
297 $r = array();
298 if ( !wfRunHooks( 'APIEditBeforeSave', array( $ep, $ep->textbox1, &$r ) ) ) {
299 if ( count( $r ) ) {
300 $r['result'] = 'Failure';
301 $apiResult->addValue( null, $this->getModuleName(), $r );
302 return;
303 } else {
304 $this->dieUsageMsg( 'hookaborted' );
305 }
306 }
307
308 // Do the actual save
309 $oldRevId = $articleObject->getRevIdFetched();
310 $result = null;
311 // Fake $wgRequest for some hooks inside EditPage
312 // @todo FIXME: This interface SUCKS
313 $oldRequest = $wgRequest;
314 $wgRequest = $req;
315
316 $status = $ep->internalAttemptSave( $result, $user->isAllowed( 'bot' ) && $params['bot'] );
317 $wgRequest = $oldRequest;
318 global $wgMaxArticleSize;
319
320 switch( $status->value ) {
321 case EditPage::AS_HOOK_ERROR:
322 case EditPage::AS_HOOK_ERROR_EXPECTED:
323 $this->dieUsageMsg( 'hookaborted' );
324
325 case EditPage::AS_IMAGE_REDIRECT_ANON:
326 $this->dieUsageMsg( 'noimageredirect-anon' );
327
328 case EditPage::AS_IMAGE_REDIRECT_LOGGED:
329 $this->dieUsageMsg( 'noimageredirect-logged' );
330
331 case EditPage::AS_SPAM_ERROR:
332 $this->dieUsageMsg( array( 'spamdetected', $result['spam'] ) );
333
334 case EditPage::AS_BLOCKED_PAGE_FOR_USER:
335 $this->dieUsageMsg( 'blockedtext' );
336
337 case EditPage::AS_MAX_ARTICLE_SIZE_EXCEEDED:
338 case EditPage::AS_CONTENT_TOO_BIG:
339 $this->dieUsageMsg( array( 'contenttoobig', $wgMaxArticleSize ) );
340
341 case EditPage::AS_READ_ONLY_PAGE_ANON:
342 $this->dieUsageMsg( 'noedit-anon' );
343
344 case EditPage::AS_READ_ONLY_PAGE_LOGGED:
345 $this->dieUsageMsg( 'noedit' );
346
347 case EditPage::AS_READ_ONLY_PAGE:
348 $this->dieReadOnly();
349
350 case EditPage::AS_RATE_LIMITED:
351 $this->dieUsageMsg( 'actionthrottledtext' );
352
353 case EditPage::AS_ARTICLE_WAS_DELETED:
354 $this->dieUsageMsg( 'wasdeleted' );
355
356 case EditPage::AS_NO_CREATE_PERMISSION:
357 $this->dieUsageMsg( 'nocreate-loggedin' );
358
359 case EditPage::AS_BLANK_ARTICLE:
360 $this->dieUsageMsg( 'blankpage' );
361
362 case EditPage::AS_CONFLICT_DETECTED:
363 $this->dieUsageMsg( 'editconflict' );
364
365 // case EditPage::AS_SUMMARY_NEEDED: Can't happen since we set wpIgnoreBlankSummary
366 case EditPage::AS_TEXTBOX_EMPTY:
367 $this->dieUsageMsg( 'emptynewsection' );
368
369 case EditPage::AS_SUCCESS_NEW_ARTICLE:
370 $r['new'] = '';
371
372 case EditPage::AS_SUCCESS_UPDATE:
373 $r['result'] = 'Success';
374 $r['pageid'] = intval( $titleObj->getArticleID() );
375 $r['title'] = $titleObj->getPrefixedText();
376 $r['contentmodel'] = $titleObj->getContentModel();
377 $newRevId = $articleObject->getLatest();
378 if ( $newRevId == $oldRevId ) {
379 $r['nochange'] = '';
380 } else {
381 $r['oldrevid'] = intval( $oldRevId );
382 $r['newrevid'] = intval( $newRevId );
383 $r['newtimestamp'] = wfTimestamp( TS_ISO_8601,
384 $pageObj->getTimestamp() );
385 }
386 break;
387
388 case EditPage::AS_SUMMARY_NEEDED:
389 $this->dieUsageMsg( 'summaryrequired' );
390
391 case EditPage::AS_END:
392 default:
393 // $status came from WikiPage::doEdit()
394 $errors = $status->getErrorsArray();
395 $this->dieUsageMsg( $errors[0] ); // TODO: Add new errors to message map
396 break;
397 }
398 $apiResult->addValue( null, $this->getModuleName(), $r );
399 }
400
401 public function mustBePosted() {
402 return true;
403 }
404
405 public function isWriteMode() {
406 return true;
407 }
408
409 public function getDescription() {
410 return 'Create and edit pages.';
411 }
412
413 public function getPossibleErrors() {
414 global $wgMaxArticleSize;
415
416 return array_merge( parent::getPossibleErrors(),
417 $this->getTitleOrPageIdErrorMessage(),
418 array(
419 array( 'missingtext' ),
420 array( 'createonly-exists' ),
421 array( 'nocreate-missing' ),
422 array( 'nosuchrevid', 'undo' ),
423 array( 'nosuchrevid', 'undoafter' ),
424 array( 'revwrongpage', 'id', 'text' ),
425 array( 'undo-failure' ),
426 array( 'hashcheckfailed' ),
427 array( 'hookaborted' ),
428 array( 'noimageredirect-anon' ),
429 array( 'noimageredirect-logged' ),
430 array( 'spamdetected', 'spam' ),
431 array( 'summaryrequired' ),
432 array( 'blockedtext' ),
433 array( 'contenttoobig', $wgMaxArticleSize ),
434 array( 'noedit-anon' ),
435 array( 'noedit' ),
436 array( 'actionthrottledtext' ),
437 array( 'wasdeleted' ),
438 array( 'nocreate-loggedin' ),
439 array( 'blankpage' ),
440 array( 'editconflict' ),
441 array( 'emptynewsection' ),
442 array( 'unknownerror', 'retval' ),
443 array( 'code' => 'nosuchsection', 'info' => 'There is no section section.' ),
444 array( 'code' => 'invalidsection', 'info' => 'The section parameter must be set to an integer or \'new\'' ),
445 array( 'code' => 'sectionsnotsupported', 'info' => 'Sections are not supported for this type of page.' ),
446 array( 'code' => 'editnotsupported', 'info' => 'Editing of this type of page is not supported using '
447 . 'the text based edit API.' ),
448 array( 'code' => 'appendnotsupported', 'info' => 'This type of page can not be edited by appending '
449 . 'or prepending text.' ),
450 array( 'code' => 'badformat', 'info' => 'The requested serialization format can not be applied to '
451 . 'the page\'s content model' ),
452 array( 'customcssprotected' ),
453 array( 'customjsprotected' ),
454 )
455 );
456 }
457
458 public function getAllowedParams() {
459 return array(
460 'title' => array(
461 ApiBase::PARAM_TYPE => 'string',
462 ),
463 'pageid' => array(
464 ApiBase::PARAM_TYPE => 'integer',
465 ),
466 'section' => null,
467 'sectiontitle' => array(
468 ApiBase::PARAM_TYPE => 'string',
469 ApiBase::PARAM_REQUIRED => false,
470 ),
471 'text' => null,
472 'token' => array(
473 ApiBase::PARAM_TYPE => 'string',
474 ApiBase::PARAM_REQUIRED => true
475 ),
476 'summary' => null,
477 'minor' => false,
478 'notminor' => false,
479 'bot' => false,
480 'basetimestamp' => null,
481 'starttimestamp' => null,
482 'recreate' => false,
483 'createonly' => false,
484 'nocreate' => false,
485 'watch' => array(
486 ApiBase::PARAM_DFLT => false,
487 ApiBase::PARAM_DEPRECATED => true,
488 ),
489 'unwatch' => array(
490 ApiBase::PARAM_DFLT => false,
491 ApiBase::PARAM_DEPRECATED => true,
492 ),
493 'watchlist' => array(
494 ApiBase::PARAM_DFLT => 'preferences',
495 ApiBase::PARAM_TYPE => array(
496 'watch',
497 'unwatch',
498 'preferences',
499 'nochange'
500 ),
501 ),
502 'md5' => null,
503 'prependtext' => null,
504 'appendtext' => null,
505 'undo' => array(
506 ApiBase::PARAM_TYPE => 'integer'
507 ),
508 'undoafter' => array(
509 ApiBase::PARAM_TYPE => 'integer'
510 ),
511 'redirect' => array(
512 ApiBase::PARAM_TYPE => 'boolean',
513 ApiBase::PARAM_DFLT => false,
514 ),
515 );
516 }
517
518 public function getParamDescription() {
519 $p = $this->getModulePrefix();
520 return array(
521 'title' => "Title of the page you want to edit. Cannot be used together with {$p}pageid",
522 'pageid' => "Page ID of the page you want to edit. Cannot be used together with {$p}title",
523 'section' => 'Section number. 0 for the top section, \'new\' for a new section',
524 'sectiontitle' => 'The title for a new section',
525 'text' => 'Page content',
526 'token' => array( 'Edit token. You can get one of these through prop=info.',
527 "The token should always be sent as the last parameter, or at least, after the {$p}text parameter"
528 ),
529 'summary' => "Edit summary. Also section title when {$p}section=new and {$p}sectiontitle is not set",
530 'minor' => 'Minor edit',
531 'notminor' => 'Non-minor edit',
532 'bot' => 'Mark this edit as bot',
533 'basetimestamp' => array( 'Timestamp of the base revision (obtained through prop=revisions&rvprop=timestamp).',
534 'Used to detect edit conflicts; leave unset to ignore conflicts'
535 ),
536 'starttimestamp' => array( 'Timestamp when you obtained the edit token.',
537 'Used to detect edit conflicts; leave unset to ignore conflicts'
538 ),
539 'recreate' => 'Override any errors about the article having been deleted in the meantime',
540 'createonly' => 'Don\'t edit the page if it exists already',
541 'nocreate' => 'Throw an error if the page doesn\'t exist',
542 'watch' => 'Add the page to your watchlist',
543 'unwatch' => 'Remove the page from your watchlist',
544 'watchlist' => 'Unconditionally add or remove the page from your watchlist, use preferences or do not change watch',
545 'md5' => array( "The MD5 hash of the {$p}text parameter, or the {$p}prependtext and {$p}appendtext parameters concatenated.",
546 'If set, the edit won\'t be done unless the hash is correct' ),
547 'prependtext' => "Add this text to the beginning of the page. Overrides {$p}text",
548 'appendtext' => array( "Add this text to the end of the page. Overrides {$p}text.",
549 "Use {$p}section=new to append a new section" ),
550 'undo' => "Undo this revision. Overrides {$p}text, {$p}prependtext and {$p}appendtext",
551 'undoafter' => 'Undo all revisions from undo to this one. If not set, just undo one revision',
552 'redirect' => 'Automatically resolve redirects',
553 );
554 }
555
556 public function getResultProperties() {
557 return array(
558 '' => array(
559 'new' => 'boolean',
560 'result' => array(
561 ApiBase::PROP_TYPE => array(
562 'Success',
563 'Failure'
564 ),
565 ),
566 'pageid' => array(
567 ApiBase::PROP_TYPE => 'integer',
568 ApiBase::PROP_NULLABLE => true
569 ),
570 'title' => array(
571 ApiBase::PROP_TYPE => 'string',
572 ApiBase::PROP_NULLABLE => true
573 ),
574 'nochange' => 'boolean',
575 'oldrevid' => array(
576 ApiBase::PROP_TYPE => 'integer',
577 ApiBase::PROP_NULLABLE => true
578 ),
579 'newrevid' => array(
580 ApiBase::PROP_TYPE => 'integer',
581 ApiBase::PROP_NULLABLE => true
582 ),
583 'newtimestamp' => array(
584 ApiBase::PROP_TYPE => 'string',
585 ApiBase::PROP_NULLABLE => true
586 )
587 )
588 );
589 }
590
591 public function needsToken() {
592 return true;
593 }
594
595 public function getTokenSalt() {
596 return '';
597 }
598
599 public function getExamples() {
600 return array(
601
602 'api.php?action=edit&title=Test&summary=test%20summary&text=article%20content&basetimestamp=20070824123454&token=%2B\\'
603 => 'Edit a page (anonymous user)',
604
605 'api.php?action=edit&title=Test&summary=NOTOC&minor=&prependtext=__NOTOC__%0A&basetimestamp=20070824123454&token=%2B\\'
606 => 'Prepend __NOTOC__ to a page (anonymous user)',
607 'api.php?action=edit&title=Test&undo=13585&undoafter=13579&basetimestamp=20070824123454&token=%2B\\'
608 => 'Undo r13579 through r13585 with autosummary (anonymous user)',
609 );
610 }
611
612 public function getHelpUrls() {
613 return 'https://www.mediawiki.org/wiki/API:Edit';
614 }
615
616 public function getVersion() {
617 return __CLASS__ . ': $Id$';
618 }
619 }