]> scripts.mit.edu Git - autoinstalls/mediawiki.git/blob - includes/api/ApiEditPage.php
MediaWiki 1.15.0
[autoinstalls/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                 if(is_null($params['title']))
48                         $this->dieUsageMsg(array('missingparam', 'title'));
49                 if(is_null($params['text']) && is_null($params['appendtext']) &&
50                                 is_null($params['prependtext']) &&
51                                 $params['undo'] == 0)
52                         $this->dieUsageMsg(array('missingtext'));
53                 if(is_null($params['token']))
54                         $this->dieUsageMsg(array('missingparam', 'token'));
55                 if(!$wgUser->matchEditToken($params['token']))
56                         $this->dieUsageMsg(array('sessionfailure'));
57
58                 $titleObj = Title::newFromText($params['title']);
59                 if(!$titleObj)
60                         $this->dieUsageMsg(array('invalidtitle', $params['title']));
61                 // Some functions depend on $wgTitle == $ep->mTitle
62                 global $wgTitle;
63                 $wgTitle = $titleObj;
64
65                 if($params['createonly'] && $titleObj->exists())
66                         $this->dieUsageMsg(array('createonly-exists'));
67                 if($params['nocreate'] && !$titleObj->exists())
68                         $this->dieUsageMsg(array('nocreate-missing'));
69
70                 // Now let's check whether we're even allowed to do this
71                 $errors = $titleObj->getUserPermissionsErrors('edit', $wgUser);
72                 if(!$titleObj->exists())
73                         $errors = array_merge($errors, $titleObj->getUserPermissionsErrors('create', $wgUser));
74                 if(count($errors))
75                         $this->dieUsageMsg($errors[0]);
76
77                 $articleObj = new Article($titleObj);
78                 $toMD5 = $params['text'];
79                 if(!is_null($params['appendtext']) || !is_null($params['prependtext']))
80                 {
81                         // For non-existent pages, Article::getContent()
82                         // returns an interface message rather than ''
83                         // We do want getContent()'s behavior for non-existent
84                         // MediaWiki: pages, though
85                         if($articleObj->getID() == 0 && $titleObj->getNamespace() != NS_MEDIAWIKI)
86                                 $content = '';
87                         else
88                                 $content = $articleObj->getContent();
89                         $params['text'] = $params['prependtext'] . $content . $params['appendtext'];
90                         $toMD5 = $params['prependtext'] . $params['appendtext'];
91                 }
92                 
93                 if($params['undo'] > 0)
94                 {
95                         if($params['undoafter'] > 0)
96                         {
97                                 if($params['undo'] < $params['undoafter'])
98                                         list($params['undo'], $params['undoafter']) =
99                                         array($params['undoafter'], $params['undo']);
100                                 $undoafterRev = Revision::newFromID($params['undoafter']);
101                         }
102                         $undoRev = Revision::newFromID($params['undo']);
103                         if(is_null($undoRev) || $undoRev->isDeleted(Revision::DELETED_TEXT))
104                                 $this->dieUsageMsg(array('nosuchrevid', $params['undo']));
105                         if($params['undoafter'] == 0)
106                                 $undoafterRev = $undoRev->getPrevious();
107                         if(is_null($undoafterRev) || $undoafterRev->isDeleted(Revision::DELETED_TEXT))
108                                 $this->dieUsageMsg(array('nosuchrevid', $params['undoafter']));
109                         if($undoRev->getPage() != $articleObj->getID())
110                                 $this->dieUsageMsg(array('revwrongpage', $undoRev->getID(), $titleObj->getPrefixedText()));
111                         if($undoafterRev->getPage() != $articleObj->getID())
112                                 $this->dieUsageMsg(array('revwrongpage', $undoafterRev->getID(), $titleObj->getPrefixedText()));
113                         $newtext = $articleObj->getUndoText($undoRev, $undoafterRev);
114                         if($newtext === false)
115                                 $this->dieUsageMsg(array('undo-failure'));
116                         $params['text'] = $newtext;
117                         // If no summary was given and we only undid one rev,
118                         // use an autosummary
119                         if(is_null($params['summary']) && $titleObj->getNextRevisionID($undoafterRev->getID()) == $params['undo'])
120                                 $params['summary'] = wfMsgForContent('undo-summary', $params['undo'], $undoRev->getUserText());
121                 }
122
123                 # See if the MD5 hash checks out
124                 if(!is_null($params['md5']))
125                         if(md5($toMD5) !== $params['md5'])
126                                 $this->dieUsageMsg(array('hashcheckfailed'));
127                 
128                 $ep = new EditPage($articleObj);
129                 // EditPage wants to parse its stuff from a WebRequest
130                 // That interface kind of sucks, but it's workable
131                 $reqArr = array('wpTextbox1' => $params['text'],
132                                 'wpEdittoken' => $params['token'],
133                                 'wpIgnoreBlankSummary' => ''
134                 );
135                 if(!is_null($params['summary']))
136                         $reqArr['wpSummary'] = $params['summary'];
137                 # Watch out for basetimestamp == ''
138                 # wfTimestamp() treats it as NOW, almost certainly causing an edit conflict
139                 if(!is_null($params['basetimestamp']) && $params['basetimestamp'] != '')
140                         $reqArr['wpEdittime'] = wfTimestamp(TS_MW, $params['basetimestamp']);
141                 else
142                         $reqArr['wpEdittime'] = $articleObj->getTimestamp();
143                 if(!is_null($params['starttimestamp']) && $params['starttimestamp'] != '')
144                         $reqArr['wpStarttime'] = wfTimestamp(TS_MW, $params['starttimestamp']);
145                 else
146                         # Fake wpStartime
147                         $reqArr['wpStarttime'] = $reqArr['wpEdittime'];
148                 if($params['minor'] || (!$params['notminor'] && $wgUser->getOption('minordefault')))
149                         $reqArr['wpMinoredit'] = '';
150                 if($params['recreate'])
151                         $reqArr['wpRecreate'] = '';
152                 if(!is_null($params['section']))
153                 {
154                         $section = intval($params['section']);
155                         if($section == 0 && $params['section'] != '0' && $params['section'] != 'new')
156                                 $this->dieUsage("The section parameter must be set to an integer or 'new'", "invalidsection");
157                         $reqArr['wpSection'] = $params['section'];
158                 }
159                 else
160                         $reqArr['wpSection'] = '';
161
162                 if($params['watch'])
163                         $watch = true;
164                 else if($params['unwatch'])
165                         $watch = false;
166                 else if($titleObj->userIsWatching())
167                         $watch = true;
168                 else if($wgUser->getOption('watchdefault'))
169                         $watch = true;
170                 else if($wgUser->getOption('watchcreations') && !$titleObj->exists())
171                         $watch = true;
172                 else
173                         $watch = false;
174                 if($watch)
175                         $reqArr['wpWatchthis'] = '';
176
177                 $req = new FauxRequest($reqArr, true);
178                 $ep->importFormData($req);
179
180                 # Run hooks
181                 # Handle CAPTCHA parameters
182                 global $wgRequest;
183                 if(!is_null($params['captchaid']))
184                         $wgRequest->setVal( 'wpCaptchaId', $params['captchaid'] );
185                 if(!is_null($params['captchaword']))
186                         $wgRequest->setVal( 'wpCaptchaWord', $params['captchaword'] );
187                 $r = array();
188                 if(!wfRunHooks('APIEditBeforeSave', array(&$ep, $ep->textbox1, &$r)))
189                 {
190                         if(count($r))
191                         {
192                                 $r['result'] = "Failure";
193                                 $this->getResult()->addValue(null, $this->getModuleName(), $r);
194                                 return;
195                         }
196                         else
197                                 $this->dieUsageMsg(array('hookaborted'));
198                 }
199
200                 # Do the actual save
201                 $oldRevId = $articleObj->getRevIdFetched();
202                 $result = null;
203                 # Fake $wgRequest for some hooks inside EditPage
204                 # FIXME: This interface SUCKS
205                 $oldRequest = $wgRequest;
206                 $wgRequest = $req;
207
208                 $retval = $ep->internalAttemptSave($result, $wgUser->isAllowed('bot') && $params['bot']);
209                 $wgRequest = $oldRequest;
210                 switch($retval)
211                 {
212                         case EditPage::AS_HOOK_ERROR:
213                         case EditPage::AS_HOOK_ERROR_EXPECTED:
214                                 $this->dieUsageMsg(array('hookaborted'));
215                         case EditPage::AS_IMAGE_REDIRECT_ANON:
216                                 $this->dieUsageMsg(array('noimageredirect-anon'));
217                         case EditPage::AS_IMAGE_REDIRECT_LOGGED:
218                                 $this->dieUsageMsg(array('noimageredirect-logged'));
219                         case EditPage::AS_SPAM_ERROR:
220                                 $this->dieUsageMsg(array('spamdetected', $result['spam']));
221                         case EditPage::AS_FILTERING:
222                                 $this->dieUsageMsg(array('filtered'));
223                         case EditPage::AS_BLOCKED_PAGE_FOR_USER:
224                                 $this->dieUsageMsg(array('blockedtext'));
225                         case EditPage::AS_MAX_ARTICLE_SIZE_EXCEEDED:
226                         case EditPage::AS_CONTENT_TOO_BIG:
227                                 global $wgMaxArticleSize;
228                                 $this->dieUsageMsg(array('contenttoobig', $wgMaxArticleSize));
229                         case EditPage::AS_READ_ONLY_PAGE_ANON:
230                                 $this->dieUsageMsg(array('noedit-anon'));
231                         case EditPage::AS_READ_ONLY_PAGE_LOGGED:
232                                 $this->dieUsageMsg(array('noedit'));
233                         case EditPage::AS_READ_ONLY_PAGE:
234                                 $this->dieUsageMsg(array('readonlytext'));
235                         case EditPage::AS_RATE_LIMITED:
236                                 $this->dieUsageMsg(array('actionthrottledtext'));
237                         case EditPage::AS_ARTICLE_WAS_DELETED:
238                                 $this->dieUsageMsg(array('wasdeleted'));
239                         case EditPage::AS_NO_CREATE_PERMISSION:
240                                 $this->dieUsageMsg(array('nocreate-loggedin'));
241                         case EditPage::AS_BLANK_ARTICLE:
242                                 $this->dieUsageMsg(array('blankpage'));
243                         case EditPage::AS_CONFLICT_DETECTED:
244                                 $this->dieUsageMsg(array('editconflict'));
245                         #case EditPage::AS_SUMMARY_NEEDED: Can't happen since we set wpIgnoreBlankSummary
246                         case EditPage::AS_TEXTBOX_EMPTY:
247                                 $this->dieUsageMsg(array('emptynewsection'));
248                         case EditPage::AS_END:
249                                 # This usually means some kind of race condition
250                                 # or DB weirdness occurred. Throw an unknown error here.
251                                 $this->dieUsageMsg(array('unknownerror'));
252                         case EditPage::AS_SUCCESS_NEW_ARTICLE:
253                                 $r['new'] = '';
254                         case EditPage::AS_SUCCESS_UPDATE:
255                                 $r['result'] = "Success";
256                                 $r['pageid'] = intval($titleObj->getArticleID());
257                                 $r['title'] = $titleObj->getPrefixedText();
258                                 # HACK: We create a new Article object here because getRevIdFetched()
259                                 # refuses to be run twice, and because Title::getLatestRevId()
260                                 # won't fetch from the master unless we select for update, which we
261                                 # don't want to do.
262                                 $newArticle = new Article($titleObj);
263                                 $newRevId = $newArticle->getRevIdFetched();
264                                 if($newRevId == $oldRevId)
265                                         $r['nochange'] = '';
266                                 else
267                                 {
268                                         $r['oldrevid'] = intval($oldRevId);
269                                         $r['newrevid'] = intval($newRevId);
270                                 }
271                                 break;
272                         default:
273                                 $this->dieUsageMsg(array('unknownerror', $retval));
274                 }
275                 $this->getResult()->addValue(null, $this->getModuleName(), $r);
276         }
277
278         public function mustBePosted() {
279                 return true;
280         }
281
282         public function isWriteMode() {
283                 return true;
284         }
285
286         protected function getDescription() {
287                 return 'Create and edit pages.';
288         }
289
290         protected function getAllowedParams() {
291                 return array (
292                         'title' => null,
293                         'section' => null,
294                         'text' => null,
295                         'token' => null,
296                         'summary' => null,
297                         'minor' => false,
298                         'notminor' => false,
299                         'bot' => false,
300                         'basetimestamp' => null,
301                         'starttimestamp' => null,
302                         'recreate' => false,
303                         'createonly' => false,
304                         'nocreate' => false,
305                         'captchaword' => null,
306                         'captchaid' => null,
307                         'watch' => false,
308                         'unwatch' => false,
309                         'md5' => null,
310                         'prependtext' => null,
311                         'appendtext' => null,
312                         'undo' => array(
313                                 ApiBase :: PARAM_TYPE => 'integer'
314                         ),
315                         'undoafter' => array(
316                                 ApiBase :: PARAM_TYPE => 'integer'
317                         ),
318                 );
319         }
320
321         protected function getParamDescription() {
322                 return array (
323                         'title' => 'Page title',
324                         'section' => 'Section number. 0 for the top section, \'new\' for a new section',
325                         'text' => 'Page content',
326                         'token' => 'Edit token. You can get one of these through prop=info',
327                         'summary' => 'Edit summary. Also section title when section=new',
328                         'minor' => 'Minor edit',
329                         'notminor' => 'Non-minor edit',
330                         'bot' => 'Mark this edit as bot',
331                         'basetimestamp' => array('Timestamp of the base revision (gotten through prop=revisions&rvprop=timestamp).',
332                                                 'Used to detect edit conflicts; leave unset to ignore conflicts.'
333                         ),
334                         'starttimestamp' => array('Timestamp when you obtained the edit token.',
335                                                 'Used to detect edit conflicts; leave unset to ignore conflicts.'
336                         ),
337                         'recreate' => 'Override any errors about the article having been deleted in the meantime',
338                         'createonly' => 'Don\'t edit the page if it exists already',
339                         'nocreate' => 'Throw an error if the page doesn\'t exist',
340                         'watch' => 'Add the page to your watchlist',
341                         'unwatch' => 'Remove the page from your watchlist',
342                         'captchaid' => 'CAPTCHA ID from previous request',
343                         'captchaword' => 'Answer to the CAPTCHA',
344                         'md5' => array( 'The MD5 hash of the text parameter, or the prependtext and appendtext parameters concatenated.',
345                                         'If set, the edit won\'t be done unless the hash is correct'),
346                         'prependtext' => array( 'Add this text to the beginning of the page. Overrides text.',
347                                                 'Don\'t use together with section: that won\'t do what you expect.'),
348                         'appendtext' => 'Add this text to the end of the page. Overrides text',
349                         'undo' => 'Undo this revision. Overrides text, prependtext and appendtext',
350                         'undoafter' => 'Undo all revisions from undo to this one. If not set, just undo one revision',
351                 );
352         }
353
354         protected function getExamples() {
355                 return array (
356                         "Edit a page (anonymous user):",
357                         "    api.php?action=edit&title=Test&summary=test%20summary&text=article%20content&basetimestamp=20070824123454&token=%2B\\",
358                         "Prepend __NOTOC__ to a page (anonymous user):",
359                         "    api.php?action=edit&title=Test&summary=NOTOC&minor&prependtext=__NOTOC__%0A&basetimestamp=20070824123454&token=%2B\\",
360                         "Undo r13579 through r13585 with autosummary(anonymous user):",
361                         "    api.php?action=edit&title=Test&undo=13585&undoafter=13579&basetimestamp=20070824123454&token=%2B\\",
362                 );
363         }
364
365         public function getVersion() {
366                 return __CLASS__ . ': $Id: ApiEditPage.php 50220 2009-05-05 14:07:59Z tstarling $';
367         }
368 }