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