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