PageRenderTime 53ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 1ms

/includes/api/ApiEditPage.php

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