MediaWiki  1.27.2
ApiParse.php
Go to the documentation of this file.
1 <?php
28 class ApiParse extends ApiBase {
29 
31  private $section = null;
32 
34  private $content = null;
35 
37  private $pstContent = null;
38 
39  private function checkReadPermissions( Title $title ) {
40  if ( !$title->userCan( 'read', $this->getUser() ) ) {
41  $this->dieUsage( "You don't have permission to view this page", 'permissiondenied' );
42  }
43  }
44 
45  public function execute() {
46  // The data is hot but user-dependent, like page views, so we set vary cookies
47  $this->getMain()->setCacheMode( 'anon-public-user-private' );
48 
49  // Get parameters
50  $params = $this->extractRequestParams();
51  $text = $params['text'];
52  $title = $params['title'];
53  if ( $title === null ) {
54  $titleProvided = false;
55  // A title is needed for parsing, so arbitrarily choose one
56  $title = 'API';
57  } else {
58  $titleProvided = true;
59  }
60 
61  $page = $params['page'];
62  $pageid = $params['pageid'];
63  $oldid = $params['oldid'];
64 
65  $model = $params['contentmodel'];
66  $format = $params['contentformat'];
67 
68  if ( !is_null( $page ) && ( !is_null( $text ) || $titleProvided ) ) {
69  $this->dieUsage(
70  'The page parameter cannot be used together with the text and title parameters',
71  'params'
72  );
73  }
74 
75  $prop = array_flip( $params['prop'] );
76 
77  if ( isset( $params['section'] ) ) {
78  $this->section = $params['section'];
79  if ( !preg_match( '/^((T-)?\d+|new)$/', $this->section ) ) {
80  $this->dieUsage(
81  'The section parameter must be a valid section id or "new"', 'invalidsection'
82  );
83  }
84  } else {
85  $this->section = false;
86  }
87 
88  // The parser needs $wgTitle to be set, apparently the
89  // $title parameter in Parser::parse isn't enough *sigh*
90  // TODO: Does this still need $wgTitle?
92 
93  $redirValues = null;
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->dieUsage(
101  'section=new cannot be combined with oldid, pageid or page parameters. ' .
102  'Please use text', 'params'
103  );
104  }
105  if ( !is_null( $oldid ) ) {
106  // Don't use the parser cache
107  $rev = Revision::newFromId( $oldid );
108  if ( !$rev ) {
109  $this->dieUsage( "There is no revision ID $oldid", 'missingrev' );
110  }
111 
112  $this->checkReadPermissions( $rev->getTitle() );
113  if ( !$rev->userCan( Revision::DELETED_TEXT, $this->getUser() ) ) {
114  $this->dieUsage( "You don't have permission to view deleted revisions", 'permissiondenied' );
115  }
116 
117  $titleObj = $rev->getTitle();
118  $wgTitle = $titleObj;
119  $pageObj = WikiPage::factory( $titleObj );
120  $popts = $this->makeParserOptions( $pageObj, $params );
121 
122  // If for some reason the "oldid" is actually the current revision, it may be cached
123  // Deliberately comparing $pageObj->getLatest() with $rev->getId(), rather than
124  // checking $rev->isCurrent(), because $pageObj is what actually ends up being used,
125  // and if its ->getLatest() is outdated, $rev->isCurrent() won't tell us that.
126  if ( $rev->getId() == $pageObj->getLatest() ) {
127  // May get from/save to parser cache
128  $p_result = $this->getParsedContent( $pageObj, $popts,
129  $pageid, isset( $prop['wikitext'] ) );
130  } else { // This is an old revision, so get the text differently
131  $this->content = $rev->getContent( Revision::FOR_THIS_USER, $this->getUser() );
132 
133  if ( $this->section !== false ) {
134  $this->content = $this->getSectionContent( $this->content, 'r' . $rev->getId() );
135  }
136 
137  // Should we save old revision parses to the parser cache?
138  $p_result = $this->content->getParserOutput( $titleObj, $rev->getId(), $popts );
139  }
140  } else { // Not $oldid, but $pageid or $page
141  if ( $params['redirects'] ) {
142  $reqParams = [
143  'redirects' => '',
144  ];
145  if ( !is_null( $pageid ) ) {
146  $reqParams['pageids'] = $pageid;
147  } else { // $page
148  $reqParams['titles'] = $page;
149  }
150  $req = new FauxRequest( $reqParams );
151  $main = new ApiMain( $req );
152  $pageSet = new ApiPageSet( $main );
153  $pageSet->execute();
154  $redirValues = $pageSet->getRedirectTitlesAsResult( $this->getResult() );
155 
156  $to = $page;
157  foreach ( $pageSet->getRedirectTitles() as $title ) {
158  $to = $title->getFullText();
159  }
160  $pageParams = [ 'title' => $to ];
161  } elseif ( !is_null( $pageid ) ) {
162  $pageParams = [ 'pageid' => $pageid ];
163  } else { // $page
164  $pageParams = [ 'title' => $page ];
165  }
166 
167  $pageObj = $this->getTitleOrPageId( $pageParams, 'fromdb' );
168  $titleObj = $pageObj->getTitle();
169  if ( !$titleObj || !$titleObj->exists() ) {
170  $this->dieUsage( "The page you specified doesn't exist", 'missingtitle' );
171  }
172 
173  $this->checkReadPermissions( $titleObj );
174  $wgTitle = $titleObj;
175 
176  if ( isset( $prop['revid'] ) ) {
177  $oldid = $pageObj->getLatest();
178  }
179 
180  $popts = $this->makeParserOptions( $pageObj, $params );
181 
182  // Don't pollute the parser cache when setting options that aren't
183  // in ParserOptions::optionsHash()
185  $suppressCache =
186  $params['disablepp'] ||
187  $params['disablelimitreport'] ||
188  $params['preview'] ||
189  $params['sectionpreview'] ||
190  $params['disabletidy'];
191 
192  if ( $suppressCache ) {
193  $this->content = $this->getContent( $pageObj, $pageid );
194  $p_result = $this->content->getParserOutput( $titleObj, null, $popts );
195  } else {
196  // Potentially cached
197  $p_result = $this->getParsedContent( $pageObj, $popts, $pageid,
198  isset( $prop['wikitext'] ) );
199  }
200  }
201  } else { // Not $oldid, $pageid, $page. Hence based on $text
202  $titleObj = Title::newFromText( $title );
203  if ( !$titleObj || $titleObj->isExternal() ) {
204  $this->dieUsageMsg( [ 'invalidtitle', $title ] );
205  }
206  $wgTitle = $titleObj;
207  if ( $titleObj->canExist() ) {
208  $pageObj = WikiPage::factory( $titleObj );
209  } else {
210  // Do like MediaWiki::initializeArticle()
211  $article = Article::newFromTitle( $titleObj, $this->getContext() );
212  $pageObj = $article->getPage();
213  }
214 
215  $popts = $this->makeParserOptions( $pageObj, $params );
216  $textProvided = !is_null( $text );
217 
218  if ( !$textProvided ) {
219  if ( $titleProvided && ( $prop || $params['generatexml'] ) ) {
220  $this->setWarning(
221  "'title' used without 'text', and parsed page properties were requested " .
222  "(did you mean to use 'page' instead of 'title'?)"
223  );
224  }
225  // Prevent warning from ContentHandler::makeContent()
226  $text = '';
227  }
228 
229  // If we are parsing text, do not use the content model of the default
230  // API title, but default to wikitext to keep BC.
231  if ( $textProvided && !$titleProvided && is_null( $model ) ) {
232  $model = CONTENT_MODEL_WIKITEXT;
233  $this->setWarning( "No 'title' or 'contentmodel' was given, assuming $model." );
234  }
235 
236  try {
237  $this->content = ContentHandler::makeContent( $text, $titleObj, $model, $format );
238  } catch ( MWContentSerializationException $ex ) {
239  $this->dieUsage( $ex->getMessage(), 'parseerror' );
240  }
241 
242  if ( $this->section !== false ) {
243  if ( $this->section === 'new' ) {
244  // Insert the section title above the content.
245  if ( !is_null( $params['sectiontitle'] ) && $params['sectiontitle'] !== '' ) {
246  $this->content = $this->content->addSectionHeader( $params['sectiontitle'] );
247  }
248  } else {
249  $this->content = $this->getSectionContent( $this->content, $titleObj->getPrefixedText() );
250  }
251  }
252 
253  if ( $params['pst'] || $params['onlypst'] ) {
254  $this->pstContent = $this->content->preSaveTransform( $titleObj, $this->getUser(), $popts );
255  }
256  if ( $params['onlypst'] ) {
257  // Build a result and bail out
258  $result_array = [];
259  $result_array['text'] = $this->pstContent->serialize( $format );
260  $result_array[ApiResult::META_BC_SUBELEMENTS][] = 'text';
261  if ( isset( $prop['wikitext'] ) ) {
262  $result_array['wikitext'] = $this->content->serialize( $format );
263  $result_array[ApiResult::META_BC_SUBELEMENTS][] = 'wikitext';
264  }
265  if ( !is_null( $params['summary'] ) ||
266  ( !is_null( $params['sectiontitle'] ) && $this->section === 'new' )
267  ) {
268  $result_array['parsedsummary'] = $this->formatSummary( $titleObj, $params );
269  $result_array[ApiResult::META_BC_SUBELEMENTS][] = 'parsedsummary';
270  }
271 
272  $result->addValue( null, $this->getModuleName(), $result_array );
273 
274  return;
275  }
276 
277  // Not cached (save or load)
278  if ( $params['pst'] ) {
279  $p_result = $this->pstContent->getParserOutput( $titleObj, null, $popts );
280  } else {
281  $p_result = $this->content->getParserOutput( $titleObj, null, $popts );
282  }
283  }
284 
285  $result_array = [];
286 
287  $result_array['title'] = $titleObj->getPrefixedText();
288  $result_array['pageid'] = $pageid ?: $pageObj->getId();
289 
290  if ( !is_null( $oldid ) ) {
291  $result_array['revid'] = intval( $oldid );
292  }
293 
294  if ( $params['redirects'] && !is_null( $redirValues ) ) {
295  $result_array['redirects'] = $redirValues;
296  }
297 
298  if ( $params['disabletoc'] ) {
299  $p_result->setTOCEnabled( false );
300  }
301 
302  if ( isset( $prop['text'] ) ) {
303  $result_array['text'] = $p_result->getText();
304  $result_array[ApiResult::META_BC_SUBELEMENTS][] = 'text';
305  }
306 
307  if ( !is_null( $params['summary'] ) ||
308  ( !is_null( $params['sectiontitle'] ) && $this->section === 'new' )
309  ) {
310  $result_array['parsedsummary'] = $this->formatSummary( $titleObj, $params );
311  $result_array[ApiResult::META_BC_SUBELEMENTS][] = 'parsedsummary';
312  }
313 
314  if ( isset( $prop['langlinks'] ) ) {
315  $langlinks = $p_result->getLanguageLinks();
316 
317  if ( $params['effectivelanglinks'] ) {
318  // Link flags are ignored for now, but may in the future be
319  // included in the result.
320  $linkFlags = [];
321  Hooks::run( 'LanguageLinks', [ $titleObj, &$langlinks, &$linkFlags ] );
322  }
323  } else {
324  $langlinks = false;
325  }
326 
327  if ( isset( $prop['langlinks'] ) ) {
328  $result_array['langlinks'] = $this->formatLangLinks( $langlinks );
329  }
330  if ( isset( $prop['categories'] ) ) {
331  $result_array['categories'] = $this->formatCategoryLinks( $p_result->getCategories() );
332  }
333  if ( isset( $prop['categorieshtml'] ) ) {
334  $result_array['categorieshtml'] = $this->categoriesHtml( $p_result->getCategories() );
335  $result_array[ApiResult::META_BC_SUBELEMENTS][] = 'categorieshtml';
336  }
337  if ( isset( $prop['links'] ) ) {
338  $result_array['links'] = $this->formatLinks( $p_result->getLinks() );
339  }
340  if ( isset( $prop['templates'] ) ) {
341  $result_array['templates'] = $this->formatLinks( $p_result->getTemplates() );
342  }
343  if ( isset( $prop['images'] ) ) {
344  $result_array['images'] = array_keys( $p_result->getImages() );
345  }
346  if ( isset( $prop['externallinks'] ) ) {
347  $result_array['externallinks'] = array_keys( $p_result->getExternalLinks() );
348  }
349  if ( isset( $prop['sections'] ) ) {
350  $result_array['sections'] = $p_result->getSections();
351  }
352 
353  if ( isset( $prop['displaytitle'] ) ) {
354  $result_array['displaytitle'] = $p_result->getDisplayTitle() ?:
355  $titleObj->getPrefixedText();
356  }
357 
358  if ( isset( $prop['headitems'] ) || isset( $prop['headhtml'] ) ) {
359  $context = new DerivativeContext( $this->getContext() );
360  $context->setTitle( $titleObj );
361  $context->setWikiPage( $pageObj );
362 
363  // We need an OutputPage tied to $context, not to the
364  // RequestContext at the root of the stack.
365  $output = new OutputPage( $context );
366  $output->addParserOutputMetadata( $p_result );
367 
368  if ( isset( $prop['headitems'] ) ) {
369  $headItems = $this->formatHeadItems( $p_result->getHeadItems() );
370 
371  $css = $this->formatCss( $output->buildCssLinksArray() );
372 
373  $scripts = [ $output->getHeadScripts() ];
374 
375  $result_array['headitems'] = array_merge( $headItems, $css, $scripts );
376  }
377 
378  if ( isset( $prop['headhtml'] ) ) {
379  $result_array['headhtml'] = $output->headElement( $context->getSkin() );
380  $result_array[ApiResult::META_BC_SUBELEMENTS][] = 'headhtml';
381  }
382  }
383 
384  if ( isset( $prop['modules'] ) ) {
385  $result_array['modules'] = array_values( array_unique( $p_result->getModules() ) );
386  $result_array['modulescripts'] = array_values( array_unique( $p_result->getModuleScripts() ) );
387  $result_array['modulestyles'] = array_values( array_unique( $p_result->getModuleStyles() ) );
388  // To be removed in 1.27
389  $result_array['modulemessages'] = [];
390  $this->setWarning( 'modulemessages is deprecated since MediaWiki 1.26' );
391  }
392 
393  if ( isset( $prop['jsconfigvars'] ) ) {
394  $result_array['jsconfigvars'] =
395  ApiResult::addMetadataToResultVars( $p_result->getJsConfigVars() );
396  }
397 
398  if ( isset( $prop['encodedjsconfigvars'] ) ) {
399  $result_array['encodedjsconfigvars'] = FormatJson::encode(
400  $p_result->getJsConfigVars(), false, FormatJson::ALL_OK
401  );
402  $result_array[ApiResult::META_SUBELEMENTS][] = 'encodedjsconfigvars';
403  }
404 
405  if ( isset( $prop['modules'] ) &&
406  !isset( $prop['jsconfigvars'] ) && !isset( $prop['encodedjsconfigvars'] ) ) {
407  $this->setWarning( 'Property "modules" was set but not "jsconfigvars" ' .
408  'or "encodedjsconfigvars". Configuration variables are necessary ' .
409  'for proper module usage.' );
410  }
411 
412  if ( isset( $prop['indicators'] ) ) {
413  $result_array['indicators'] = (array)$p_result->getIndicators();
414  ApiResult::setArrayType( $result_array['indicators'], 'BCkvp', 'name' );
415  }
416 
417  if ( isset( $prop['iwlinks'] ) ) {
418  $result_array['iwlinks'] = $this->formatIWLinks( $p_result->getInterwikiLinks() );
419  }
420 
421  if ( isset( $prop['wikitext'] ) ) {
422  $result_array['wikitext'] = $this->content->serialize( $format );
423  $result_array[ApiResult::META_BC_SUBELEMENTS][] = 'wikitext';
424  if ( !is_null( $this->pstContent ) ) {
425  $result_array['psttext'] = $this->pstContent->serialize( $format );
426  $result_array[ApiResult::META_BC_SUBELEMENTS][] = 'psttext';
427  }
428  }
429  if ( isset( $prop['properties'] ) ) {
430  $result_array['properties'] = (array)$p_result->getProperties();
431  ApiResult::setArrayType( $result_array['properties'], 'BCkvp', 'name' );
432  }
433 
434  if ( isset( $prop['limitreportdata'] ) ) {
435  $result_array['limitreportdata'] =
436  $this->formatLimitReportData( $p_result->getLimitReportData() );
437  }
438  if ( isset( $prop['limitreporthtml'] ) ) {
439  $result_array['limitreporthtml'] = EditPage::getPreviewLimitReport( $p_result );
440  $result_array[ApiResult::META_BC_SUBELEMENTS][] = 'limitreporthtml';
441  }
442 
443  if ( isset( $prop['parsetree'] ) || $params['generatexml'] ) {
444  if ( $this->content->getModel() != CONTENT_MODEL_WIKITEXT ) {
445  $this->dieUsage( 'parsetree is only supported for wikitext content', 'notwikitext' );
446  }
447 
448  $wgParser->startExternalParse( $titleObj, $popts, Parser::OT_PREPROCESS );
449  $dom = $wgParser->preprocessToDom( $this->content->getNativeData() );
450  if ( is_callable( [ $dom, 'saveXML' ] ) ) {
451  $xml = $dom->saveXML();
452  } else {
453  $xml = $dom->__toString();
454  }
455  $result_array['parsetree'] = $xml;
456  $result_array[ApiResult::META_BC_SUBELEMENTS][] = 'parsetree';
457  }
458 
459  $result_mapping = [
460  'redirects' => 'r',
461  'langlinks' => 'll',
462  'categories' => 'cl',
463  'links' => 'pl',
464  'templates' => 'tl',
465  'images' => 'img',
466  'externallinks' => 'el',
467  'iwlinks' => 'iw',
468  'sections' => 's',
469  'headitems' => 'hi',
470  'modules' => 'm',
471  'indicators' => 'ind',
472  'modulescripts' => 'm',
473  'modulestyles' => 'm',
474  'modulemessages' => 'm',
475  'properties' => 'pp',
476  'limitreportdata' => 'lr',
477  ];
478  $this->setIndexedTagNames( $result_array, $result_mapping );
479  $result->addValue( null, $this->getModuleName(), $result_array );
480  }
481 
490  protected function makeParserOptions( WikiPage $pageObj, array $params ) {
491 
492  $popts = $pageObj->makeParserOptions( $this->getContext() );
493  $popts->enableLimitReport( !$params['disablepp'] && !$params['disablelimitreport'] );
494  $popts->setIsPreview( $params['preview'] || $params['sectionpreview'] );
495  $popts->setIsSectionPreview( $params['sectionpreview'] );
496  $popts->setEditSection( !$params['disableeditsection'] );
497  if ( $params['disabletidy'] ) {
498  $popts->setTidy( false );
499  }
500 
501  return $popts;
502  }
503 
511  private function getParsedContent( WikiPage $page, $popts, $pageId = null, $getWikitext = false ) {
512  $this->content = $this->getContent( $page, $pageId );
513 
514  if ( $this->section !== false && $this->content !== null ) {
515  // Not cached (save or load)
516  return $this->content->getParserOutput( $page->getTitle(), null, $popts );
517  }
518 
519  // Try the parser cache first
520  // getParserOutput will save to Parser cache if able
521  $pout = $page->getParserOutput( $popts );
522  if ( !$pout ) {
523  $this->dieUsage( "There is no revision ID {$page->getLatest()}", 'missingrev' );
524  }
525  if ( $getWikitext ) {
526  $this->content = $page->getContent( Revision::RAW );
527  }
528 
529  return $pout;
530  }
531 
539  private function getContent( WikiPage $page, $pageId = null ) {
540  $content = $page->getContent( Revision::RAW ); // XXX: really raw?
541 
542  if ( $this->section !== false && $content !== null ) {
543  $content = $this->getSectionContent(
544  $content,
545  !is_null( $pageId ) ? 'page id ' . $pageId : $page->getTitle()->getPrefixedText()
546  );
547  }
548  return $content;
549  }
550 
558  private function getSectionContent( Content $content, $what ) {
559  // Not cached (save or load)
560  $section = $content->getSection( $this->section );
561  if ( $section === false ) {
562  $this->dieUsage( "There is no section {$this->section} in $what", 'nosuchsection' );
563  }
564  if ( $section === null ) {
565  $this->dieUsage( "Sections are not supported by $what", 'nosuchsection' );
566  $section = false;
567  }
568 
569  return $section;
570  }
571 
579  private function formatSummary( $title, $params ) {
581  $summary = !is_null( $params['summary'] ) ? $params['summary'] : '';
582  $sectionTitle = !is_null( $params['sectiontitle'] ) ? $params['sectiontitle'] : '';
583 
584  if ( $this->section === 'new' && ( $sectionTitle === '' || $summary === '' ) ) {
585  if ( $sectionTitle !== '' ) {
586  $summary = $params['sectiontitle'];
587  }
588  if ( $summary !== '' ) {
589  $summary = wfMessage( 'newsectionsummary' )
590  ->rawParams( $wgParser->stripSectionName( $summary ) )
591  ->inContentLanguage()->text();
592  }
593  }
594  return Linker::formatComment( $summary, $title, $this->section === 'new' );
595  }
596 
597  private function formatLangLinks( $links ) {
598  $result = [];
599  foreach ( $links as $link ) {
600  $entry = [];
601  $bits = explode( ':', $link, 2 );
602  $title = Title::newFromText( $link );
603 
604  $entry['lang'] = $bits[0];
605  if ( $title ) {
606  $entry['url'] = wfExpandUrl( $title->getFullURL(), PROTO_CURRENT );
607  // localised language name in 'uselang' language
608  $entry['langname'] = Language::fetchLanguageName(
609  $title->getInterwiki(),
610  $this->getLanguage()->getCode()
611  );
612 
613  // native language name
614  $entry['autonym'] = Language::fetchLanguageName( $title->getInterwiki() );
615  }
616  ApiResult::setContentValue( $entry, 'title', $bits[1] );
617  $result[] = $entry;
618  }
619 
620  return $result;
621  }
622 
623  private function formatCategoryLinks( $links ) {
624  $result = [];
625 
626  if ( !$links ) {
627  return $result;
628  }
629 
630  // Fetch hiddencat property
631  $lb = new LinkBatch;
632  $lb->setArray( [ NS_CATEGORY => $links ] );
633  $db = $this->getDB();
634  $res = $db->select( [ 'page', 'page_props' ],
635  [ 'page_title', 'pp_propname' ],
636  $lb->constructSet( 'page', $db ),
637  __METHOD__,
638  [],
639  [ 'page_props' => [
640  'LEFT JOIN', [ 'pp_propname' => 'hiddencat', 'pp_page = page_id' ]
641  ] ]
642  );
643  $hiddencats = [];
644  foreach ( $res as $row ) {
645  $hiddencats[$row->page_title] = isset( $row->pp_propname );
646  }
647 
648  foreach ( $links as $link => $sortkey ) {
649  $entry = [];
650  $entry['sortkey'] = $sortkey;
651  // array keys will cast numeric category names to ints, so cast back to string
652  ApiResult::setContentValue( $entry, 'category', (string)$link );
653  if ( !isset( $hiddencats[$link] ) ) {
654  $entry['missing'] = true;
655  } elseif ( $hiddencats[$link] ) {
656  $entry['hidden'] = true;
657  }
658  $result[] = $entry;
659  }
660 
661  return $result;
662  }
663 
664  private function categoriesHtml( $categories ) {
665  $context = $this->getContext();
666  $context->getOutput()->addCategoryLinks( $categories );
667 
668  return $context->getSkin()->getCategories();
669  }
670 
671  private function formatLinks( $links ) {
672  $result = [];
673  foreach ( $links as $ns => $nslinks ) {
674  foreach ( $nslinks as $title => $id ) {
675  $entry = [];
676  $entry['ns'] = $ns;
677  ApiResult::setContentValue( $entry, 'title', Title::makeTitle( $ns, $title )->getFullText() );
678  $entry['exists'] = $id != 0;
679  $result[] = $entry;
680  }
681  }
682 
683  return $result;
684  }
685 
686  private function formatIWLinks( $iw ) {
687  $result = [];
688  foreach ( $iw as $prefix => $titles ) {
689  foreach ( array_keys( $titles ) as $title ) {
690  $entry = [];
691  $entry['prefix'] = $prefix;
692 
693  $title = Title::newFromText( "{$prefix}:{$title}" );
694  if ( $title ) {
695  $entry['url'] = wfExpandUrl( $title->getFullURL(), PROTO_CURRENT );
696  }
697 
698  ApiResult::setContentValue( $entry, 'title', $title->getFullText() );
699  $result[] = $entry;
700  }
701  }
702 
703  return $result;
704  }
705 
706  private function formatHeadItems( $headItems ) {
707  $result = [];
708  foreach ( $headItems as $tag => $content ) {
709  $entry = [];
710  $entry['tag'] = $tag;
711  ApiResult::setContentValue( $entry, 'content', $content );
712  $result[] = $entry;
713  }
714 
715  return $result;
716  }
717 
718  private function formatCss( $css ) {
719  $result = [];
720  foreach ( $css as $file => $link ) {
721  $entry = [];
722  $entry['file'] = $file;
723  ApiResult::setContentValue( $entry, 'link', $link );
724  $result[] = $entry;
725  }
726 
727  return $result;
728  }
729 
730  private function formatLimitReportData( $limitReportData ) {
731  $result = [];
732 
733  foreach ( $limitReportData as $name => $value ) {
734  $entry = [];
735  $entry['name'] = $name;
736  if ( !is_array( $value ) ) {
737  $value = [ $value ];
738  }
740  $entry = array_merge( $entry, $value );
741  $result[] = $entry;
742  }
743 
744  return $result;
745  }
746 
747  private function setIndexedTagNames( &$array, $mapping ) {
748  foreach ( $mapping as $key => $name ) {
749  if ( isset( $array[$key] ) ) {
750  ApiResult::setIndexedTagName( $array[$key], $name );
751  }
752  }
753  }
754 
755  public function getAllowedParams() {
756  return [
757  'title' => null,
758  'text' => [
759  ApiBase::PARAM_TYPE => 'text',
760  ],
761  'summary' => null,
762  'page' => null,
763  'pageid' => [
764  ApiBase::PARAM_TYPE => 'integer',
765  ],
766  'redirects' => false,
767  'oldid' => [
768  ApiBase::PARAM_TYPE => 'integer',
769  ],
770  'prop' => [
771  ApiBase::PARAM_DFLT => 'text|langlinks|categories|links|templates|' .
772  'images|externallinks|sections|revid|displaytitle|iwlinks|properties',
773  ApiBase::PARAM_ISMULTI => true,
775  'text',
776  'langlinks',
777  'categories',
778  'categorieshtml',
779  'links',
780  'templates',
781  'images',
782  'externallinks',
783  'sections',
784  'revid',
785  'displaytitle',
786  'headitems',
787  'headhtml',
788  'modules',
789  'jsconfigvars',
790  'encodedjsconfigvars',
791  'indicators',
792  'iwlinks',
793  'wikitext',
794  'properties',
795  'limitreportdata',
796  'limitreporthtml',
797  'parsetree',
798  ],
800  'parsetree' => [ 'apihelp-parse-paramvalue-prop-parsetree', CONTENT_MODEL_WIKITEXT ],
801  ],
802  ],
803  'pst' => false,
804  'onlypst' => false,
805  'effectivelanglinks' => false,
806  'section' => null,
807  'sectiontitle' => [
808  ApiBase::PARAM_TYPE => 'string',
809  ],
810  'disablepp' => [
811  ApiBase::PARAM_DFLT => false,
813  ],
814  'disablelimitreport' => false,
815  'disableeditsection' => false,
816  'disabletidy' => false,
817  'generatexml' => [
818  ApiBase::PARAM_DFLT => false,
820  'apihelp-parse-param-generatexml', CONTENT_MODEL_WIKITEXT
821  ],
823  ],
824  'preview' => false,
825  'sectionpreview' => false,
826  'disabletoc' => false,
827  'contentformat' => [
829  ],
830  'contentmodel' => [
832  ]
833  ];
834  }
835 
836  protected function getExamplesMessages() {
837  return [
838  'action=parse&page=Project:Sandbox'
839  => 'apihelp-parse-example-page',
840  'action=parse&text={{Project:Sandbox}}&contentmodel=wikitext'
841  => 'apihelp-parse-example-text',
842  'action=parse&text={{PAGENAME}}&title=Test'
843  => 'apihelp-parse-example-texttitle',
844  'action=parse&summary=Some+[[link]]&prop='
845  => 'apihelp-parse-example-summary',
846  ];
847  }
848 
849  public function getHelpUrls() {
850  return 'https://www.mediawiki.org/wiki/API:Parsing_wikitext#parse';
851  }
852 }
static factory(Title $title)
Create a WikiPage object of the appropriate class for the given title.
Definition: WikiPage.php:99
getExamplesMessages()
Definition: ApiParse.php:836
const FOR_THIS_USER
Definition: Revision.php:84
makeParserOptions($context)
Get parser options suitable for rendering the primary article wikitext.
Definition: WikiPage.php:1974
const PARAM_TYPE
(string|string[]) Either an array of allowed value strings, or a string type as described below...
Definition: ApiBase.php:88
the array() calling protocol came about after MediaWiki 1.4rc1.
formatHeadItems($headItems)
Definition: ApiParse.php:706
getResult()
Get the result object.
Definition: ApiBase.php:584
getLanguage()
Get the Language object.
const CONTENT_MODEL_WIKITEXT
Definition: Defines.php:277
magic word the default is to use $key to get the and $key value or $key value text $key value html to format the value $key
Definition: hooks.txt:2321
getSection($sectionId)
Returns the section with the given ID.
getParserOutput(ParserOptions $parserOptions, $oldid=null)
Get a ParserOutput for the given ParserOptions and revision ID.
Definition: WikiPage.php:1055
This class contains a list of pages that the client has requested.
Definition: ApiPageSet.php:41
static getAllContentFormats()
per default it will return the text for text based content
const PARAM_DFLT
(null|boolean|integer|string) Default value of the parameter.
Definition: ApiBase.php:50
getMain()
Get the main module.
Definition: ApiBase.php:480
$wgParser
Definition: Setup.php:809
static getContentModels()
getDB()
Gets a default slave database connection object.
Definition: ApiBase.php:612
An IContextSource implementation which will inherit context from another source but allow individual ...
const ALL_OK
Skip escaping as many characters as reasonably possible.
Definition: FormatJson.php:55
formatLimitReportData($limitReportData)
Definition: ApiParse.php:730
extractRequestParams($parseLimit=true)
Using getAllowedParams(), this function makes an array of the values provided by the user...
Definition: ApiBase.php:685
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:78
$value
const PROTO_CURRENT
Definition: Defines.php:264
static getPreviewLimitReport($output)
Get the Limit report for page previews.
Definition: EditPage.php:3377
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
static newFromText($text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:277
Represents a title within MediaWiki.
Definition: Title.php:34
when a variable name is used in a it is silently declared as a new local masking the global
Definition: design.txt:93
wfExpandUrl($url, $defaultProto=PROTO_CURRENT)
Expand a potentially local URL to a fully-qualified URL.
setIndexedTagNames(&$array, $mapping)
Definition: ApiParse.php:747
static setContentValue(array &$arr, $name, $value, $flags=0)
Add an output value to the array by name and mark as META_CONTENT.
Definition: ApiResult.php:480
IContextSource $context
static setIndexedTagName(array &$arr, $tag)
Set the tag name for numeric-keyed values in XML format.
Definition: ApiResult.php:618
const OT_PREPROCESS
Definition: Parser.php:119
userCan($action, $user=null, $rigor= 'secure')
Can $user perform $action on this page?
Definition: Title.php:1917
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:Associative array mapping language codes to prefixed links of the form"language:title".&$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':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:1796
the value to return A Title object or null for latest to be modified or replaced by the hook handler or if authentication is not possible after cache objects are set for highlighting & $link
Definition: hooks.txt:2581
categoriesHtml($categories)
Definition: ApiParse.php:664
Class representing a list of titles The execute() method checks them all for existence and adds them ...
Definition: LinkBatch.php:31
getSectionContent(Content $content, $what)
Extract the requested section from the given Content.
Definition: ApiParse.php:558
getTitleOrPageId($params, $load=false)
Get a WikiPage object from a title or pageid param, if possible.
Definition: ApiBase.php:840
getContent($audience=Revision::FOR_PUBLIC, User $user=null)
Get the content of the current revision.
Definition: WikiPage.php:654
$css
getHelpUrls()
Definition: ApiParse.php:849
$res
Definition: database.txt:21
$summary
Base interface for content objects.
Definition: Content.php:34
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 and may include noclasses after processing 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 unsetoffset-wrap String Wrap the message in html(usually something like"&lt
getContext()
Get the base IContextSource object.
static encode($value, $pretty=false, $escaping=0)
Returns the JSON representation of a value.
Definition: FormatJson.php:127
$params
getTitle()
Get the title object of the article.
Definition: WikiPage.php:217
const NS_CATEGORY
Definition: Defines.php:83
This is the main API class, used for both external and internal processing.
Definition: ApiMain.php:41
static newFromTitle($title, IContextSource $context)
Create an Article object of the appropriate class for the given page.
Definition: Article.php:114
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:912
getModuleName()
Get the name of the module being executed by this instance.
Definition: ApiBase.php:464
static run($event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:131
execute()
Definition: ApiParse.php:45
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books $tag
Definition: hooks.txt:965
static makeContent($text, Title $title=null, $modelId=null, $format=null)
Convenience function for creating a Content object from a given textual representation.
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:1584
setWarning($warning)
Set warning section for this module.
Definition: ApiBase.php:1495
const RAW
Definition: Revision.php:85
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
Definition: distributors.txt:9
formatCss($css)
Definition: ApiParse.php:718
This class should be covered by a general architecture document which does not exist as of January 20...
Definition: OutputPage.php:42
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:1290
static fetchLanguageName($code, $inLanguage=null, $include= 'all')
Definition: Language.php:886
const PARAM_HELP_MSG
(string|array|Message) Specify an alternative i18n documentation message for this parameter...
Definition: ApiBase.php:125
const DELETED_TEXT
Definition: Revision.php:76
static setIndexedTagNameRecursive(array &$arr, $tag)
Set indexed tag name on $arr and all subarrays.
Definition: ApiResult.php:643
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist e g Watchlist removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context the output can only depend on parameters provided to this hook not on global state indicating whether full HTML should be generated If generation of HTML may be but other information should still be present in the ParserOutput object & $output
Definition: hooks.txt:1004
formatLangLinks($links)
Definition: ApiParse.php:597
Class representing a MediaWiki article and history.
Definition: WikiPage.php:29
getParsedContent(WikiPage $page, $popts, $pageId=null, $getWikitext=false)
Definition: ApiParse.php:511
static newFromId($id, $flags=0)
Load a page revision from a given revision ID number.
Definition: Revision.php:99
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:35
this hook is for auditing only $req
Definition: hooks.txt:965
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
static addMetadataToResultVars($vars, $forceHash=true)
Add the correct metadata to an array of vars we want to export through the API.
Definition: ApiResult.php:1156
getSkin()
Get the Skin object.
getAllowedParams()
Definition: ApiParse.php:755
const META_SUBELEMENTS
Key for the 'subelements' metadata item.
Definition: ApiResult.php:76
const PARAM_ISMULTI
(boolean) Accept multiple pipe-separated values for this parameter (e.g.
Definition: ApiBase.php:53
getContent(WikiPage $page, $pageId=null)
Get the content for the given page and the requested section.
Definition: ApiParse.php:539
formatSummary($title, $params)
This mimicks the behavior of EditPage in formatting a summary.
Definition: ApiParse.php:579
dieUsage($description, $errorCode, $httpRespCode=0, $extradata=null)
Throw a UsageException, which will (if uncaught) call the main module's error handler and die with an...
Definition: ApiBase.php:1526
This abstract class implements many basic API functions, and is the base of all API classes...
Definition: ApiBase.php:39
getOutput()
Get the OutputPage object.
const PARAM_DEPRECATED
(boolean) Is the parameter deprecated (will show a warning)?
Definition: ApiBase.php:106
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:91
if(!$wgRequest->checkUrlExtension()) if(!$wgEnableAPI) $wgTitle
Definition: api.php:57
static setArrayType(array &$arr, $type, $kvpKeyName=null)
Set the array data type.
Definition: ApiResult.php:730
makeParserOptions(WikiPage $pageObj, array $params)
Constructs a ParserOptions object.
Definition: ApiParse.php:490
const META_BC_SUBELEMENTS
Key for the 'BC subelements' metadata item.
Definition: ApiResult.php:141
formatCategoryLinks($links)
Definition: ApiParse.php:623
checkReadPermissions(Title $title)
Definition: ApiParse.php:39
getUser()
Get the User object.
dieUsageMsg($error)
Output the error message related to a certain array.
Definition: ApiBase.php:2144
static & makeTitle($ns, $title, $fragment= '', $interwiki= '')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:524
formatIWLinks($iw)
Definition: ApiParse.php:686
Exception representing a failure to serialize or unserialize a content object.
do that in ParserLimitReportFormat instead use this to modify the parameters of the image and a DIV can begin in one section and end in another Make sure your code can handle that case gracefully See the EditSectionClearerLink extension for an example zero but section is usually empty its values are the globals values before the output is cached $page
Definition: hooks.txt:2338
formatLinks($links)
Definition: ApiParse.php:671
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:310