Debian Codegraph @

includes/api/ApiParse.php

raw symbols SCIP
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
23 namespace MediaWiki\Api;
24
25 use Article;
26 use MediaWiki\Cache\LinkBatchFactory;
27 use MediaWiki\Cache\LinkCache;
28 use MediaWiki\CommentFormatter\CommentFormatter;
29 use MediaWiki\Content\Content;
30 use MediaWiki\Content\IContentHandlerFactory;
31 use MediaWiki\Content\Renderer\ContentRenderer;
32 use MediaWiki\Content\Transform\ContentTransformer;
33 use MediaWiki\Context\DerivativeContext;
34 use MediaWiki\EditPage\EditPage;
35 use MediaWiki\Json\FormatJson;
36 use MediaWiki\Json\JsonCodec;
37 use MediaWiki\Language\RawMessage;
38 use MediaWiki\Languages\LanguageNameUtils;
39 use MediaWiki\Message\Message;
40 use MediaWiki\Output\OutputPage;
41 use MediaWiki\Page\PageReference;
42 use MediaWiki\Page\WikiPageFactory;
43 use MediaWiki\Parser\Parser;
44 use MediaWiki\Parser\ParserFactory;
45 use MediaWiki\Parser\ParserOptions;
46 use MediaWiki\Parser\ParserOutput;
47 use MediaWiki\Parser\ParserOutputFlags;
48 use MediaWiki\PoolCounter\PoolCounterWorkViaCallback;
49 use MediaWiki\Request\FauxRequest;
50 use MediaWiki\Revision\RevisionLookup;
51 use MediaWiki\Revision\RevisionRecord;
52 use MediaWiki\Revision\SlotRecord;
53 use MediaWiki\Title\Title;
54 use MediaWiki\Title\TitleFormatter;
55 use MediaWiki\Title\TitleValue;
56 use MediaWiki\User\TempUser\TempUserCreator;
57 use MediaWiki\User\UserFactory;
58 use MediaWiki\Utils\UrlUtils;
59 use MediaWiki\WikiMap\WikiMap;
60 use MWContentSerializationException;
61 use Skin;
62 use SkinFactory;
63 use Wikimedia\ParamValidator\ParamValidator;
64 use Wikimedia\ParamValidator\TypeDef\EnumDef;
65 use Wikimedia\Parsoid\Core\TOCData;
66 use WikiPage;
67
68 /**
69 * @ingroup API
70 */
71 class ApiParse extends ApiBase {
72
73 /** @var string|false|null */
74 private $section = null;
75
76 /** @var Content|null */
77 private $content = null;
78
79 /** @var Content|null */
80 private $pstContent = null;
81
82 private bool $contentIsDeleted = false;
83 private bool $contentIsSuppressed = false;
84
85 private RevisionLookup $revisionLookup;
86 private SkinFactory $skinFactory;
87 private LanguageNameUtils $languageNameUtils;
88 private LinkBatchFactory $linkBatchFactory;
89 private LinkCache $linkCache;
90 private IContentHandlerFactory $contentHandlerFactory;
91 private ParserFactory $parserFactory;
92 private WikiPageFactory $wikiPageFactory;
93 private ContentTransformer $contentTransformer;
94 private CommentFormatter $commentFormatter;
95 private ContentRenderer $contentRenderer;
96 private TempUserCreator $tempUserCreator;
97 private UserFactory $userFactory;
98 private UrlUtils $urlUtils;
99 private TitleFormatter $titleFormatter;
100 private JsonCodec $jsonCodec;
101
102 public function __construct(
103 ApiMain $main,
104 string $action,
105 RevisionLookup $revisionLookup,
106 SkinFactory $skinFactory,
107 LanguageNameUtils $languageNameUtils,
108 LinkBatchFactory $linkBatchFactory,
109 LinkCache $linkCache,
110 IContentHandlerFactory $contentHandlerFactory,
111 ParserFactory $parserFactory,
112 WikiPageFactory $wikiPageFactory,
113 ContentRenderer $contentRenderer,
114 ContentTransformer $contentTransformer,
115 CommentFormatter $commentFormatter,
116 TempUserCreator $tempUserCreator,
117 UserFactory $userFactory,
118 UrlUtils $urlUtils,
119 TitleFormatter $titleFormatter,
120 JsonCodec $jsonCodec
121 ) {
122 parent::__construct( $main, $action );
123 $this->revisionLookup = $revisionLookup;
124 $this->skinFactory = $skinFactory;
125 $this->languageNameUtils = $languageNameUtils;
126 $this->linkBatchFactory = $linkBatchFactory;
127 $this->linkCache = $linkCache;
128 $this->contentHandlerFactory = $contentHandlerFactory;
129 $this->parserFactory = $parserFactory;
130 $this->wikiPageFactory = $wikiPageFactory;
131 $this->contentRenderer = $contentRenderer;
132 $this->contentTransformer = $contentTransformer;
133 $this->commentFormatter = $commentFormatter;
134 $this->tempUserCreator = $tempUserCreator;
135 $this->userFactory = $userFactory;
136 $this->urlUtils = $urlUtils;
137 $this->titleFormatter = $titleFormatter;
138 $this->jsonCodec = $jsonCodec;
139 }
140
141 private function getPoolKey(): string {
142 $poolKey = WikiMap::getCurrentWikiDbDomain() . ':ApiParse:';
143 if ( !$this->getUser()->isRegistered() ) {
144 $poolKey .= 'a:' . $this->getUser()->getName();
145 } else {
146 $poolKey .= 'u:' . $this->getUser()->getId();
147 }
148 return $poolKey;
149 }
150
151 private function getContentParserOutput(
152 Content $content,
153 PageReference $page,
154 ?RevisionRecord $revision,
155 ParserOptions $popts
156 ) {
157 $worker = new PoolCounterWorkViaCallback( 'ApiParser', $this->getPoolKey(),
158 [
159 'doWork' => function () use ( $content, $page, $revision, $popts ) {
160 return $this->contentRenderer->getParserOutput(
161 $content, $page, $revision, $popts
162 );
163 },
164 'error' => function () {
165 $this->dieWithError( 'apierror-concurrency-limit' );
166 },
167 ]
168 );
169 return $worker->execute();
170 }
171
172 private function getUserForPreview() {
173 $user = $this->getUser();
174 if ( $this->tempUserCreator->shouldAutoCreate( $user, 'edit' ) ) {
175 return $this->userFactory->newUnsavedTempUser(
176 $this->tempUserCreator->getStashedName( $this->getRequest()->getSession() )
177 );
178 }
179 return $user;
180 }
181
182 private function getPageParserOutput(
183 WikiPage $page,
184 $revId,
185 ParserOptions $popts,
186 bool $suppressCache
187 ) {
188 $worker = new PoolCounterWorkViaCallback( 'ApiParser', $this->getPoolKey(),
189 [
190 'doWork' => static function () use ( $page, $revId, $popts, $suppressCache ) {
191 return $page->getParserOutput( $popts, $revId, $suppressCache );
192 },
193 'error' => function () {
194 $this->dieWithError( 'apierror-concurrency-limit' );
195 },
196 ]
197 );
198 return $worker->execute();
199 }
200
201 public function execute() {
202 // The data is hot but user-dependent, like page views, so we set vary cookies
203 $this->getMain()->setCacheMode( 'anon-public-user-private' );
204
205 // Get parameters
206 $params = $this->extractRequestParams();
207
208 // No easy way to say that text and title or revid are allowed together
209 // while the rest aren't, so just do it in three calls.
210 $this->requireMaxOneParameter( $params, 'page', 'pageid', 'oldid', 'text' );
211 $this->requireMaxOneParameter( $params, 'page', 'pageid', 'oldid', 'title' );
212 $this->requireMaxOneParameter( $params, 'page', 'pageid', 'oldid', 'revid' );
213
214 $text = $params['text'];
215 $title = $params['title'];
216 if ( $title === null ) {
217 $titleProvided = false;
218 // A title is needed for parsing, so arbitrarily choose one
219 $title = 'API';
220 } else {
221 $titleProvided = true;
222 }
223
224 $page = $params['page'];
225 $pageid = $params['pageid'];
226 $oldid = $params['oldid'];
227
228 $prop = array_fill_keys( $params['prop'], true );
229
230 if ( isset( $params['section'] ) ) {
231 $this->section = $params['section'];
232 if ( !preg_match( '/^((T-)?\d+|new)$/', $this->section ) ) {
233 $this->dieWithError( 'apierror-invalidsection' );
234 }
235 } else {
236 $this->section = false;
237 }
238
239 // The parser needs $wgTitle to be set, apparently the
240 // $title parameter in Parser::parse isn't enough *sigh*
241 // TODO: Does this still need $wgTitle?
242 // phpcs:ignore MediaWiki.Usage.DeprecatedGlobalVariables.Deprecated$wgTitle
243 global $wgTitle;
244
245 $format = null;
246 $redirValues = null;
247
248 $needContent = isset( $prop['wikitext'] ) ||
249 isset( $prop['parsetree'] ) || $params['generatexml'];
250
251 // Return result
252 $result = $this->getResult();
253
254 if ( $oldid !== null || $pageid !== null || $page !== null ) {
255 if ( $this->section === 'new' ) {
256 $this->dieWithError( 'apierror-invalidparammix-parse-new-section', 'invalidparammix' );
257 }
258 if ( $oldid !== null ) {
259 // Don't use the parser cache
260 $rev = $this->revisionLookup->getRevisionById( $oldid );
261 if ( !$rev ) {
262 $this->dieWithError( [ 'apierror-nosuchrevid', $oldid ] );
263 }
264
265 $this->checkTitleUserPermissions( $rev->getPage(), 'read' );
266
267 if ( !$rev->userCan( RevisionRecord::DELETED_TEXT, $this->getAuthority() ) ) {
268 $this->dieWithError(
269 [ 'apierror-permissiondenied', $this->msg( 'action-deletedtext' ) ]
270 );
271 }
272
273 $revLinkTarget = $rev->getPageAsLinkTarget();
274 $titleObj = Title::newFromLinkTarget( $revLinkTarget );
275 $wgTitle = $titleObj;
276 $pageObj = $this->wikiPageFactory->newFromTitle( $titleObj );
277 [ $popts, $reset, $suppressCache ] = $this->makeParserOptions( $pageObj, $params );
278 $p_result = $this->getParsedContent(
279 $pageObj, $popts, $suppressCache, $pageid, $rev, $needContent
280 );
281 } else { // Not $oldid, but $pageid or $page
282 if ( $params['redirects'] ) {
283 $reqParams = [
284 'redirects' => '',
285 ];
286 $pageParams = [];
287 if ( $pageid !== null ) {
288 $reqParams['pageids'] = $pageid;
289 $pageParams['pageid'] = $pageid;
290 } else { // $page
291 $reqParams['titles'] = $page;
292 $pageParams['title'] = $page;
293 }
294 $req = new FauxRequest( $reqParams );
295 $main = new ApiMain( $req );
296 $pageSet = new ApiPageSet( $main );
297 $pageSet->execute();
298 $redirValues = $pageSet->getRedirectTitlesAsResult( $this->getResult() );
299
300 foreach ( $pageSet->getRedirectTargets() as $redirectTarget ) {
301 $pageParams = [ 'title' => $this->titleFormatter->getFullText( $redirectTarget ) ];
302 }
303 } elseif ( $pageid !== null ) {
304 $pageParams = [ 'pageid' => $pageid ];
305 } else { // $page
306 $pageParams = [ 'title' => $page ];
307 }
308
309 $pageObj = $this->getTitleOrPageId( $pageParams, 'fromdb' );
310 $titleObj = $pageObj->getTitle();
311 if ( !$titleObj->exists() ) {
312 $this->dieWithError( 'apierror-missingtitle' );
313 }
314
315 $this->checkTitleUserPermissions( $titleObj, 'read' );
316 $wgTitle = $titleObj;
317
318 if ( isset( $prop['revid'] ) ) {
319 $oldid = $pageObj->getLatest();
320 }
321
322 [ $popts, $reset, $suppressCache ] = $this->makeParserOptions( $pageObj, $params );
323 $p_result = $this->getParsedContent(
324 $pageObj, $popts, $suppressCache, $pageid, null, $needContent
325 );
326 }
327 } else { // Not $oldid, $pageid, $page. Hence based on $text
328 $model = $params['contentmodel'];
329 $format = $params['contentformat'];
330
331 $titleObj = Title::newFromText( $title );
332 if ( !$titleObj || $titleObj->isExternal() ) {
333 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $title ) ] );
334 }
335 $revid = $params['revid'];
336 $rev = null;
337 if ( $revid !== null ) {
338 $rev = $this->revisionLookup->getRevisionById( $revid );
339 if ( !$rev ) {
340 $this->dieWithError( [ 'apierror-nosuchrevid', $revid ] );
341 }
342 $pTitleObj = $titleObj;
343 $titleObj = Title::newFromLinkTarget( $rev->getPageAsLinkTarget() );
344 if ( $titleProvided ) {
345 if ( !$titleObj->equals( $pTitleObj ) ) {
346 $this->addWarning( [ 'apierror-revwrongpage', $rev->getId(),
347 wfEscapeWikiText( $pTitleObj->getPrefixedText() ) ] );
348 }
349 } else {
350 // Consider the title derived from the revid as having
351 // been provided.
352 $titleProvided = true;
353 }
354 }
355 $wgTitle = $titleObj;
356 if ( $titleObj->canExist() ) {
357 $pageObj = $this->wikiPageFactory->newFromTitle( $titleObj );
358 [ $popts, $reset ] = $this->makeParserOptions( $pageObj, $params );
359 } else {
360 // Allow parsing wikitext in the context of special pages (T51477)
361 $pageObj = null;
362 $popts = ParserOptions::newFromContext( $this->getContext() );
363 [ $popts, $reset ] = $this->tweakParserOptions( $popts, $titleObj, $params );
364 }
365
366 $textProvided = $text !== null;
367
368 if ( !$textProvided ) {
369 if ( $titleProvided && ( $prop || $params['generatexml'] ) ) {
370 if ( $revid !== null ) {
371 $this->addWarning( 'apiwarn-parse-revidwithouttext' );
372 } else {
373 $this->addWarning( 'apiwarn-parse-titlewithouttext' );
374 }
375 }
376 // Prevent warning from ContentHandler::makeContent()
377 $text = '';
378 }
379
380 // If we are parsing text, do not use the content model of the default
381 // API title, but default to wikitext to keep BC.
382 if ( $textProvided && !$titleProvided && $model === null ) {
383 $model = CONTENT_MODEL_WIKITEXT;
384 $this->addWarning( [ 'apiwarn-parse-nocontentmodel', $model ] );
385 } elseif ( $model === null ) {
386 $model = $titleObj->getContentModel();
387 }
388
389 $contentHandler = $this->contentHandlerFactory->getContentHandler( $model );
390 // Not in the default format, check supported or not
391 if ( $format && !$contentHandler->isSupportedFormat( $format ) ) {
392 $this->dieWithError( [ 'apierror-badformat-generic', $format, $model ] );
393 }
394
395 try {
396 $this->content = $contentHandler->unserializeContent( $text, $format );
397 } catch ( MWContentSerializationException $ex ) {
398 $this->dieWithException( $ex, [
399 'wrap' => ApiMessage::create( 'apierror-contentserializationexception', 'parseerror' )
400 ] );
401 }
402
403 if ( $this->section !== false ) {
404 if ( $this->section === 'new' ) {
405 // Insert the section title above the content.
406 if ( $params['sectiontitle'] !== null ) {
407 $this->content = $this->content->addSectionHeader( $params['sectiontitle'] );
408 }
409 } else {
410 $this->content = $this->getSectionContent( $this->content, $titleObj->getPrefixedText() );
411 }
412 }
413
414 if ( $params['pst'] || $params['onlypst'] ) {
415 $this->pstContent = $this->contentTransformer->preSaveTransform(
416 $this->content,
417 $titleObj,
418 $this->getUserForPreview(),
419 $popts
420 );
421 }
422 if ( $params['onlypst'] ) {
423 // Build a result and bail out
424 $result_array = [];
425 $result_array['text'] = $this->pstContent->serialize( $format );
426 $result_array[ApiResult::META_BC_SUBELEMENTS][] = 'text';
427 if ( isset( $prop['wikitext'] ) ) {
428 $result_array['wikitext'] = $this->content->serialize( $format );
429 $result_array[ApiResult::META_BC_SUBELEMENTS][] = 'wikitext';
430 }
431 if ( $params['summary'] !== null ||
432 ( $params['sectiontitle'] !== null && $this->section === 'new' )
433 ) {
434 $result_array['parsedsummary'] = $this->formatSummary( $titleObj, $params );
435 $result_array[ApiResult::META_BC_SUBELEMENTS][] = 'parsedsummary';
436 }
437
438 $result->addValue( null, $this->getModuleName(), $result_array );
439
440 return;
441 }
442
443 // Not cached (save or load)
444 if ( $params['pst'] ) {
445 $p_result = $this->getContentParserOutput( $this->pstContent, $titleObj, $rev, $popts );
446 } else {
447 $p_result = $this->getContentParserOutput( $this->content, $titleObj, $rev, $popts );
448 }
449 }
450
451 $result_array = [];
452
453 $result_array['title'] = $titleObj->getPrefixedText();
454 $result_array['pageid'] = $pageid ?: $titleObj->getArticleID();
455 if ( $this->contentIsDeleted ) {
456 $result_array['textdeleted'] = true;
457 }
458 if ( $this->contentIsSuppressed ) {
459 $result_array['textsuppressed'] = true;
460 }
461
462 if ( isset( $params['useskin'] ) ) {
463 $skin = $this->skinFactory->makeSkin( Skin::normalizeKey( $params['useskin'] ) );
464 } else {
465 $skin = null;
466 }
467
468 $outputPage = null;
469 $context = null;
470 if (
471 $skin || isset( $prop['subtitle'] ) || isset( $prop['headhtml'] ) || isset( $prop['categorieshtml'] ) ||
472 isset( $params['mobileformat'] )
473 ) {
474 // Enabling the skin via 'useskin', 'subtitle', 'headhtml', or 'categorieshtml'
475 // gets OutputPage and Skin involved, which (among others) applies
476 // these hooks:
477 // - Hook: LanguageLinks
478 // - Hook: SkinSubPageSubtitle
479 // - Hook: OutputPageParserOutput
480 // - Hook: OutputPageMakeCategoryLinks
481 // - Hook: OutputPageRenderCategoryLink
482 // - Hook: OutputPageBeforeHTML
483 // HACK Adding the 'mobileformat' parameter *also* enables the skin, for compatibility with legacy
484 // apps. This behavior should be considered deprecated so new users should not rely on this and
485 // always use the "useskin" parameter to enable "skin mode".
486 // Ideally this would be done with another hook so that MobileFrontend could enable skin mode, but
487 // as this is just for a deprecated feature, we are hard-coding this param into core.
488 $context = new DerivativeContext( $this->getContext() );
489 $context->setTitle( $titleObj );
490
491 if ( $pageObj ) {
492 $context->setWikiPage( $pageObj );
493 }
494 // Some hooks only apply to pages when action=view, which this API
495 // call is simulating.
496 $context->setRequest( new FauxRequest( [ 'action' => 'view' ] ) );
497
498 if ( $skin ) {
499 // Use the skin specified by 'useskin'
500 $context->setSkin( $skin );
501 // Context clones the skin, refetch to stay in sync. (T166022)
502 $skin = $context->getSkin();
503 } else {
504 // Make sure the context's skin refers to the context. Without this,
505 // $outputPage->getSkin()->getOutput() !== $outputPage which
506 // confuses some of the output.
507 $context->setSkin( $context->getSkin() );
508 }
509
510 $outputPage = new OutputPage( $context );
511 // Required for subtitle to appear
512 $outputPage->setArticleFlag( true );
513
514 $outputPage->addParserOutputMetadata( $p_result );
515 if ( $this->content ) {
516 $outputPage->addContentOverride( $titleObj, $this->content );
517 }
518 $context->setOutput( $outputPage );
519
520 if ( $skin ) {
521 // Based on OutputPage::output()
522 $outputPage->loadSkinModules( $skin );
523 }
524
525 $this->getHookRunner()->onApiParseMakeOutputPage( $this, $outputPage );
526 }
527
528 if ( $oldid !== null ) {
529 $result_array['revid'] = (int)$oldid;
530 }
531
532 if ( $params['redirects'] && $redirValues !== null ) {
533 $result_array['redirects'] = $redirValues;
534 }
535
536 if ( isset( $prop['text'] ) ) {
537 $skin = $context ? $context->getSkin() : null;
538 $skinOptions = $skin ? $skin->getOptions() : [
539 'toc' => true,
540 ];
541 // TODO T371004 move runOutputPipeline out of $parserOutput
542 // TODO T371022 it should be reasonably straightforward to move this to a clone, but it requires
543 // careful checking of the clone and of what happens on the boundary of OutputPage. Leaving this as
544 // "getText-equivalent" for now; will fix in a later, independent patch.
545 $oldText = $p_result->getRawText();
546 $result_array['text'] = $p_result->runOutputPipeline( $popts, [
547 'allowClone' => false,
548 'allowTOC' => !$params['disabletoc'],
549 'injectTOC' => $skinOptions['toc'],
550 'enableSectionEditLinks' => !$params['disableeditsection'],
551 'wrapperDivClass' => $params['wrapoutputclass'],
552 'deduplicateStyles' => !$params['disablestylededuplication'],
553 'userLang' => $context ? $context->getLanguage() : null,
554 'skin' => $skin,
555 'includeDebugInfo' => !$params['disablepp'] && !$params['disablelimitreport']
556 ] )->getContentHolderText();
557 $p_result->setRawText( $oldText );
558 $result_array[ApiResult::META_BC_SUBELEMENTS][] = 'text';
559 if ( $context ) {
560 $this->getHookRunner()->onOutputPageBeforeHTML( $context->getOutput(), $result_array['text'] );
561 }
562 }
563
564 if ( $params['summary'] !== null ||
565 ( $params['sectiontitle'] !== null && $this->section === 'new' )
566 ) {
567 $result_array['parsedsummary'] = $this->formatSummary( $titleObj, $params );
568 $result_array[ApiResult::META_BC_SUBELEMENTS][] = 'parsedsummary';
569 }
570
571 if ( isset( $prop['langlinks'] ) ) {
572 if ( $skin ) {
573 $langlinks = $outputPage->getLanguageLinks();
574 } else {
575 $langlinks = $p_result->getLanguageLinks();
576 // The deprecated 'effectivelanglinks' option pre-dates OutputPage
577 // support via 'useskin'. If not already applied, then run just this
578 // one hook of OutputPage::addParserOutputMetadata here.
579 if ( $params['effectivelanglinks'] ) {
580 $linkFlags = [];
581 $this->getHookRunner()->onLanguageLinks( $titleObj, $langlinks, $linkFlags );
582 }
583 }
584
585 $result_array['langlinks'] = $this->formatLangLinks( $langlinks );
586 }
587 if ( isset( $prop['categories'] ) ) {
588 $result_array['categories'] = $this->formatCategoryLinks( $p_result->getCategoryMap() );
589 }
590 if ( isset( $prop['categorieshtml'] ) ) {
591 $result_array['categorieshtml'] = $outputPage->getSkin()->getCategories();
592 $result_array[ApiResult::META_BC_SUBELEMENTS][] = 'categorieshtml';
593 }
594 if ( isset( $prop['links'] ) ) {
595 $result_array['links'] = $this->formatLinks( $p_result->getLinks() );
596 }
597 if ( isset( $prop['templates'] ) ) {
598 $result_array['templates'] = $this->formatLinks( $p_result->getTemplates() );
599 }
600 if ( isset( $prop['images'] ) ) {
601 // Cast image links to string since PHP coerces numeric string array keys to numbers
602 // (T346265).
603 $result_array['images'] = array_map(
604 fn ( $link ) => (string)$link,
605 array_keys( $p_result->getImages() )
606 );
607 }
608 if ( isset( $prop['externallinks'] ) ) {
609 $result_array['externallinks'] = array_keys( $p_result->getExternalLinks() );
610 }
611 if ( isset( $prop['sections'] ) ) {
612 $result_array['sections'] = $p_result->getSections();
613 }
614 if ( isset( $prop['tocdata'] ) ) {
615 $result_array['tocdata'] = $this->jsonCodec->toJsonArray(
616 $p_result->getTOCData(), TOCData::class
617 );
618 }
619 if ( isset( $prop['sections'] ) || isset( $prop['tocdata'] ) ) {
620 $result_array['showtoc'] = $p_result->getOutputFlag( ParserOutputFlags::SHOW_TOC );
621 }
622 if ( isset( $prop['parsewarnings'] ) ) {
623 $result_array['parsewarnings'] = $p_result->getWarnings();
624 }
625 if ( isset( $prop['parsewarningshtml'] ) ) {
626 $warnings = $p_result->getWarnings();
627 $warningsHtml = array_map( static function ( $warning ) {
628 return ( new RawMessage( '$1', [ $warning ] ) )->parse();
629 }, $warnings );
630 $result_array['parsewarningshtml'] = $warningsHtml;
631 }
632
633 if ( isset( $prop['displaytitle'] ) ) {
634 $result_array['displaytitle'] = $p_result->getDisplayTitle() !== false
635 ? $p_result->getDisplayTitle()
636 : htmlspecialchars( $titleObj->getPrefixedText(), ENT_NOQUOTES );
637 }
638
639 if ( isset( $prop['subtitle'] ) ) {
640 // Get the subtitle without its container element to support UI refreshing
641 $result_array['subtitle'] = $context->getSkin()->prepareSubtitle( false );
642 }
643
644 if ( isset( $prop['headitems'] ) ) {
645 if ( $skin ) {
646 $result_array['headitems'] = $this->formatHeadItems( $outputPage->getHeadItemsArray() );
647 } else {
648 $result_array['headitems'] = $this->formatHeadItems( $p_result->getHeadItems() );
649 }
650 }
651
652 if ( isset( $prop['headhtml'] ) ) {
653 $result_array['headhtml'] = $outputPage->headElement( $context->getSkin() );
654 $result_array[ApiResult::META_BC_SUBELEMENTS][] = 'headhtml';
655 }
656
657 if ( isset( $prop['modules'] ) ) {
658 if ( $skin ) {
659 $result_array['modules'] = $outputPage->getModules();
660 // Deprecated since 1.32 (T188689)
661 $result_array['modulescripts'] = [];
662 $result_array['modulestyles'] = $outputPage->getModuleStyles();
663 } else {
664 $result_array['modules'] = array_values( array_unique( $p_result->getModules() ) );
665 // Deprecated since 1.32 (T188689)
666 $result_array['modulescripts'] = [];
667 $result_array['modulestyles'] = array_values( array_unique( $p_result->getModuleStyles() ) );
668 }
669 }
670
671 if ( isset( $prop['jsconfigvars'] ) ) {
672 $showStrategyKeys = (bool)( $params['showstrategykeys'] );
673 $jsconfigvars = $skin ? $outputPage->getJsConfigVars() : $p_result->getJsConfigVars( $showStrategyKeys );
674 $result_array['jsconfigvars'] = ApiResult::addMetadataToResultVars( $jsconfigvars );
675 }
676
677 if ( isset( $prop['encodedjsconfigvars'] ) ) {
678 $jsconfigvars = $skin ? $outputPage->getJsConfigVars() : $p_result->getJsConfigVars();
679 $result_array['encodedjsconfigvars'] = FormatJson::encode(
680 $jsconfigvars,
681 false,
682 FormatJson::ALL_OK
683 );
684 $result_array[ApiResult::META_SUBELEMENTS][] = 'encodedjsconfigvars';
685 }
686
687 if ( isset( $prop['modules'] ) &&
688 !isset( $prop['jsconfigvars'] ) && !isset( $prop['encodedjsconfigvars'] ) ) {
689 $this->addWarning( 'apiwarn-moduleswithoutvars' );
690 }
691
692 if ( isset( $prop['indicators'] ) ) {
693 if ( $skin ) {
694 $result_array['indicators'] = $outputPage->getIndicators();
695 } else {
696 $result_array['indicators'] = $p_result->getIndicators();
697 }
698 ApiResult::setArrayType( $result_array['indicators'], 'BCkvp', 'name' );
699 }
700
701 if ( isset( $prop['iwlinks'] ) ) {
702 $result_array['iwlinks'] = $this->formatIWLinks( $p_result->getInterwikiLinks() );
703 }
704
705 if ( isset( $prop['wikitext'] ) ) {
706 $result_array['wikitext'] = $this->content->serialize( $format );
707 $result_array[ApiResult::META_BC_SUBELEMENTS][] = 'wikitext';
708 // @phan-suppress-next-line PhanImpossibleTypeComparison
709 if ( $this->pstContent !== null ) {
710 $result_array['psttext'] = $this->pstContent->serialize( $format );
711 $result_array[ApiResult::META_BC_SUBELEMENTS][] = 'psttext';
712 }
713 }
714 if ( isset( $prop['properties'] ) ) {
715 $result_array['properties'] = $p_result->getPageProperties();
716 ApiResult::setArrayType( $result_array['properties'], 'BCkvp', 'name' );
717 }
718
719 if ( isset( $prop['limitreportdata'] ) ) {
720 $result_array['limitreportdata'] =
721 $this->formatLimitReportData( $p_result->getLimitReportData() );
722 }
723 if ( isset( $prop['limitreporthtml'] ) ) {
724 $result_array['limitreporthtml'] = EditPage::getPreviewLimitReport( $p_result );
725 $result_array[ApiResult::META_BC_SUBELEMENTS][] = 'limitreporthtml';
726 }
727
728 if ( isset( $prop['parsetree'] ) || $params['generatexml'] ) {
729 if ( $this->content->getModel() != CONTENT_MODEL_WIKITEXT ) {
730 $this->dieWithError( 'apierror-parsetree-notwikitext', 'notwikitext' );
731 }
732
733 $parser = $this->parserFactory->getInstance();
734 $parser->startExternalParse( $titleObj, $popts, Parser::OT_PREPROCESS );
735 // @phan-suppress-next-line PhanUndeclaredMethod
736 $xml = $parser->preprocessToDom( $this->content->getText() )->__toString();
737 $result_array['parsetree'] = $xml;
738 $result_array[ApiResult::META_BC_SUBELEMENTS][] = 'parsetree';
739 }
740
741 $result_mapping = [
742 'redirects' => 'r',
743 'langlinks' => 'll',
744 'categories' => 'cl',
745 'links' => 'pl',
746 'templates' => 'tl',
747 'images' => 'img',
748 'externallinks' => 'el',
749 'iwlinks' => 'iw',
750 'sections' => 's',
751 'tocdata' => 'toc',
752 'headitems' => 'hi',
753 'modules' => 'm',
754 'indicators' => 'ind',
755 'modulescripts' => 'm',
756 'modulestyles' => 'm',
757 'properties' => 'pp',
758 'limitreportdata' => 'lr',
759 'parsewarnings' => 'pw',
760 'parsewarningshtml' => 'pw',
761 ];
762 $this->setIndexedTagNames( $result_array, $result_mapping );
763 $result->addValue( null, $this->getModuleName(), $result_array );
764 }
765
766 /**
767 * Constructs a ParserOptions object
768 *
769 * @param WikiPage $pageObj
770 * @param array $params
771 *
772 * @return array [ ParserOptions, ScopedCallback, bool $suppressCache ]
773 */
774 private function makeParserOptions( WikiPage $pageObj, array $params ) {
775 $popts = $pageObj->makeParserOptions( $this->getContext() );
776 $popts->setRenderReason( 'api-parse' );
777 if ( $params['usearticle'] ) {
778 # T349037: The ArticleParserOptions hook should be broadened to take
779 # a WikiPage (aka $pageObj) instead of an Article. But for now
780 # fake the Article.
781 $article = Article::newFromWikiPage( $pageObj, $this->getContext() );
782 # Allow extensions to vary parser options used for article rendering,
783 # in the same way Article does
784 $this->getHookRunner()->onArticleParserOptions( $article, $popts );
785 }
786 return $this->tweakParserOptions( $popts, $pageObj->getTitle(), $params );
787 }
788
789 /**
790 * Tweaks a ParserOptions object
791 *
792 * @param ParserOptions $popts
793 * @param Title $title
794 * @param array $params
795 *
796 * @return array [ ParserOptions, ScopedCallback, bool $suppressCache ]
797 */
798 private function tweakParserOptions( ParserOptions $popts, Title $title, array $params ) {
799 $popts->setIsPreview( $params['preview'] || $params['sectionpreview'] );
800 $popts->setIsSectionPreview( $params['sectionpreview'] );
801
802 if ( $params['wrapoutputclass'] !== '' ) {
803 $popts->setWrapOutputClass( $params['wrapoutputclass'] );
804 }
805 if ( $params['parsoid'] ) {
806 $popts->setUseParsoid();
807 }
808
809 $reset = null;
810 $suppressCache = false;
811 $this->getHookRunner()->onApiMakeParserOptions( $popts, $title,
812 $params, $this, $reset, $suppressCache );
813
814 return [ $popts, $reset, $suppressCache ];
815 }
816
817 /**
818 * @param WikiPage $page
819 * @param ParserOptions $popts
820 * @param bool $suppressCache
821 * @param int $pageId
822 * @param RevisionRecord|null $rev
823 * @param bool $getContent
824 * @return ParserOutput
825 */
826 private function getParsedContent(
827 WikiPage $page, $popts, $suppressCache, $pageId, $rev, $getContent
828 ) {
829 $revId = $rev ? $rev->getId() : null;
830 $isDeleted = $rev && $rev->isDeleted( RevisionRecord::DELETED_TEXT );
831
832 if ( $getContent || $this->section !== false || $isDeleted ) {
833 if ( $rev ) {
834 $this->content = $rev->getContent(
835 SlotRecord::MAIN, RevisionRecord::FOR_THIS_USER, $this->getAuthority()
836 );
837 if ( !$this->content ) {
838 $this->dieWithError( [ 'apierror-missingcontent-revid', $revId ] );
839 }
840 } else {
841 $this->content = $page->getContent( RevisionRecord::FOR_THIS_USER, $this->getAuthority() );
842 if ( !$this->content ) {
843 $this->dieWithError( [ 'apierror-missingcontent-pageid', $page->getId() ] );
844 }
845 }
846 $this->contentIsDeleted = $isDeleted;
847 $this->contentIsSuppressed = $rev &&
848 $rev->isDeleted( RevisionRecord::DELETED_TEXT | RevisionRecord::DELETED_RESTRICTED );
849 }
850
851 if ( $this->section !== false ) {
852 $this->content = $this->getSectionContent(
853 $this->content,
854 $pageId === null ? $page->getTitle()->getPrefixedText() : $this->msg( 'pageid', $pageId )
855 );
856 return $this->getContentParserOutput(
857 $this->content, $page->getTitle(),
858 $rev,
859 $popts
860 );
861 }
862
863 if ( $isDeleted ) {
864 // getParserOutput can't do revdeled revisions
865
866 $pout = $this->getContentParserOutput(
867 $this->content, $page->getTitle(),
868 $rev,
869 $popts
870 );
871 } else {
872 // getParserOutput will save to Parser cache if able
873 $pout = $this->getPageParserOutput( $page, $revId, $popts, $suppressCache );
874 }
875 if ( !$pout ) {
876 // @codeCoverageIgnoreStart
877 $this->dieWithError( [ 'apierror-nosuchrevid', $revId ?: $page->getLatest() ] );
878 // @codeCoverageIgnoreEnd
879 }
880
881 return $pout;
882 }
883
884 /**
885 * Extract the requested section from the given Content
886 *
887 * @param Content $content
888 * @param string|Message $what Identifies the content in error messages, e.g. page title.
889 * @return Content
890 */
891 private function getSectionContent( Content $content, $what ) {
892 // Not cached (save or load)
893 $section = $content->getSection( $this->section );
894 if ( $section === false ) {
895 $this->dieWithError( [ 'apierror-nosuchsection-what', $this->section, $what ], 'nosuchsection' );
896 }
897 if ( $section === null ) {
898 $this->dieWithError( [ 'apierror-sectionsnotsupported-what', $what ], 'nosuchsection' );
899 }
900
901 // @phan-suppress-next-line PhanTypeMismatchReturnNullable T240141
902 return $section;
903 }
904
905 /**
906 * This mimics the behavior of EditPage in formatting a summary
907 *
908 * @param Title $title of the page being parsed
909 * @param array $params The API parameters of the request
910 * @return string HTML
911 */
912 private function formatSummary( $title, $params ) {
913 $summary = $params['summary'] ?? '';
914 $sectionTitle = $params['sectiontitle'] ?? '';
915
916 if ( $this->section === 'new' && ( $sectionTitle === '' || $summary === '' ) ) {
917 if ( $sectionTitle !== '' ) {
918 $summary = $params['sectiontitle'];
919 }
920 if ( $summary !== '' ) {
921 $summary = $this->msg( 'newsectionsummary' )
922 ->rawParams( $this->parserFactory->getMainInstance()->stripSectionName( $summary ) )
923 ->inContentLanguage()->text();
924 }
925 }
926 return $this->commentFormatter->format( $summary, $title, $this->section === 'new' );
927 }
928
929 private function formatLangLinks( $links ) {
930 $result = [];
931 foreach ( $links as $link ) {
932 $entry = [];
933 [ $lang, $titleWithFrag ] = explode( ':', $link, 2 );
934 [ $title, $frag ] = array_pad( explode( '#', $titleWithFrag, 2 ), 2, '' );
935 $title = TitleValue::tryNew( NS_MAIN, $title, $frag, $lang );
936 $title = $title ? Title::newFromLinkTarget( $title ) : null;
937
938 $entry['lang'] = $lang;
939 if ( $title ) {
940 $entry['url'] = (string)$this->urlUtils->expand( $title->getFullURL(), PROTO_CURRENT );
941 // title validity implies language code validity
942 // localised language name in 'uselang' language
943 $entry['langname'] = $this->languageNameUtils->getLanguageName(
944 $lang,
945 $this->getLanguage()->getCode()
946 );
947
948 // native language name
949 $entry['autonym'] = $this->languageNameUtils->getLanguageName( $lang );
950 }
951 ApiResult::setContentValue( $entry, 'title', $titleWithFrag );
952 $result[] = $entry;
953 }
954
955 return $result;
956 }
957
958 private function formatCategoryLinks( $links ) {
959 $result = [];
960
961 if ( !$links ) {
962 return $result;
963 }
964
965 // Fetch hiddencat property
966 $lb = $this->linkBatchFactory->newLinkBatch();
967 $lb->setArray( [ NS_CATEGORY => $links ] );
968 $db = $this->getDB();
969 $res = $db->newSelectQueryBuilder()
970 ->select( [ 'page_title', 'pp_propname' ] )
971 ->from( 'page' )
972 ->where( $lb->constructSet( 'page', $db ) )
973 ->leftJoin( 'page_props', null, [ 'pp_propname' => 'hiddencat', 'pp_page = page_id' ] )
974 ->caller( __METHOD__ )
975 ->fetchResultSet();
976 $hiddencats = [];
977 foreach ( $res as $row ) {
978 $hiddencats[$row->page_title] = isset( $row->pp_propname );
979 }
980
981 foreach ( $links as $link => $sortkey ) {
982 $entry = [];
983 $entry['sortkey'] = $sortkey;
984 // array keys will cast numeric category names to ints, so cast back to string
985 ApiResult::setContentValue( $entry, 'category', (string)$link );
986 if ( !isset( $hiddencats[$link] ) ) {
987 $entry['missing'] = true;
988
989 // We already know the link doesn't exist in the database, so
990 // tell LinkCache that before calling $title->isKnown().
991 $title = Title::makeTitle( NS_CATEGORY, $link );
992 $this->linkCache->addBadLinkObj( $title );
993 if ( $title->isKnown() ) {
994 $entry['known'] = true;
995 }
996 } elseif ( $hiddencats[$link] ) {
997 $entry['hidden'] = true;
998 }
999 $result[] = $entry;
1000 }
1001
1002 return $result;
1003 }
1004
1005 private function formatLinks( $links ) {
1006 $result = [];
1007 foreach ( $links as $ns => $nslinks ) {
1008 foreach ( $nslinks as $title => $id ) {
1009 $entry = [];
1010 $entry['ns'] = $ns;
1011 ApiResult::setContentValue( $entry, 'title', Title::makeTitle( $ns, $title )->getFullText() );
1012 $entry['exists'] = $id != 0;
1013 $result[] = $entry;
1014 }
1015 }
1016
1017 return $result;
1018 }
1019
1020 private function formatIWLinks( $iw ) {
1021 $result = [];
1022 foreach ( $iw as $prefix => $titles ) {
1023 foreach ( $titles as $title => $_ ) {
1024 $entry = [];
1025 $entry['prefix'] = $prefix;
1026
1027 $title = Title::newFromText( "{$prefix}:{$title}" );
1028 if ( $title ) {
1029 $entry['url'] = (string)$this->urlUtils->expand( $title->getFullURL(), PROTO_CURRENT );
1030 }
1031
1032 ApiResult::setContentValue( $entry, 'title', $title->getFullText() );
1033 $result[] = $entry;
1034 }
1035 }
1036
1037 return $result;
1038 }
1039
1040 private function formatHeadItems( $headItems ) {
1041 $result = [];
1042 foreach ( $headItems as $tag => $content ) {
1043 $entry = [];
1044 $entry['tag'] = $tag;
1045 ApiResult::setContentValue( $entry, 'content', $content );
1046 $result[] = $entry;
1047 }
1048
1049 return $result;
1050 }
1051
1052 private function formatLimitReportData( $limitReportData ) {
1053 $result = [];
1054
1055 foreach ( $limitReportData as $name => $value ) {
1056 $entry = [];
1057 $entry['name'] = $name;
1058 if ( !is_array( $value ) ) {
1059 $value = [ $value ];
1060 }
1061 ApiResult::setIndexedTagNameRecursive( $value, 'param' );
1062 $entry = array_merge( $entry, $value );
1063 $result[] = $entry;
1064 }
1065
1066 return $result;
1067 }
1068
1069 private function setIndexedTagNames( &$array, $mapping ) {
1070 foreach ( $mapping as $key => $name ) {
1071 if ( isset( $array[$key] ) ) {
1072 ApiResult::setIndexedTagName( $array[$key], $name );
1073 }
1074 }
1075 }
1076
1077 public function getAllowedParams() {
1078 return [
1079 'title' => null,
1080 'text' => [
1081 ParamValidator::PARAM_TYPE => 'text',
1082 ],
1083 'revid' => [
1084 ParamValidator::PARAM_TYPE => 'integer',
1085 ],
1086 'summary' => null,
1087 'page' => null,
1088 'pageid' => [
1089 ParamValidator::PARAM_TYPE => 'integer',
1090 ],
1091 'redirects' => false,
1092 'oldid' => [
1093 ParamValidator::PARAM_TYPE => 'integer',
1094 ],
1095 'prop' => [
1096 ParamValidator::PARAM_DEFAULT => 'text|langlinks|categories|links|templates|' .
1097 'images|externallinks|sections|tocdata|revid|displaytitle|iwlinks|' .
1098 'properties|parsewarnings',
1099 ParamValidator::PARAM_ISMULTI => true,
1100 ParamValidator::PARAM_TYPE => [
1101 'text',
1102 'langlinks',
1103 'categories',
1104 'categorieshtml',
1105 'links',
1106 'templates',
1107 'images',
1108 'externallinks',
1109 'sections',
1110 'tocdata',
1111 'revid',
1112 'displaytitle',
1113 'subtitle',
1114 'headhtml',
1115 'modules',
1116 'jsconfigvars',
1117 'encodedjsconfigvars',
1118 'indicators',
1119 'iwlinks',
1120 'wikitext',
1121 'properties',
1122 'limitreportdata',
1123 'limitreporthtml',
1124 'parsetree',
1125 'parsewarnings',
1126 'parsewarningshtml',
1127 'headitems',
1128 ],
1129 ApiBase::PARAM_HELP_MSG_PER_VALUE => [
1130 'parsetree' => [ 'apihelp-parse-paramvalue-prop-parsetree', CONTENT_MODEL_WIKITEXT ],
1131 ],
1132 EnumDef::PARAM_DEPRECATED_VALUES => [
1133 'headitems' => 'apiwarn-deprecation-parse-headitems',
1134 ],
1135 ],
1136 'wrapoutputclass' => 'mw-parser-output',
1137 'usearticle' => false, // since 1.43
1138 'parsoid' => false, // since 1.41
1139 'pst' => false,
1140 'onlypst' => false,
1141 'effectivelanglinks' => [
1142 ParamValidator::PARAM_DEFAULT => false,
1143 ParamValidator::PARAM_DEPRECATED => true,
1144 ],
1145 'section' => null,
1146 'sectiontitle' => [
1147 ParamValidator::PARAM_TYPE => 'string',
1148 ],
1149 'disablepp' => [
1150 ParamValidator::PARAM_DEFAULT => false,
1151 ParamValidator::PARAM_DEPRECATED => true,
1152 ],
1153 'disablelimitreport' => false,
1154 'disableeditsection' => false,
1155 'disablestylededuplication' => false,
1156 'showstrategykeys' => false,
1157 'generatexml' => [
1158 ParamValidator::PARAM_DEFAULT => false,
1159 ApiBase::PARAM_HELP_MSG => [
1160 'apihelp-parse-param-generatexml', CONTENT_MODEL_WIKITEXT
1161 ],
1162 ParamValidator::PARAM_DEPRECATED => true,
1163 ],
1164 'preview' => false,
1165 'sectionpreview' => false,
1166 'disabletoc' => false,
1167 'useskin' => [
1168 // T237856; We use all installed skins here to allow hidden (but usable) skins
1169 // to continue working correctly with some features such as Live Preview
1170 ParamValidator::PARAM_TYPE => array_keys( $this->skinFactory->getInstalledSkins() ),
1171 ],
1172 'contentformat' => [
1173 ParamValidator::PARAM_TYPE => $this->contentHandlerFactory->getAllContentFormats(),
1174 ],
1175 'contentmodel' => [
1176 ParamValidator::PARAM_TYPE => $this->contentHandlerFactory->getContentModels(),
1177 ],
1178 ];
1179 }
1180
1181 protected function getExamplesMessages() {
1182 return [
1183 'action=parse&page=Project:Sandbox'
1184 => 'apihelp-parse-example-page',
1185 'action=parse&text={{Project:Sandbox}}&contentmodel=wikitext'
1186 => 'apihelp-parse-example-text',
1187 'action=parse&text={{PAGENAME}}&title=Test'
1188 => 'apihelp-parse-example-texttitle',
1189 'action=parse&summary=Some+[[link]]&prop='
1190 => 'apihelp-parse-example-summary',
1191 ];
1192 }
1193
1194 public function getHelpUrls() {
1195 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Parsing_wikitext';
1196 }
1197 }
1198
1199 /** @deprecated class alias since 1.43 */
1200 class_alias( ApiParse::class, 'ApiParse' );