MediaWiki REL1_30
ApiParse.php
Go to the documentation of this file.
1<?php
26
30class ApiParse extends ApiBase {
31
33 private $section = null;
34
36 private $content = null;
37
39 private $pstContent = null;
40
42 private $contentIsDeleted = false, $contentIsSuppressed = false;
43
44 public function execute() {
45 // The data is hot but user-dependent, like page views, so we set vary cookies
46 $this->getMain()->setCacheMode( 'anon-public-user-private' );
47
48 // Get parameters
50
51 // No easy way to say that text and title or revid are allowed together
52 // while the rest aren't, so just do it in three calls.
53 $this->requireMaxOneParameter( $params, 'page', 'pageid', 'oldid', 'text' );
54 $this->requireMaxOneParameter( $params, 'page', 'pageid', 'oldid', 'title' );
55 $this->requireMaxOneParameter( $params, 'page', 'pageid', 'oldid', 'revid' );
56
57 $text = $params['text'];
58 $title = $params['title'];
59 if ( $title === null ) {
60 $titleProvided = false;
61 // A title is needed for parsing, so arbitrarily choose one
62 $title = 'API';
63 } else {
64 $titleProvided = true;
65 }
66
67 $page = $params['page'];
68 $pageid = $params['pageid'];
69 $oldid = $params['oldid'];
70
71 $model = $params['contentmodel'];
72 $format = $params['contentformat'];
73
74 $prop = array_flip( $params['prop'] );
75
76 if ( isset( $params['section'] ) ) {
77 $this->section = $params['section'];
78 if ( !preg_match( '/^((T-)?\d+|new)$/', $this->section ) ) {
79 $this->dieWithError( 'apierror-invalidsection' );
80 }
81 } else {
82 $this->section = false;
83 }
84
85 // The parser needs $wgTitle to be set, apparently the
86 // $title parameter in Parser::parse isn't enough *sigh*
87 // TODO: Does this still need $wgTitle?
89
90 $redirValues = null;
91
92 $needContent = isset( $prop['wikitext'] ) ||
93 isset( $prop['parsetree'] ) || $params['generatexml'];
94
95 // Return result
96 $result = $this->getResult();
97
98 if ( !is_null( $oldid ) || !is_null( $pageid ) || !is_null( $page ) ) {
99 if ( $this->section === 'new' ) {
100 $this->dieWithError( 'apierror-invalidparammix-parse-new-section', 'invalidparammix' );
101 }
102 if ( !is_null( $oldid ) ) {
103 // Don't use the parser cache
104 $rev = Revision::newFromId( $oldid );
105 if ( !$rev ) {
106 $this->dieWithError( [ 'apierror-nosuchrevid', $oldid ] );
107 }
108
109 $this->checkTitleUserPermissions( $rev->getTitle(), 'read' );
110 if ( !$rev->userCan( Revision::DELETED_TEXT, $this->getUser() ) ) {
111 $this->dieWithError(
112 [ 'apierror-permissiondenied', $this->msg( 'action-deletedtext' ) ]
113 );
114 }
115
116 $titleObj = $rev->getTitle();
117 $wgTitle = $titleObj;
118 $pageObj = WikiPage::factory( $titleObj );
119 list( $popts, $reset, $suppressCache ) = $this->makeParserOptions( $pageObj, $params );
120 $p_result = $this->getParsedContent(
121 $pageObj, $popts, $suppressCache, $pageid, $rev, $needContent
122 );
123 } else { // Not $oldid, but $pageid or $page
124 if ( $params['redirects'] ) {
125 $reqParams = [
126 'redirects' => '',
127 ];
128 if ( !is_null( $pageid ) ) {
129 $reqParams['pageids'] = $pageid;
130 } else { // $page
131 $reqParams['titles'] = $page;
132 }
133 $req = new FauxRequest( $reqParams );
134 $main = new ApiMain( $req );
135 $pageSet = new ApiPageSet( $main );
136 $pageSet->execute();
137 $redirValues = $pageSet->getRedirectTitlesAsResult( $this->getResult() );
138
139 $to = $page;
140 foreach ( $pageSet->getRedirectTitles() as $title ) {
141 $to = $title->getFullText();
142 }
143 $pageParams = [ 'title' => $to ];
144 } elseif ( !is_null( $pageid ) ) {
145 $pageParams = [ 'pageid' => $pageid ];
146 } else { // $page
147 $pageParams = [ 'title' => $page ];
148 }
149
150 $pageObj = $this->getTitleOrPageId( $pageParams, 'fromdb' );
151 $titleObj = $pageObj->getTitle();
152 if ( !$titleObj || !$titleObj->exists() ) {
153 $this->dieWithError( 'apierror-missingtitle' );
154 }
155
156 $this->checkTitleUserPermissions( $titleObj, 'read' );
157 $wgTitle = $titleObj;
158
159 if ( isset( $prop['revid'] ) ) {
160 $oldid = $pageObj->getLatest();
161 }
162
163 list( $popts, $reset, $suppressCache ) = $this->makeParserOptions( $pageObj, $params );
164 $p_result = $this->getParsedContent(
165 $pageObj, $popts, $suppressCache, $pageid, null, $needContent
166 );
167 }
168 } else { // Not $oldid, $pageid, $page. Hence based on $text
169 $titleObj = Title::newFromText( $title );
170 if ( !$titleObj || $titleObj->isExternal() ) {
171 $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $title ) ] );
172 }
173 $revid = $params['revid'];
174 if ( $revid !== null ) {
175 $rev = Revision::newFromId( $revid );
176 if ( !$rev ) {
177 $this->dieWithError( [ 'apierror-nosuchrevid', $revid ] );
178 }
179 $pTitleObj = $titleObj;
180 $titleObj = $rev->getTitle();
181 if ( $titleProvided ) {
182 if ( !$titleObj->equals( $pTitleObj ) ) {
183 $this->addWarning( [ 'apierror-revwrongpage', $rev->getId(),
184 wfEscapeWikiText( $pTitleObj->getPrefixedText() ) ] );
185 }
186 } else {
187 // Consider the title derived from the revid as having
188 // been provided.
189 $titleProvided = true;
190 }
191 }
192 $wgTitle = $titleObj;
193 if ( $titleObj->canExist() ) {
194 $pageObj = WikiPage::factory( $titleObj );
195 } else {
196 // Do like MediaWiki::initializeArticle()
197 $article = Article::newFromTitle( $titleObj, $this->getContext() );
198 $pageObj = $article->getPage();
199 }
200
201 list( $popts, $reset ) = $this->makeParserOptions( $pageObj, $params );
202 $textProvided = !is_null( $text );
203
204 if ( !$textProvided ) {
205 if ( $titleProvided && ( $prop || $params['generatexml'] ) ) {
206 if ( $revid !== null ) {
207 $this->addWarning( 'apiwarn-parse-revidwithouttext' );
208 } else {
209 $this->addWarning( 'apiwarn-parse-titlewithouttext' );
210 }
211 }
212 // Prevent warning from ContentHandler::makeContent()
213 $text = '';
214 }
215
216 // If we are parsing text, do not use the content model of the default
217 // API title, but default to wikitext to keep BC.
218 if ( $textProvided && !$titleProvided && is_null( $model ) ) {
219 $model = CONTENT_MODEL_WIKITEXT;
220 $this->addWarning( [ 'apiwarn-parse-nocontentmodel', $model ] );
221 }
222
223 try {
224 $this->content = ContentHandler::makeContent( $text, $titleObj, $model, $format );
225 } catch ( MWContentSerializationException $ex ) {
226 $this->dieWithException( $ex, [
227 'wrap' => ApiMessage::create( 'apierror-contentserializationexception', 'parseerror' )
228 ] );
229 }
230
231 if ( $this->section !== false ) {
232 if ( $this->section === 'new' ) {
233 // Insert the section title above the content.
234 if ( !is_null( $params['sectiontitle'] ) && $params['sectiontitle'] !== '' ) {
235 $this->content = $this->content->addSectionHeader( $params['sectiontitle'] );
236 }
237 } else {
238 $this->content = $this->getSectionContent( $this->content, $titleObj->getPrefixedText() );
239 }
240 }
241
242 if ( $params['pst'] || $params['onlypst'] ) {
243 $this->pstContent = $this->content->preSaveTransform( $titleObj, $this->getUser(), $popts );
244 }
245 if ( $params['onlypst'] ) {
246 // Build a result and bail out
247 $result_array = [];
248 if ( $this->contentIsDeleted ) {
249 $result_array['textdeleted'] = true;
250 }
251 if ( $this->contentIsSuppressed ) {
252 $result_array['textsuppressed'] = true;
253 }
254 $result_array['text'] = $this->pstContent->serialize( $format );
255 $result_array[ApiResult::META_BC_SUBELEMENTS][] = 'text';
256 if ( isset( $prop['wikitext'] ) ) {
257 $result_array['wikitext'] = $this->content->serialize( $format );
258 $result_array[ApiResult::META_BC_SUBELEMENTS][] = 'wikitext';
259 }
260 if ( !is_null( $params['summary'] ) ||
261 ( !is_null( $params['sectiontitle'] ) && $this->section === 'new' )
262 ) {
263 $result_array['parsedsummary'] = $this->formatSummary( $titleObj, $params );
264 $result_array[ApiResult::META_BC_SUBELEMENTS][] = 'parsedsummary';
265 }
266
267 $result->addValue( null, $this->getModuleName(), $result_array );
268
269 return;
270 }
271
272 // Not cached (save or load)
273 if ( $params['pst'] ) {
274 $p_result = $this->pstContent->getParserOutput( $titleObj, $revid, $popts );
275 } else {
276 $p_result = $this->content->getParserOutput( $titleObj, $revid, $popts );
277 }
278 }
279
280 $result_array = [];
281
282 $result_array['title'] = $titleObj->getPrefixedText();
283 $result_array['pageid'] = $pageid ?: $pageObj->getId();
284 if ( $this->contentIsDeleted ) {
285 $result_array['textdeleted'] = true;
286 }
287 if ( $this->contentIsSuppressed ) {
288 $result_array['textsuppressed'] = true;
289 }
290
291 if ( $params['disabletoc'] ) {
292 $p_result->setTOCEnabled( false );
293 }
294
295 if ( isset( $params['useskin'] ) ) {
296 $factory = MediaWikiServices::getInstance()->getSkinFactory();
297 $skin = $factory->makeSkin( Skin::normalizeKey( $params['useskin'] ) );
298 } else {
299 $skin = null;
300 }
301
302 $outputPage = null;
303 if ( $skin || isset( $prop['headhtml'] ) || isset( $prop['categorieshtml'] ) ) {
304 // Enabling the skin via 'useskin', 'headhtml', or 'categorieshtml'
305 // gets OutputPage and Skin involved, which (among others) applies
306 // these hooks:
307 // - ParserOutputHooks
308 // - Hook: LanguageLinks
309 // - Hook: OutputPageParserOutput
310 // - Hook: OutputPageMakeCategoryLinks
311 $context = new DerivativeContext( $this->getContext() );
312 $context->setTitle( $titleObj );
313 $context->setWikiPage( $pageObj );
314
315 if ( $skin ) {
316 // Use the skin specified by 'useskin'
317 $context->setSkin( $skin );
318 // Context clones the skin, refetch to stay in sync. (T166022)
320 } else {
321 // Make sure the context's skin refers to the context. Without this,
322 // $outputPage->getSkin()->getOutput() !== $outputPage which
323 // confuses some of the output.
324 $context->setSkin( $context->getSkin() );
325 }
326
327 $outputPage = new OutputPage( $context );
328 $outputPage->addParserOutputMetadata( $p_result );
329 $context->setOutput( $outputPage );
330
331 if ( $skin ) {
332 // Based on OutputPage::output()
333 foreach ( $skin->getDefaultModules() as $group ) {
334 $outputPage->addModules( $group );
335 }
336 }
337 }
338
339 if ( !is_null( $oldid ) ) {
340 $result_array['revid'] = intval( $oldid );
341 }
342
343 if ( $params['redirects'] && !is_null( $redirValues ) ) {
344 $result_array['redirects'] = $redirValues;
345 }
346
347 if ( isset( $prop['text'] ) ) {
348 $result_array['text'] = $p_result->getText();
349 $result_array[ApiResult::META_BC_SUBELEMENTS][] = 'text';
350 }
351
352 if ( !is_null( $params['summary'] ) ||
353 ( !is_null( $params['sectiontitle'] ) && $this->section === 'new' )
354 ) {
355 $result_array['parsedsummary'] = $this->formatSummary( $titleObj, $params );
356 $result_array[ApiResult::META_BC_SUBELEMENTS][] = 'parsedsummary';
357 }
358
359 if ( isset( $prop['langlinks'] ) ) {
360 if ( $skin ) {
361 $langlinks = $outputPage->getLanguageLinks();
362 } else {
363 $langlinks = $p_result->getLanguageLinks();
364 // The deprecated 'effectivelanglinks' option depredates OutputPage
365 // support via 'useskin'. If not already applied, then run just this
366 // one hook of OutputPage::addParserOutputMetadata here.
367 if ( $params['effectivelanglinks'] ) {
368 $linkFlags = [];
369 Hooks::run( 'LanguageLinks', [ $titleObj, &$langlinks, &$linkFlags ] );
370 }
371 }
372
373 $result_array['langlinks'] = $this->formatLangLinks( $langlinks );
374 }
375 if ( isset( $prop['categories'] ) ) {
376 $result_array['categories'] = $this->formatCategoryLinks( $p_result->getCategories() );
377 }
378 if ( isset( $prop['categorieshtml'] ) ) {
379 $result_array['categorieshtml'] = $outputPage->getSkin()->getCategories();
380 $result_array[ApiResult::META_BC_SUBELEMENTS][] = 'categorieshtml';
381 }
382 if ( isset( $prop['links'] ) ) {
383 $result_array['links'] = $this->formatLinks( $p_result->getLinks() );
384 }
385 if ( isset( $prop['templates'] ) ) {
386 $result_array['templates'] = $this->formatLinks( $p_result->getTemplates() );
387 }
388 if ( isset( $prop['images'] ) ) {
389 $result_array['images'] = array_keys( $p_result->getImages() );
390 }
391 if ( isset( $prop['externallinks'] ) ) {
392 $result_array['externallinks'] = array_keys( $p_result->getExternalLinks() );
393 }
394 if ( isset( $prop['sections'] ) ) {
395 $result_array['sections'] = $p_result->getSections();
396 }
397 if ( isset( $prop['parsewarnings'] ) ) {
398 $result_array['parsewarnings'] = $p_result->getWarnings();
399 }
400
401 if ( isset( $prop['displaytitle'] ) ) {
402 $result_array['displaytitle'] = $p_result->getDisplayTitle() ?:
403 $titleObj->getPrefixedText();
404 }
405
406 if ( isset( $prop['headitems'] ) ) {
407 if ( $skin ) {
408 $result_array['headitems'] = $this->formatHeadItems( $outputPage->getHeadItemsArray() );
409 } else {
410 $result_array['headitems'] = $this->formatHeadItems( $p_result->getHeadItems() );
411 }
412 }
413
414 if ( isset( $prop['headhtml'] ) ) {
415 $result_array['headhtml'] = $outputPage->headElement( $context->getSkin() );
416 $result_array[ApiResult::META_BC_SUBELEMENTS][] = 'headhtml';
417 }
418
419 if ( isset( $prop['modules'] ) ) {
420 if ( $skin ) {
421 $result_array['modules'] = $outputPage->getModules();
422 $result_array['modulescripts'] = $outputPage->getModuleScripts();
423 $result_array['modulestyles'] = $outputPage->getModuleStyles();
424 } else {
425 $result_array['modules'] = array_values( array_unique( $p_result->getModules() ) );
426 $result_array['modulescripts'] = array_values( array_unique( $p_result->getModuleScripts() ) );
427 $result_array['modulestyles'] = array_values( array_unique( $p_result->getModuleStyles() ) );
428 }
429 }
430
431 if ( isset( $prop['jsconfigvars'] ) ) {
432 $jsconfigvars = $skin ? $outputPage->getJsConfigVars() : $p_result->getJsConfigVars();
433 $result_array['jsconfigvars'] = ApiResult::addMetadataToResultVars( $jsconfigvars );
434 }
435
436 if ( isset( $prop['encodedjsconfigvars'] ) ) {
437 $jsconfigvars = $skin ? $outputPage->getJsConfigVars() : $p_result->getJsConfigVars();
438 $result_array['encodedjsconfigvars'] = FormatJson::encode(
439 $jsconfigvars,
440 false,
441 FormatJson::ALL_OK
442 );
443 $result_array[ApiResult::META_SUBELEMENTS][] = 'encodedjsconfigvars';
444 }
445
446 if ( isset( $prop['modules'] ) &&
447 !isset( $prop['jsconfigvars'] ) && !isset( $prop['encodedjsconfigvars'] ) ) {
448 $this->addWarning( 'apiwarn-moduleswithoutvars' );
449 }
450
451 if ( isset( $prop['indicators'] ) ) {
452 if ( $skin ) {
453 $result_array['indicators'] = (array)$outputPage->getIndicators();
454 } else {
455 $result_array['indicators'] = (array)$p_result->getIndicators();
456 }
457 ApiResult::setArrayType( $result_array['indicators'], 'BCkvp', 'name' );
458 }
459
460 if ( isset( $prop['iwlinks'] ) ) {
461 $result_array['iwlinks'] = $this->formatIWLinks( $p_result->getInterwikiLinks() );
462 }
463
464 if ( isset( $prop['wikitext'] ) ) {
465 $result_array['wikitext'] = $this->content->serialize( $format );
466 $result_array[ApiResult::META_BC_SUBELEMENTS][] = 'wikitext';
467 if ( !is_null( $this->pstContent ) ) {
468 $result_array['psttext'] = $this->pstContent->serialize( $format );
469 $result_array[ApiResult::META_BC_SUBELEMENTS][] = 'psttext';
470 }
471 }
472 if ( isset( $prop['properties'] ) ) {
473 $result_array['properties'] = (array)$p_result->getProperties();
474 ApiResult::setArrayType( $result_array['properties'], 'BCkvp', 'name' );
475 }
476
477 if ( isset( $prop['limitreportdata'] ) ) {
478 $result_array['limitreportdata'] =
479 $this->formatLimitReportData( $p_result->getLimitReportData() );
480 }
481 if ( isset( $prop['limitreporthtml'] ) ) {
482 $result_array['limitreporthtml'] = EditPage::getPreviewLimitReport( $p_result );
483 $result_array[ApiResult::META_BC_SUBELEMENTS][] = 'limitreporthtml';
484 }
485
486 if ( isset( $prop['parsetree'] ) || $params['generatexml'] ) {
487 if ( $this->content->getModel() != CONTENT_MODEL_WIKITEXT ) {
488 $this->dieWithError( 'apierror-parsetree-notwikitext', 'notwikitext' );
489 }
490
491 $wgParser->startExternalParse( $titleObj, $popts, Parser::OT_PREPROCESS );
492 $dom = $wgParser->preprocessToDom( $this->content->getNativeData() );
493 if ( is_callable( [ $dom, 'saveXML' ] ) ) {
494 $xml = $dom->saveXML();
495 } else {
496 $xml = $dom->__toString();
497 }
498 $result_array['parsetree'] = $xml;
499 $result_array[ApiResult::META_BC_SUBELEMENTS][] = 'parsetree';
500 }
501
502 $result_mapping = [
503 'redirects' => 'r',
504 'langlinks' => 'll',
505 'categories' => 'cl',
506 'links' => 'pl',
507 'templates' => 'tl',
508 'images' => 'img',
509 'externallinks' => 'el',
510 'iwlinks' => 'iw',
511 'sections' => 's',
512 'headitems' => 'hi',
513 'modules' => 'm',
514 'indicators' => 'ind',
515 'modulescripts' => 'm',
516 'modulestyles' => 'm',
517 'properties' => 'pp',
518 'limitreportdata' => 'lr',
519 'parsewarnings' => 'pw'
520 ];
521 $this->setIndexedTagNames( $result_array, $result_mapping );
522 $result->addValue( null, $this->getModuleName(), $result_array );
523 }
524
533 protected function makeParserOptions( WikiPage $pageObj, array $params ) {
534 $popts = $pageObj->makeParserOptions( $this->getContext() );
535 $popts->enableLimitReport( !$params['disablepp'] && !$params['disablelimitreport'] );
536 $popts->setIsPreview( $params['preview'] || $params['sectionpreview'] );
537 $popts->setIsSectionPreview( $params['sectionpreview'] );
538 $popts->setEditSection( !$params['disableeditsection'] );
539 if ( $params['disabletidy'] ) {
540 $popts->setTidy( false );
541 }
542 $popts->setWrapOutputClass(
543 $params['wrapoutputclass'] === '' ? false : $params['wrapoutputclass']
544 );
545
546 $reset = null;
547 $suppressCache = false;
548 Hooks::run( 'ApiMakeParserOptions',
549 [ $popts, $pageObj->getTitle(), $params, $this, &$reset, &$suppressCache ] );
550
551 // Force cache suppression when $popts aren't cacheable.
552 $suppressCache = $suppressCache || !$popts->isSafeToCache();
553
554 return [ $popts, $reset, $suppressCache ];
555 }
556
566 private function getParsedContent(
567 WikiPage $page, $popts, $suppressCache, $pageId, $rev, $getContent
568 ) {
569 $revId = $rev ? $rev->getId() : null;
570 $isDeleted = $rev && $rev->isDeleted( Revision::DELETED_TEXT );
571
572 if ( $getContent || $this->section !== false || $isDeleted ) {
573 if ( $rev ) {
574 $this->content = $rev->getContent( Revision::FOR_THIS_USER, $this->getUser() );
575 if ( !$this->content ) {
576 $this->dieWithError( [ 'apierror-missingcontent-revid', $revId ] );
577 }
578 } else {
579 $this->content = $page->getContent( Revision::FOR_THIS_USER, $this->getUser() );
580 if ( !$this->content ) {
581 $this->dieWithError( [ 'apierror-missingcontent-pageid', $pageId ] );
582 }
583 }
584 $this->contentIsDeleted = $isDeleted;
585 $this->contentIsSuppressed = $rev &&
587 }
588
589 if ( $this->section !== false ) {
590 $this->content = $this->getSectionContent(
591 $this->content,
592 $pageId === null ? $page->getTitle()->getPrefixedText() : $this->msg( 'pageid', $pageId )
593 );
594 return $this->content->getParserOutput( $page->getTitle(), $revId, $popts );
595 }
596
597 if ( $isDeleted ) {
598 // getParserOutput can't do revdeled revisions
599 $pout = $this->content->getParserOutput( $page->getTitle(), $revId, $popts );
600 } else {
601 // getParserOutput will save to Parser cache if able
602 $pout = $page->getParserOutput( $popts, $revId, $suppressCache );
603 }
604 if ( !$pout ) {
605 $this->dieWithError( [ 'apierror-nosuchrevid', $revId ?: $page->getLatest() ] );
606 }
607
608 return $pout;
609 }
610
618 private function getSectionContent( Content $content, $what ) {
619 // Not cached (save or load)
620 $section = $content->getSection( $this->section );
621 if ( $section === false ) {
622 $this->dieWithError( [ 'apierror-nosuchsection-what', $this->section, $what ], 'nosuchsection' );
623 }
624 if ( $section === null ) {
625 $this->dieWithError( [ 'apierror-sectionsnotsupported-what', $what ], 'nosuchsection' );
626 $section = false;
627 }
628
629 return $section;
630 }
631
639 private function formatSummary( $title, $params ) {
641 $summary = !is_null( $params['summary'] ) ? $params['summary'] : '';
642 $sectionTitle = !is_null( $params['sectiontitle'] ) ? $params['sectiontitle'] : '';
643
644 if ( $this->section === 'new' && ( $sectionTitle === '' || $summary === '' ) ) {
645 if ( $sectionTitle !== '' ) {
646 $summary = $params['sectiontitle'];
647 }
648 if ( $summary !== '' ) {
649 $summary = wfMessage( 'newsectionsummary' )
650 ->rawParams( $wgParser->stripSectionName( $summary ) )
651 ->inContentLanguage()->text();
652 }
653 }
654 return Linker::formatComment( $summary, $title, $this->section === 'new' );
655 }
656
657 private function formatLangLinks( $links ) {
658 $result = [];
659 foreach ( $links as $link ) {
660 $entry = [];
661 $bits = explode( ':', $link, 2 );
662 $title = Title::newFromText( $link );
663
664 $entry['lang'] = $bits[0];
665 if ( $title ) {
666 $entry['url'] = wfExpandUrl( $title->getFullURL(), PROTO_CURRENT );
667 // localised language name in 'uselang' language
668 $entry['langname'] = Language::fetchLanguageName(
669 $title->getInterwiki(),
670 $this->getLanguage()->getCode()
671 );
672
673 // native language name
674 $entry['autonym'] = Language::fetchLanguageName( $title->getInterwiki() );
675 }
676 ApiResult::setContentValue( $entry, 'title', $bits[1] );
677 $result[] = $entry;
678 }
679
680 return $result;
681 }
682
683 private function formatCategoryLinks( $links ) {
684 $result = [];
685
686 if ( !$links ) {
687 return $result;
688 }
689
690 // Fetch hiddencat property
691 $lb = new LinkBatch;
692 $lb->setArray( [ NS_CATEGORY => $links ] );
693 $db = $this->getDB();
694 $res = $db->select( [ 'page', 'page_props' ],
695 [ 'page_title', 'pp_propname' ],
696 $lb->constructSet( 'page', $db ),
697 __METHOD__,
698 [],
699 [ 'page_props' => [
700 'LEFT JOIN', [ 'pp_propname' => 'hiddencat', 'pp_page = page_id' ]
701 ] ]
702 );
703 $hiddencats = [];
704 foreach ( $res as $row ) {
705 $hiddencats[$row->page_title] = isset( $row->pp_propname );
706 }
707
708 $linkCache = LinkCache::singleton();
709
710 foreach ( $links as $link => $sortkey ) {
711 $entry = [];
712 $entry['sortkey'] = $sortkey;
713 // array keys will cast numeric category names to ints, so cast back to string
714 ApiResult::setContentValue( $entry, 'category', (string)$link );
715 if ( !isset( $hiddencats[$link] ) ) {
716 $entry['missing'] = true;
717
718 // We already know the link doesn't exist in the database, so
719 // tell LinkCache that before calling $title->isKnown().
720 $title = Title::makeTitle( NS_CATEGORY, $link );
721 $linkCache->addBadLinkObj( $title );
722 if ( $title->isKnown() ) {
723 $entry['known'] = true;
724 }
725 } elseif ( $hiddencats[$link] ) {
726 $entry['hidden'] = true;
727 }
728 $result[] = $entry;
729 }
730
731 return $result;
732 }
733
734 private function formatLinks( $links ) {
735 $result = [];
736 foreach ( $links as $ns => $nslinks ) {
737 foreach ( $nslinks as $title => $id ) {
738 $entry = [];
739 $entry['ns'] = $ns;
740 ApiResult::setContentValue( $entry, 'title', Title::makeTitle( $ns, $title )->getFullText() );
741 $entry['exists'] = $id != 0;
742 $result[] = $entry;
743 }
744 }
745
746 return $result;
747 }
748
749 private function formatIWLinks( $iw ) {
750 $result = [];
751 foreach ( $iw as $prefix => $titles ) {
752 foreach ( array_keys( $titles ) as $title ) {
753 $entry = [];
754 $entry['prefix'] = $prefix;
755
756 $title = Title::newFromText( "{$prefix}:{$title}" );
757 if ( $title ) {
758 $entry['url'] = wfExpandUrl( $title->getFullURL(), PROTO_CURRENT );
759 }
760
761 ApiResult::setContentValue( $entry, 'title', $title->getFullText() );
762 $result[] = $entry;
763 }
764 }
765
766 return $result;
767 }
768
769 private function formatHeadItems( $headItems ) {
770 $result = [];
771 foreach ( $headItems as $tag => $content ) {
772 $entry = [];
773 $entry['tag'] = $tag;
774 ApiResult::setContentValue( $entry, 'content', $content );
775 $result[] = $entry;
776 }
777
778 return $result;
779 }
780
781 private function formatLimitReportData( $limitReportData ) {
782 $result = [];
783
784 foreach ( $limitReportData as $name => $value ) {
785 $entry = [];
786 $entry['name'] = $name;
787 if ( !is_array( $value ) ) {
788 $value = [ $value ];
789 }
791 $entry = array_merge( $entry, $value );
792 $result[] = $entry;
793 }
794
795 return $result;
796 }
797
798 private function setIndexedTagNames( &$array, $mapping ) {
799 foreach ( $mapping as $key => $name ) {
800 if ( isset( $array[$key] ) ) {
801 ApiResult::setIndexedTagName( $array[$key], $name );
802 }
803 }
804 }
805
806 public function getAllowedParams() {
807 return [
808 'title' => null,
809 'text' => [
810 ApiBase::PARAM_TYPE => 'text',
811 ],
812 'revid' => [
813 ApiBase::PARAM_TYPE => 'integer',
814 ],
815 'summary' => null,
816 'page' => null,
817 'pageid' => [
818 ApiBase::PARAM_TYPE => 'integer',
819 ],
820 'redirects' => false,
821 'oldid' => [
822 ApiBase::PARAM_TYPE => 'integer',
823 ],
824 'prop' => [
825 ApiBase::PARAM_DFLT => 'text|langlinks|categories|links|templates|' .
826 'images|externallinks|sections|revid|displaytitle|iwlinks|' .
827 'properties|parsewarnings',
830 'text',
831 'langlinks',
832 'categories',
833 'categorieshtml',
834 'links',
835 'templates',
836 'images',
837 'externallinks',
838 'sections',
839 'revid',
840 'displaytitle',
841 'headhtml',
842 'modules',
843 'jsconfigvars',
844 'encodedjsconfigvars',
845 'indicators',
846 'iwlinks',
847 'wikitext',
848 'properties',
849 'limitreportdata',
850 'limitreporthtml',
851 'parsetree',
852 'parsewarnings',
853 'headitems',
854 ],
856 'parsetree' => [ 'apihelp-parse-paramvalue-prop-parsetree', CONTENT_MODEL_WIKITEXT ],
857 ],
859 'headitems' => 'apiwarn-deprecation-parse-headitems',
860 ],
861 ],
862 'wrapoutputclass' => 'mw-parser-output',
863 'pst' => false,
864 'onlypst' => false,
865 'effectivelanglinks' => [
866 ApiBase::PARAM_DFLT => false,
868 ],
869 'section' => null,
870 'sectiontitle' => [
871 ApiBase::PARAM_TYPE => 'string',
872 ],
873 'disablepp' => [
874 ApiBase::PARAM_DFLT => false,
876 ],
877 'disablelimitreport' => false,
878 'disableeditsection' => false,
879 'disabletidy' => false,
880 'generatexml' => [
881 ApiBase::PARAM_DFLT => false,
883 'apihelp-parse-param-generatexml', CONTENT_MODEL_WIKITEXT
884 ],
886 ],
887 'preview' => false,
888 'sectionpreview' => false,
889 'disabletoc' => false,
890 'useskin' => [
892 ],
893 'contentformat' => [
895 ],
896 'contentmodel' => [
898 ]
899 ];
900 }
901
902 protected function getExamplesMessages() {
903 return [
904 'action=parse&page=Project:Sandbox'
905 => 'apihelp-parse-example-page',
906 'action=parse&text={{Project:Sandbox}}&contentmodel=wikitext'
907 => 'apihelp-parse-example-text',
908 'action=parse&text={{PAGENAME}}&title=Test'
909 => 'apihelp-parse-example-texttitle',
910 'action=parse&summary=Some+[[link]]&prop='
911 => 'apihelp-parse-example-summary',
912 ];
913 }
914
915 public function getHelpUrls() {
916 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Parsing_wikitext#parse';
917 }
918}
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
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:832
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:41
const PARAM_DEPRECATED
(boolean) Is the parameter deprecated (will show a warning)?
Definition ApiBase.php:109
getDB()
Gets a default replica DB connection object.
Definition ApiBase.php:660
dieWithError( $msg, $code=null, $data=null, $httpCode=null)
Abort execution with an error.
Definition ApiBase.php:1855
const PARAM_DEPRECATED_VALUES
(array) When PARAM_TYPE is an array, this indicates which of the values are deprecated.
Definition ApiBase.php:205
getMain()
Get the main module.
Definition ApiBase.php:528
const PARAM_TYPE
(string|string[]) Either an array of allowed value strings, or a string type as described below.
Definition ApiBase.php:91
const PARAM_DFLT
(null|boolean|integer|string) Default value of the parameter.
Definition ApiBase.php:52
extractRequestParams( $parseLimit=true)
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition ApiBase.php:740
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:160
getResult()
Get the result object.
Definition ApiBase.php:632
requireMaxOneParameter( $params, $required)
Die if more than one of a certain set of parameters is set and not false.
Definition ApiBase.php:814
dieWithException( $exception, array $options=[])
Abort execution with an error derived from an exception.
Definition ApiBase.php:1867
const PARAM_HELP_MSG
(string|array|Message) Specify an alternative i18n documentation message for this parameter.
Definition ApiBase.php:128
addWarning( $msg, $code=null, $data=null)
Add a warning for this module.
Definition ApiBase.php:1779
getModuleName()
Get the name of the module being executed by this instance.
Definition ApiBase.php:512
getTitleOrPageId( $params, $load=false)
Get a WikiPage object from a title or pageid param, if possible.
Definition ApiBase.php:917
checkTitleUserPermissions(Title $title, $actions, $user=null)
Helper function for permission-denied errors.
Definition ApiBase.php:1984
const PARAM_ISMULTI
(boolean) Accept multiple pipe-separated values for this parameter (e.g.
Definition ApiBase.php:55
This is the main API class, used for both external and internal processing.
Definition ApiMain.php:45
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:639
getAllowedParams()
Returns an array of allowed parameters (parameter name) => (default value) or (parameter name) => (ar...
Definition ApiParse.php:806
formatLinks( $links)
Definition ApiParse.php:734
getParsedContent(WikiPage $page, $popts, $suppressCache, $pageId, $rev, $getContent)
Definition ApiParse.php:566
formatHeadItems( $headItems)
Definition ApiParse.php:769
formatIWLinks( $iw)
Definition ApiParse.php:749
formatLangLinks( $links)
Definition ApiParse.php:657
getExamplesMessages()
Returns usage examples for this module.
Definition ApiParse.php:902
bool $contentIsDeleted
Definition ApiParse.php:42
formatCategoryLinks( $links)
Definition ApiParse.php:683
formatLimitReportData( $limitReportData)
Definition ApiParse.php:781
makeParserOptions(WikiPage $pageObj, array $params)
Constructs a ParserOptions object.
Definition ApiParse.php:533
bool $contentIsSuppressed
Definition ApiParse.php:42
getSectionContent(Content $content, $what)
Extract the requested section from the given Content.
Definition ApiParse.php:618
getHelpUrls()
Return links to more detailed help pages about the module.
Definition ApiParse.php:915
setIndexedTagNames(&$array, $mapping)
Definition ApiParse.php:798
execute()
Evaluates the parameters, performs the requested query, and sets up the result.
Definition ApiParse.php:44
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:113
static getAllContentFormats()
static makeContent( $text, Title $title=null, $modelId=null, $format=null)
Convenience function for creating a Content object from a given textual representation.
static getContentModels()
msg( $key)
Get a Message object with context set Parameters are the same as wfMessage()
getUser()
Get the User object.
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:1099
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...
const DELETED_TEXT
Definition Revision.php:90
const DELETED_RESTRICTED
Definition Revision.php:93
const FOR_THIS_USER
Definition Revision.php:99
static newFromId( $id, $flags=0)
Load a page revision from a given revision ID number.
Definition Revision.php:116
static getAllowedSkins()
Fetch the list of user-selectable skins in regards to $wgSkipSkins.
Definition Skin.php:74
static normalizeKey( $key)
Normalize a skin preference value to a form that can be loaded.
Definition Skin.php:95
Class representing a MediaWiki article and history.
Definition WikiPage.php:37
static factory(Title $title)
Create a WikiPage object of the appropriate class for the given title.
Definition WikiPage.php:121
getLatest()
Get the page_latest field.
Definition WikiPage.php:572
makeParserOptions( $context)
Get parser options suitable for rendering the primary article wikitext.
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:666
getTitle()
Get the title object of the article.
Definition WikiPage.php:239
per default it will return the text for text based content
$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
when a variable name is used in a it is silently declared as a new local masking the global
Definition design.txt:95
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
const PROTO_CURRENT
Definition Defines.php:223
const CONTENT_MODEL_WIKITEXT
Definition Defines.php:236
const NS_CATEGORY
Definition Defines.php:79
this hook is for auditing only $req
Definition hooks.txt:988
the array() calling protocol came about after MediaWiki 1.4rc1.
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page. Return false to stop further processing of the tag $reader:XMLReader object & $pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports. & $fullInterwikiPrefix:Interwiki prefix, may contain colons. & $pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable. Can be used to lazy-load the import sources list. & $importSources:The value of $wgImportSources. Modify as necessary. See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. & $title:Title object for the current page & $request:WebRequest & $ignoreRedirect:boolean to skip redirect check & $target:Title/string of redirect target & $article:Article object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) & $article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() & $ip:IP being check & $result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetMagic':DEPRECATED! Use $magicWords in a file listed in $wgExtensionMessagesFiles instead. Use this to define synonyms of magic words depending of the language & $magicExtensions:associative array of magic words synonyms $lang:language code(string) 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetSpecialPageAliases':DEPRECATED! Use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead. Use to define aliases of special pages names depending of the language & $specialPageAliases:associative array of magic words synonyms $lang:language code(string) 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links:Array with elements of the form "language:title" in the order that they will be output. & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LanguageSelector':Hook to change the language selector available on a page. $out:The output page. $cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED! Use HtmlPageLinkRendererBegin instead. Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) $result
Definition hooks.txt:1963
Using a hook running we can avoid having all this option specific stuff in our mainline code Using the function array $article
Definition hooks.txt:77
namespace and then decline to actually register it file or subcat img or subcat $title
Definition hooks.txt:962
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:2989
Allows to change the fields on the form that will be generated $name
Definition hooks.txt:302
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return an< a > element with HTML attributes $attribs and contents $html will be returned If you return $ret will be returned $skin
Definition hooks.txt:1981
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:1760
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition injection.txt:37
Base interface for content objects.
Definition Content.php:34
getSkin()
Get the Skin object.
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