MediaWiki  1.23.15
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  } else {
80  $this->section = false;
81  }
82 
83  // The parser needs $wgTitle to be set, apparently the
84  // $title parameter in Parser::parse isn't enough *sigh*
85  // TODO: Does this still need $wgTitle?
87 
88  // Currently unnecessary, code to act as a safeguard against any change
89  // in current behavior of uselang
90  $oldLang = null;
91  if ( isset( $params['uselang'] )
92  && $params['uselang'] != $this->getContext()->getLanguage()->getCode()
93  ) {
94  $oldLang = $this->getContext()->getLanguage(); // Backup language
95  $this->getContext()->setLanguage( Language::factory( $params['uselang'] ) );
96  }
97 
98  $redirValues = null;
99 
100  // Return result
101  $result = $this->getResult();
102 
103  if ( !is_null( $oldid ) || !is_null( $pageid ) || !is_null( $page ) ) {
104  if ( !is_null( $oldid ) ) {
105  // Don't use the parser cache
106  $rev = Revision::newFromID( $oldid );
107  if ( !$rev ) {
108  $this->dieUsage( "There is no revision ID $oldid", 'missingrev' );
109  }
110 
111  $this->checkReadPermissions( $rev->getTitle() );
112  if ( !$rev->userCan( Revision::DELETED_TEXT, $this->getUser() ) ) {
113  $this->dieUsage( "You don't have permission to view deleted revisions", 'permissiondenied' );
114  }
115 
116  $titleObj = $rev->getTitle();
117  $wgTitle = $titleObj;
118  $pageObj = WikiPage::factory( $titleObj );
119  $popts = $this->makeParserOptions( $pageObj, $params );
120 
121  // If for some reason the "oldid" is actually the current revision, it may be cached
122  if ( $rev->isCurrent() ) {
123  // May get from/save to parser cache
124  $p_result = $this->getParsedContent( $pageObj, $popts,
125  $pageid, isset( $prop['wikitext'] ) );
126  } else { // This is an old revision, so get the text differently
127  $this->content = $rev->getContent( Revision::FOR_THIS_USER, $this->getUser() );
128 
129  if ( $this->section !== false ) {
130  $this->content = $this->getSectionContent( $this->content, 'r' . $rev->getId() );
131  }
132 
133  // Should we save old revision parses to the parser cache?
134  $p_result = $this->content->getParserOutput( $titleObj, $rev->getId(), $popts );
135  }
136  } else { // Not $oldid, but $pageid or $page
137  if ( $params['redirects'] ) {
138  $reqParams = array(
139  'action' => 'query',
140  'redirects' => '',
141  );
142  if ( !is_null( $pageid ) ) {
143  $reqParams['pageids'] = $pageid;
144  } else { // $page
145  $reqParams['titles'] = $page;
146  }
147  $req = new FauxRequest( $reqParams );
148  $main = new ApiMain( $req );
149  $main->execute();
150  $data = $main->getResultData();
151  $redirValues = isset( $data['query']['redirects'] )
152  ? $data['query']['redirects']
153  : array();
154  $to = $page;
155  foreach ( (array)$redirValues as $r ) {
156  $to = $r['to'];
157  }
158  $pageParams = array( 'title' => $to );
159  } elseif ( !is_null( $pageid ) ) {
160  $pageParams = array( 'pageid' => $pageid );
161  } else { // $page
162  $pageParams = array( 'title' => $page );
163  }
164 
165  $pageObj = $this->getTitleOrPageId( $pageParams, 'fromdb' );
166  $titleObj = $pageObj->getTitle();
167  if ( !$titleObj || !$titleObj->exists() ) {
168  $this->dieUsage( "The page you specified doesn't exist", 'missingtitle' );
169  }
170 
171  $this->checkReadPermissions( $titleObj );
172  $wgTitle = $titleObj;
173 
174  if ( isset( $prop['revid'] ) ) {
175  $oldid = $pageObj->getLatest();
176  }
177 
178  $popts = $this->makeParserOptions( $pageObj, $params );
179 
180  // Potentially cached
181  $p_result = $this->getParsedContent( $pageObj, $popts, $pageid,
182  isset( $prop['wikitext'] ) );
183  }
184  } else { // Not $oldid, $pageid, $page. Hence based on $text
185  $titleObj = Title::newFromText( $title );
186  if ( !$titleObj || $titleObj->isExternal() ) {
187  $this->dieUsageMsg( array( 'invalidtitle', $title ) );
188  }
189  $wgTitle = $titleObj;
190  if ( $titleObj->canExist() ) {
191  $pageObj = WikiPage::factory( $titleObj );
192  } else {
193  // Do like MediaWiki::initializeArticle()
194  $article = Article::newFromTitle( $titleObj, $this->getContext() );
195  $pageObj = $article->getPage();
196  }
197 
198  $popts = $this->makeParserOptions( $pageObj, $params );
199  $textProvided = !is_null( $text );
200 
201  if ( !$textProvided ) {
202  if ( $titleProvided && ( $prop || $params['generatexml'] ) ) {
203  $this->setWarning(
204  "'title' used without 'text', and parsed page properties were requested " .
205  "(did you mean to use 'page' instead of 'title'?)"
206  );
207  }
208  // Prevent warning from ContentHandler::makeContent()
209  $text = '';
210  }
211 
212  // If we are parsing text, do not use the content model of the default
213  // API title, but default to wikitext to keep BC.
214  if ( $textProvided && !$titleProvided && is_null( $model ) ) {
215  $model = CONTENT_MODEL_WIKITEXT;
216  $this->setWarning( "No 'title' or 'contentmodel' was given, assuming $model." );
217  }
218 
219  try {
220  $this->content = ContentHandler::makeContent( $text, $titleObj, $model, $format );
221  } catch ( MWContentSerializationException $ex ) {
222  $this->dieUsage( $ex->getMessage(), 'parseerror' );
223  }
224 
225  if ( $this->section !== false ) {
226  $this->content = $this->getSectionContent( $this->content, $titleObj->getText() );
227  }
228 
229  if ( $params['pst'] || $params['onlypst'] ) {
230  $this->pstContent = $this->content->preSaveTransform( $titleObj, $this->getUser(), $popts );
231  }
232  if ( $params['onlypst'] ) {
233  // Build a result and bail out
234  $result_array = array();
235  $result_array['text'] = array();
236  ApiResult::setContent( $result_array['text'], $this->pstContent->serialize( $format ) );
237  if ( isset( $prop['wikitext'] ) ) {
238  $result_array['wikitext'] = array();
239  ApiResult::setContent( $result_array['wikitext'], $this->content->serialize( $format ) );
240  }
241  $result->addValue( null, $this->getModuleName(), $result_array );
242 
243  return;
244  }
245 
246  // Not cached (save or load)
247  if ( $params['pst'] ) {
248  $p_result = $this->pstContent->getParserOutput( $titleObj, null, $popts );
249  } else {
250  $p_result = $this->content->getParserOutput( $titleObj, null, $popts );
251  }
252  }
253 
254  $result_array = array();
255 
256  $result_array['title'] = $titleObj->getPrefixedText();
257 
258  if ( !is_null( $oldid ) ) {
259  $result_array['revid'] = intval( $oldid );
260  }
261 
262  if ( $params['redirects'] && !is_null( $redirValues ) ) {
263  $result_array['redirects'] = $redirValues;
264  }
265 
266  if ( $params['disabletoc'] ) {
267  $p_result->setTOCEnabled( false );
268  }
269 
270  if ( isset( $prop['text'] ) ) {
271  $result_array['text'] = array();
272  ApiResult::setContent( $result_array['text'], $p_result->getText() );
273  }
274 
275  if ( !is_null( $params['summary'] ) ) {
276  $result_array['parsedsummary'] = array();
278  $result_array['parsedsummary'],
279  Linker::formatComment( $params['summary'], $titleObj )
280  );
281  }
282 
283  if ( isset( $prop['langlinks'] ) || isset( $prop['languageshtml'] ) ) {
284  $langlinks = $p_result->getLanguageLinks();
285 
286  if ( $params['effectivelanglinks'] ) {
287  // Link flags are ignored for now, but may in the future be
288  // included in the result.
289  $linkFlags = array();
290  wfRunHooks( 'LanguageLinks', array( $titleObj, &$langlinks, &$linkFlags ) );
291  }
292  } else {
293  $langlinks = false;
294  }
295 
296  if ( isset( $prop['langlinks'] ) ) {
297  $result_array['langlinks'] = $this->formatLangLinks( $langlinks );
298  }
299  if ( isset( $prop['languageshtml'] ) ) {
300  $languagesHtml = $this->languagesHtml( $langlinks );
301 
302  $result_array['languageshtml'] = array();
303  ApiResult::setContent( $result_array['languageshtml'], $languagesHtml );
304  }
305  if ( isset( $prop['categories'] ) ) {
306  $result_array['categories'] = $this->formatCategoryLinks( $p_result->getCategories() );
307  }
308  if ( isset( $prop['categorieshtml'] ) ) {
309  $categoriesHtml = $this->categoriesHtml( $p_result->getCategories() );
310  $result_array['categorieshtml'] = array();
311  ApiResult::setContent( $result_array['categorieshtml'], $categoriesHtml );
312  }
313  if ( isset( $prop['links'] ) ) {
314  $result_array['links'] = $this->formatLinks( $p_result->getLinks() );
315  }
316  if ( isset( $prop['templates'] ) ) {
317  $result_array['templates'] = $this->formatLinks( $p_result->getTemplates() );
318  }
319  if ( isset( $prop['images'] ) ) {
320  $result_array['images'] = array_keys( $p_result->getImages() );
321  }
322  if ( isset( $prop['externallinks'] ) ) {
323  $result_array['externallinks'] = array_keys( $p_result->getExternalLinks() );
324  }
325  if ( isset( $prop['sections'] ) ) {
326  $result_array['sections'] = $p_result->getSections();
327  }
328 
329  if ( isset( $prop['displaytitle'] ) ) {
330  $result_array['displaytitle'] = $p_result->getDisplayTitle() ?
331  $p_result->getDisplayTitle() :
332  $titleObj->getPrefixedText();
333  }
334 
335  if ( isset( $prop['headitems'] ) || isset( $prop['headhtml'] ) ) {
336  $context = new DerivativeContext( $this->getContext() );
337  $context->setTitle( $titleObj );
338  $context->setWikiPage( $pageObj );
339 
340  // We need an OutputPage tied to $context, not to the
341  // RequestContext at the root of the stack.
342  $output = new OutputPage( $context );
343  $output->addParserOutputNoText( $p_result );
344 
345  if ( isset( $prop['headitems'] ) ) {
346  $headItems = $this->formatHeadItems( $p_result->getHeadItems() );
347 
348  $css = $this->formatCss( $output->buildCssLinksArray() );
349 
350  $scripts = array( $output->getHeadScripts() );
351 
352  $result_array['headitems'] = array_merge( $headItems, $css, $scripts );
353  }
354 
355  if ( isset( $prop['headhtml'] ) ) {
356  $result_array['headhtml'] = array();
358  $result_array['headhtml'],
359  $output->headElement( $context->getSkin() )
360  );
361  }
362  }
363 
364  if ( isset( $prop['iwlinks'] ) ) {
365  $result_array['iwlinks'] = $this->formatIWLinks( $p_result->getInterwikiLinks() );
366  }
367 
368  if ( isset( $prop['wikitext'] ) ) {
369  $result_array['wikitext'] = array();
370  ApiResult::setContent( $result_array['wikitext'], $this->content->serialize( $format ) );
371  if ( !is_null( $this->pstContent ) ) {
372  $result_array['psttext'] = array();
373  ApiResult::setContent( $result_array['psttext'], $this->pstContent->serialize( $format ) );
374  }
375  }
376  if ( isset( $prop['properties'] ) ) {
377  $result_array['properties'] = $this->formatProperties( $p_result->getProperties() );
378  }
379 
380  if ( isset( $prop['limitreportdata'] ) ) {
381  $result_array['limitreportdata'] = $this->formatLimitReportData( $p_result->getLimitReportData() );
382  }
383  if ( isset( $prop['limitreporthtml'] ) ) {
384  $limitreportHtml = EditPage::getPreviewLimitReport( $p_result );
385  $result_array['limitreporthtml'] = array();
386  ApiResult::setContent( $result_array['limitreporthtml'], $limitreportHtml );
387  }
388 
389  if ( $params['generatexml'] ) {
390  if ( $this->content->getModel() != CONTENT_MODEL_WIKITEXT ) {
391  $this->dieUsage( "generatexml is only supported for wikitext content", "notwikitext" );
392  }
393 
394  $wgParser->startExternalParse( $titleObj, $popts, OT_PREPROCESS );
395  $dom = $wgParser->preprocessToDom( $this->content->getNativeData() );
396  if ( is_callable( array( $dom, 'saveXML' ) ) ) {
397  $xml = $dom->saveXML();
398  } else {
399  $xml = $dom->__toString();
400  }
401  $result_array['parsetree'] = array();
402  ApiResult::setContent( $result_array['parsetree'], $xml );
403  }
404 
405  $result_mapping = array(
406  'redirects' => 'r',
407  'langlinks' => 'll',
408  'categories' => 'cl',
409  'links' => 'pl',
410  'templates' => 'tl',
411  'images' => 'img',
412  'externallinks' => 'el',
413  'iwlinks' => 'iw',
414  'sections' => 's',
415  'headitems' => 'hi',
416  'properties' => 'pp',
417  'limitreportdata' => 'lr',
418  );
419  $this->setIndexedTagNames( $result_array, $result_mapping );
420  $result->addValue( null, $this->getModuleName(), $result_array );
421 
422  if ( !is_null( $oldLang ) ) {
423  $this->getContext()->setLanguage( $oldLang ); // Reset language to $oldLang
424  }
425  }
426 
435  protected function makeParserOptions( WikiPage $pageObj, array $params ) {
436  wfProfileIn( __METHOD__ );
437 
438  $popts = $pageObj->makeParserOptions( $this->getContext() );
439  $popts->enableLimitReport( !$params['disablepp'] );
440  $popts->setIsPreview( $params['preview'] || $params['sectionpreview'] );
441  $popts->setIsSectionPreview( $params['sectionpreview'] );
442 
443  wfProfileOut( __METHOD__ );
444 
445  return $popts;
446  }
447 
455  private function getParsedContent( WikiPage $page, $popts, $pageId = null, $getWikitext = false ) {
456  $this->content = $page->getContent( Revision::RAW ); //XXX: really raw?
457 
458  if ( $this->section !== false && $this->content !== null ) {
459  $this->content = $this->getSectionContent(
460  $this->content,
461  !is_null( $pageId ) ? 'page id ' . $pageId : $page->getTitle()->getText()
462  );
463 
464  // Not cached (save or load)
465  return $this->content->getParserOutput( $page->getTitle(), null, $popts );
466  }
467 
468  // Try the parser cache first
469  // getParserOutput will save to Parser cache if able
470  $pout = $page->getParserOutput( $popts );
471  if ( !$pout ) {
472  $this->dieUsage( "There is no revision ID {$page->getLatest()}", 'missingrev' );
473  }
474  if ( $getWikitext ) {
475  $this->content = $page->getContent( Revision::RAW );
476  }
477 
478  return $pout;
479  }
480 
481  private function getSectionContent( Content $content, $what ) {
482  // Not cached (save or load)
483  $section = $content->getSection( $this->section );
484  if ( $section === false ) {
485  $this->dieUsage( "There is no section {$this->section} in " . $what, 'nosuchsection' );
486  }
487  if ( $section === null ) {
488  $this->dieUsage( "Sections are not supported by " . $what, 'nosuchsection' );
489  $section = false;
490  }
491 
492  return $section;
493  }
494 
495  private function formatLangLinks( $links ) {
496  $result = array();
497  foreach ( $links as $link ) {
498  $entry = array();
499  $bits = explode( ':', $link, 2 );
501 
502  $entry['lang'] = $bits[0];
503  if ( $title ) {
504  $entry['url'] = wfExpandUrl( $title->getFullURL(), PROTO_CURRENT );
505  // localised language name in user language (maybe set by uselang=)
506  $entry['langname'] = Language::fetchLanguageName( $title->getInterwiki(), $this->getLanguage()->getCode() );
507  // native language name
508  $entry['autonym'] = Language::fetchLanguageName( $title->getInterwiki() );
509  }
510  ApiResult::setContent( $entry, $bits[1] );
511  $result[] = $entry;
512  }
513 
514  return $result;
515  }
516 
517  private function formatCategoryLinks( $links ) {
518  $result = array();
519 
520  if ( !$links ) {
521  return $result;
522  }
523 
524  // Fetch hiddencat property
525  $lb = new LinkBatch;
526  $lb->setArray( array( NS_CATEGORY => $links ) );
527  $db = $this->getDB();
528  $res = $db->select( array( 'page', 'page_props' ),
529  array( 'page_title', 'pp_propname' ),
530  $lb->constructSet( 'page', $db ),
531  __METHOD__,
532  array(),
533  array( 'page_props' => array(
534  'LEFT JOIN', array( 'pp_propname' => 'hiddencat', 'pp_page = page_id' )
535  ) )
536  );
537  $hiddencats = array();
538  foreach ( $res as $row ) {
539  $hiddencats[$row->page_title] = isset( $row->pp_propname );
540  }
541 
542  foreach ( $links as $link => $sortkey ) {
543  $entry = array();
544  $entry['sortkey'] = $sortkey;
545  ApiResult::setContent( $entry, $link );
546  if ( !isset( $hiddencats[$link] ) ) {
547  $entry['missing'] = '';
548  } elseif ( $hiddencats[$link] ) {
549  $entry['hidden'] = '';
550  }
551  $result[] = $entry;
552  }
553 
554  return $result;
555  }
556 
557  private function categoriesHtml( $categories ) {
558  $context = $this->getContext();
559  $context->getOutput()->addCategoryLinks( $categories );
560 
561  return $context->getSkin()->getCategories();
562  }
563 
570  private function languagesHtml( $languages ) {
571  wfDeprecated( __METHOD__, '1.18' );
572  $this->setWarning( '"action=parse&prop=languageshtml" is deprecated ' .
573  'and will be removed in MediaWiki 1.24. Use "prop=langlinks" ' .
574  'to generate your own HTML.' );
575 
576  global $wgContLang, $wgHideInterlanguageLinks;
577 
578  if ( $wgHideInterlanguageLinks || count( $languages ) == 0 ) {
579  return '';
580  }
581 
582  $s = htmlspecialchars( wfMessage( 'otherlanguages' )->text() .
583  wfMessage( 'colon-separator' )->text() );
584 
585  $langs = array();
586  foreach ( $languages as $l ) {
587  $nt = Title::newFromText( $l );
588  $text = Language::fetchLanguageName( $nt->getInterwiki() );
589 
590  $langs[] = Html::element( 'a',
591  array( 'href' => $nt->getFullURL(), 'title' => $nt->getText(), 'class' => 'external' ),
592  $text == '' ? $l : $text );
593  }
594 
595  $s .= implode( wfMessage( 'pipe-separator' )->escaped(), $langs );
596 
597  if ( $wgContLang->isRTL() ) {
598  $s = Html::rawElement( 'span', array( 'dir' => 'LTR' ), $s );
599  }
600 
601  return $s;
602  }
603 
604  private function formatLinks( $links ) {
605  $result = array();
606  foreach ( $links as $ns => $nslinks ) {
607  foreach ( $nslinks as $title => $id ) {
608  $entry = array();
609  $entry['ns'] = $ns;
610  ApiResult::setContent( $entry, Title::makeTitle( $ns, $title )->getFullText() );
611  if ( $id != 0 ) {
612  $entry['exists'] = '';
613  }
614  $result[] = $entry;
615  }
616  }
617 
618  return $result;
619  }
620 
621  private function formatIWLinks( $iw ) {
622  $result = array();
623  foreach ( $iw as $prefix => $titles ) {
624  foreach ( array_keys( $titles ) as $title ) {
625  $entry = array();
626  $entry['prefix'] = $prefix;
627 
628  $title = Title::newFromText( "{$prefix}:{$title}" );
629  if ( $title ) {
630  $entry['url'] = wfExpandUrl( $title->getFullURL(), PROTO_CURRENT );
631  }
632 
633  ApiResult::setContent( $entry, $title->getFullText() );
634  $result[] = $entry;
635  }
636  }
637 
638  return $result;
639  }
640 
641  private function formatHeadItems( $headItems ) {
642  $result = array();
643  foreach ( $headItems as $tag => $content ) {
644  $entry = array();
645  $entry['tag'] = $tag;
646  ApiResult::setContent( $entry, $content );
647  $result[] = $entry;
648  }
649 
650  return $result;
651  }
652 
653  private function formatProperties( $properties ) {
654  $result = array();
655  foreach ( $properties as $name => $value ) {
656  $entry = array();
657  $entry['name'] = $name;
658  ApiResult::setContent( $entry, $value );
659  $result[] = $entry;
660  }
661 
662  return $result;
663  }
664 
665  private function formatCss( $css ) {
666  $result = array();
667  foreach ( $css as $file => $link ) {
668  $entry = array();
669  $entry['file'] = $file;
670  ApiResult::setContent( $entry, $link );
671  $result[] = $entry;
672  }
673 
674  return $result;
675  }
676 
677  private function formatLimitReportData( $limitReportData ) {
678  $result = array();
679  $apiResult = $this->getResult();
680 
681  foreach ( $limitReportData as $name => $value ) {
682  $entry = array();
683  $entry['name'] = $name;
684  if ( !is_array( $value ) ) {
685  $value = array( $value );
686  }
687  $apiResult->setIndexedTagName( $value, 'param' );
688  $apiResult->setIndexedTagName_recursive( $value, 'param' );
689  $entry = array_merge( $entry, $value );
690  $result[] = $entry;
691  }
692 
693  return $result;
694  }
695 
696  private function setIndexedTagNames( &$array, $mapping ) {
697  foreach ( $mapping as $key => $name ) {
698  if ( isset( $array[$key] ) ) {
699  $this->getResult()->setIndexedTagName( $array[$key], $name );
700  }
701  }
702  }
703 
704  public function getAllowedParams() {
705  return array(
706  'title' => null,
707  'text' => null,
708  'summary' => null,
709  'page' => null,
710  'pageid' => array(
711  ApiBase::PARAM_TYPE => 'integer',
712  ),
713  'redirects' => false,
714  'oldid' => array(
715  ApiBase::PARAM_TYPE => 'integer',
716  ),
717  'prop' => array(
718  ApiBase::PARAM_DFLT => 'text|langlinks|categories|links|templates|' .
719  'images|externallinks|sections|revid|displaytitle|iwlinks|properties',
720  ApiBase::PARAM_ISMULTI => true,
722  'text',
723  'langlinks',
724  'languageshtml',
725  'categories',
726  'categorieshtml',
727  'links',
728  'templates',
729  'images',
730  'externallinks',
731  'sections',
732  'revid',
733  'displaytitle',
734  'headitems',
735  'headhtml',
736  'iwlinks',
737  'wikitext',
738  'properties',
739  'limitreportdata',
740  'limitreporthtml',
741  )
742  ),
743  'pst' => false,
744  'onlypst' => false,
745  'effectivelanglinks' => false,
746  'uselang' => null,
747  'section' => null,
748  'disablepp' => false,
749  'generatexml' => false,
750  'preview' => false,
751  'sectionpreview' => false,
752  'disabletoc' => false,
753  'contentformat' => array(
755  ),
756  'contentmodel' => array(
758  )
759  );
760  }
761 
762  public function getParamDescription() {
763  $p = $this->getModulePrefix();
764  $wikitext = CONTENT_MODEL_WIKITEXT;
765 
766  return array(
767  'text' => "Text to parse. Use {$p}title or {$p}contentmodel to control the content model",
768  'summary' => 'Summary to parse',
769  'redirects' => "If the {$p}page or the {$p}pageid parameter is set to a redirect, resolve it",
770  'title' => "Title of page the text belongs to. " .
771  "If omitted, {$p}contentmodel must be specified, and \"API\" will be used as the title",
772  'page' => "Parse the content of this page. Cannot be used together with {$p}text and {$p}title",
773  'pageid' => "Parse the content of this page. Overrides {$p}page",
774  'oldid' => "Parse the content of this revision. Overrides {$p}page and {$p}pageid",
775  'prop' => array(
776  'Which pieces of information to get',
777  ' text - Gives the parsed text of the wikitext',
778  ' langlinks - Gives the language links in the parsed wikitext',
779  ' categories - Gives the categories in the parsed wikitext',
780  ' categorieshtml - Gives the HTML version of the categories',
781  ' languageshtml - DEPRECATED. Will be removed in MediaWiki 1.24.',
782  ' Gives the HTML version of the language links',
783  ' links - Gives the internal links in the parsed wikitext',
784  ' templates - Gives the templates in the parsed wikitext',
785  ' images - Gives the images in the parsed wikitext',
786  ' externallinks - Gives the external links in the parsed wikitext',
787  ' sections - Gives the sections in the parsed wikitext',
788  ' revid - Adds the revision ID of the parsed page',
789  ' displaytitle - Adds the title of the parsed wikitext',
790  ' headitems - Gives items to put in the <head> of the page',
791  ' headhtml - Gives parsed <head> of the page',
792  ' iwlinks - Gives interwiki links in the parsed wikitext',
793  ' wikitext - Gives the original wikitext that was parsed',
794  ' properties - Gives various properties defined in the parsed wikitext',
795  ' limitreportdata - Gives the limit report in a structured way.',
796  " Gives no data, when {$p}disablepp is set.",
797  ' limitreporthtml - Gives the HTML version of the limit report.',
798  " Gives no data, when {$p}disablepp is set.",
799  ),
800  'effectivelanglinks' => array(
801  'Includes language links supplied by extensions',
802  '(for use with prop=langlinks|languageshtml)',
803  ),
804  'pst' => array(
805  'Do a pre-save transform on the input before parsing it',
806  "Only valid when used with {$p}text",
807  ),
808  'onlypst' => array(
809  'Do a pre-save transform (PST) on the input, but don\'t parse it',
810  'Returns the same wikitext, after a PST has been applied.',
811  "Only valid when used with {$p}text",
812  ),
813  'uselang' => 'Which language to parse the request in',
814  'section' => 'Only retrieve the content of this section number',
815  'disablepp' => 'Disable the PP Report from the parser output',
816  'generatexml' => "Generate XML parse tree (requires contentmodel=$wikitext)",
817  'preview' => 'Parse in preview mode',
818  'sectionpreview' => 'Parse in section preview mode (enables preview mode too)',
819  'disabletoc' => 'Disable table of contents in output',
820  'contentformat' => array(
821  'Content serialization format used for the input text',
822  "Only valid when used with {$p}text",
823  ),
824  'contentmodel' => array(
825  "Content model of the input text. If omitted, ${p}title must be specified, " .
826  "and default will be the model of the specified ${p}title",
827  "Only valid when used with {$p}text",
828  ),
829  );
830  }
831 
832  public function getDescription() {
833  $p = $this->getModulePrefix();
834 
835  return array(
836  'Parses content and returns parser output.',
837  'See the various prop-Modules of action=query to get information from the current' .
838  'version of a page.',
839  'There are several ways to specify the text to parse:',
840  "1) Specify a page or revision, using {$p}page, {$p}pageid, or {$p}oldid.",
841  "2) Specify content explicitly, using {$p}text, {$p}title, and {$p}contentmodel.",
842  "3) Specify only a summary to parse. {$p}prop should be given an empty value.",
843  );
844  }
845 
846  public function getPossibleErrors() {
847  return array_merge( parent::getPossibleErrors(), array(
848  array(
849  'code' => 'params',
850  'info' => 'The page parameter cannot be used together with the text and title parameters'
851  ),
852  array( 'code' => 'missingrev', 'info' => 'There is no revision ID oldid' ),
853  array(
854  'code' => 'permissiondenied',
855  'info' => 'You don\'t have permission to view deleted revisions'
856  ),
857  array( 'code' => 'missingtitle', 'info' => 'The page you specified doesn\'t exist' ),
858  array( 'code' => 'nosuchsection', 'info' => 'There is no section sectionnumber in page' ),
859  array( 'nosuchpageid' ),
860  array( 'invalidtitle', 'title' ),
861  array( 'code' => 'parseerror', 'info' => 'Failed to parse the given text.' ),
862  array(
863  'code' => 'notwikitext',
864  'info' => 'The requested operation is only supported on wikitext content.'
865  ),
866  ) );
867  }
868 
869  public function getExamples() {
870  return array(
871  'api.php?action=parse&page=Project:Sandbox' => 'Parse a page',
872  'api.php?action=parse&text={{Project:Sandbox}}&contentmodel=wikitext' => 'Parse wikitext',
873  'api.php?action=parse&text={{PAGENAME}}&title=Test'
874  => 'Parse wikitext, specifying the page title',
875  'api.php?action=parse&summary=Some+[[link]]&prop=' => 'Parse a summary',
876  );
877  }
878 
879  public function getHelpUrls() {
880  return 'https://www.mediawiki.org/wiki/API:Parsing_wikitext#parse';
881  }
882 }
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:618
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:759
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:492
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:662
ApiBase\dieUsageMsg
dieUsageMsg( $error)
Output the error message related to a certain array.
Definition: ApiBase.php:1953
ApiBase\getTitleOrPageId
getTitleOrPageId( $params, $load=false)
Definition: ApiBase.php:873
ApiBase\PARAM_TYPE
const PARAM_TYPE
Definition: ApiBase.php:50
ApiParse\formatLinks
formatLinks( $links)
Definition: ApiParse.php:601
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:2336
ApiParse\checkReadPermissions
checkReadPermissions(Title $title)
Definition: ApiParse.php:36
$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:1263
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:2160
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:452
DerivativeContext
An IContextSource implementation which will inherit context from another source but allow individual ...
Definition: DerivativeContext.php:32
$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:876
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:843
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:1174
$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:141
ApiParse\getAllowedParams
getAllowedParams()
Returns an array of allowed parameters (parameter name) => (default value) or (parameter name) => (ar...
Definition: ApiParse.php:701
ApiParse\formatLimitReportData
formatLimitReportData( $limitReportData)
Definition: ApiParse.php:674
ApiParse\getDescription
getDescription()
Returns the description string for this module.
Definition: ApiParse.php:829
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:4066
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:866
NS_CATEGORY
const NS_CATEGORY
Definition: Defines.php:93
OutputPage
This class should be covered by a general architecture document which does not exist as of January 20...
Definition: OutputPage.php:38
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:514
$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:707
$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:1383
ApiParse\setIndexedTagNames
setIndexedTagNames(&$array, $mapping)
Definition: ApiParse.php:693
ApiParse\languagesHtml
languagesHtml( $languages)
Definition: ApiParse.php:567
Revision\RAW
const RAW
Definition: Revision.php:74
Language\fetchLanguageName
static fetchLanguageName( $code, $inLanguage=null, $include='all')
Definition: Language.php:941
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:554
ApiBase\setWarning
setWarning( $warning)
Set warning section for this module.
Definition: ApiBase.php:245
Title
Represents a title within MediaWiki.
Definition: Title.php:35
$wgParser
$wgParser
Definition: Setup.php:587
$output
& $output
Definition: hooks.txt:375
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:478
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:638
Html\rawElement
static rawElement( $element, $attribs=array(), $contents='')
Returns an HTML element in a string.
Definition: Html.php:121
ApiParse\formatProperties
formatProperties( $properties)
Definition: ApiParse.php:650
ApiParse\makeParserOptions
makeParserOptions(WikiPage $pageObj, array $params)
Constructs a ParserOptions object.
Definition: ApiParse.php:432
$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:544
$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:42
Article\newFromTitle
static newFromTitle( $title, IContextSource $context)
Create an Article object of the appropriate class for the given page.
Definition: Article.php:142