ApiParse.php 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922
  1. <?php
  2. /**
  3. * Copyright © 2007 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 2 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License along
  16. * with this program; if not, write to the Free Software Foundation, Inc.,
  17. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
  18. * http://www.gnu.org/copyleft/gpl.html
  19. *
  20. * @file
  21. */
  22. use MediaWiki\MediaWikiServices;
  23. use MediaWiki\Revision\RevisionRecord;
  24. /**
  25. * @ingroup API
  26. */
  27. class ApiParse extends ApiBase {
  28. /** @var string $section */
  29. private $section = null;
  30. /** @var Content $content */
  31. private $content = null;
  32. /** @var Content $pstContent */
  33. private $pstContent = null;
  34. /** @var bool */
  35. private $contentIsDeleted = false, $contentIsSuppressed = false;
  36. public function execute() {
  37. // The data is hot but user-dependent, like page views, so we set vary cookies
  38. $this->getMain()->setCacheMode( 'anon-public-user-private' );
  39. // Get parameters
  40. $params = $this->extractRequestParams();
  41. // No easy way to say that text and title or revid are allowed together
  42. // while the rest aren't, so just do it in three calls.
  43. $this->requireMaxOneParameter( $params, 'page', 'pageid', 'oldid', 'text' );
  44. $this->requireMaxOneParameter( $params, 'page', 'pageid', 'oldid', 'title' );
  45. $this->requireMaxOneParameter( $params, 'page', 'pageid', 'oldid', 'revid' );
  46. $text = $params['text'];
  47. $title = $params['title'];
  48. if ( $title === null ) {
  49. $titleProvided = false;
  50. // A title is needed for parsing, so arbitrarily choose one
  51. $title = 'API';
  52. } else {
  53. $titleProvided = true;
  54. }
  55. $page = $params['page'];
  56. $pageid = $params['pageid'];
  57. $oldid = $params['oldid'];
  58. $model = $params['contentmodel'];
  59. $format = $params['contentformat'];
  60. $prop = array_flip( $params['prop'] );
  61. if ( isset( $params['section'] ) ) {
  62. $this->section = $params['section'];
  63. if ( !preg_match( '/^((T-)?\d+|new)$/', $this->section ) ) {
  64. $this->dieWithError( 'apierror-invalidsection' );
  65. }
  66. } else {
  67. $this->section = false;
  68. }
  69. // The parser needs $wgTitle to be set, apparently the
  70. // $title parameter in Parser::parse isn't enough *sigh*
  71. // TODO: Does this still need $wgTitle?
  72. global $wgTitle;
  73. $redirValues = null;
  74. $needContent = isset( $prop['wikitext'] ) ||
  75. isset( $prop['parsetree'] ) || $params['generatexml'];
  76. // Return result
  77. $result = $this->getResult();
  78. if ( !is_null( $oldid ) || !is_null( $pageid ) || !is_null( $page ) ) {
  79. if ( $this->section === 'new' ) {
  80. $this->dieWithError( 'apierror-invalidparammix-parse-new-section', 'invalidparammix' );
  81. }
  82. if ( !is_null( $oldid ) ) {
  83. // Don't use the parser cache
  84. $rev = Revision::newFromId( $oldid );
  85. if ( !$rev ) {
  86. $this->dieWithError( [ 'apierror-nosuchrevid', $oldid ] );
  87. }
  88. $this->checkTitleUserPermissions( $rev->getTitle(), 'read' );
  89. if ( !$rev->userCan( RevisionRecord::DELETED_TEXT, $this->getUser() ) ) {
  90. $this->dieWithError(
  91. [ 'apierror-permissiondenied', $this->msg( 'action-deletedtext' ) ]
  92. );
  93. }
  94. $titleObj = $rev->getTitle();
  95. $wgTitle = $titleObj;
  96. $pageObj = WikiPage::factory( $titleObj );
  97. list( $popts, $reset, $suppressCache ) = $this->makeParserOptions( $pageObj, $params );
  98. $p_result = $this->getParsedContent(
  99. $pageObj, $popts, $suppressCache, $pageid, $rev, $needContent
  100. );
  101. } else { // Not $oldid, but $pageid or $page
  102. if ( $params['redirects'] ) {
  103. $reqParams = [
  104. 'redirects' => '',
  105. ];
  106. if ( !is_null( $pageid ) ) {
  107. $reqParams['pageids'] = $pageid;
  108. } else { // $page
  109. $reqParams['titles'] = $page;
  110. }
  111. $req = new FauxRequest( $reqParams );
  112. $main = new ApiMain( $req );
  113. $pageSet = new ApiPageSet( $main );
  114. $pageSet->execute();
  115. $redirValues = $pageSet->getRedirectTitlesAsResult( $this->getResult() );
  116. $to = $page;
  117. foreach ( $pageSet->getRedirectTitles() as $title ) {
  118. $to = $title->getFullText();
  119. }
  120. $pageParams = [ 'title' => $to ];
  121. } elseif ( !is_null( $pageid ) ) {
  122. $pageParams = [ 'pageid' => $pageid ];
  123. } else { // $page
  124. $pageParams = [ 'title' => $page ];
  125. }
  126. $pageObj = $this->getTitleOrPageId( $pageParams, 'fromdb' );
  127. $titleObj = $pageObj->getTitle();
  128. if ( !$titleObj || !$titleObj->exists() ) {
  129. $this->dieWithError( 'apierror-missingtitle' );
  130. }
  131. $this->checkTitleUserPermissions( $titleObj, 'read' );
  132. $wgTitle = $titleObj;
  133. if ( isset( $prop['revid'] ) ) {
  134. $oldid = $pageObj->getLatest();
  135. }
  136. list( $popts, $reset, $suppressCache ) = $this->makeParserOptions( $pageObj, $params );
  137. $p_result = $this->getParsedContent(
  138. $pageObj, $popts, $suppressCache, $pageid, null, $needContent
  139. );
  140. }
  141. } else { // Not $oldid, $pageid, $page. Hence based on $text
  142. $titleObj = Title::newFromText( $title );
  143. if ( !$titleObj || $titleObj->isExternal() ) {
  144. $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $title ) ] );
  145. }
  146. $revid = $params['revid'];
  147. if ( $revid !== null ) {
  148. $rev = Revision::newFromId( $revid );
  149. if ( !$rev ) {
  150. $this->dieWithError( [ 'apierror-nosuchrevid', $revid ] );
  151. }
  152. $pTitleObj = $titleObj;
  153. $titleObj = $rev->getTitle();
  154. if ( $titleProvided ) {
  155. if ( !$titleObj->equals( $pTitleObj ) ) {
  156. $this->addWarning( [ 'apierror-revwrongpage', $rev->getId(),
  157. wfEscapeWikiText( $pTitleObj->getPrefixedText() ) ] );
  158. }
  159. } else {
  160. // Consider the title derived from the revid as having
  161. // been provided.
  162. $titleProvided = true;
  163. }
  164. }
  165. $wgTitle = $titleObj;
  166. if ( $titleObj->canExist() ) {
  167. $pageObj = WikiPage::factory( $titleObj );
  168. } else {
  169. // Do like MediaWiki::initializeArticle()
  170. $article = Article::newFromTitle( $titleObj, $this->getContext() );
  171. $pageObj = $article->getPage();
  172. }
  173. list( $popts, $reset ) = $this->makeParserOptions( $pageObj, $params );
  174. $textProvided = !is_null( $text );
  175. if ( !$textProvided ) {
  176. if ( $titleProvided && ( $prop || $params['generatexml'] ) ) {
  177. if ( $revid !== null ) {
  178. $this->addWarning( 'apiwarn-parse-revidwithouttext' );
  179. } else {
  180. $this->addWarning( 'apiwarn-parse-titlewithouttext' );
  181. }
  182. }
  183. // Prevent warning from ContentHandler::makeContent()
  184. $text = '';
  185. }
  186. // If we are parsing text, do not use the content model of the default
  187. // API title, but default to wikitext to keep BC.
  188. if ( $textProvided && !$titleProvided && is_null( $model ) ) {
  189. $model = CONTENT_MODEL_WIKITEXT;
  190. $this->addWarning( [ 'apiwarn-parse-nocontentmodel', $model ] );
  191. }
  192. try {
  193. $this->content = ContentHandler::makeContent( $text, $titleObj, $model, $format );
  194. } catch ( MWContentSerializationException $ex ) {
  195. $this->dieWithException( $ex, [
  196. 'wrap' => ApiMessage::create( 'apierror-contentserializationexception', 'parseerror' )
  197. ] );
  198. }
  199. if ( $this->section !== false ) {
  200. if ( $this->section === 'new' ) {
  201. // Insert the section title above the content.
  202. if ( !is_null( $params['sectiontitle'] ) && $params['sectiontitle'] !== '' ) {
  203. $this->content = $this->content->addSectionHeader( $params['sectiontitle'] );
  204. }
  205. } else {
  206. $this->content = $this->getSectionContent( $this->content, $titleObj->getPrefixedText() );
  207. }
  208. }
  209. if ( $params['pst'] || $params['onlypst'] ) {
  210. $this->pstContent = $this->content->preSaveTransform( $titleObj, $this->getUser(), $popts );
  211. }
  212. if ( $params['onlypst'] ) {
  213. // Build a result and bail out
  214. $result_array = [];
  215. $result_array['text'] = $this->pstContent->serialize( $format );
  216. $result_array[ApiResult::META_BC_SUBELEMENTS][] = 'text';
  217. if ( isset( $prop['wikitext'] ) ) {
  218. $result_array['wikitext'] = $this->content->serialize( $format );
  219. $result_array[ApiResult::META_BC_SUBELEMENTS][] = 'wikitext';
  220. }
  221. if ( !is_null( $params['summary'] ) ||
  222. ( !is_null( $params['sectiontitle'] ) && $this->section === 'new' )
  223. ) {
  224. $result_array['parsedsummary'] = $this->formatSummary( $titleObj, $params );
  225. $result_array[ApiResult::META_BC_SUBELEMENTS][] = 'parsedsummary';
  226. }
  227. $result->addValue( null, $this->getModuleName(), $result_array );
  228. return;
  229. }
  230. // Not cached (save or load)
  231. if ( $params['pst'] ) {
  232. $p_result = $this->pstContent->getParserOutput( $titleObj, $revid, $popts );
  233. } else {
  234. $p_result = $this->content->getParserOutput( $titleObj, $revid, $popts );
  235. }
  236. }
  237. $result_array = [];
  238. $result_array['title'] = $titleObj->getPrefixedText();
  239. $result_array['pageid'] = $pageid ?: $pageObj->getId();
  240. if ( $this->contentIsDeleted ) {
  241. $result_array['textdeleted'] = true;
  242. }
  243. if ( $this->contentIsSuppressed ) {
  244. $result_array['textsuppressed'] = true;
  245. }
  246. if ( isset( $params['useskin'] ) ) {
  247. $factory = MediaWikiServices::getInstance()->getSkinFactory();
  248. $skin = $factory->makeSkin( Skin::normalizeKey( $params['useskin'] ) );
  249. } else {
  250. $skin = null;
  251. }
  252. $outputPage = null;
  253. if ( $skin || isset( $prop['headhtml'] ) || isset( $prop['categorieshtml'] ) ) {
  254. // Enabling the skin via 'useskin', 'headhtml', or 'categorieshtml'
  255. // gets OutputPage and Skin involved, which (among others) applies
  256. // these hooks:
  257. // - ParserOutputHooks
  258. // - Hook: LanguageLinks
  259. // - Hook: OutputPageParserOutput
  260. // - Hook: OutputPageMakeCategoryLinks
  261. $context = new DerivativeContext( $this->getContext() );
  262. $context->setTitle( $titleObj );
  263. $context->setWikiPage( $pageObj );
  264. if ( $skin ) {
  265. // Use the skin specified by 'useskin'
  266. $context->setSkin( $skin );
  267. // Context clones the skin, refetch to stay in sync. (T166022)
  268. $skin = $context->getSkin();
  269. } else {
  270. // Make sure the context's skin refers to the context. Without this,
  271. // $outputPage->getSkin()->getOutput() !== $outputPage which
  272. // confuses some of the output.
  273. $context->setSkin( $context->getSkin() );
  274. }
  275. $outputPage = new OutputPage( $context );
  276. $outputPage->addParserOutputMetadata( $p_result );
  277. if ( $this->content ) {
  278. $outputPage->addContentOverride( $titleObj, $this->content );
  279. }
  280. $context->setOutput( $outputPage );
  281. if ( $skin ) {
  282. // Based on OutputPage::headElement()
  283. $skin->setupSkinUserCss( $outputPage );
  284. // Based on OutputPage::output()
  285. $outputPage->loadSkinModules( $skin );
  286. }
  287. Hooks::run( 'ApiParseMakeOutputPage', [ $this, $outputPage ] );
  288. }
  289. if ( !is_null( $oldid ) ) {
  290. $result_array['revid'] = (int)$oldid;
  291. }
  292. if ( $params['redirects'] && !is_null( $redirValues ) ) {
  293. $result_array['redirects'] = $redirValues;
  294. }
  295. if ( isset( $prop['text'] ) ) {
  296. $result_array['text'] = $p_result->getText( [
  297. 'allowTOC' => !$params['disabletoc'],
  298. 'enableSectionEditLinks' => !$params['disableeditsection'],
  299. 'wrapperDivClass' => $params['wrapoutputclass'],
  300. 'deduplicateStyles' => !$params['disablestylededuplication'],
  301. ] );
  302. $result_array[ApiResult::META_BC_SUBELEMENTS][] = 'text';
  303. }
  304. if ( !is_null( $params['summary'] ) ||
  305. ( !is_null( $params['sectiontitle'] ) && $this->section === 'new' )
  306. ) {
  307. $result_array['parsedsummary'] = $this->formatSummary( $titleObj, $params );
  308. $result_array[ApiResult::META_BC_SUBELEMENTS][] = 'parsedsummary';
  309. }
  310. if ( isset( $prop['langlinks'] ) ) {
  311. if ( $skin ) {
  312. $langlinks = $outputPage->getLanguageLinks();
  313. } else {
  314. $langlinks = $p_result->getLanguageLinks();
  315. // The deprecated 'effectivelanglinks' option depredates OutputPage
  316. // support via 'useskin'. If not already applied, then run just this
  317. // one hook of OutputPage::addParserOutputMetadata here.
  318. if ( $params['effectivelanglinks'] ) {
  319. $linkFlags = [];
  320. Hooks::run( 'LanguageLinks', [ $titleObj, &$langlinks, &$linkFlags ] );
  321. }
  322. }
  323. $result_array['langlinks'] = $this->formatLangLinks( $langlinks );
  324. }
  325. if ( isset( $prop['categories'] ) ) {
  326. $result_array['categories'] = $this->formatCategoryLinks( $p_result->getCategories() );
  327. }
  328. if ( isset( $prop['categorieshtml'] ) ) {
  329. $result_array['categorieshtml'] = $outputPage->getSkin()->getCategories();
  330. $result_array[ApiResult::META_BC_SUBELEMENTS][] = 'categorieshtml';
  331. }
  332. if ( isset( $prop['links'] ) ) {
  333. $result_array['links'] = $this->formatLinks( $p_result->getLinks() );
  334. }
  335. if ( isset( $prop['templates'] ) ) {
  336. $result_array['templates'] = $this->formatLinks( $p_result->getTemplates() );
  337. }
  338. if ( isset( $prop['images'] ) ) {
  339. $result_array['images'] = array_keys( $p_result->getImages() );
  340. }
  341. if ( isset( $prop['externallinks'] ) ) {
  342. $result_array['externallinks'] = array_keys( $p_result->getExternalLinks() );
  343. }
  344. if ( isset( $prop['sections'] ) ) {
  345. $result_array['sections'] = $p_result->getSections();
  346. }
  347. if ( isset( $prop['parsewarnings'] ) ) {
  348. $result_array['parsewarnings'] = $p_result->getWarnings();
  349. }
  350. if ( isset( $prop['displaytitle'] ) ) {
  351. $result_array['displaytitle'] = $p_result->getDisplayTitle() !== false
  352. ? $p_result->getDisplayTitle() : $titleObj->getPrefixedText();
  353. }
  354. if ( isset( $prop['headitems'] ) ) {
  355. if ( $skin ) {
  356. $result_array['headitems'] = $this->formatHeadItems( $outputPage->getHeadItemsArray() );
  357. } else {
  358. $result_array['headitems'] = $this->formatHeadItems( $p_result->getHeadItems() );
  359. }
  360. }
  361. if ( isset( $prop['headhtml'] ) ) {
  362. $result_array['headhtml'] = $outputPage->headElement( $context->getSkin() );
  363. $result_array[ApiResult::META_BC_SUBELEMENTS][] = 'headhtml';
  364. }
  365. if ( isset( $prop['modules'] ) ) {
  366. if ( $skin ) {
  367. $result_array['modules'] = $outputPage->getModules();
  368. // Deprecated since 1.32 (T188689)
  369. $result_array['modulescripts'] = [];
  370. $result_array['modulestyles'] = $outputPage->getModuleStyles();
  371. } else {
  372. $result_array['modules'] = array_values( array_unique( $p_result->getModules() ) );
  373. // Deprecated since 1.32 (T188689)
  374. $result_array['modulescripts'] = [];
  375. $result_array['modulestyles'] = array_values( array_unique( $p_result->getModuleStyles() ) );
  376. }
  377. }
  378. if ( isset( $prop['jsconfigvars'] ) ) {
  379. $jsconfigvars = $skin ? $outputPage->getJsConfigVars() : $p_result->getJsConfigVars();
  380. $result_array['jsconfigvars'] = ApiResult::addMetadataToResultVars( $jsconfigvars );
  381. }
  382. if ( isset( $prop['encodedjsconfigvars'] ) ) {
  383. $jsconfigvars = $skin ? $outputPage->getJsConfigVars() : $p_result->getJsConfigVars();
  384. $result_array['encodedjsconfigvars'] = FormatJson::encode(
  385. $jsconfigvars,
  386. false,
  387. FormatJson::ALL_OK
  388. );
  389. $result_array[ApiResult::META_SUBELEMENTS][] = 'encodedjsconfigvars';
  390. }
  391. if ( isset( $prop['modules'] ) &&
  392. !isset( $prop['jsconfigvars'] ) && !isset( $prop['encodedjsconfigvars'] ) ) {
  393. $this->addWarning( 'apiwarn-moduleswithoutvars' );
  394. }
  395. if ( isset( $prop['indicators'] ) ) {
  396. if ( $skin ) {
  397. $result_array['indicators'] = (array)$outputPage->getIndicators();
  398. } else {
  399. $result_array['indicators'] = (array)$p_result->getIndicators();
  400. }
  401. ApiResult::setArrayType( $result_array['indicators'], 'BCkvp', 'name' );
  402. }
  403. if ( isset( $prop['iwlinks'] ) ) {
  404. $result_array['iwlinks'] = $this->formatIWLinks( $p_result->getInterwikiLinks() );
  405. }
  406. if ( isset( $prop['wikitext'] ) ) {
  407. $result_array['wikitext'] = $this->content->serialize( $format );
  408. $result_array[ApiResult::META_BC_SUBELEMENTS][] = 'wikitext';
  409. if ( !is_null( $this->pstContent ) ) {
  410. $result_array['psttext'] = $this->pstContent->serialize( $format );
  411. $result_array[ApiResult::META_BC_SUBELEMENTS][] = 'psttext';
  412. }
  413. }
  414. if ( isset( $prop['properties'] ) ) {
  415. $result_array['properties'] = (array)$p_result->getProperties();
  416. ApiResult::setArrayType( $result_array['properties'], 'BCkvp', 'name' );
  417. }
  418. if ( isset( $prop['limitreportdata'] ) ) {
  419. $result_array['limitreportdata'] =
  420. $this->formatLimitReportData( $p_result->getLimitReportData() );
  421. }
  422. if ( isset( $prop['limitreporthtml'] ) ) {
  423. $result_array['limitreporthtml'] = EditPage::getPreviewLimitReport( $p_result );
  424. $result_array[ApiResult::META_BC_SUBELEMENTS][] = 'limitreporthtml';
  425. }
  426. if ( isset( $prop['parsetree'] ) || $params['generatexml'] ) {
  427. if ( $this->content->getModel() != CONTENT_MODEL_WIKITEXT ) {
  428. $this->dieWithError( 'apierror-parsetree-notwikitext', 'notwikitext' );
  429. }
  430. $parser = MediaWikiServices::getInstance()->getParser();
  431. $parser->startExternalParse( $titleObj, $popts, Parser::OT_PREPROCESS );
  432. // @phan-suppress-next-line PhanUndeclaredMethod
  433. $xml = $parser->preprocessToDom( $this->content->getText() )->__toString();
  434. $result_array['parsetree'] = $xml;
  435. $result_array[ApiResult::META_BC_SUBELEMENTS][] = 'parsetree';
  436. }
  437. $result_mapping = [
  438. 'redirects' => 'r',
  439. 'langlinks' => 'll',
  440. 'categories' => 'cl',
  441. 'links' => 'pl',
  442. 'templates' => 'tl',
  443. 'images' => 'img',
  444. 'externallinks' => 'el',
  445. 'iwlinks' => 'iw',
  446. 'sections' => 's',
  447. 'headitems' => 'hi',
  448. 'modules' => 'm',
  449. 'indicators' => 'ind',
  450. 'modulescripts' => 'm',
  451. 'modulestyles' => 'm',
  452. 'properties' => 'pp',
  453. 'limitreportdata' => 'lr',
  454. 'parsewarnings' => 'pw'
  455. ];
  456. $this->setIndexedTagNames( $result_array, $result_mapping );
  457. $result->addValue( null, $this->getModuleName(), $result_array );
  458. }
  459. /**
  460. * Constructs a ParserOptions object
  461. *
  462. * @param WikiPage $pageObj
  463. * @param array $params
  464. *
  465. * @return array [ ParserOptions, ScopedCallback, bool $suppressCache ]
  466. */
  467. protected function makeParserOptions( WikiPage $pageObj, array $params ) {
  468. $popts = $pageObj->makeParserOptions( $this->getContext() );
  469. $popts->enableLimitReport( !$params['disablepp'] && !$params['disablelimitreport'] );
  470. $popts->setIsPreview( $params['preview'] || $params['sectionpreview'] );
  471. $popts->setIsSectionPreview( $params['sectionpreview'] );
  472. if ( $params['disabletidy'] ) {
  473. $popts->setTidy( false );
  474. }
  475. if ( $params['wrapoutputclass'] !== '' ) {
  476. $popts->setWrapOutputClass( $params['wrapoutputclass'] );
  477. }
  478. $reset = null;
  479. $suppressCache = false;
  480. Hooks::run( 'ApiMakeParserOptions',
  481. [ $popts, $pageObj->getTitle(), $params, $this, &$reset, &$suppressCache ] );
  482. // Force cache suppression when $popts aren't cacheable.
  483. $suppressCache = $suppressCache || !$popts->isSafeToCache();
  484. return [ $popts, $reset, $suppressCache ];
  485. }
  486. /**
  487. * @param WikiPage $page
  488. * @param ParserOptions $popts
  489. * @param bool $suppressCache
  490. * @param int $pageId
  491. * @param Revision|null $rev
  492. * @param bool $getContent
  493. * @return ParserOutput
  494. */
  495. private function getParsedContent(
  496. WikiPage $page, $popts, $suppressCache, $pageId, $rev, $getContent
  497. ) {
  498. $revId = $rev ? $rev->getId() : null;
  499. $isDeleted = $rev && $rev->isDeleted( RevisionRecord::DELETED_TEXT );
  500. if ( $getContent || $this->section !== false || $isDeleted ) {
  501. if ( $rev ) {
  502. $this->content = $rev->getContent( RevisionRecord::FOR_THIS_USER, $this->getUser() );
  503. if ( !$this->content ) {
  504. $this->dieWithError( [ 'apierror-missingcontent-revid', $revId ] );
  505. }
  506. } else {
  507. $this->content = $page->getContent( RevisionRecord::FOR_THIS_USER, $this->getUser() );
  508. if ( !$this->content ) {
  509. $this->dieWithError( [ 'apierror-missingcontent-pageid', $page->getId() ] );
  510. }
  511. }
  512. $this->contentIsDeleted = $isDeleted;
  513. $this->contentIsSuppressed = $rev &&
  514. $rev->isDeleted( RevisionRecord::DELETED_TEXT | RevisionRecord::DELETED_RESTRICTED );
  515. }
  516. if ( $this->section !== false ) {
  517. $this->content = $this->getSectionContent(
  518. $this->content,
  519. $pageId === null ? $page->getTitle()->getPrefixedText() : $this->msg( 'pageid', $pageId )
  520. );
  521. return $this->content->getParserOutput( $page->getTitle(), $revId, $popts );
  522. }
  523. if ( $isDeleted ) {
  524. // getParserOutput can't do revdeled revisions
  525. $pout = $this->content->getParserOutput( $page->getTitle(), $revId, $popts );
  526. } else {
  527. // getParserOutput will save to Parser cache if able
  528. $pout = $page->getParserOutput( $popts, $revId, $suppressCache );
  529. }
  530. if ( !$pout ) {
  531. // @codeCoverageIgnoreStart
  532. $this->dieWithError( [ 'apierror-nosuchrevid', $revId ?: $page->getLatest() ] );
  533. // @codeCoverageIgnoreEnd
  534. }
  535. return $pout;
  536. }
  537. /**
  538. * Extract the requested section from the given Content
  539. *
  540. * @param Content $content
  541. * @param string|Message $what Identifies the content in error messages, e.g. page title.
  542. * @return Content
  543. */
  544. private function getSectionContent( Content $content, $what ) {
  545. // Not cached (save or load)
  546. $section = $content->getSection( $this->section );
  547. if ( $section === false ) {
  548. $this->dieWithError( [ 'apierror-nosuchsection-what', $this->section, $what ], 'nosuchsection' );
  549. }
  550. if ( $section === null ) {
  551. $this->dieWithError( [ 'apierror-sectionsnotsupported-what', $what ], 'nosuchsection' );
  552. $section = false;
  553. }
  554. return $section;
  555. }
  556. /**
  557. * This mimicks the behavior of EditPage in formatting a summary
  558. *
  559. * @param Title $title of the page being parsed
  560. * @param array $params The API parameters of the request
  561. * @return Content|bool
  562. */
  563. private function formatSummary( $title, $params ) {
  564. $summary = $params['summary'] ?? '';
  565. $sectionTitle = $params['sectiontitle'] ?? '';
  566. if ( $this->section === 'new' && ( $sectionTitle === '' || $summary === '' ) ) {
  567. if ( $sectionTitle !== '' ) {
  568. $summary = $params['sectiontitle'];
  569. }
  570. if ( $summary !== '' ) {
  571. $summary = wfMessage( 'newsectionsummary' )
  572. ->rawParams( MediaWikiServices::getInstance()->getParser()
  573. ->stripSectionName( $summary ) )
  574. ->inContentLanguage()->text();
  575. }
  576. }
  577. return Linker::formatComment( $summary, $title, $this->section === 'new' );
  578. }
  579. private function formatLangLinks( $links ) {
  580. $result = [];
  581. foreach ( $links as $link ) {
  582. $entry = [];
  583. $bits = explode( ':', $link, 2 );
  584. $title = Title::newFromText( $link );
  585. $entry['lang'] = $bits[0];
  586. if ( $title ) {
  587. $entry['url'] = wfExpandUrl( $title->getFullURL(), PROTO_CURRENT );
  588. // localised language name in 'uselang' language
  589. $entry['langname'] = Language::fetchLanguageName(
  590. $title->getInterwiki(),
  591. $this->getLanguage()->getCode()
  592. );
  593. // native language name
  594. $entry['autonym'] = Language::fetchLanguageName( $title->getInterwiki() );
  595. }
  596. ApiResult::setContentValue( $entry, 'title', $bits[1] );
  597. $result[] = $entry;
  598. }
  599. return $result;
  600. }
  601. private function formatCategoryLinks( $links ) {
  602. $result = [];
  603. if ( !$links ) {
  604. return $result;
  605. }
  606. // Fetch hiddencat property
  607. $lb = new LinkBatch;
  608. $lb->setArray( [ NS_CATEGORY => $links ] );
  609. $db = $this->getDB();
  610. $res = $db->select( [ 'page', 'page_props' ],
  611. [ 'page_title', 'pp_propname' ],
  612. $lb->constructSet( 'page', $db ),
  613. __METHOD__,
  614. [],
  615. [ 'page_props' => [
  616. 'LEFT JOIN', [ 'pp_propname' => 'hiddencat', 'pp_page = page_id' ]
  617. ] ]
  618. );
  619. $hiddencats = [];
  620. foreach ( $res as $row ) {
  621. $hiddencats[$row->page_title] = isset( $row->pp_propname );
  622. }
  623. $linkCache = MediaWikiServices::getInstance()->getLinkCache();
  624. foreach ( $links as $link => $sortkey ) {
  625. $entry = [];
  626. $entry['sortkey'] = $sortkey;
  627. // array keys will cast numeric category names to ints, so cast back to string
  628. ApiResult::setContentValue( $entry, 'category', (string)$link );
  629. if ( !isset( $hiddencats[$link] ) ) {
  630. $entry['missing'] = true;
  631. // We already know the link doesn't exist in the database, so
  632. // tell LinkCache that before calling $title->isKnown().
  633. $title = Title::makeTitle( NS_CATEGORY, $link );
  634. $linkCache->addBadLinkObj( $title );
  635. if ( $title->isKnown() ) {
  636. $entry['known'] = true;
  637. }
  638. } elseif ( $hiddencats[$link] ) {
  639. $entry['hidden'] = true;
  640. }
  641. $result[] = $entry;
  642. }
  643. return $result;
  644. }
  645. private function formatLinks( $links ) {
  646. $result = [];
  647. foreach ( $links as $ns => $nslinks ) {
  648. foreach ( $nslinks as $title => $id ) {
  649. $entry = [];
  650. $entry['ns'] = $ns;
  651. ApiResult::setContentValue( $entry, 'title', Title::makeTitle( $ns, $title )->getFullText() );
  652. $entry['exists'] = $id != 0;
  653. $result[] = $entry;
  654. }
  655. }
  656. return $result;
  657. }
  658. private function formatIWLinks( $iw ) {
  659. $result = [];
  660. foreach ( $iw as $prefix => $titles ) {
  661. foreach ( array_keys( $titles ) as $title ) {
  662. $entry = [];
  663. $entry['prefix'] = $prefix;
  664. $title = Title::newFromText( "{$prefix}:{$title}" );
  665. if ( $title ) {
  666. $entry['url'] = wfExpandUrl( $title->getFullURL(), PROTO_CURRENT );
  667. }
  668. ApiResult::setContentValue( $entry, 'title', $title->getFullText() );
  669. $result[] = $entry;
  670. }
  671. }
  672. return $result;
  673. }
  674. private function formatHeadItems( $headItems ) {
  675. $result = [];
  676. foreach ( $headItems as $tag => $content ) {
  677. $entry = [];
  678. $entry['tag'] = $tag;
  679. ApiResult::setContentValue( $entry, 'content', $content );
  680. $result[] = $entry;
  681. }
  682. return $result;
  683. }
  684. private function formatLimitReportData( $limitReportData ) {
  685. $result = [];
  686. foreach ( $limitReportData as $name => $value ) {
  687. $entry = [];
  688. $entry['name'] = $name;
  689. if ( !is_array( $value ) ) {
  690. $value = [ $value ];
  691. }
  692. ApiResult::setIndexedTagNameRecursive( $value, 'param' );
  693. $entry = array_merge( $entry, $value );
  694. $result[] = $entry;
  695. }
  696. return $result;
  697. }
  698. private function setIndexedTagNames( &$array, $mapping ) {
  699. foreach ( $mapping as $key => $name ) {
  700. if ( isset( $array[$key] ) ) {
  701. ApiResult::setIndexedTagName( $array[$key], $name );
  702. }
  703. }
  704. }
  705. public function getAllowedParams() {
  706. return [
  707. 'title' => null,
  708. 'text' => [
  709. ApiBase::PARAM_TYPE => 'text',
  710. ],
  711. 'revid' => [
  712. ApiBase::PARAM_TYPE => 'integer',
  713. ],
  714. 'summary' => null,
  715. 'page' => null,
  716. 'pageid' => [
  717. ApiBase::PARAM_TYPE => 'integer',
  718. ],
  719. 'redirects' => false,
  720. 'oldid' => [
  721. ApiBase::PARAM_TYPE => 'integer',
  722. ],
  723. 'prop' => [
  724. ApiBase::PARAM_DFLT => 'text|langlinks|categories|links|templates|' .
  725. 'images|externallinks|sections|revid|displaytitle|iwlinks|' .
  726. 'properties|parsewarnings',
  727. ApiBase::PARAM_ISMULTI => true,
  728. ApiBase::PARAM_TYPE => [
  729. 'text',
  730. 'langlinks',
  731. 'categories',
  732. 'categorieshtml',
  733. 'links',
  734. 'templates',
  735. 'images',
  736. 'externallinks',
  737. 'sections',
  738. 'revid',
  739. 'displaytitle',
  740. 'headhtml',
  741. 'modules',
  742. 'jsconfigvars',
  743. 'encodedjsconfigvars',
  744. 'indicators',
  745. 'iwlinks',
  746. 'wikitext',
  747. 'properties',
  748. 'limitreportdata',
  749. 'limitreporthtml',
  750. 'parsetree',
  751. 'parsewarnings',
  752. 'headitems',
  753. ],
  754. ApiBase::PARAM_HELP_MSG_PER_VALUE => [
  755. 'parsetree' => [ 'apihelp-parse-paramvalue-prop-parsetree', CONTENT_MODEL_WIKITEXT ],
  756. ],
  757. ApiBase::PARAM_DEPRECATED_VALUES => [
  758. 'headitems' => 'apiwarn-deprecation-parse-headitems',
  759. ],
  760. ],
  761. 'wrapoutputclass' => 'mw-parser-output',
  762. 'pst' => false,
  763. 'onlypst' => false,
  764. 'effectivelanglinks' => [
  765. ApiBase::PARAM_DFLT => false,
  766. ApiBase::PARAM_DEPRECATED => true,
  767. ],
  768. 'section' => null,
  769. 'sectiontitle' => [
  770. ApiBase::PARAM_TYPE => 'string',
  771. ],
  772. 'disablepp' => [
  773. ApiBase::PARAM_DFLT => false,
  774. ApiBase::PARAM_DEPRECATED => true,
  775. ],
  776. 'disablelimitreport' => false,
  777. 'disableeditsection' => false,
  778. 'disabletidy' => [
  779. ApiBase::PARAM_DFLT => false,
  780. ApiBase::PARAM_DEPRECATED => true, // Since 1.32
  781. ],
  782. 'disablestylededuplication' => false,
  783. 'generatexml' => [
  784. ApiBase::PARAM_DFLT => false,
  785. ApiBase::PARAM_HELP_MSG => [
  786. 'apihelp-parse-param-generatexml', CONTENT_MODEL_WIKITEXT
  787. ],
  788. ApiBase::PARAM_DEPRECATED => true,
  789. ],
  790. 'preview' => false,
  791. 'sectionpreview' => false,
  792. 'disabletoc' => false,
  793. 'useskin' => [
  794. ApiBase::PARAM_TYPE => array_keys( Skin::getAllowedSkins() ),
  795. ],
  796. 'contentformat' => [
  797. ApiBase::PARAM_TYPE => ContentHandler::getAllContentFormats(),
  798. ],
  799. 'contentmodel' => [
  800. ApiBase::PARAM_TYPE => ContentHandler::getContentModels(),
  801. ]
  802. ];
  803. }
  804. protected function getExamplesMessages() {
  805. return [
  806. 'action=parse&page=Project:Sandbox'
  807. => 'apihelp-parse-example-page',
  808. 'action=parse&text={{Project:Sandbox}}&contentmodel=wikitext'
  809. => 'apihelp-parse-example-text',
  810. 'action=parse&text={{PAGENAME}}&title=Test'
  811. => 'apihelp-parse-example-texttitle',
  812. 'action=parse&summary=Some+[[link]]&prop='
  813. => 'apihelp-parse-example-summary',
  814. ];
  815. }
  816. public function getHelpUrls() {
  817. return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Parsing_wikitext#parse';
  818. }
  819. }