MediaWiki REL1_31
ApiParse.php
Go to the documentation of this file.
1<?php
24
28class ApiParse extends ApiBase {
29
31 private $section = null;
32
34 private $content = null;
35
37 private $pstContent = null;
38
40 private $contentIsDeleted = false, $contentIsSuppressed = false;
41
42 public function execute() {
43 // The data is hot but user-dependent, like page views, so we set vary cookies
44 $this->getMain()->setCacheMode( 'anon-public-user-private' );
45
46 // Get parameters
48
49 // No easy way to say that text and title or revid are allowed together
50 // while the rest aren't, so just do it in three calls.
51 $this->requireMaxOneParameter( $params, 'page', 'pageid', 'oldid', 'text' );
52 $this->requireMaxOneParameter( $params, 'page', 'pageid', 'oldid', 'title' );
53 $this->requireMaxOneParameter( $params, 'page', 'pageid', 'oldid', 'revid' );
54
55 $text = $params['text'];
56 $title = $params['title'];
57 if ( $title === null ) {
58 $titleProvided = false;
59 // A title is needed for parsing, so arbitrarily choose one
60 $title = 'API';
61 } else {
62 $titleProvided = true;
63 }
64
65 $page = $params['page'];
66 $pageid = $params['pageid'];
67 $oldid = $params['oldid'];
68
69 $model = $params['contentmodel'];
70 $format = $params['contentformat'];
71
72 $prop = array_flip( $params['prop'] );
73
74 if ( isset( $params['section'] ) ) {
75 $this->section = $params['section'];
76 if ( !preg_match( '/^((T-)?\d+|new)$/', $this->section ) ) {
77 $this->dieWithError( 'apierror-invalidsection' );
78 }
79 } else {
80 $this->section = false;
81 }
82
83 // The parser needs $wgTitle to be set, apparently the
84 // $title parameter in Parser::parse isn't enough *sigh*
85 // TODO: Does this still need $wgTitle?
86 global $wgParser, $wgTitle;
87
88 $redirValues = null;
89
90 $needContent = isset( $prop['wikitext'] ) ||
91 isset( $prop['parsetree'] ) || $params['generatexml'];
92
93 // Return result
94 $result = $this->getResult();
95
96 if ( !is_null( $oldid ) || !is_null( $pageid ) || !is_null( $page ) ) {
97 if ( $this->section === 'new' ) {
98 $this->dieWithError( 'apierror-invalidparammix-parse-new-section', 'invalidparammix' );
99 }
100 if ( !is_null( $oldid ) ) {
101 // Don't use the parser cache
102 $rev = Revision::newFromId( $oldid );
103 if ( !$rev ) {
104 $this->dieWithError( [ 'apierror-nosuchrevid', $oldid ] );
105 }
106
107 $this->checkTitleUserPermissions( $rev->getTitle(), 'read' );
108 if ( !$rev->userCan( Revision::DELETED_TEXT, $this->getUser() ) ) {
109 $this->dieWithError(
110 [ 'apierror-permissiondenied', $this->msg( 'action-deletedtext' ) ]
111 );
112 }
113
114 $titleObj = $rev->getTitle();
115 $wgTitle = $titleObj;
116 $pageObj = WikiPage::factory( $titleObj );
117 list( $popts, $reset, $suppressCache ) = $this->makeParserOptions( $pageObj, $params );
118 $p_result = $this->getParsedContent(
119 $pageObj, $popts, $suppressCache, $pageid, $rev, $needContent
120 );
121 } else { // Not $oldid, but $pageid or $page
122 if ( $params['redirects'] ) {
123 $reqParams = [
124 'redirects' => '',
125 ];
126 if ( !is_null( $pageid ) ) {
127 $reqParams['pageids'] = $pageid;
128 } else { // $page
129 $reqParams['titles'] = $page;
130 }
131 $req = new FauxRequest( $reqParams );
132 $main = new ApiMain( $req );
133 $pageSet = new ApiPageSet( $main );
134 $pageSet->execute();
135 $redirValues = $pageSet->getRedirectTitlesAsResult( $this->getResult() );
136
137 $to = $page;
138 foreach ( $pageSet->getRedirectTitles() as $title ) {
139 $to = $title->getFullText();
140 }
141 $pageParams = [ 'title' => $to ];
142 } elseif ( !is_null( $pageid ) ) {
143 $pageParams = [ 'pageid' => $pageid ];
144 } else { // $page
145 $pageParams = [ 'title' => $page ];
146 }
147
148 $pageObj = $this->getTitleOrPageId( $pageParams, 'fromdb' );
149 $titleObj = $pageObj->getTitle();
150 if ( !$titleObj || !$titleObj->exists() ) {
151 $this->dieWithError( 'apierror-missingtitle' );
152 }
153
154 $this->checkTitleUserPermissions( $titleObj, 'read' );
155 $wgTitle = $titleObj;
156
157 if ( isset( $prop['revid'] ) ) {
158 $oldid = $pageObj->getLatest();
159 }
160
161 list( $popts, $reset, $suppressCache ) = $this->makeParserOptions( $pageObj, $params );
162 $p_result = $this->getParsedContent(
163 $pageObj, $popts, $suppressCache, $pageid, null, $needContent
164 );
165 }
166 } else { // Not $oldid, $pageid, $page. Hence based on $text
167 $titleObj = Title::newFromText( $title );
168 if ( !$titleObj || $titleObj->isExternal() ) {
169 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $title ) ] );
170 }
171 $revid = $params['revid'];
172 if ( $revid !== null ) {
173 $rev = Revision::newFromId( $revid );
174 if ( !$rev ) {
175 $this->dieWithError( [ 'apierror-nosuchrevid', $revid ] );
176 }
177 $pTitleObj = $titleObj;
178 $titleObj = $rev->getTitle();
179 if ( $titleProvided ) {
180 if ( !$titleObj->equals( $pTitleObj ) ) {
181 $this->addWarning( [ 'apierror-revwrongpage', $rev->getId(),
182 wfEscapeWikiText( $pTitleObj->getPrefixedText() ) ] );
183 }
184 } else {
185 // Consider the title derived from the revid as having
186 // been provided.
187 $titleProvided = true;
188 }
189 }
190 $wgTitle = $titleObj;
191 if ( $titleObj->canExist() ) {
192 $pageObj = WikiPage::factory( $titleObj );
193 } else {
194 // Do like MediaWiki::initializeArticle()
195 $article = Article::newFromTitle( $titleObj, $this->getContext() );
196 $pageObj = $article->getPage();
197 }
198
199 list( $popts, $reset ) = $this->makeParserOptions( $pageObj, $params );
200 $textProvided = !is_null( $text );
201
202 if ( !$textProvided ) {
203 if ( $titleProvided && ( $prop || $params['generatexml'] ) ) {
204 if ( $revid !== null ) {
205 $this->addWarning( 'apiwarn-parse-revidwithouttext' );
206 } else {
207 $this->addWarning( 'apiwarn-parse-titlewithouttext' );
208 }
209 }
210 // Prevent warning from ContentHandler::makeContent()
211 $text = '';
212 }
213
214 // If we are parsing text, do not use the content model of the default
215 // API title, but default to wikitext to keep BC.
216 if ( $textProvided && !$titleProvided && is_null( $model ) ) {
217 $model = CONTENT_MODEL_WIKITEXT;
218 $this->addWarning( [ 'apiwarn-parse-nocontentmodel', $model ] );
219 }
220
221 try {
222 $this->content = ContentHandler::makeContent( $text, $titleObj, $model, $format );
223 } catch ( MWContentSerializationException $ex ) {
224 $this->dieWithException( $ex, [
225 'wrap' => ApiMessage::create( 'apierror-contentserializationexception', 'parseerror' )
226 ] );
227 }
228
229 if ( $this->section !== false ) {
230 if ( $this->section === 'new' ) {
231 // Insert the section title above the content.
232 if ( !is_null( $params['sectiontitle'] ) && $params['sectiontitle'] !== '' ) {
233 $this->content = $this->content->addSectionHeader( $params['sectiontitle'] );
234 }
235 } else {
236 $this->content = $this->getSectionContent( $this->content, $titleObj->getPrefixedText() );
237 }
238 }
239
240 if ( $params['pst'] || $params['onlypst'] ) {
241 $this->pstContent = $this->content->preSaveTransform( $titleObj, $this->getUser(), $popts );
242 }
243 if ( $params['onlypst'] ) {
244 // Build a result and bail out
245 $result_array = [];
246 $result_array['text'] = $this->pstContent->serialize( $format );
247 $result_array[ApiResult::META_BC_SUBELEMENTS][] = 'text';
248 if ( isset( $prop['wikitext'] ) ) {
249 $result_array['wikitext'] = $this->content->serialize( $format );
250 $result_array[ApiResult::META_BC_SUBELEMENTS][] = 'wikitext';
251 }
252 if ( !is_null( $params['summary'] ) ||
253 ( !is_null( $params['sectiontitle'] ) && $this->section === 'new' )
254 ) {
255 $result_array['parsedsummary'] = $this->formatSummary( $titleObj, $params );
256 $result_array[ApiResult::META_BC_SUBELEMENTS][] = 'parsedsummary';
257 }
258
259 $result->addValue( null, $this->getModuleName(), $result_array );
260
261 return;
262 }
263
264 // Not cached (save or load)
265 if ( $params['pst'] ) {
266 $p_result = $this->pstContent->getParserOutput( $titleObj, $revid, $popts );
267 } else {
268 $p_result = $this->content->getParserOutput( $titleObj, $revid, $popts );
269 }
270 }
271
272 $result_array = [];
273
274 $result_array['title'] = $titleObj->getPrefixedText();
275 $result_array['pageid'] = $pageid ?: $pageObj->getId();
276 if ( $this->contentIsDeleted ) {
277 $result_array['textdeleted'] = true;
278 }
279 if ( $this->contentIsSuppressed ) {
280 $result_array['textsuppressed'] = true;
281 }
282
283 if ( isset( $params['useskin'] ) ) {
284 $factory = MediaWikiServices::getInstance()->getSkinFactory();
285 $skin = $factory->makeSkin( Skin::normalizeKey( $params['useskin'] ) );
286 } else {
287 $skin = null;
288 }
289
290 $outputPage = null;
291 if ( $skin || isset( $prop['headhtml'] ) || isset( $prop['categorieshtml'] ) ) {
292 // Enabling the skin via 'useskin', 'headhtml', or 'categorieshtml'
293 // gets OutputPage and Skin involved, which (among others) applies
294 // these hooks:
295 // - ParserOutputHooks
296 // - Hook: LanguageLinks
297 // - Hook: OutputPageParserOutput
298 // - Hook: OutputPageMakeCategoryLinks
299 $context = new DerivativeContext( $this->getContext() );
300 $context->setTitle( $titleObj );
301 $context->setWikiPage( $pageObj );
302
303 if ( $skin ) {
304 // Use the skin specified by 'useskin'
305 $context->setSkin( $skin );
306 // Context clones the skin, refetch to stay in sync. (T166022)
307 $skin = $context->getSkin();
308 } else {
309 // Make sure the context's skin refers to the context. Without this,
310 // $outputPage->getSkin()->getOutput() !== $outputPage which
311 // confuses some of the output.
312 $context->setSkin( $context->getSkin() );
313 }
314
315 $outputPage = new OutputPage( $context );
316 $outputPage->addParserOutputMetadata( $p_result );
317 $context->setOutput( $outputPage );
318
319 if ( $skin ) {
320 // Based on OutputPage::headElement()
321 $skin->setupSkinUserCss( $outputPage );
322 // Based on OutputPage::output()
323 foreach ( $skin->getDefaultModules() as $group ) {
324 $outputPage->addModules( $group );
325 }
326 }
327 }
328
329 if ( !is_null( $oldid ) ) {
330 $result_array['revid'] = intval( $oldid );
331 }
332
333 if ( $params['redirects'] && !is_null( $redirValues ) ) {
334 $result_array['redirects'] = $redirValues;
335 }
336
337 if ( isset( $prop['text'] ) ) {
338 $result_array['text'] = $p_result->getText( [
339 'allowTOC' => !$params['disabletoc'],
340 'enableSectionEditLinks' => !$params['disableeditsection'],
341 'unwrap' => $params['wrapoutputclass'] === '',
342 'deduplicateStyles' => !$params['disablestylededuplication'],
343 ] );
344 $result_array[ApiResult::META_BC_SUBELEMENTS][] = 'text';
345 }
346
347 if ( !is_null( $params['summary'] ) ||
348 ( !is_null( $params['sectiontitle'] ) && $this->section === 'new' )
349 ) {
350 $result_array['parsedsummary'] = $this->formatSummary( $titleObj, $params );
351 $result_array[ApiResult::META_BC_SUBELEMENTS][] = 'parsedsummary';
352 }
353
354 if ( isset( $prop['langlinks'] ) ) {
355 if ( $skin ) {
356 $langlinks = $outputPage->getLanguageLinks();
357 } else {
358 $langlinks = $p_result->getLanguageLinks();
359 // The deprecated 'effectivelanglinks' option depredates OutputPage
360 // support via 'useskin'. If not already applied, then run just this
361 // one hook of OutputPage::addParserOutputMetadata here.
362 if ( $params['effectivelanglinks'] ) {
363 $linkFlags = [];
364 Hooks::run( 'LanguageLinks', [ $titleObj, &$langlinks, &$linkFlags ] );
365 }
366 }
367
368 $result_array['langlinks'] = $this->formatLangLinks( $langlinks );
369 }
370 if ( isset( $prop['categories'] ) ) {
371 $result_array['categories'] = $this->formatCategoryLinks( $p_result->getCategories() );
372 }
373 if ( isset( $prop['categorieshtml'] ) ) {
374 $result_array['categorieshtml'] = $outputPage->getSkin()->getCategories();
375 $result_array[ApiResult::META_BC_SUBELEMENTS][] = 'categorieshtml';
376 }
377 if ( isset( $prop['links'] ) ) {
378 $result_array['links'] = $this->formatLinks( $p_result->getLinks() );
379 }
380 if ( isset( $prop['templates'] ) ) {
381 $result_array['templates'] = $this->formatLinks( $p_result->getTemplates() );
382 }
383 if ( isset( $prop['images'] ) ) {
384 $result_array['images'] = array_keys( $p_result->getImages() );
385 }
386 if ( isset( $prop['externallinks'] ) ) {
387 $result_array['externallinks'] = array_keys( $p_result->getExternalLinks() );
388 }
389 if ( isset( $prop['sections'] ) ) {
390 $result_array['sections'] = $p_result->getSections();
391 }
392 if ( isset( $prop['parsewarnings'] ) ) {
393 $result_array['parsewarnings'] = $p_result->getWarnings();
394 }
395
396 if ( isset( $prop['displaytitle'] ) ) {
397 $result_array['displaytitle'] = $p_result->getDisplayTitle() !== false
398 ? $p_result->getDisplayTitle() : $titleObj->getPrefixedText();
399 }
400
401 if ( isset( $prop['headitems'] ) ) {
402 if ( $skin ) {
403 $result_array['headitems'] = $this->formatHeadItems( $outputPage->getHeadItemsArray() );
404 } else {
405 $result_array['headitems'] = $this->formatHeadItems( $p_result->getHeadItems() );
406 }
407 }
408
409 if ( isset( $prop['headhtml'] ) ) {
410 $result_array['headhtml'] = $outputPage->headElement( $context->getSkin() );
411 $result_array[ApiResult::META_BC_SUBELEMENTS][] = 'headhtml';
412 }
413
414 if ( isset( $prop['modules'] ) ) {
415 if ( $skin ) {
416 $result_array['modules'] = $outputPage->getModules();
417 $result_array['modulescripts'] = $outputPage->getModuleScripts();
418 $result_array['modulestyles'] = $outputPage->getModuleStyles();
419 } else {
420 $result_array['modules'] = array_values( array_unique( $p_result->getModules() ) );
421 $result_array['modulescripts'] = array_values( array_unique( $p_result->getModuleScripts() ) );
422 $result_array['modulestyles'] = array_values( array_unique( $p_result->getModuleStyles() ) );
423 }
424 }
425
426 if ( isset( $prop['jsconfigvars'] ) ) {
427 $jsconfigvars = $skin ? $outputPage->getJsConfigVars() : $p_result->getJsConfigVars();
428 $result_array['jsconfigvars'] = ApiResult::addMetadataToResultVars( $jsconfigvars );
429 }
430
431 if ( isset( $prop['encodedjsconfigvars'] ) ) {
432 $jsconfigvars = $skin ? $outputPage->getJsConfigVars() : $p_result->getJsConfigVars();
433 $result_array['encodedjsconfigvars'] = FormatJson::encode(
434 $jsconfigvars,
435 false,
436 FormatJson::ALL_OK
437 );
438 $result_array[ApiResult::META_SUBELEMENTS][] = 'encodedjsconfigvars';
439 }
440
441 if ( isset( $prop['modules'] ) &&
442 !isset( $prop['jsconfigvars'] ) && !isset( $prop['encodedjsconfigvars'] ) ) {
443 $this->addWarning( 'apiwarn-moduleswithoutvars' );
444 }
445
446 if ( isset( $prop['indicators'] ) ) {
447 if ( $skin ) {
448 $result_array['indicators'] = (array)$outputPage->getIndicators();
449 } else {
450 $result_array['indicators'] = (array)$p_result->getIndicators();
451 }
452 ApiResult::setArrayType( $result_array['indicators'], 'BCkvp', 'name' );
453 }
454
455 if ( isset( $prop['iwlinks'] ) ) {
456 $result_array['iwlinks'] = $this->formatIWLinks( $p_result->getInterwikiLinks() );
457 }
458
459 if ( isset( $prop['wikitext'] ) ) {
460 $result_array['wikitext'] = $this->content->serialize( $format );
461 $result_array[ApiResult::META_BC_SUBELEMENTS][] = 'wikitext';
462 if ( !is_null( $this->pstContent ) ) {
463 $result_array['psttext'] = $this->pstContent->serialize( $format );
464 $result_array[ApiResult::META_BC_SUBELEMENTS][] = 'psttext';
465 }
466 }
467 if ( isset( $prop['properties'] ) ) {
468 $result_array['properties'] = (array)$p_result->getProperties();
469 ApiResult::setArrayType( $result_array['properties'], 'BCkvp', 'name' );
470 }
471
472 if ( isset( $prop['limitreportdata'] ) ) {
473 $result_array['limitreportdata'] =
474 $this->formatLimitReportData( $p_result->getLimitReportData() );
475 }
476 if ( isset( $prop['limitreporthtml'] ) ) {
477 $result_array['limitreporthtml'] = EditPage::getPreviewLimitReport( $p_result );
478 $result_array[ApiResult::META_BC_SUBELEMENTS][] = 'limitreporthtml';
479 }
480
481 if ( isset( $prop['parsetree'] ) || $params['generatexml'] ) {
482 if ( $this->content->getModel() != CONTENT_MODEL_WIKITEXT ) {
483 $this->dieWithError( 'apierror-parsetree-notwikitext', 'notwikitext' );
484 }
485
486 $wgParser->startExternalParse( $titleObj, $popts, Parser::OT_PREPROCESS );
487 $xml = $wgParser->preprocessToDom( $this->content->getNativeData() )->__toString();
488 $result_array['parsetree'] = $xml;
489 $result_array[ApiResult::META_BC_SUBELEMENTS][] = 'parsetree';
490 }
491
492 $result_mapping = [
493 'redirects' => 'r',
494 'langlinks' => 'll',
495 'categories' => 'cl',
496 'links' => 'pl',
497 'templates' => 'tl',
498 'images' => 'img',
499 'externallinks' => 'el',
500 'iwlinks' => 'iw',
501 'sections' => 's',
502 'headitems' => 'hi',
503 'modules' => 'm',
504 'indicators' => 'ind',
505 'modulescripts' => 'm',
506 'modulestyles' => 'm',
507 'properties' => 'pp',
508 'limitreportdata' => 'lr',
509 'parsewarnings' => 'pw'
510 ];
511 $this->setIndexedTagNames( $result_array, $result_mapping );
512 $result->addValue( null, $this->getModuleName(), $result_array );
513 }
514
523 protected function makeParserOptions( WikiPage $pageObj, array $params ) {
524 $popts = $pageObj->makeParserOptions( $this->getContext() );
525 $popts->enableLimitReport( !$params['disablepp'] && !$params['disablelimitreport'] );
526 $popts->setIsPreview( $params['preview'] || $params['sectionpreview'] );
527 $popts->setIsSectionPreview( $params['sectionpreview'] );
528 if ( $params['disabletidy'] ) {
529 $popts->setTidy( false );
530 }
531 if ( $params['wrapoutputclass'] !== '' ) {
532 $popts->setWrapOutputClass( $params['wrapoutputclass'] );
533 }
534
535 $reset = null;
536 $suppressCache = false;
537 Hooks::run( 'ApiMakeParserOptions',
538 [ $popts, $pageObj->getTitle(), $params, $this, &$reset, &$suppressCache ] );
539
540 // Force cache suppression when $popts aren't cacheable.
541 $suppressCache = $suppressCache || !$popts->isSafeToCache();
542
543 return [ $popts, $reset, $suppressCache ];
544 }
545
555 private function getParsedContent(
556 WikiPage $page, $popts, $suppressCache, $pageId, $rev, $getContent
557 ) {
558 $revId = $rev ? $rev->getId() : null;
559 $isDeleted = $rev && $rev->isDeleted( Revision::DELETED_TEXT );
560
561 if ( $getContent || $this->section !== false || $isDeleted ) {
562 if ( $rev ) {
563 $this->content = $rev->getContent( Revision::FOR_THIS_USER, $this->getUser() );
564 if ( !$this->content ) {
565 $this->dieWithError( [ 'apierror-missingcontent-revid', $revId ] );
566 }
567 } else {
568 $this->content = $page->getContent( Revision::FOR_THIS_USER, $this->getUser() );
569 if ( !$this->content ) {
570 $this->dieWithError( [ 'apierror-missingcontent-pageid', $page->getId() ] );
571 }
572 }
573 $this->contentIsDeleted = $isDeleted;
574 $this->contentIsSuppressed = $rev &&
575 $rev->isDeleted( Revision::DELETED_TEXT | Revision::DELETED_RESTRICTED );
576 }
577
578 if ( $this->section !== false ) {
579 $this->content = $this->getSectionContent(
580 $this->content,
581 $pageId === null ? $page->getTitle()->getPrefixedText() : $this->msg( 'pageid', $pageId )
582 );
583 return $this->content->getParserOutput( $page->getTitle(), $revId, $popts );
584 }
585
586 if ( $isDeleted ) {
587 // getParserOutput can't do revdeled revisions
588 $pout = $this->content->getParserOutput( $page->getTitle(), $revId, $popts );
589 } else {
590 // getParserOutput will save to Parser cache if able
591 $pout = $page->getParserOutput( $popts, $revId, $suppressCache );
592 }
593 if ( !$pout ) {
594 $this->dieWithError( [ 'apierror-nosuchrevid', $revId ?: $page->getLatest() ] ); // @codeCoverageIgnore
595 }
596
597 return $pout;
598 }
599
607 private function getSectionContent( Content $content, $what ) {
608 // Not cached (save or load)
609 $section = $content->getSection( $this->section );
610 if ( $section === false ) {
611 $this->dieWithError( [ 'apierror-nosuchsection-what', $this->section, $what ], 'nosuchsection' );
612 }
613 if ( $section === null ) {
614 $this->dieWithError( [ 'apierror-sectionsnotsupported-what', $what ], 'nosuchsection' );
615 $section = false;
616 }
617
618 return $section;
619 }
620
628 private function formatSummary( $title, $params ) {
629 global $wgParser;
630 $summary = !is_null( $params['summary'] ) ? $params['summary'] : '';
631 $sectionTitle = !is_null( $params['sectiontitle'] ) ? $params['sectiontitle'] : '';
632
633 if ( $this->section === 'new' && ( $sectionTitle === '' || $summary === '' ) ) {
634 if ( $sectionTitle !== '' ) {
635 $summary = $params['sectiontitle'];
636 }
637 if ( $summary !== '' ) {
638 $summary = wfMessage( 'newsectionsummary' )
639 ->rawParams( $wgParser->stripSectionName( $summary ) )
640 ->inContentLanguage()->text();
641 }
642 }
643 return Linker::formatComment( $summary, $title, $this->section === 'new' );
644 }
645
646 private function formatLangLinks( $links ) {
647 $result = [];
648 foreach ( $links as $link ) {
649 $entry = [];
650 $bits = explode( ':', $link, 2 );
651 $title = Title::newFromText( $link );
652
653 $entry['lang'] = $bits[0];
654 if ( $title ) {
655 $entry['url'] = wfExpandUrl( $title->getFullURL(), PROTO_CURRENT );
656 // localised language name in 'uselang' language
657 $entry['langname'] = Language::fetchLanguageName(
658 $title->getInterwiki(),
659 $this->getLanguage()->getCode()
660 );
661
662 // native language name
663 $entry['autonym'] = Language::fetchLanguageName( $title->getInterwiki() );
664 }
665 ApiResult::setContentValue( $entry, 'title', $bits[1] );
666 $result[] = $entry;
667 }
668
669 return $result;
670 }
671
672 private function formatCategoryLinks( $links ) {
673 $result = [];
674
675 if ( !$links ) {
676 return $result;
677 }
678
679 // Fetch hiddencat property
680 $lb = new LinkBatch;
681 $lb->setArray( [ NS_CATEGORY => $links ] );
682 $db = $this->getDB();
683 $res = $db->select( [ 'page', 'page_props' ],
684 [ 'page_title', 'pp_propname' ],
685 $lb->constructSet( 'page', $db ),
686 __METHOD__,
687 [],
688 [ 'page_props' => [
689 'LEFT JOIN', [ 'pp_propname' => 'hiddencat', 'pp_page = page_id' ]
690 ] ]
691 );
692 $hiddencats = [];
693 foreach ( $res as $row ) {
694 $hiddencats[$row->page_title] = isset( $row->pp_propname );
695 }
696
697 $linkCache = LinkCache::singleton();
698
699 foreach ( $links as $link => $sortkey ) {
700 $entry = [];
701 $entry['sortkey'] = $sortkey;
702 // array keys will cast numeric category names to ints, so cast back to string
703 ApiResult::setContentValue( $entry, 'category', (string)$link );
704 if ( !isset( $hiddencats[$link] ) ) {
705 $entry['missing'] = true;
706
707 // We already know the link doesn't exist in the database, so
708 // tell LinkCache that before calling $title->isKnown().
709 $title = Title::makeTitle( NS_CATEGORY, $link );
710 $linkCache->addBadLinkObj( $title );
711 if ( $title->isKnown() ) {
712 $entry['known'] = true;
713 }
714 } elseif ( $hiddencats[$link] ) {
715 $entry['hidden'] = true;
716 }
717 $result[] = $entry;
718 }
719
720 return $result;
721 }
722
723 private function formatLinks( $links ) {
724 $result = [];
725 foreach ( $links as $ns => $nslinks ) {
726 foreach ( $nslinks as $title => $id ) {
727 $entry = [];
728 $entry['ns'] = $ns;
729 ApiResult::setContentValue( $entry, 'title', Title::makeTitle( $ns, $title )->getFullText() );
730 $entry['exists'] = $id != 0;
731 $result[] = $entry;
732 }
733 }
734
735 return $result;
736 }
737
738 private function formatIWLinks( $iw ) {
739 $result = [];
740 foreach ( $iw as $prefix => $titles ) {
741 foreach ( array_keys( $titles ) as $title ) {
742 $entry = [];
743 $entry['prefix'] = $prefix;
744
745 $title = Title::newFromText( "{$prefix}:{$title}" );
746 if ( $title ) {
747 $entry['url'] = wfExpandUrl( $title->getFullURL(), PROTO_CURRENT );
748 }
749
750 ApiResult::setContentValue( $entry, 'title', $title->getFullText() );
751 $result[] = $entry;
752 }
753 }
754
755 return $result;
756 }
757
758 private function formatHeadItems( $headItems ) {
759 $result = [];
760 foreach ( $headItems as $tag => $content ) {
761 $entry = [];
762 $entry['tag'] = $tag;
763 ApiResult::setContentValue( $entry, 'content', $content );
764 $result[] = $entry;
765 }
766
767 return $result;
768 }
769
770 private function formatLimitReportData( $limitReportData ) {
771 $result = [];
772
773 foreach ( $limitReportData as $name => $value ) {
774 $entry = [];
775 $entry['name'] = $name;
776 if ( !is_array( $value ) ) {
777 $value = [ $value ];
778 }
780 $entry = array_merge( $entry, $value );
781 $result[] = $entry;
782 }
783
784 return $result;
785 }
786
787 private function setIndexedTagNames( &$array, $mapping ) {
788 foreach ( $mapping as $key => $name ) {
789 if ( isset( $array[$key] ) ) {
790 ApiResult::setIndexedTagName( $array[$key], $name );
791 }
792 }
793 }
794
795 public function getAllowedParams() {
796 return [
797 'title' => null,
798 'text' => [
799 ApiBase::PARAM_TYPE => 'text',
800 ],
801 'revid' => [
802 ApiBase::PARAM_TYPE => 'integer',
803 ],
804 'summary' => null,
805 'page' => null,
806 'pageid' => [
807 ApiBase::PARAM_TYPE => 'integer',
808 ],
809 'redirects' => false,
810 'oldid' => [
811 ApiBase::PARAM_TYPE => 'integer',
812 ],
813 'prop' => [
814 ApiBase::PARAM_DFLT => 'text|langlinks|categories|links|templates|' .
815 'images|externallinks|sections|revid|displaytitle|iwlinks|' .
816 'properties|parsewarnings',
819 'text',
820 'langlinks',
821 'categories',
822 'categorieshtml',
823 'links',
824 'templates',
825 'images',
826 'externallinks',
827 'sections',
828 'revid',
829 'displaytitle',
830 'headhtml',
831 'modules',
832 'jsconfigvars',
833 'encodedjsconfigvars',
834 'indicators',
835 'iwlinks',
836 'wikitext',
837 'properties',
838 'limitreportdata',
839 'limitreporthtml',
840 'parsetree',
841 'parsewarnings',
842 'headitems',
843 ],
845 'parsetree' => [ 'apihelp-parse-paramvalue-prop-parsetree', CONTENT_MODEL_WIKITEXT ],
846 ],
848 'headitems' => 'apiwarn-deprecation-parse-headitems',
849 ],
850 ],
851 'wrapoutputclass' => 'mw-parser-output',
852 'pst' => false,
853 'onlypst' => false,
854 'effectivelanglinks' => [
855 ApiBase::PARAM_DFLT => false,
857 ],
858 'section' => null,
859 'sectiontitle' => [
860 ApiBase::PARAM_TYPE => 'string',
861 ],
862 'disablepp' => [
863 ApiBase::PARAM_DFLT => false,
865 ],
866 'disablelimitreport' => false,
867 'disableeditsection' => false,
868 'disabletidy' => false,
869 'disablestylededuplication' => false,
870 'generatexml' => [
871 ApiBase::PARAM_DFLT => false,
873 'apihelp-parse-param-generatexml', CONTENT_MODEL_WIKITEXT
874 ],
876 ],
877 'preview' => false,
878 'sectionpreview' => false,
879 'disabletoc' => false,
880 'useskin' => [
881 ApiBase::PARAM_TYPE => array_keys( Skin::getAllowedSkins() ),
882 ],
883 'contentformat' => [
884 ApiBase::PARAM_TYPE => ContentHandler::getAllContentFormats(),
885 ],
886 'contentmodel' => [
887 ApiBase::PARAM_TYPE => ContentHandler::getContentModels(),
888 ]
889 ];
890 }
891
892 protected function getExamplesMessages() {
893 return [
894 'action=parse&page=Project:Sandbox'
895 => 'apihelp-parse-example-page',
896 'action=parse&text={{Project:Sandbox}}&contentmodel=wikitext'
897 => 'apihelp-parse-example-text',
898 'action=parse&text={{PAGENAME}}&title=Test'
899 => 'apihelp-parse-example-texttitle',
900 'action=parse&summary=Some+[[link]]&prop='
901 => 'apihelp-parse-example-summary',
902 ];
903 }
904
905 public function getHelpUrls() {
906 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Parsing_wikitext#parse';
907 }
908}
wfExpandUrl( $url, $defaultProto=PROTO_CURRENT)
Expand a potentially local URL to a fully-qualified URL.
wfEscapeWikiText( $text)
Escapes the given text so that it may be output using addWikiText() without any linking,...
$wgParser
Definition Setup.php:917
if(! $wgRequest->checkUrlExtension()) if(isset($_SERVER[ 'PATH_INFO']) &&$_SERVER[ 'PATH_INFO'] !='') if(! $wgEnableAPI) $wgTitle
Definition api.php:68
This abstract class implements many basic API functions, and is the base of all API classes.
Definition ApiBase.php:37
const PARAM_DEPRECATED
(boolean) Is the parameter deprecated (will show a warning)?
Definition ApiBase.php:105
getDB()
Gets a default replica DB connection object.
Definition ApiBase.php:669
dieWithError( $msg, $code=null, $data=null, $httpCode=null)
Abort execution with an error.
Definition ApiBase.php:1895
const PARAM_DEPRECATED_VALUES
(array) When PARAM_TYPE is an array, this indicates which of the values are deprecated.
Definition ApiBase.php:202
getMain()
Get the main module.
Definition ApiBase.php:537
const PARAM_TYPE
(string|string[]) Either an array of allowed value strings, or a string type as described below.
Definition ApiBase.php:87
const PARAM_DFLT
(null|boolean|integer|string) Default value of the parameter.
Definition ApiBase.php:48
extractRequestParams( $parseLimit=true)
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition ApiBase.php:749
const PARAM_HELP_MSG_PER_VALUE
((string|array|Message)[]) When PARAM_TYPE is an array, this is an array mapping those values to $msg...
Definition ApiBase.php:157
getResult()
Get the result object.
Definition ApiBase.php:641
requireMaxOneParameter( $params, $required)
Die if more than one of a certain set of parameters is set and not false.
Definition ApiBase.php:823
dieWithException( $exception, array $options=[])
Abort execution with an error derived from an exception.
Definition ApiBase.php:1907
const PARAM_HELP_MSG
(string|array|Message) Specify an alternative i18n documentation message for this parameter.
Definition ApiBase.php:124
addWarning( $msg, $code=null, $data=null)
Add a warning for this module.
Definition ApiBase.php:1819
getModuleName()
Get the name of the module being executed by this instance.
Definition ApiBase.php:521
getTitleOrPageId( $params, $load=false)
Get a WikiPage object from a title or pageid param, if possible.
Definition ApiBase.php:926
checkTitleUserPermissions(Title $title, $actions, $user=null)
Helper function for permission-denied errors.
Definition ApiBase.php:2024
const PARAM_ISMULTI
(boolean) Accept multiple pipe-separated values for this parameter (e.g.
Definition ApiBase.php:51
This is the main API class, used for both external and internal processing.
Definition ApiMain.php:43
static create( $msg, $code=null, array $data=null)
Create an IApiMessage for the message.
This class contains a list of pages that the client has requested.
formatSummary( $title, $params)
This mimicks the behavior of EditPage in formatting a summary.
Definition ApiParse.php:628
getAllowedParams()
Returns an array of allowed parameters (parameter name) => (default value) or (parameter name) => (ar...
Definition ApiParse.php:795
formatLinks( $links)
Definition ApiParse.php:723
getParsedContent(WikiPage $page, $popts, $suppressCache, $pageId, $rev, $getContent)
Definition ApiParse.php:555
formatHeadItems( $headItems)
Definition ApiParse.php:758
formatIWLinks( $iw)
Definition ApiParse.php:738
formatLangLinks( $links)
Definition ApiParse.php:646
getExamplesMessages()
Returns usage examples for this module.
Definition ApiParse.php:892
bool $contentIsDeleted
Definition ApiParse.php:40
formatCategoryLinks( $links)
Definition ApiParse.php:672
formatLimitReportData( $limitReportData)
Definition ApiParse.php:770
makeParserOptions(WikiPage $pageObj, array $params)
Constructs a ParserOptions object.
Definition ApiParse.php:523
bool $contentIsSuppressed
Definition ApiParse.php:40
getSectionContent(Content $content, $what)
Extract the requested section from the given Content.
Definition ApiParse.php:607
getHelpUrls()
Return links to more detailed help pages about the module.
Definition ApiParse.php:905
setIndexedTagNames(&$array, $mapping)
Definition ApiParse.php:787
execute()
Evaluates the parameters, performs the requested query, and sets up the result.
Definition ApiParse.php:42
static setArrayType(array &$arr, $type, $kvpKeyName=null)
Set the array data type.
static addMetadataToResultVars( $vars, $forceHash=true)
Add the correct metadata to an array of vars we want to export through the API.
const META_SUBELEMENTS
Key for the 'subelements' metadata item.
Definition ApiResult.php:76
const META_BC_SUBELEMENTS
Key for the 'BC subelements' metadata item.
static setIndexedTagName(array &$arr, $tag)
Set the tag name for numeric-keyed values in XML format.
static setContentValue(array &$arr, $name, $value, $flags=0)
Add an output value to the array by name and mark as META_CONTENT.
static setIndexedTagNameRecursive(array &$arr, $tag)
Set indexed tag name on $arr and all subarrays.
static newFromTitle( $title, IContextSource $context)
Create an Article object of the appropriate class for the given page.
Definition Article.php:120
msg( $key)
Get a Message object with context set Parameters are the same as wfMessage()
IContextSource $context
getContext()
Get the base IContextSource object.
An IContextSource implementation which will inherit context from another source but allow individual ...
static getPreviewLimitReport( $output)
Get the Limit report for page previews.
WebRequest clone which takes values from a provided array.
Class representing a list of titles The execute() method checks them all for existence and adds them ...
Definition LinkBatch.php:34
setArray( $array)
Set the link list to a given 2-d array First key is the namespace, second is the DB key,...
Definition LinkBatch.php:97
static formatComment( $comment, $title=null, $local=false, $wikiId=null)
This function is called by all recent changes variants, by the page history, and by the user contribu...
Definition Linker.php:1109
Exception representing a failure to serialize or unserialize a content object.
MediaWikiServices is the service locator for the application scope of MediaWiki.
This class should be covered by a general architecture document which does not exist as of January 20...
Class representing a MediaWiki article and history.
Definition WikiPage.php:37
getLatest()
Get the page_latest field.
Definition WikiPage.php:624
getParserOutput(ParserOptions $parserOptions, $oldid=null, $forceParse=false)
Get a ParserOutput for the given ParserOptions and revision ID.
getContent( $audience=Revision::FOR_PUBLIC, User $user=null)
Get the content of the current revision.
Definition WikiPage.php:718
getTitle()
Get the title object of the article.
Definition WikiPage.php:236
$res
Definition database.txt:21
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition deferred.txt:11
this hook is for auditing only $req
Definition hooks.txt:990
the array() calling protocol came about after MediaWiki 1.4rc1.
namespace being checked & $result
Definition hooks.txt:2323
either a unescaped string or a HtmlArmor object after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a set this to the key of the message First element is the message additional optional elements are parameters for the key that are processed with wfMessage() -> params() ->parseAsBlock() - offset Set to overwrite offset parameter in $wgRequest set to '' to unset offset - wrap String Wrap the message in html(usually something like "&lt;div ...>$1&lt;/div>"). - flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException':Called before an exception(or PHP error) is logged. This is meant for integration with external error aggregation services
usually copyright or history_copyright This message must be in HTML not wikitext & $link
Definition hooks.txt:3021
Allows to change the fields on the form that will be generated $name
Definition hooks.txt:302
presenting them properly to the user as errors is done by the caller return true use this to change the list i e etc $rev
Definition hooks.txt:1777
const PROTO_CURRENT
Definition Defines.php:232
const CONTENT_MODEL_WIKITEXT
Definition Defines.php:245
const NS_CATEGORY
Definition Defines.php:88
Base interface for content objects.
Definition Content.php:34
linkcache txt The LinkCache class maintains a list of article titles and the information about whether or not the article exists in the database This is used to mark up links when displaying a page If the same link appears more than once on any page then it only has to be looked up once In most cases link lookups are done in batches with the LinkBatch class or the equivalent in so the link cache is mostly useful for short snippets of parsed and for links in the navigation areas of the skin The link cache was formerly used to track links used in a document for the purposes of updating the link tables This application is now deprecated To create a you can use the following $titles
Definition linkcache.txt:17
$params