3 * Created on Dec 01, 2007
5 * Copyright © 2007 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 * http://www.gnu.org/copyleft/gpl.html
28 class ApiParse
extends ApiBase
{
30 /** @var string $section */
31 private $section = null;
33 /** @var Content $content */
34 private $content = null;
36 /** @var Content $pstContent */
37 private $pstContent = null;
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' );
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
52 $titleProvided = true;
55 $page = $params['page'];
56 $pageid = $params['pageid'];
57 $oldid = $params['oldid'];
59 $model = $params['contentmodel'];
60 $format = $params['contentformat'];
62 if ( !is_null( $page ) && ( !is_null( $text ) ||
$titleProvided ) ) {
64 'The page parameter cannot be used together with the text and title parameters',
69 $prop = array_flip( $params['prop'] );
71 if ( isset( $params['section'] ) ) {
72 $this->section
= $params['section'];
73 if ( !preg_match( '/^((T-)?\d+|new)$/', $this->section
) ) {
74 $this->dieUsage( "The section parameter must be a valid section id or 'new'", "invalidsection" );
77 $this->section
= false;
80 // The parser needs $wgTitle to be set, apparently the
81 // $title parameter in Parser::parse isn't enough *sigh*
82 // TODO: Does this still need $wgTitle?
83 global $wgParser, $wgTitle;
88 $result = $this->getResult();
90 if ( !is_null( $oldid ) ||
!is_null( $pageid ) ||
!is_null( $page ) ) {
91 if ( !is_null( $oldid ) ) {
92 // Don't use the parser cache
93 $rev = Revision
::newFromId( $oldid );
95 $this->dieUsage( "There is no revision ID $oldid", 'missingrev' );
97 if ( !$rev->userCan( Revision
::DELETED_TEXT
, $this->getUser() ) ) {
98 $this->dieUsage( "You don't have permission to view deleted revisions", 'permissiondenied' );
101 $titleObj = $rev->getTitle();
102 $wgTitle = $titleObj;
103 $pageObj = WikiPage
::factory( $titleObj );
104 $popts = $this->makeParserOptions( $pageObj, $params );
106 // If for some reason the "oldid" is actually the current revision, it may be cached
107 if ( $rev->isCurrent() ) {
108 // May get from/save to parser cache
109 $p_result = $this->getParsedContent( $pageObj, $popts,
110 $pageid, isset( $prop['wikitext'] ) );
111 } else { // This is an old revision, so get the text differently
112 $this->content
= $rev->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
114 if ( $this->section
!== false ) {
115 $this->content
= $this->getSectionContent( $this->content
, 'r' . $rev->getId() );
118 // Should we save old revision parses to the parser cache?
119 $p_result = $this->content
->getParserOutput( $titleObj, $rev->getId(), $popts );
121 } else { // Not $oldid, but $pageid or $page
122 if ( $params['redirects'] ) {
127 if ( !is_null( $pageid ) ) {
128 $reqParams['pageids'] = $pageid;
130 $reqParams['titles'] = $page;
132 $req = new FauxRequest( $reqParams );
133 $main = new ApiMain( $req );
135 $data = $main->getResultData();
136 $redirValues = isset( $data['query']['redirects'] )
137 ?
$data['query']['redirects']
140 foreach ( (array)$redirValues as $r ) {
143 $pageParams = array( 'title' => $to );
144 } elseif ( !is_null( $pageid ) ) {
145 $pageParams = array( 'pageid' => $pageid );
147 $pageParams = array( 'title' => $page );
150 $pageObj = $this->getTitleOrPageId( $pageParams, 'fromdb' );
151 $titleObj = $pageObj->getTitle();
152 if ( !$titleObj ||
!$titleObj->exists() ) {
153 $this->dieUsage( "The page you specified doesn't exist", 'missingtitle' );
155 $wgTitle = $titleObj;
157 if ( isset( $prop['revid'] ) ) {
158 $oldid = $pageObj->getLatest();
161 $popts = $this->makeParserOptions( $pageObj, $params );
163 // Potentially cached
164 $p_result = $this->getParsedContent( $pageObj, $popts, $pageid,
165 isset( $prop['wikitext'] ) );
167 } else { // Not $oldid, $pageid, $page. Hence based on $text
168 $titleObj = Title
::newFromText( $title );
169 if ( !$titleObj ||
$titleObj->isExternal() ) {
170 $this->dieUsageMsg( array( 'invalidtitle', $title ) );
172 $wgTitle = $titleObj;
173 if ( $titleObj->canExist() ) {
174 $pageObj = WikiPage
::factory( $titleObj );
176 // Do like MediaWiki::initializeArticle()
177 $article = Article
::newFromTitle( $titleObj, $this->getContext() );
178 $pageObj = $article->getPage();
181 $popts = $this->makeParserOptions( $pageObj, $params );
182 $textProvided = !is_null( $text );
184 if ( !$textProvided ) {
185 if ( $titleProvided && ( $prop ||
$params['generatexml'] ) ) {
187 "'title' used without 'text', and parsed page properties were requested " .
188 "(did you mean to use 'page' instead of 'title'?)"
191 // Prevent warning from ContentHandler::makeContent()
195 // If we are parsing text, do not use the content model of the default
196 // API title, but default to wikitext to keep BC.
197 if ( $textProvided && !$titleProvided && is_null( $model ) ) {
198 $model = CONTENT_MODEL_WIKITEXT
;
199 $this->setWarning( "No 'title' or 'contentmodel' was given, assuming $model." );
203 $this->content
= ContentHandler
::makeContent( $text, $titleObj, $model, $format );
204 } catch ( MWContentSerializationException
$ex ) {
205 $this->dieUsage( $ex->getMessage(), 'parseerror' );
208 if ( $this->section
!== false ) {
209 if ( $this->section
=== 'new' ) {
210 // Insert the section title above the content.
211 if ( !is_null( $params['sectiontitle'] ) && $params['sectiontitle'] !== '' ) {
212 $this->content
= $this->content
->addSectionHeader( $params['sectiontitle'] );
215 $this->content
= $this->getSectionContent( $this->content
, $titleObj->getPrefixedText() );
219 if ( $params['pst'] ||
$params['onlypst'] ) {
220 $this->pstContent
= $this->content
->preSaveTransform( $titleObj, $this->getUser(), $popts );
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 ) );
231 if ( !is_null( $params['summary'] ) ||
232 ( !is_null( $params['sectiontitle'] ) && $this->section
=== 'new' )
234 $result_array['parsedsummary'] = array();
235 ApiResult
::setContent( $result_array['parsedsummary'], $this->formatSummary( $titleObj, $params ) );
238 $result->addValue( null, $this->getModuleName(), $result_array );
243 // Not cached (save or load)
244 if ( $params['pst'] ) {
245 $p_result = $this->pstContent
->getParserOutput( $titleObj, null, $popts );
247 $p_result = $this->content
->getParserOutput( $titleObj, null, $popts );
251 $result_array = array();
253 $result_array['title'] = $titleObj->getPrefixedText();
255 if ( !is_null( $oldid ) ) {
256 $result_array['revid'] = intval( $oldid );
259 if ( $params['redirects'] && !is_null( $redirValues ) ) {
260 $result_array['redirects'] = $redirValues;
263 if ( $params['disabletoc'] ) {
264 $p_result->setTOCEnabled( false );
267 if ( isset( $prop['text'] ) ) {
268 $result_array['text'] = array();
269 ApiResult
::setContent( $result_array['text'], $p_result->getText() );
272 if ( !is_null( $params['summary'] ) ||
273 ( !is_null( $params['sectiontitle'] ) && $this->section
=== 'new' )
275 $result_array['parsedsummary'] = array();
276 ApiResult
::setContent( $result_array['parsedsummary'], $this->formatSummary( $titleObj, $params ) );
279 if ( isset( $prop['langlinks'] ) ) {
280 $langlinks = $p_result->getLanguageLinks();
282 if ( $params['effectivelanglinks'] ) {
283 // Link flags are ignored for now, but may in the future be
284 // included in the result.
285 $linkFlags = array();
286 Hooks
::run( 'LanguageLinks', array( $titleObj, &$langlinks, &$linkFlags ) );
292 if ( isset( $prop['langlinks'] ) ) {
293 $result_array['langlinks'] = $this->formatLangLinks( $langlinks );
295 if ( isset( $prop['categories'] ) ) {
296 $result_array['categories'] = $this->formatCategoryLinks( $p_result->getCategories() );
298 if ( isset( $prop['categorieshtml'] ) ) {
299 $categoriesHtml = $this->categoriesHtml( $p_result->getCategories() );
300 $result_array['categorieshtml'] = array();
301 ApiResult
::setContent( $result_array['categorieshtml'], $categoriesHtml );
303 if ( isset( $prop['links'] ) ) {
304 $result_array['links'] = $this->formatLinks( $p_result->getLinks() );
306 if ( isset( $prop['templates'] ) ) {
307 $result_array['templates'] = $this->formatLinks( $p_result->getTemplates() );
309 if ( isset( $prop['images'] ) ) {
310 $result_array['images'] = array_keys( $p_result->getImages() );
312 if ( isset( $prop['externallinks'] ) ) {
313 $result_array['externallinks'] = array_keys( $p_result->getExternalLinks() );
315 if ( isset( $prop['sections'] ) ) {
316 $result_array['sections'] = $p_result->getSections();
319 if ( isset( $prop['displaytitle'] ) ) {
320 $result_array['displaytitle'] = $p_result->getDisplayTitle() ?
321 $p_result->getDisplayTitle() :
322 $titleObj->getPrefixedText();
325 if ( isset( $prop['headitems'] ) ||
isset( $prop['headhtml'] ) ) {
326 $context = $this->getContext();
327 $context->setTitle( $titleObj );
328 $context->getOutput()->addParserOutputMetadata( $p_result );
330 if ( isset( $prop['headitems'] ) ) {
331 $headItems = $this->formatHeadItems( $p_result->getHeadItems() );
333 $css = $this->formatCss( $context->getOutput()->buildCssLinksArray() );
335 $scripts = array( $context->getOutput()->getHeadScripts() );
337 $result_array['headitems'] = array_merge( $headItems, $css, $scripts );
340 if ( isset( $prop['headhtml'] ) ) {
341 $result_array['headhtml'] = array();
342 ApiResult
::setContent(
343 $result_array['headhtml'],
344 $context->getOutput()->headElement( $context->getSkin() )
349 if ( isset( $prop['modules'] ) ) {
350 $result_array['modules'] = array_values( array_unique( $p_result->getModules() ) );
351 $result_array['modulescripts'] = array_values( array_unique( $p_result->getModuleScripts() ) );
352 $result_array['modulestyles'] = array_values( array_unique( $p_result->getModuleStyles() ) );
353 $result_array['modulemessages'] = array_values( array_unique( $p_result->getModuleMessages() ) );
356 if ( isset( $prop['indicators'] ) ) {
357 foreach ( $p_result->getIndicators() as $name => $content ) {
358 $indicator = array( 'name' => $name );
359 ApiResult
::setContent( $indicator, $content );
360 $result_array['indicators'][] = $indicator;
364 if ( isset( $prop['iwlinks'] ) ) {
365 $result_array['iwlinks'] = $this->formatIWLinks( $p_result->getInterwikiLinks() );
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 ) );
376 if ( isset( $prop['properties'] ) ) {
377 $result_array['properties'] = $this->formatProperties( $p_result->getProperties() );
380 if ( isset( $prop['limitreportdata'] ) ) {
381 $result_array['limitreportdata'] =
382 $this->formatLimitReportData( $p_result->getLimitReportData() );
384 if ( isset( $prop['limitreporthtml'] ) ) {
385 $limitreportHtml = EditPage
::getPreviewLimitReport( $p_result );
386 $result_array['limitreporthtml'] = array();
387 ApiResult
::setContent( $result_array['limitreporthtml'], $limitreportHtml );
390 if ( $params['generatexml'] ) {
391 if ( $this->content
->getModel() != CONTENT_MODEL_WIKITEXT
) {
392 $this->dieUsage( "generatexml is only supported for wikitext content", "notwikitext" );
395 $wgParser->startExternalParse( $titleObj, $popts, Parser
::OT_PREPROCESS
);
396 $dom = $wgParser->preprocessToDom( $this->content
->getNativeData() );
397 if ( is_callable( array( $dom, 'saveXML' ) ) ) {
398 $xml = $dom->saveXML();
400 $xml = $dom->__toString();
402 $result_array['parsetree'] = array();
403 ApiResult
::setContent( $result_array['parsetree'], $xml );
406 $result_mapping = array(
409 'categories' => 'cl',
413 'externallinks' => 'el',
418 'indicators' => 'ind',
419 'modulescripts' => 'm',
420 'modulestyles' => 'm',
421 'modulemessages' => 'm',
422 'properties' => 'pp',
423 'limitreportdata' => 'lr',
425 $this->setIndexedTagNames( $result_array, $result_mapping );
426 $result->addValue( null, $this->getModuleName(), $result_array );
430 * Constructs a ParserOptions object
432 * @param WikiPage $pageObj
433 * @param array $params
435 * @return ParserOptions
437 protected function makeParserOptions( WikiPage
$pageObj, array $params ) {
439 $popts = $pageObj->makeParserOptions( $this->getContext() );
440 $popts->enableLimitReport( !$params['disablepp'] );
441 $popts->setIsPreview( $params['preview'] ||
$params['sectionpreview'] );
442 $popts->setIsSectionPreview( $params['sectionpreview'] );
443 $popts->setEditSection( !$params['disableeditsection'] );
449 * @param WikiPage $page
450 * @param ParserOptions $popts
452 * @param bool $getWikitext
453 * @return ParserOutput
455 private function getParsedContent( WikiPage
$page, $popts, $pageId = null, $getWikitext = false ) {
456 $this->content
= $page->getContent( Revision
::RAW
); //XXX: really raw?
458 if ( $this->section
!== false && $this->content
!== null ) {
459 $this->content
= $this->getSectionContent(
461 !is_null( $pageId ) ?
'page id ' . $pageId : $page->getTitle()->getPrefixedText()
464 // Not cached (save or load)
465 return $this->content
->getParserOutput( $page->getTitle(), null, $popts );
468 // Try the parser cache first
469 // getParserOutput will save to Parser cache if able
470 $pout = $page->getParserOutput( $popts );
472 $this->dieUsage( "There is no revision ID {$page->getLatest()}", 'missingrev' );
474 if ( $getWikitext ) {
475 $this->content
= $page->getContent( Revision
::RAW
);
482 * @param Content $content
483 * @param string $what Identifies the content in error messages, e.g. page title.
484 * @return Content|bool
486 private function getSectionContent( Content
$content, $what ) {
487 // Not cached (save or load)
488 $section = $content->getSection( $this->section
);
489 if ( $section === false ) {
490 $this->dieUsage( "There is no section {$this->section} in " . $what, 'nosuchsection' );
492 if ( $section === null ) {
493 $this->dieUsage( "Sections are not supported by " . $what, 'nosuchsection' );
501 * This mimicks the behavior of EditPage in formatting a summary
503 * @param Title $title of the page being parsed
504 * @param Array $params the API parameters of the request
505 * @return Content|bool
507 private function formatSummary( $title, $params ) {
509 $summary = !is_null( $params['summary'] ) ?
$params['summary'] : '';
510 $sectionTitle = !is_null( $params['sectiontitle'] ) ?
$params['sectiontitle'] : '';
512 if ( $this->section
=== 'new' && ( $sectionTitle === '' ||
$summary === '' ) ) {
513 if( $sectionTitle !== '' ) {
514 $summary = $params['sectiontitle'];
516 if ( $summary !== '' ) {
517 $summary = wfMessage( 'newsectionsummary' )->rawParams( $wgParser->stripSectionName( $summary ) )
518 ->inContentLanguage()->text();
521 return Linker
::formatComment( $summary, $title, $this->section
=== 'new' );
524 private function formatLangLinks( $links ) {
526 foreach ( $links as $link ) {
528 $bits = explode( ':', $link, 2 );
529 $title = Title
::newFromText( $link );
531 $entry['lang'] = $bits[0];
533 $entry['url'] = wfExpandUrl( $title->getFullURL(), PROTO_CURRENT
);
534 // localised language name in 'uselang' language
535 $entry['langname'] = Language
::fetchLanguageName(
536 $title->getInterwiki(),
537 $this->getLanguage()->getCode()
540 // native language name
541 $entry['autonym'] = Language
::fetchLanguageName( $title->getInterwiki() );
543 ApiResult
::setContent( $entry, $bits[1] );
550 private function formatCategoryLinks( $links ) {
557 // Fetch hiddencat property
559 $lb->setArray( array( NS_CATEGORY
=> $links ) );
560 $db = $this->getDB();
561 $res = $db->select( array( 'page', 'page_props' ),
562 array( 'page_title', 'pp_propname' ),
563 $lb->constructSet( 'page', $db ),
566 array( 'page_props' => array(
567 'LEFT JOIN', array( 'pp_propname' => 'hiddencat', 'pp_page = page_id' )
570 $hiddencats = array();
571 foreach ( $res as $row ) {
572 $hiddencats[$row->page_title
] = isset( $row->pp_propname
);
575 foreach ( $links as $link => $sortkey ) {
577 $entry['sortkey'] = $sortkey;
578 ApiResult
::setContent( $entry, $link );
579 if ( !isset( $hiddencats[$link] ) ) {
580 $entry['missing'] = '';
581 } elseif ( $hiddencats[$link] ) {
582 $entry['hidden'] = '';
590 private function categoriesHtml( $categories ) {
591 $context = $this->getContext();
592 $context->getOutput()->addCategoryLinks( $categories );
594 return $context->getSkin()->getCategories();
597 private function formatLinks( $links ) {
599 foreach ( $links as $ns => $nslinks ) {
600 foreach ( $nslinks as $title => $id ) {
603 ApiResult
::setContent( $entry, Title
::makeTitle( $ns, $title )->getFullText() );
605 $entry['exists'] = '';
614 private function formatIWLinks( $iw ) {
616 foreach ( $iw as $prefix => $titles ) {
617 foreach ( array_keys( $titles ) as $title ) {
619 $entry['prefix'] = $prefix;
621 $title = Title
::newFromText( "{$prefix}:{$title}" );
623 $entry['url'] = wfExpandUrl( $title->getFullURL(), PROTO_CURRENT
);
626 ApiResult
::setContent( $entry, $title->getFullText() );
634 private function formatHeadItems( $headItems ) {
636 foreach ( $headItems as $tag => $content ) {
638 $entry['tag'] = $tag;
639 ApiResult
::setContent( $entry, $content );
646 private function formatProperties( $properties ) {
648 foreach ( $properties as $name => $value ) {
650 $entry['name'] = $name;
651 ApiResult
::setContent( $entry, $value );
658 private function formatCss( $css ) {
660 foreach ( $css as $file => $link ) {
662 $entry['file'] = $file;
663 ApiResult
::setContent( $entry, $link );
670 private function formatLimitReportData( $limitReportData ) {
672 $apiResult = $this->getResult();
674 foreach ( $limitReportData as $name => $value ) {
676 $entry['name'] = $name;
677 if ( !is_array( $value ) ) {
678 $value = array( $value );
680 $apiResult->setIndexedTagName( $value, 'param' );
681 $apiResult->setIndexedTagName_recursive( $value, 'param' );
682 $entry = array_merge( $entry, $value );
689 private function setIndexedTagNames( &$array, $mapping ) {
690 foreach ( $mapping as $key => $name ) {
691 if ( isset( $array[$key] ) ) {
692 $this->getResult()->setIndexedTagName( $array[$key], $name );
697 public function getAllowedParams() {
704 ApiBase
::PARAM_TYPE
=> 'integer',
706 'redirects' => false,
708 ApiBase
::PARAM_TYPE
=> 'integer',
711 ApiBase
::PARAM_DFLT
=> 'text|langlinks|categories|links|templates|' .
712 'images|externallinks|sections|revid|displaytitle|iwlinks|properties',
713 ApiBase
::PARAM_ISMULTI
=> true,
714 ApiBase
::PARAM_TYPE
=> array(
739 'effectivelanglinks' => false,
741 'sectiontitle' => array(
742 ApiBase
::PARAM_TYPE
=> 'string',
744 'disablepp' => false,
745 'disableeditsection' => false,
746 'generatexml' => array(
747 ApiBase
::PARAM_DFLT
=> false,
748 ApiBase
::PARAM_HELP_MSG
=> array(
749 'apihelp-parse-param-generatexml', CONTENT_MODEL_WIKITEXT
753 'sectionpreview' => false,
754 'disabletoc' => false,
755 'contentformat' => array(
756 ApiBase
::PARAM_TYPE
=> ContentHandler
::getAllContentFormats(),
758 'contentmodel' => array(
759 ApiBase
::PARAM_TYPE
=> ContentHandler
::getContentModels(),
764 protected function getExamplesMessages() {
766 'action=parse&page=Project:Sandbox'
767 => 'apihelp-parse-example-page',
768 'action=parse&text={{Project:Sandbox}}&contentmodel=wikitext'
769 => 'apihelp-parse-example-text',
770 'action=parse&text={{PAGENAME}}&title=Test'
771 => 'apihelp-parse-example-texttitle',
772 'action=parse&summary=Some+[[link]]&prop='
773 => 'apihelp-parse-example-summary',
777 public function getHelpUrls() {
778 return 'https://www.mediawiki.org/wiki/API:Parsing_wikitext#parse';