]> scripts.mit.edu Git - autoinstalls/mediawiki.git/blob - includes/api/ApiEditPage.php
MediaWiki 1.17.4
[autoinstalls/mediawiki.git] / includes / api / ApiEditPage.php
1 <?php
2 /**
3  * API for MediaWiki 1.8+
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 if ( !defined( 'MEDIAWIKI' ) ) {
28         // Eclipse helper - will be ignored in production
29         require_once( "ApiBase.php" );
30 }
31
32 /**
33  * A module that allows for editing and creating pages.
34  *
35  * Currently, this wraps around the EditPage class in an ugly way,
36  * EditPage.php should be rewritten to provide a cleaner interface
37  * @ingroup API
38  */
39 class ApiEditPage extends ApiBase {
40
41         public function __construct( $query, $moduleName ) {
42                 parent::__construct( $query, $moduleName );
43         }
44
45         public function execute() {
46                 global $wgUser;
47                 $params = $this->extractRequestParams();
48
49                 if ( is_null( $params['text'] ) && is_null( $params['appendtext'] ) &&
50                                 is_null( $params['prependtext'] ) &&
51                                 $params['undo'] == 0 )
52                 {
53                         $this->dieUsageMsg( array( 'missingtext' ) );
54                 }
55
56                 $titleObj = Title::newFromText( $params['title'] );
57                 if ( !$titleObj || $titleObj->isExternal() ) {
58                         $this->dieUsageMsg( array( 'invalidtitle', $params['title'] ) );
59                 }
60                 
61                 if( $params['redirect'] ) {
62                         if( $titleObj->isRedirect() ) {
63                                 $oldTitle = $titleObj;
64                                 
65                                 $titles = Title::newFromRedirectArray( Revision::newFromTitle( $oldTitle )->getText( Revision::FOR_THIS_USER ) );
66
67                                 $redirValues = array();
68                                 foreach ( $titles as $id => $newTitle ) {
69                                         
70                                         if( !isset( $titles[ $id - 1 ] ) ) {
71                                                 $titles[ $id - 1 ] = $oldTitle;
72                                         }
73                                         
74                                         $redirValues[] = array(
75                                                 'from' => $titles[ $id - 1 ]->getPrefixedText(),
76                                                 'to' => $newTitle->getPrefixedText()
77                                         );
78                                         
79                                         $titleObj = $newTitle;
80                                 }
81                 
82                                 $this->getResult()->setIndexedTagName( $redirValues, 'r' );
83                                 $this->getResult()->addValue( null, 'redirects', $redirValues );
84
85                         }
86                 }
87
88                 // Some functions depend on $wgTitle == $ep->mTitle
89                 global $wgTitle;
90                 $wgTitle = $titleObj;
91
92                 if ( $params['createonly'] && $titleObj->exists() ) {
93                         $this->dieUsageMsg( array( 'createonly-exists' ) );
94                 }
95                 if ( $params['nocreate'] && !$titleObj->exists() ) {
96                         $this->dieUsageMsg( array( 'nocreate-missing' ) );
97                 }
98
99                 // Now let's check whether we're even allowed to do this
100                 $errors = $titleObj->getUserPermissionsErrors( 'edit', $wgUser );
101                 if ( !$titleObj->exists() ) {
102                         $errors = array_merge( $errors, $titleObj->getUserPermissionsErrors( 'create', $wgUser ) );
103                 }
104                 if ( count( $errors ) ) {
105                         $this->dieUsageMsg( $errors[0] );
106                 }
107
108                 $articleObj = new Article( $titleObj );
109                 $toMD5 = $params['text'];
110                 if ( !is_null( $params['appendtext'] ) || !is_null( $params['prependtext'] ) )
111                 {
112                         // For non-existent pages, Article::getContent()
113                         // returns an interface message rather than ''
114                         // We do want getContent()'s behavior for non-existent
115                         // MediaWiki: pages, though
116                         if ( $articleObj->getID() == 0 && $titleObj->getNamespace() != NS_MEDIAWIKI ) {
117                                 $content = '';
118                         } else {
119                                 $content = $articleObj->getContent();
120                         }
121
122                         if ( !is_null( $params['section'] ) ) {
123                                 // Process the content for section edits
124                                 global $wgParser;
125                                 $section = intval( $params['section'] );
126                                 $content = $wgParser->getSection( $content, $section, false );
127                                 if ( $content === false ) {
128                                         $this->dieUsage( "There is no section {$section}.", 'nosuchsection' );
129                                 }
130                         }
131                         $params['text'] = $params['prependtext'] . $content . $params['appendtext'];
132                         $toMD5 = $params['prependtext'] . $params['appendtext'];
133                 }
134
135                 if ( $params['undo'] > 0 ) {
136                         if ( $params['undoafter'] > 0 ) {
137                                 if ( $params['undo'] < $params['undoafter'] ) {
138                                         list( $params['undo'], $params['undoafter'] ) =
139                                         array( $params['undoafter'], $params['undo'] );
140                                 }
141                                 $undoafterRev = Revision::newFromID( $params['undoafter'] );
142                         }
143                         $undoRev = Revision::newFromID( $params['undo'] );
144                         if ( is_null( $undoRev ) || $undoRev->isDeleted( Revision::DELETED_TEXT ) ) {
145                                 $this->dieUsageMsg( array( 'nosuchrevid', $params['undo'] ) );
146                         }
147
148                         if ( $params['undoafter'] == 0 ) {
149                                 $undoafterRev = $undoRev->getPrevious();
150                         }
151                         if ( is_null( $undoafterRev ) || $undoafterRev->isDeleted( Revision::DELETED_TEXT ) ) {
152                                 $this->dieUsageMsg( array( 'nosuchrevid', $params['undoafter'] ) );
153                         }
154
155                         if ( $undoRev->getPage() != $articleObj->getID() ) {
156                                 $this->dieUsageMsg( array( 'revwrongpage', $undoRev->getID(), $titleObj->getPrefixedText() ) );
157                         }
158                         if ( $undoafterRev->getPage() != $articleObj->getID() ) {
159                                 $this->dieUsageMsg( array( 'revwrongpage', $undoafterRev->getID(), $titleObj->getPrefixedText() ) );
160                         }
161
162                         $newtext = $articleObj->getUndoText( $undoRev, $undoafterRev );
163                         if ( $newtext === false ) {
164                                 $this->dieUsageMsg( array( 'undo-failure' ) );
165                         }
166                         $params['text'] = $newtext;
167                         // If no summary was given and we only undid one rev,
168                         // use an autosummary
169                         if ( is_null( $params['summary'] ) && $titleObj->getNextRevisionID( $undoafterRev->getID() ) == $params['undo'] ) {
170                                 $params['summary'] = wfMsgForContent( 'undo-summary', $params['undo'], $undoRev->getUserText() );
171                         }
172                 }
173
174                 // See if the MD5 hash checks out
175                 if ( !is_null( $params['md5'] ) && md5( $toMD5 ) !== $params['md5'] ) {
176                         $this->dieUsageMsg( array( 'hashcheckfailed' ) );
177                 }
178
179                 $ep = new EditPage( $articleObj );
180                 // EditPage wants to parse its stuff from a WebRequest
181                 // That interface kind of sucks, but it's workable
182                 $reqArr = array(
183                         'wpTextbox1' => $params['text'],
184                         'wpEditToken' => $params['token'],
185                         'wpIgnoreBlankSummary' => ''
186                 );
187
188                 if ( !is_null( $params['summary'] ) ) {
189                         $reqArr['wpSummary'] = $params['summary'];
190                 }
191
192                 // Watch out for basetimestamp == ''
193                 // wfTimestamp() treats it as NOW, almost certainly causing an edit conflict
194                 if ( !is_null( $params['basetimestamp'] ) && $params['basetimestamp'] != '' ) {
195                         $reqArr['wpEdittime'] = wfTimestamp( TS_MW, $params['basetimestamp'] );
196                 } else {
197                         $reqArr['wpEdittime'] = $articleObj->getTimestamp();
198                 }
199
200                 if ( !is_null( $params['starttimestamp'] ) && $params['starttimestamp'] != '' ) {
201                         $reqArr['wpStarttime'] = wfTimestamp( TS_MW, $params['starttimestamp'] );
202                 } else {
203                         $reqArr['wpStarttime'] = wfTimestampNow();      // Fake wpStartime
204                 }
205
206                 if ( $params['minor'] || ( !$params['notminor'] && $wgUser->getOption( 'minordefault' ) ) )     {
207                         $reqArr['wpMinoredit'] = '';
208                 }
209
210                 if ( $params['recreate'] ) {
211                         $reqArr['wpRecreate'] = '';
212                 }
213
214                 if ( !is_null( $params['section'] ) ) {
215                         $section = intval( $params['section'] );
216                         if ( $section == 0 && $params['section'] != '0' && $params['section'] != 'new' ) {
217                                 $this->dieUsage( "The section parameter must be set to an integer or 'new'", "invalidsection" );
218                         }
219                         $reqArr['wpSection'] = $params['section'];
220                 } else {
221                         $reqArr['wpSection'] = '';
222                 }
223
224                 $watch = $this->getWatchlistValue( $params['watchlist'], $titleObj );
225
226                 // Deprecated parameters
227                 if ( $params['watch'] ) {
228                         $watch = true;
229                 } elseif ( $params['unwatch'] ) {
230                         $watch = false;
231                 }
232
233                 if ( $watch ) {
234                         $reqArr['wpWatchthis'] = '';
235                 }
236
237                 $req = new FauxRequest( $reqArr, true );
238                 $ep->importFormData( $req );
239
240                 // Run hooks
241                 // Handle CAPTCHA parameters
242                 global $wgRequest;
243                 if ( !is_null( $params['captchaid'] ) ) {
244                         $wgRequest->setVal( 'wpCaptchaId', $params['captchaid'] );
245                 }
246                 if ( !is_null( $params['captchaword'] ) ) {
247                         $wgRequest->setVal( 'wpCaptchaWord', $params['captchaword'] );
248                 }
249
250                 $r = array();
251                 if ( !wfRunHooks( 'APIEditBeforeSave', array( $ep, $ep->textbox1, &$r ) ) ) {
252                         if ( count( $r ) ) {
253                                 $r['result'] = 'Failure';
254                                 $this->getResult()->addValue( null, $this->getModuleName(), $r );
255                                 return;
256                         } else {
257                                 $this->dieUsageMsg( array( 'hookaborted' ) );
258                         }
259                 }
260
261                 // Do the actual save
262                 $oldRevId = $articleObj->getRevIdFetched();
263                 $result = null;
264                 // Fake $wgRequest for some hooks inside EditPage
265                 // FIXME: This interface SUCKS
266                 $oldRequest = $wgRequest;
267                 $wgRequest = $req;
268
269                 $retval = $ep->internalAttemptSave( $result, $wgUser->isAllowed( 'bot' ) && $params['bot'] );
270                 $wgRequest = $oldRequest;
271                 global $wgMaxArticleSize;
272
273                 switch( $retval ) {
274                         case EditPage::AS_HOOK_ERROR:
275                         case EditPage::AS_HOOK_ERROR_EXPECTED:
276                                 $this->dieUsageMsg( array( 'hookaborted' ) );
277
278                         case EditPage::AS_IMAGE_REDIRECT_ANON:
279                                 $this->dieUsageMsg( array( 'noimageredirect-anon' ) );
280
281                         case EditPage::AS_IMAGE_REDIRECT_LOGGED:
282                                 $this->dieUsageMsg( array( 'noimageredirect-logged' ) );
283
284                         case EditPage::AS_SPAM_ERROR:
285                                 $this->dieUsageMsg( array( 'spamdetected', $result['spam'] ) );
286
287                         case EditPage::AS_FILTERING:
288                                 $this->dieUsageMsg( array( 'filtered' ) );
289
290                         case EditPage::AS_BLOCKED_PAGE_FOR_USER:
291                                 $this->dieUsageMsg( array( 'blockedtext' ) );
292
293                         case EditPage::AS_MAX_ARTICLE_SIZE_EXCEEDED:
294                         case EditPage::AS_CONTENT_TOO_BIG:
295                                 $this->dieUsageMsg( array( 'contenttoobig', $wgMaxArticleSize ) );
296
297                         case EditPage::AS_READ_ONLY_PAGE_ANON:
298                                 $this->dieUsageMsg( array( 'noedit-anon' ) );
299
300                         case EditPage::AS_READ_ONLY_PAGE_LOGGED:
301                                 $this->dieUsageMsg( array( 'noedit' ) );
302
303                         case EditPage::AS_READ_ONLY_PAGE:
304                                 $this->dieReadOnly();
305
306                         case EditPage::AS_RATE_LIMITED:
307                                 $this->dieUsageMsg( array( 'actionthrottledtext' ) );
308
309                         case EditPage::AS_ARTICLE_WAS_DELETED:
310                                 $this->dieUsageMsg( array( 'wasdeleted' ) );
311
312                         case EditPage::AS_NO_CREATE_PERMISSION:
313                                 $this->dieUsageMsg( array( 'nocreate-loggedin' ) );
314
315                         case EditPage::AS_BLANK_ARTICLE:
316                                 $this->dieUsageMsg( array( 'blankpage' ) );
317
318                         case EditPage::AS_CONFLICT_DETECTED:
319                                 $this->dieUsageMsg( array( 'editconflict' ) );
320
321                         // case EditPage::AS_SUMMARY_NEEDED: Can't happen since we set wpIgnoreBlankSummary
322                         case EditPage::AS_TEXTBOX_EMPTY:
323                                 $this->dieUsageMsg( array( 'emptynewsection' ) );
324
325                         case EditPage::AS_SUCCESS_NEW_ARTICLE:
326                                 $r['new'] = '';
327
328                         case EditPage::AS_SUCCESS_UPDATE:
329                                 $r['result'] = 'Success';
330                                 $r['pageid'] = intval( $titleObj->getArticleID() );
331                                 $r['title'] = $titleObj->getPrefixedText();
332                                 // HACK: We create a new Article object here because getRevIdFetched()
333                                 // refuses to be run twice, and because Title::getLatestRevId()
334                                 // won't fetch from the master unless we select for update, which we
335                                 // don't want to do.
336                                 $newArticle = new Article( $titleObj );
337                                 $newRevId = $newArticle->getRevIdFetched();
338                                 if ( $newRevId == $oldRevId ) {
339                                         $r['nochange'] = '';
340                                 } else {
341                                         $r['oldrevid'] = intval( $oldRevId );
342                                         $r['newrevid'] = intval( $newRevId );
343                                         $r['newtimestamp'] = wfTimestamp( TS_ISO_8601,
344                                                 $newArticle->getTimestamp() );
345                                 }
346                                 break;
347
348                         case EditPage::AS_SUMMARY_NEEDED:
349                                 $this->dieUsageMsg( array( 'summaryrequired' ) );
350
351                         case EditPage::AS_END:
352                                 // This usually means some kind of race condition
353                                 // or DB weirdness occurred. Fall through to throw an unknown
354                                 // error.
355
356                                 // This needs fixing higher up, as Article::doEdit should be
357                                 // used rather than Article::updateArticle, so that specific
358                                 // error conditions can be returned
359                         default:
360                                 $this->dieUsageMsg( array( 'unknownerror', $retval ) );
361                 }
362                 $this->getResult()->addValue( null, $this->getModuleName(), $r );
363         }
364
365         public function mustBePosted() {
366                 return true;
367         }
368
369         public function isWriteMode() {
370                 return true;
371         }
372
373         protected function getDescription() {
374                 return 'Create and edit pages.';
375         }
376
377         public function getPossibleErrors() {
378                 global $wgMaxArticleSize;
379
380                 return array_merge( parent::getPossibleErrors(), array(
381                         array( 'missingtext' ),
382                         array( 'invalidtitle', 'title' ),
383                         array( 'createonly-exists' ),
384                         array( 'nocreate-missing' ),
385                         array( 'nosuchrevid', 'undo' ),
386                         array( 'nosuchrevid', 'undoafter' ),
387                         array( 'revwrongpage', 'id', 'text' ),
388                         array( 'undo-failure' ),
389                         array( 'hashcheckfailed' ),
390                         array( 'hookaborted' ),
391                         array( 'noimageredirect-anon' ),
392                         array( 'noimageredirect-logged' ),
393                         array( 'spamdetected', 'spam' ),
394                         array( 'summaryrequired' ),
395                         array( 'filtered' ),
396                         array( 'blockedtext' ),
397                         array( 'contenttoobig', $wgMaxArticleSize ),
398                         array( 'noedit-anon' ),
399                         array( 'noedit' ),
400                         array( 'actionthrottledtext' ),
401                         array( 'wasdeleted' ),
402                         array( 'nocreate-loggedin' ),
403                         array( 'blankpage' ),
404                         array( 'editconflict' ),
405                         array( 'emptynewsection' ),
406                         array( 'unknownerror', 'retval' ),
407                         array( 'code' => 'nosuchsection', 'info' => 'There is no section section.' ),
408                         array( 'code' => 'invalidsection', 'info' => 'The section parameter must be set to an integer or \'new\'' ),
409                 ) );
410         }
411
412         protected function getAllowedParams() {
413                 return array(
414                         'title' => array(
415                                 ApiBase::PARAM_TYPE => 'string',
416                                 ApiBase::PARAM_REQUIRED => true
417                         ),
418                         'section' => null,
419                         'text' => null,
420                         'token' => null,
421                         'summary' => null,
422                         'minor' => false,
423                         'notminor' => false,
424                         'bot' => false,
425                         'basetimestamp' => null,
426                         'starttimestamp' => null,
427                         'recreate' => false,
428                         'createonly' => false,
429                         'nocreate' => false,
430                         'captchaword' => null,
431                         'captchaid' => null,
432                         'watch' => array(
433                                 ApiBase::PARAM_DFLT => false,
434                                 ApiBase::PARAM_DEPRECATED => true,
435                         ),
436                         'unwatch' => array(
437                                 ApiBase::PARAM_DFLT => false,
438                                 ApiBase::PARAM_DEPRECATED => true,
439                         ),
440                         'watchlist' => array(
441                                 ApiBase::PARAM_DFLT => 'preferences',
442                                 ApiBase::PARAM_TYPE => array(
443                                         'watch',
444                                         'unwatch',
445                                         'preferences',
446                                         'nochange'
447                                 ),
448                         ),
449                         'md5' => null,
450                         'prependtext' => null,
451                         'appendtext' => null,
452                         'undo' => array(
453                                 ApiBase::PARAM_TYPE => 'integer'
454                         ),
455                         'undoafter' => array(
456                                 ApiBase::PARAM_TYPE => 'integer'
457                         ),
458                         'redirect' => array(
459                                 ApiBase::PARAM_TYPE => 'boolean',
460                                 ApiBase::PARAM_DFLT => false,
461                         ),
462                 );
463         }
464
465         protected function getParamDescription() {
466                 $p = $this->getModulePrefix();
467                 return array(
468                         'title' => 'Page title',
469                         'section' => 'Section number. 0 for the top section, \'new\' for a new section',
470                         'text' => 'Page content',
471                         'token' => 'Edit token. You can get one of these through prop=info',
472                         'summary' => 'Edit summary. Also section title when section=new',
473                         'minor' => 'Minor edit',
474                         'notminor' => 'Non-minor edit',
475                         'bot' => 'Mark this edit as bot',
476                         'basetimestamp' => array( 'Timestamp of the base revision (gotten through prop=revisions&rvprop=timestamp).',
477                                                 'Used to detect edit conflicts; leave unset to ignore conflicts.'
478                         ),
479                         'starttimestamp' => array( 'Timestamp when you obtained the edit token.',
480                                                 'Used to detect edit conflicts; leave unset to ignore conflicts'
481                         ),
482                         'recreate' => 'Override any errors about the article having been deleted in the meantime',
483                         'createonly' => 'Don\'t edit the page if it exists already',
484                         'nocreate' => 'Throw an error if the page doesn\'t exist',
485                         'watch' => 'Add the page to your watchlist',
486                         'unwatch' => 'Remove the page from your watchlist',
487                         'watchlist' => 'Unconditionally add or remove the page from your watchlist, use preferences or do not change watch',
488                         'captchaid' => 'CAPTCHA ID from previous request',
489                         'captchaword' => 'Answer to the CAPTCHA',
490                         'md5' => array( "The MD5 hash of the {$p}text parameter, or the {$p}prependtext and {$p}appendtext parameters concatenated.",
491                                         'If set, the edit won\'t be done unless the hash is correct' ),
492                         'prependtext' => "Add this text to the beginning of the page. Overrides {$p}text",
493                         'appendtext' => "Add this text to the end of the page. Overrides {$p}text",
494                         'undo' => "Undo this revision. Overrides {$p}text, {$p}prependtext and {$p}appendtext",
495                         'undoafter' => 'Undo all revisions from undo to this one. If not set, just undo one revision',
496                         'redirect' => 'Automatically resolve redirects',
497                 );
498         }
499
500         public function needsToken() {
501                 return true;
502         }
503
504         public function getTokenSalt() {
505                 return '';
506         }
507
508         protected function getExamples() {
509                 return array(
510                         'Edit a page (anonymous user):',
511                         '    api.php?action=edit&title=Test&summary=test%20summary&text=article%20content&basetimestamp=20070824123454&token=%2B\\',
512                         'Prepend __NOTOC__ to a page (anonymous user):',
513                         '    api.php?action=edit&title=Test&summary=NOTOC&minor=&prependtext=__NOTOC__%0A&basetimestamp=20070824123454&token=%2B\\',
514                         'Undo r13579 through r13585 with autosummary (anonymous user):',
515                         '    api.php?action=edit&title=Test&undo=13585&undoafter=13579&basetimestamp=20070824123454&token=%2B\\',
516                 );
517         }
518
519         public function getVersion() {
520                 return __CLASS__ . ': $Id$';
521         }
522 }