ApiEditPage.php 13 KB

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