ApiParse.php 28 KB

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