MediaWiki  1.23.0
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  public function execute() {
40  // The data is hot but user-dependent, like page views, so we set vary cookies
41  $this->getMain()->setCacheMode( 'anon-public-user-private' );
42 
43  // Get parameters
44  $params = $this->extractRequestParams();
45  $text = $params['text'];
46  $title = $params['title'];
47  if ( $title === null ) {
48  $titleProvided = false;
49  // A title is needed for parsing, so arbitrarily choose one
50  $title = 'API';
51  } else {
52  $titleProvided = true;
53  }
54 
55  $page = $params['page'];
56  $pageid = $params['pageid'];
57  $oldid = $params['oldid'];
58 
59  $model = $params['contentmodel'];
60  $format = $params['contentformat'];
61 
62  if ( !is_null( $page ) && ( !is_null( $text ) || $titleProvided ) ) {
63  $this->dieUsage(
64  'The page parameter cannot be used together with the text and title parameters',
65  'params'
66  );
67  }
68 
69  $prop = array_flip( $params['prop'] );
70 
71  if ( isset( $params['section'] ) ) {
72  $this->section = $params['section'];
73  } else {
74  $this->section = false;
75  }
76 
77  // The parser needs $wgTitle to be set, apparently the
78  // $title parameter in Parser::parse isn't enough *sigh*
79  // TODO: Does this still need $wgTitle?
81 
82  // Currently unnecessary, code to act as a safeguard against any change
83  // in current behavior of uselang
84  $oldLang = null;
85  if ( isset( $params['uselang'] )
86  && $params['uselang'] != $this->getContext()->getLanguage()->getCode()
87  ) {
88  $oldLang = $this->getContext()->getLanguage(); // Backup language
89  $this->getContext()->setLanguage( Language::factory( $params['uselang'] ) );
90  }
91 
92  $redirValues = null;
93 
94  // Return result
95  $result = $this->getResult();
96 
97  if ( !is_null( $oldid ) || !is_null( $pageid ) || !is_null( $page ) ) {
98  if ( !is_null( $oldid ) ) {
99  // Don't use the parser cache
100  $rev = Revision::newFromID( $oldid );
101  if ( !$rev ) {
102  $this->dieUsage( "There is no revision ID $oldid", 'missingrev' );
103  }
104  if ( !$rev->userCan( Revision::DELETED_TEXT, $this->getUser() ) ) {
105  $this->dieUsage( "You don't have permission to view deleted revisions", 'permissiondenied' );
106  }
107 
108  $titleObj = $rev->getTitle();
109  $wgTitle = $titleObj;
110  $pageObj = WikiPage::factory( $titleObj );
111  $popts = $this->makeParserOptions( $pageObj, $params );
112 
113  // If for some reason the "oldid" is actually the current revision, it may be cached
114  if ( $rev->isCurrent() ) {
115  // May get from/save to parser cache
116  $p_result = $this->getParsedContent( $pageObj, $popts,
117  $pageid, isset( $prop['wikitext'] ) );
118  } else { // This is an old revision, so get the text differently
119  $this->content = $rev->getContent( Revision::FOR_THIS_USER, $this->getUser() );
120 
121  if ( $this->section !== false ) {
122  $this->content = $this->getSectionContent( $this->content, 'r' . $rev->getId() );
123  }
124 
125  // Should we save old revision parses to the parser cache?
126  $p_result = $this->content->getParserOutput( $titleObj, $rev->getId(), $popts );
127  }
128  } else { // Not $oldid, but $pageid or $page
129  if ( $params['redirects'] ) {
130  $reqParams = array(
131  'action' => 'query',
132  'redirects' => '',
133  );
134  if ( !is_null( $pageid ) ) {
135  $reqParams['pageids'] = $pageid;
136  } else { // $page
137  $reqParams['titles'] = $page;
138  }
139  $req = new FauxRequest( $reqParams );
140  $main = new ApiMain( $req );
141  $main->execute();
142  $data = $main->getResultData();
143  $redirValues = isset( $data['query']['redirects'] )
144  ? $data['query']['redirects']
145  : array();
146  $to = $page;
147  foreach ( (array)$redirValues as $r ) {
148  $to = $r['to'];
149  }
150  $pageParams = array( 'title' => $to );
151  } elseif ( !is_null( $pageid ) ) {
152  $pageParams = array( 'pageid' => $pageid );
153  } else { // $page
154  $pageParams = array( 'title' => $page );
155  }
156 
157  $pageObj = $this->getTitleOrPageId( $pageParams, 'fromdb' );
158  $titleObj = $pageObj->getTitle();
159  if ( !$titleObj || !$titleObj->exists() ) {
160  $this->dieUsage( "The page you specified doesn't exist", 'missingtitle' );
161  }
162  $wgTitle = $titleObj;
163 
164  if ( isset( $prop['revid'] ) ) {
165  $oldid = $pageObj->getLatest();
166  }
167 
168  $popts = $this->makeParserOptions( $pageObj, $params );
169 
170  // Potentially cached
171  $p_result = $this->getParsedContent( $pageObj, $popts, $pageid,
172  isset( $prop['wikitext'] ) );
173  }
174  } else { // Not $oldid, $pageid, $page. Hence based on $text
175  $titleObj = Title::newFromText( $title );
176  if ( !$titleObj || $titleObj->isExternal() ) {
177  $this->dieUsageMsg( array( 'invalidtitle', $title ) );
178  }
179  $wgTitle = $titleObj;
180  if ( $titleObj->canExist() ) {
181  $pageObj = WikiPage::factory( $titleObj );
182  } else {
183  // Do like MediaWiki::initializeArticle()
184  $article = Article::newFromTitle( $titleObj, $this->getContext() );
185  $pageObj = $article->getPage();
186  }
187 
188  $popts = $this->makeParserOptions( $pageObj, $params );
189  $textProvided = !is_null( $text );
190 
191  if ( !$textProvided ) {
192  if ( $titleProvided && ( $prop || $params['generatexml'] ) ) {
193  $this->setWarning(
194  "'title' used without 'text', and parsed page properties were requested " .
195  "(did you mean to use 'page' instead of 'title'?)"
196  );
197  }
198  // Prevent warning from ContentHandler::makeContent()
199  $text = '';
200  }
201 
202  // If we are parsing text, do not use the content model of the default
203  // API title, but default to wikitext to keep BC.
204  if ( $textProvided && !$titleProvided && is_null( $model ) ) {
205  $model = CONTENT_MODEL_WIKITEXT;
206  $this->setWarning( "No 'title' or 'contentmodel' was given, assuming $model." );
207  }
208 
209  try {
210  $this->content = ContentHandler::makeContent( $text, $titleObj, $model, $format );
211  } catch ( MWContentSerializationException $ex ) {
212  $this->dieUsage( $ex->getMessage(), 'parseerror' );
213  }
214 
215  if ( $this->section !== false ) {
216  $this->content = $this->getSectionContent( $this->content, $titleObj->getText() );
217  }
218 
219  if ( $params['pst'] || $params['onlypst'] ) {
220  $this->pstContent = $this->content->preSaveTransform( $titleObj, $this->getUser(), $popts );
221  }
222  if ( $params['onlypst'] ) {
223  // Build a result and bail out
224  $result_array = array();
225  $result_array['text'] = array();
226  ApiResult::setContent( $result_array['text'], $this->pstContent->serialize( $format ) );
227  if ( isset( $prop['wikitext'] ) ) {
228  $result_array['wikitext'] = array();
229  ApiResult::setContent( $result_array['wikitext'], $this->content->serialize( $format ) );
230  }
231  $result->addValue( null, $this->getModuleName(), $result_array );
232 
233  return;
234  }
235 
236  // Not cached (save or load)
237  if ( $params['pst'] ) {
238  $p_result = $this->pstContent->getParserOutput( $titleObj, null, $popts );
239  } else {
240  $p_result = $this->content->getParserOutput( $titleObj, null, $popts );
241  }
242  }
243 
244  $result_array = array();
245 
246  $result_array['title'] = $titleObj->getPrefixedText();
247 
248  if ( !is_null( $oldid ) ) {
249  $result_array['revid'] = intval( $oldid );
250  }
251 
252  if ( $params['redirects'] && !is_null( $redirValues ) ) {
253  $result_array['redirects'] = $redirValues;
254  }
255 
256  if ( $params['disabletoc'] ) {
257  $p_result->setTOCEnabled( false );
258  }
259 
260  if ( isset( $prop['text'] ) ) {
261  $result_array['text'] = array();
262  ApiResult::setContent( $result_array['text'], $p_result->getText() );
263  }
264 
265  if ( !is_null( $params['summary'] ) ) {
266  $result_array['parsedsummary'] = array();
268  $result_array['parsedsummary'],
269  Linker::formatComment( $params['summary'], $titleObj )
270  );
271  }
272 
273  if ( isset( $prop['langlinks'] ) || isset( $prop['languageshtml'] ) ) {
274  $langlinks = $p_result->getLanguageLinks();
275 
276  if ( $params['effectivelanglinks'] ) {
277  // Link flags are ignored for now, but may in the future be
278  // included in the result.
279  $linkFlags = array();
280  wfRunHooks( 'LanguageLinks', array( $titleObj, &$langlinks, &$linkFlags ) );
281  }
282  } else {
283  $langlinks = false;
284  }
285 
286  if ( isset( $prop['langlinks'] ) ) {
287  $result_array['langlinks'] = $this->formatLangLinks( $langlinks );
288  }
289  if ( isset( $prop['languageshtml'] ) ) {
290  $languagesHtml = $this->languagesHtml( $langlinks );
291 
292  $result_array['languageshtml'] = array();
293  ApiResult::setContent( $result_array['languageshtml'], $languagesHtml );
294  }
295  if ( isset( $prop['categories'] ) ) {
296  $result_array['categories'] = $this->formatCategoryLinks( $p_result->getCategories() );
297  }
298  if ( isset( $prop['categorieshtml'] ) ) {
299  $categoriesHtml = $this->categoriesHtml( $p_result->getCategories() );
300  $result_array['categorieshtml'] = array();
301  ApiResult::setContent( $result_array['categorieshtml'], $categoriesHtml );
302  }
303  if ( isset( $prop['links'] ) ) {
304  $result_array['links'] = $this->formatLinks( $p_result->getLinks() );
305  }
306  if ( isset( $prop['templates'] ) ) {
307  $result_array['templates'] = $this->formatLinks( $p_result->getTemplates() );
308  }
309  if ( isset( $prop['images'] ) ) {
310  $result_array['images'] = array_keys( $p_result->getImages() );
311  }
312  if ( isset( $prop['externallinks'] ) ) {
313  $result_array['externallinks'] = array_keys( $p_result->getExternalLinks() );
314  }
315  if ( isset( $prop['sections'] ) ) {
316  $result_array['sections'] = $p_result->getSections();
317  }
318 
319  if ( isset( $prop['displaytitle'] ) ) {
320  $result_array['displaytitle'] = $p_result->getDisplayTitle() ?
321  $p_result->getDisplayTitle() :
322  $titleObj->getPrefixedText();
323  }
324 
325  if ( isset( $prop['headitems'] ) || isset( $prop['headhtml'] ) ) {
326  $context = $this->getContext();
327  $context->setTitle( $titleObj );
328  $context->getOutput()->addParserOutputNoText( $p_result );
329 
330  if ( isset( $prop['headitems'] ) ) {
331  $headItems = $this->formatHeadItems( $p_result->getHeadItems() );
332 
333  $css = $this->formatCss( $context->getOutput()->buildCssLinksArray() );
334 
335  $scripts = array( $context->getOutput()->getHeadScripts() );
336 
337  $result_array['headitems'] = array_merge( $headItems, $css, $scripts );
338  }
339 
340  if ( isset( $prop['headhtml'] ) ) {
341  $result_array['headhtml'] = array();
343  $result_array['headhtml'],
344  $context->getOutput()->headElement( $context->getSkin() )
345  );
346  }
347  }
348 
349  if ( isset( $prop['iwlinks'] ) ) {
350  $result_array['iwlinks'] = $this->formatIWLinks( $p_result->getInterwikiLinks() );
351  }
352 
353  if ( isset( $prop['wikitext'] ) ) {
354  $result_array['wikitext'] = array();
355  ApiResult::setContent( $result_array['wikitext'], $this->content->serialize( $format ) );
356  if ( !is_null( $this->pstContent ) ) {
357  $result_array['psttext'] = array();
358  ApiResult::setContent( $result_array['psttext'], $this->pstContent->serialize( $format ) );
359  }
360  }
361  if ( isset( $prop['properties'] ) ) {
362  $result_array['properties'] = $this->formatProperties( $p_result->getProperties() );
363  }
364 
365  if ( isset( $prop['limitreportdata'] ) ) {
366  $result_array['limitreportdata'] = $this->formatLimitReportData( $p_result->getLimitReportData() );
367  }
368  if ( isset( $prop['limitreporthtml'] ) ) {
369  $limitreportHtml = EditPage::getPreviewLimitReport( $p_result );
370  $result_array['limitreporthtml'] = array();
371  ApiResult::setContent( $result_array['limitreporthtml'], $limitreportHtml );
372  }
373 
374  if ( $params['generatexml'] ) {
375  if ( $this->content->getModel() != CONTENT_MODEL_WIKITEXT ) {
376  $this->dieUsage( "generatexml is only supported for wikitext content", "notwikitext" );
377  }
378 
379  $wgParser->startExternalParse( $titleObj, $popts, OT_PREPROCESS );
380  $dom = $wgParser->preprocessToDom( $this->content->getNativeData() );
381  if ( is_callable( array( $dom, 'saveXML' ) ) ) {
382  $xml = $dom->saveXML();
383  } else {
384  $xml = $dom->__toString();
385  }
386  $result_array['parsetree'] = array();
387  ApiResult::setContent( $result_array['parsetree'], $xml );
388  }
389 
390  $result_mapping = array(
391  'redirects' => 'r',
392  'langlinks' => 'll',
393  'categories' => 'cl',
394  'links' => 'pl',
395  'templates' => 'tl',
396  'images' => 'img',
397  'externallinks' => 'el',
398  'iwlinks' => 'iw',
399  'sections' => 's',
400  'headitems' => 'hi',
401  'properties' => 'pp',
402  'limitreportdata' => 'lr',
403  );
404  $this->setIndexedTagNames( $result_array, $result_mapping );
405  $result->addValue( null, $this->getModuleName(), $result_array );
406 
407  if ( !is_null( $oldLang ) ) {
408  $this->getContext()->setLanguage( $oldLang ); // Reset language to $oldLang
409  }
410  }
411 
420  protected function makeParserOptions( WikiPage $pageObj, array $params ) {
421  wfProfileIn( __METHOD__ );
422 
423  $popts = $pageObj->makeParserOptions( $this->getContext() );
424  $popts->enableLimitReport( !$params['disablepp'] );
425  $popts->setIsPreview( $params['preview'] || $params['sectionpreview'] );
426  $popts->setIsSectionPreview( $params['sectionpreview'] );
427 
428  wfProfileOut( __METHOD__ );
429 
430  return $popts;
431  }
432 
440  private function getParsedContent( WikiPage $page, $popts, $pageId = null, $getWikitext = false ) {
441  $this->content = $page->getContent( Revision::RAW ); //XXX: really raw?
442 
443  if ( $this->section !== false && $this->content !== null ) {
444  $this->content = $this->getSectionContent(
445  $this->content,
446  !is_null( $pageId ) ? 'page id ' . $pageId : $page->getTitle()->getText()
447  );
448 
449  // Not cached (save or load)
450  return $this->content->getParserOutput( $page->getTitle(), null, $popts );
451  }
452 
453  // Try the parser cache first
454  // getParserOutput will save to Parser cache if able
455  $pout = $page->getParserOutput( $popts );
456  if ( !$pout ) {
457  $this->dieUsage( "There is no revision ID {$page->getLatest()}", 'missingrev' );
458  }
459  if ( $getWikitext ) {
460  $this->content = $page->getContent( Revision::RAW );
461  }
462 
463  return $pout;
464  }
465 
466  private function getSectionContent( Content $content, $what ) {
467  // Not cached (save or load)
468  $section = $content->getSection( $this->section );
469  if ( $section === false ) {
470  $this->dieUsage( "There is no section {$this->section} in " . $what, 'nosuchsection' );
471  }
472  if ( $section === null ) {
473  $this->dieUsage( "Sections are not supported by " . $what, 'nosuchsection' );
474  $section = false;
475  }
476 
477  return $section;
478  }
479 
480  private function formatLangLinks( $links ) {
481  $result = array();
482  foreach ( $links as $link ) {
483  $entry = array();
484  $bits = explode( ':', $link, 2 );
486 
487  $entry['lang'] = $bits[0];
488  if ( $title ) {
489  $entry['url'] = wfExpandUrl( $title->getFullURL(), PROTO_CURRENT );
490  // localised language name in user language (maybe set by uselang=)
491  $entry['langname'] = Language::fetchLanguageName( $title->getInterwiki(), $this->getLanguage()->getCode() );
492  // native language name
493  $entry['autonym'] = Language::fetchLanguageName( $title->getInterwiki() );
494  }
495  ApiResult::setContent( $entry, $bits[1] );
496  $result[] = $entry;
497  }
498 
499  return $result;
500  }
501 
502  private function formatCategoryLinks( $links ) {
503  $result = array();
504 
505  if ( !$links ) {
506  return $result;
507  }
508 
509  // Fetch hiddencat property
510  $lb = new LinkBatch;
511  $lb->setArray( array( NS_CATEGORY => $links ) );
512  $db = $this->getDB();
513  $res = $db->select( array( 'page', 'page_props' ),
514  array( 'page_title', 'pp_propname' ),
515  $lb->constructSet( 'page', $db ),
516  __METHOD__,
517  array(),
518  array( 'page_props' => array(
519  'LEFT JOIN', array( 'pp_propname' => 'hiddencat', 'pp_page = page_id' )
520  ) )
521  );
522  $hiddencats = array();
523  foreach ( $res as $row ) {
524  $hiddencats[$row->page_title] = isset( $row->pp_propname );
525  }
526 
527  foreach ( $links as $link => $sortkey ) {
528  $entry = array();
529  $entry['sortkey'] = $sortkey;
530  ApiResult::setContent( $entry, $link );
531  if ( !isset( $hiddencats[$link] ) ) {
532  $entry['missing'] = '';
533  } elseif ( $hiddencats[$link] ) {
534  $entry['hidden'] = '';
535  }
536  $result[] = $entry;
537  }
538 
539  return $result;
540  }
541 
542  private function categoriesHtml( $categories ) {
543  $context = $this->getContext();
544  $context->getOutput()->addCategoryLinks( $categories );
545 
546  return $context->getSkin()->getCategories();
547  }
548 
555  private function languagesHtml( $languages ) {
556  wfDeprecated( __METHOD__, '1.18' );
557  $this->setWarning( '"action=parse&prop=languageshtml" is deprecated ' .
558  'and will be removed in MediaWiki 1.24. Use "prop=langlinks" ' .
559  'to generate your own HTML.' );
560 
561  global $wgContLang, $wgHideInterlanguageLinks;
562 
563  if ( $wgHideInterlanguageLinks || count( $languages ) == 0 ) {
564  return '';
565  }
566 
567  $s = htmlspecialchars( wfMessage( 'otherlanguages' )->text() .
568  wfMessage( 'colon-separator' )->text() );
569 
570  $langs = array();
571  foreach ( $languages as $l ) {
572  $nt = Title::newFromText( $l );
573  $text = Language::fetchLanguageName( $nt->getInterwiki() );
574 
575  $langs[] = Html::element( 'a',
576  array( 'href' => $nt->getFullURL(), 'title' => $nt->getText(), 'class' => 'external' ),
577  $text == '' ? $l : $text );
578  }
579 
580  $s .= implode( wfMessage( 'pipe-separator' )->escaped(), $langs );
581 
582  if ( $wgContLang->isRTL() ) {
583  $s = Html::rawElement( 'span', array( 'dir' => 'LTR' ), $s );
584  }
585 
586  return $s;
587  }
588 
589  private function formatLinks( $links ) {
590  $result = array();
591  foreach ( $links as $ns => $nslinks ) {
592  foreach ( $nslinks as $title => $id ) {
593  $entry = array();
594  $entry['ns'] = $ns;
595  ApiResult::setContent( $entry, Title::makeTitle( $ns, $title )->getFullText() );
596  if ( $id != 0 ) {
597  $entry['exists'] = '';
598  }
599  $result[] = $entry;
600  }
601  }
602 
603  return $result;
604  }
605 
606  private function formatIWLinks( $iw ) {
607  $result = array();
608  foreach ( $iw as $prefix => $titles ) {
609  foreach ( array_keys( $titles ) as $title ) {
610  $entry = array();
611  $entry['prefix'] = $prefix;
612 
613  $title = Title::newFromText( "{$prefix}:{$title}" );
614  if ( $title ) {
615  $entry['url'] = wfExpandUrl( $title->getFullURL(), PROTO_CURRENT );
616  }
617 
618  ApiResult::setContent( $entry, $title->getFullText() );
619  $result[] = $entry;
620  }
621  }
622 
623  return $result;
624  }
625 
626  private function formatHeadItems( $headItems ) {
627  $result = array();
628  foreach ( $headItems as $tag => $content ) {
629  $entry = array();
630  $entry['tag'] = $tag;
631  ApiResult::setContent( $entry, $content );
632  $result[] = $entry;
633  }
634 
635  return $result;
636  }
637 
638  private function formatProperties( $properties ) {
639  $result = array();
640  foreach ( $properties as $name => $value ) {
641  $entry = array();
642  $entry['name'] = $name;
643  ApiResult::setContent( $entry, $value );
644  $result[] = $entry;
645  }
646 
647  return $result;
648  }
649 
650  private function formatCss( $css ) {
651  $result = array();
652  foreach ( $css as $file => $link ) {
653  $entry = array();
654  $entry['file'] = $file;
655  ApiResult::setContent( $entry, $link );
656  $result[] = $entry;
657  }
658 
659  return $result;
660  }
661 
662  private function formatLimitReportData( $limitReportData ) {
663  $result = array();
664  $apiResult = $this->getResult();
665 
666  foreach ( $limitReportData as $name => $value ) {
667  $entry = array();
668  $entry['name'] = $name;
669  if ( !is_array( $value ) ) {
670  $value = array( $value );
671  }
672  $apiResult->setIndexedTagName( $value, 'param' );
673  $apiResult->setIndexedTagName_recursive( $value, 'param' );
674  $entry = array_merge( $entry, $value );
675  $result[] = $entry;
676  }
677 
678  return $result;
679  }
680 
681  private function setIndexedTagNames( &$array, $mapping ) {
682  foreach ( $mapping as $key => $name ) {
683  if ( isset( $array[$key] ) ) {
684  $this->getResult()->setIndexedTagName( $array[$key], $name );
685  }
686  }
687  }
688 
689  public function getAllowedParams() {
690  return array(
691  'title' => null,
692  'text' => null,
693  'summary' => null,
694  'page' => null,
695  'pageid' => array(
696  ApiBase::PARAM_TYPE => 'integer',
697  ),
698  'redirects' => false,
699  'oldid' => array(
700  ApiBase::PARAM_TYPE => 'integer',
701  ),
702  'prop' => array(
703  ApiBase::PARAM_DFLT => 'text|langlinks|categories|links|templates|' .
704  'images|externallinks|sections|revid|displaytitle|iwlinks|properties',
705  ApiBase::PARAM_ISMULTI => true,
707  'text',
708  'langlinks',
709  'languageshtml',
710  'categories',
711  'categorieshtml',
712  'links',
713  'templates',
714  'images',
715  'externallinks',
716  'sections',
717  'revid',
718  'displaytitle',
719  'headitems',
720  'headhtml',
721  'iwlinks',
722  'wikitext',
723  'properties',
724  'limitreportdata',
725  'limitreporthtml',
726  )
727  ),
728  'pst' => false,
729  'onlypst' => false,
730  'effectivelanglinks' => false,
731  'uselang' => null,
732  'section' => null,
733  'disablepp' => false,
734  'generatexml' => false,
735  'preview' => false,
736  'sectionpreview' => false,
737  'disabletoc' => false,
738  'contentformat' => array(
740  ),
741  'contentmodel' => array(
743  )
744  );
745  }
746 
747  public function getParamDescription() {
748  $p = $this->getModulePrefix();
749  $wikitext = CONTENT_MODEL_WIKITEXT;
750 
751  return array(
752  'text' => "Text to parse. Use {$p}title or {$p}contentmodel to control the content model",
753  'summary' => 'Summary to parse',
754  'redirects' => "If the {$p}page or the {$p}pageid parameter is set to a redirect, resolve it",
755  'title' => "Title of page the text belongs to. " .
756  "If omitted, {$p}contentmodel must be specified, and \"API\" will be used as the title",
757  'page' => "Parse the content of this page. Cannot be used together with {$p}text and {$p}title",
758  'pageid' => "Parse the content of this page. Overrides {$p}page",
759  'oldid' => "Parse the content of this revision. Overrides {$p}page and {$p}pageid",
760  'prop' => array(
761  'Which pieces of information to get',
762  ' text - Gives the parsed text of the wikitext',
763  ' langlinks - Gives the language links in the parsed wikitext',
764  ' categories - Gives the categories in the parsed wikitext',
765  ' categorieshtml - Gives the HTML version of the categories',
766  ' languageshtml - DEPRECATED. Will be removed in MediaWiki 1.24.',
767  ' Gives the HTML version of the language links',
768  ' links - Gives the internal links in the parsed wikitext',
769  ' templates - Gives the templates in the parsed wikitext',
770  ' images - Gives the images in the parsed wikitext',
771  ' externallinks - Gives the external links in the parsed wikitext',
772  ' sections - Gives the sections in the parsed wikitext',
773  ' revid - Adds the revision ID of the parsed page',
774  ' displaytitle - Adds the title of the parsed wikitext',
775  ' headitems - Gives items to put in the <head> of the page',
776  ' headhtml - Gives parsed <head> of the page',
777  ' iwlinks - Gives interwiki links in the parsed wikitext',
778  ' wikitext - Gives the original wikitext that was parsed',
779  ' properties - Gives various properties defined in the parsed wikitext',
780  ' limitreportdata - Gives the limit report in a structured way.',
781  " Gives no data, when {$p}disablepp is set.",
782  ' limitreporthtml - Gives the HTML version of the limit report.',
783  " Gives no data, when {$p}disablepp is set.",
784  ),
785  'effectivelanglinks' => array(
786  'Includes language links supplied by extensions',
787  '(for use with prop=langlinks|languageshtml)',
788  ),
789  'pst' => array(
790  'Do a pre-save transform on the input before parsing it',
791  "Only valid when used with {$p}text",
792  ),
793  'onlypst' => array(
794  'Do a pre-save transform (PST) on the input, but don\'t parse it',
795  'Returns the same wikitext, after a PST has been applied.',
796  "Only valid when used with {$p}text",
797  ),
798  'uselang' => 'Which language to parse the request in',
799  'section' => 'Only retrieve the content of this section number',
800  'disablepp' => 'Disable the PP Report from the parser output',
801  'generatexml' => "Generate XML parse tree (requires contentmodel=$wikitext)",
802  'preview' => 'Parse in preview mode',
803  'sectionpreview' => 'Parse in section preview mode (enables preview mode too)',
804  'disabletoc' => 'Disable table of contents in output',
805  'contentformat' => array(
806  'Content serialization format used for the input text',
807  "Only valid when used with {$p}text",
808  ),
809  'contentmodel' => array(
810  "Content model of the input text. If omitted, ${p}title must be specified, " .
811  "and default will be the model of the specified ${p}title",
812  "Only valid when used with {$p}text",
813  ),
814  );
815  }
816 
817  public function getDescription() {
818  $p = $this->getModulePrefix();
819 
820  return array(
821  'Parses content and returns parser output.',
822  'See the various prop-Modules of action=query to get information from the current' .
823  'version of a page.',
824  'There are several ways to specify the text to parse:',
825  "1) Specify a page or revision, using {$p}page, {$p}pageid, or {$p}oldid.",
826  "2) Specify content explicitly, using {$p}text, {$p}title, and {$p}contentmodel.",
827  "3) Specify only a summary to parse. {$p}prop should be given an empty value.",
828  );
829  }
830 
831  public function getPossibleErrors() {
832  return array_merge( parent::getPossibleErrors(), array(
833  array(
834  'code' => 'params',
835  'info' => 'The page parameter cannot be used together with the text and title parameters'
836  ),
837  array( 'code' => 'missingrev', 'info' => 'There is no revision ID oldid' ),
838  array(
839  'code' => 'permissiondenied',
840  'info' => 'You don\'t have permission to view deleted revisions'
841  ),
842  array( 'code' => 'missingtitle', 'info' => 'The page you specified doesn\'t exist' ),
843  array( 'code' => 'nosuchsection', 'info' => 'There is no section sectionnumber in page' ),
844  array( 'nosuchpageid' ),
845  array( 'invalidtitle', 'title' ),
846  array( 'code' => 'parseerror', 'info' => 'Failed to parse the given text.' ),
847  array(
848  'code' => 'notwikitext',
849  'info' => 'The requested operation is only supported on wikitext content.'
850  ),
851  ) );
852  }
853 
854  public function getExamples() {
855  return array(
856  'api.php?action=parse&page=Project:Sandbox' => 'Parse a page',
857  'api.php?action=parse&text={{Project:Sandbox}}&contentmodel=wikitext' => 'Parse wikitext',
858  'api.php?action=parse&text={{PAGENAME}}&title=Test'
859  => 'Parse wikitext, specifying the page title',
860  'api.php?action=parse&summary=Some+[[link]]&prop=' => 'Parse a summary',
861  );
862  }
863 
864  public function getHelpUrls() {
865  return 'https://www.mediawiki.org/wiki/API:Parsing_wikitext#parse';
866  }
867 }
ApiMain
This is the main API class, used for both external and internal processing.
Definition: ApiMain.php:41
ContextSource\$context
IContextSource $context
Definition: ContextSource.php:33
ApiParse\formatIWLinks
formatIWLinks( $iw)
Definition: ApiParse.php:603
Title\makeTitle
static & makeTitle( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:398
$result
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. $reader:XMLReader object $logInfo:Array of information Return false to stop further processing of the tag 'ImportHandlePageXMLTag':When parsing a XML tag in a page. $reader:XMLReader object $pageInfo:Array of information Return false to stop further processing of the tag 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information Return false to stop further processing of the tag 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. $reader:XMLReader object Return false to stop further processing of the tag 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. $reader:XMLReader object $revisionInfo:Array of information Return false to stop further processing of the tag '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 '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. '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 '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 '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 wfIsTrustedProxy() $ip:IP being check $result:Change this value to override the result of wfIsTrustedProxy() '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 User::isValidEmailAddr(), 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. '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 '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) '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. '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:1528
FauxRequest
WebRequest clone which takes values from a provided array.
Definition: WebRequest.php:1275
Title\newFromText
static newFromText( $text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:189
ContextSource\getContext
getContext()
Get the RequestContext object.
Definition: ContextSource.php:40
ContentHandler\getAllContentFormats
static getAllContentFormats()
Definition: ContentHandler.php:376
ApiParse\getParamDescription
getParamDescription()
Returns an array of parameter descriptions.
Definition: ApiParse.php:744
php
skin txt MediaWiki includes four core it has been set as the default in MediaWiki since the replacing Monobook it had been been the default skin since before being replaced by Vector largely rewritten in while keeping its appearance Several legacy skins were removed in the as the burden of supporting them became too heavy to bear Those in etc for skin dependent CSS etc for skin dependent JavaScript These can also be customised on a per user by etc This feature has led to a wide variety of user styles becoming that gallery is a good place to ending in php
Definition: skin.txt:62
content
per default it will return the text for text based content
Definition: contenthandler.txt:107
IContextSource\getSkin
getSkin()
Get the Skin object.
LinkBatch
Class representing a list of titles The execute() method checks them all for existence and adds them ...
Definition: LinkBatch.php:30
ApiParse\formatLangLinks
formatLangLinks( $links)
Definition: ApiParse.php:477
ApiResult\setContent
static setContent(&$arr, $value, $subElemName=null)
Adds a content element to an array.
Definition: ApiResult.php:201
text
design txt This is a brief overview of the new design More thorough and up to date information is available on the documentation wiki at etc Handles the details of getting and saving to the user table of the and dealing with sessions and cookies OutputPage Encapsulates the entire HTML page that will be sent in response to any server request It is used by calling its functions to add text
Definition: design.txt:12
ApiParse\formatCss
formatCss( $css)
Definition: ApiParse.php:647
ApiBase\dieUsageMsg
dieUsageMsg( $error)
Output the error message related to a certain array.
Definition: ApiBase.php:1929
ApiBase\getTitleOrPageId
getTitleOrPageId( $params, $load=false)
Definition: ApiBase.php:853
ApiBase\PARAM_TYPE
const PARAM_TYPE
Definition: ApiBase.php:50
ApiParse\formatLinks
formatLinks( $links)
Definition: ApiParse.php:586
ApiBase\getResult
getResult()
Get the result object.
Definition: ApiBase.php:205
wfProfileIn
wfProfileIn( $functionname)
Begin profiling of a function.
Definition: Profiler.php:33
WikiPage
Class representing a MediaWiki article and history.
Definition: WikiPage.php:37
OT_PREPROCESS
const OT_PREPROCESS
Definition: Defines.php:232
$params
$params
Definition: styleTest.css.php:40
WikiPage\makeParserOptions
makeParserOptions( $context)
Get parser options suitable for rendering the primary article wikitext.
Definition: WikiPage.php:2012
$s
$s
Definition: mergeMessageFileList.php:156
ApiBase\getDB
getDB()
Gets a default slave database connection object.
Definition: ApiBase.php:2312
$wgContLang
this class mediates it Skin Encapsulates a look and feel for the wiki All of the functions that render HTML and make choices about how to render it are here and are called from various other places when and is meant to be subclassed with other skins that may override some of its functions The User object contains a reference to a and so rather than having a global skin object we just rely on the global User and get the skin with $wgUser and also has some character encoding functions and other locale stuff The current user interface language is instantiated as and the content language as $wgContLang
Definition: design.txt:56
Linker\formatComment
static formatComment( $comment, $title=null, $local=false)
This function is called by all recent changes variants, by the page history, and by the user contribu...
Definition: Linker.php:1254
CONTENT_MODEL_WIKITEXT
const CONTENT_MODEL_WIKITEXT
Definition: Defines.php:283
ContextSource\getUser
getUser()
Get the User object.
Definition: ContextSource.php:132
$link
set to $title object and return false for a match for latest after cache objects are set use the ContentHandler facility to handle CSS and JavaScript for highlighting & $link
Definition: hooks.txt:2149
ApiBase
This abstract class implements many basic API functions, and is the base of all API classes.
Definition: ApiBase.php:42
ContextSource\getLanguage
getLanguage()
Get the Language object.
Definition: ContextSource.php:154
Revision\FOR_THIS_USER
const FOR_THIS_USER
Definition: Revision.php:73
ApiParse\getParsedContent
getParsedContent(WikiPage $page, $popts, $pageId=null, $getWikitext=false)
Definition: ApiParse.php:437
$lb
if( $wgAPIRequestLog) $lb
Definition: api.php:126
ApiParse
Definition: ApiParse.php:28
ApiParse\$pstContent
Content $pstContent
$pstContent *
Definition: ApiParse.php:34
ApiParse\getHelpUrls
getHelpUrls()
Definition: ApiParse.php:861
WikiPage\factory
static factory(Title $title)
Create a WikiPage object of the appropriate class for the given title.
Definition: WikiPage.php:103
ApiParse\getPossibleErrors
getPossibleErrors()
Returns a list of all possible errors returned by the module.
Definition: ApiParse.php:828
Content\getSection
getSection( $sectionId)
Returns the section with the given ID.
wfDeprecated
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
Definition: GlobalFunctions.php:1127
$titles
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
$css
$css
Definition: styleTest.css.php:50
ContentHandler\getContentModels
static getContentModels()
Definition: ContentHandler.php:370
Html\element
static element( $element, $attribs=array(), $contents='')
Identical to rawElement(), but HTML-escapes $contents (like Xml::element()).
Definition: Html.php:148
ApiParse\getAllowedParams
getAllowedParams()
Returns an array of allowed parameters (parameter name) => (default value) or (parameter name) => (ar...
Definition: ApiParse.php:686
ApiParse\formatLimitReportData
formatLimitReportData( $limitReportData)
Definition: ApiParse.php:659
ApiParse\getDescription
getDescription()
Returns the description string for this module.
Definition: ApiParse.php:814
WikiPage\getTitle
getTitle()
Get the title object of the article.
Definition: WikiPage.php:221
MWContentSerializationException
Exception representing a failure to serialize or unserialize a content object.
Definition: ContentHandler.php:33
wfProfileOut
wfProfileOut( $functionname='missing')
Stop profiling of a function.
Definition: Profiler.php:46
PROTO_CURRENT
const PROTO_CURRENT
Definition: Defines.php:270
wfMessage
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 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
WikiPage\getContent
getContent( $audience=Revision::FOR_PUBLIC, User $user=null)
Get the content of the current revision.
Definition: WikiPage.php:663
wfRunHooks
wfRunHooks( $event, array $args=array(), $deprecatedVersion=null)
Call hook functions defined in $wgHooks.
Definition: GlobalFunctions.php:4001
array
the array() calling protocol came about after MediaWiki 1.4rc1.
List of Api Query prop modules.
global
when a variable name is used in a it is silently declared as a new masking the global
Definition: design.txt:93
ApiParse\getExamples
getExamples()
Returns usage examples for this module.
Definition: ApiParse.php:851
NS_CATEGORY
const NS_CATEGORY
Definition: Defines.php:93
ContentHandler\makeContent
static makeContent( $text, Title $title=null, $modelId=null, $format=null)
Convenience function for creating a Content object from a given textual representation.
Definition: ContentHandler.php:144
ApiBase\getModulePrefix
getModulePrefix()
Get parameter prefix (usually two letters or an empty string).
Definition: ApiBase.php:165
ApiParse\formatCategoryLinks
formatCategoryLinks( $links)
Definition: ApiParse.php:499
$languages
$languages
Definition: rebuildLanguage.php:129
ApiBase\extractRequestParams
extractRequestParams( $parseLimit=true)
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition: ApiBase.php:687
$title
presenting them properly to the user as errors is done by the caller $title
Definition: hooks.txt:1324
$name
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:336
$value
$value
Definition: styleTest.css.php:45
ApiBase\dieUsage
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:1363
ApiParse\setIndexedTagNames
setIndexedTagNames(&$array, $mapping)
Definition: ApiParse.php:678
ApiParse\languagesHtml
languagesHtml( $languages)
Definition: ApiParse.php:552
Revision\RAW
const RAW
Definition: Revision.php:74
Language\fetchLanguageName
static fetchLanguageName( $code, $inLanguage=null, $include='all')
Definition: Language.php:936
Content
Base interface for content objects.
Definition: Content.php:34
$file
if(PHP_SAPI !='cli') $file
Definition: UtfNormalTest2.php:30
$rev
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:1337
ApiParse\categoriesHtml
categoriesHtml( $categories)
Definition: ApiParse.php:539
ApiBase\setWarning
setWarning( $warning)
Set warning section for this module.
Definition: ApiBase.php:245
$wgParser
$wgParser
Definition: Setup.php:567
ApiBase\PARAM_DFLT
const PARAM_DFLT
Definition: ApiBase.php:46
as
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
ApiBase\getModuleName
getModuleName()
Get the name of the module being executed by this instance.
Definition: ApiBase.php:148
ApiBase\PARAM_ISMULTI
const PARAM_ISMULTI
Definition: ApiBase.php:48
ApiParse\$section
String $section
$section *
Definition: ApiParse.php:30
ApiParse\getSectionContent
getSectionContent(Content $content, $what)
Definition: ApiParse.php:463
ApiBase\getMain
getMain()
Get the main module.
Definition: ApiBase.php:188
Language\factory
static factory( $code)
Get a cached or new language object for a given language code.
Definition: Language.php:184
ApiParse\formatHeadItems
formatHeadItems( $headItems)
Definition: ApiParse.php:623
Html\rawElement
static rawElement( $element, $attribs=array(), $contents='')
Returns an HTML element in a string.
Definition: Html.php:124
ApiParse\formatProperties
formatProperties( $properties)
Definition: ApiParse.php:635
ApiParse\makeParserOptions
makeParserOptions(WikiPage $pageObj, array $params)
Constructs a ParserOptions object.
Definition: ApiParse.php:417
$article
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
IContextSource\getOutput
getOutput()
Get the OutputPage object.
$res
$res
Definition: database.txt:21
ApiParse\$content
Content $content
$content *
Definition: ApiParse.php:32
section
section
Definition: parserTests.txt:378
Revision\DELETED_TEXT
const DELETED_TEXT
Definition: Revision.php:65
WikiPage\getParserOutput
getParserOutput(ParserOptions $parserOptions, $oldid=null)
Get a ParserOutput for the given ParserOptions and revision ID.
Definition: WikiPage.php:1138
wfExpandUrl
wfExpandUrl( $url, $defaultProto=PROTO_CURRENT)
Expand a potentially local URL to a fully-qualified URL.
Definition: GlobalFunctions.php:497
$wgTitle
if(! $wgRequest->checkUrlExtension()) if(! $wgEnableAPI) $wgTitle
Definition: api.php:63
ApiParse\execute
execute()
Evaluates the parameters, performs the requested query, and sets up the result.
Definition: ApiParse.php:36
Article\newFromTitle
static newFromTitle( $title, IContextSource $context)
Create an Article object of the appropriate class for the given page.
Definition: Article.php:142