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 ( $this->section
=== 'new' ) {
92 $this->dieUsage( 'section=new cannot be combined with oldid, pageid or page parameters. Please use text', 'params' );
94 if ( !is_null( $oldid ) ) {
95 // Don't use the parser cache
96 $rev = Revision
::newFromId( $oldid );
98 $this->dieUsage( "There is no revision ID $oldid", 'missingrev' );
100 if ( !$rev->userCan( Revision
::DELETED_TEXT
, $this->getUser() ) ) {
101 $this->dieUsage( "You don't have permission to view deleted revisions", 'permissiondenied' );
104 $titleObj = $rev->getTitle();
105 $wgTitle = $titleObj;
106 $pageObj = WikiPage
::factory( $titleObj );
107 $popts = $this->makeParserOptions( $pageObj, $params );
109 // If for some reason the "oldid" is actually the current revision, it may be cached
110 // Deliberately comparing $pageObj->getLatest() with $rev->getId(), rather than
111 // checking $rev->isCurrent(), because $pageObj is what actually ends up being used,
112 // and if its ->getLatest() is outdated, $rev->isCurrent() won't tell us that.
113 if ( $rev->getId() == $pageObj->getLatest() ) {
114 // May get from/save to parser cache
115 $p_result = $this->getParsedContent( $pageObj, $popts,
116 $pageid, isset( $prop['wikitext'] ) );
117 } else { // This is an old revision, so get the text differently
118 $this->content
= $rev->getContent( Revision
::FOR_THIS_USER
, $this->getUser() );
120 if ( $this->section
!== false ) {
121 $this->content
= $this->getSectionContent( $this->content
, 'r' . $rev->getId() );
124 // Should we save old revision parses to the parser cache?
125 $p_result = $this->content
->getParserOutput( $titleObj, $rev->getId(), $popts );
127 } else { // Not $oldid, but $pageid or $page
128 if ( $params['redirects'] ) {
133 if ( !is_null( $pageid ) ) {
134 $reqParams['pageids'] = $pageid;
136 $reqParams['titles'] = $page;
138 $req = new FauxRequest( $reqParams );
139 $main = new ApiMain( $req );
141 $data = $main->getResultData();
142 $redirValues = isset( $data['query']['redirects'] )
143 ?
$data['query']['redirects']
146 foreach ( (array)$redirValues as $r ) {
149 $pageParams = array( 'title' => $to );
150 } elseif ( !is_null( $pageid ) ) {
151 $pageParams = array( 'pageid' => $pageid );
153 $pageParams = array( 'title' => $page );
156 $pageObj = $this->getTitleOrPageId( $pageParams, 'fromdb' );
157 $titleObj = $pageObj->getTitle();
158 if ( !$titleObj ||
!$titleObj->exists() ) {
159 $this->dieUsage( "The page you specified doesn't exist", 'missingtitle' );
161 $wgTitle = $titleObj;
163 if ( isset( $prop['revid'] ) ) {
164 $oldid = $pageObj->getLatest();
167 $popts = $this->makeParserOptions( $pageObj, $params );
169 // Potentially cached
170 $p_result = $this->getParsedContent( $pageObj, $popts, $pageid,
171 isset( $prop['wikitext'] ) );
173 } else { // Not $oldid, $pageid, $page. Hence based on $text
174 $titleObj = Title
::newFromText( $title );
175 if ( !$titleObj ||
$titleObj->isExternal() ) {
176 $this->dieUsageMsg( array( 'invalidtitle', $title ) );
178 $wgTitle = $titleObj;
179 if ( $titleObj->canExist() ) {
180 $pageObj = WikiPage
::factory( $titleObj );
182 // Do like MediaWiki::initializeArticle()
183 $article = Article
::newFromTitle( $titleObj, $this->getContext() );
184 $pageObj = $article->getPage();
187 $popts = $this->makeParserOptions( $pageObj, $params );
188 $textProvided = !is_null( $text );
190 if ( !$textProvided ) {
191 if ( $titleProvided && ( $prop ||
$params['generatexml'] ) ) {
193 "'title' used without 'text', and parsed page properties were requested " .
194 "(did you mean to use 'page' instead of 'title'?)"
197 // Prevent warning from ContentHandler::makeContent()
201 // If we are parsing text, do not use the content model of the default
202 // API title, but default to wikitext to keep BC.
203 if ( $textProvided && !$titleProvided && is_null( $model ) ) {
204 $model = CONTENT_MODEL_WIKITEXT
;
205 $this->setWarning( "No 'title' or 'contentmodel' was given, assuming $model." );
209 $this->content
= ContentHandler
::makeContent( $text, $titleObj, $model, $format );
210 } catch ( MWContentSerializationException
$ex ) {
211 $this->dieUsage( $ex->getMessage(), 'parseerror' );
214 if ( $this->section
!== false ) {
215 if ( $this->section
=== 'new' ) {
216 // Insert the section title above the content.
217 if ( !is_null( $params['sectiontitle'] ) && $params['sectiontitle'] !== '' ) {
218 $this->content
= $this->content
->addSectionHeader( $params['sectiontitle'] );
221 $this->content
= $this->getSectionContent( $this->content
, $titleObj->getPrefixedText() );
225 if ( $params['pst'] ||
$params['onlypst'] ) {
226 $this->pstContent
= $this->content
->preSaveTransform( $titleObj, $this->getUser(), $popts );
228 if ( $params['onlypst'] ) {
229 // Build a result and bail out
230 $result_array = array();
231 $result_array['text'] = array();
232 ApiResult
::setContent( $result_array['text'], $this->pstContent
->serialize( $format ) );
233 if ( isset( $prop['wikitext'] ) ) {
234 $result_array['wikitext'] = array();
235 ApiResult
::setContent( $result_array['wikitext'], $this->content
->serialize( $format ) );
237 if ( !is_null( $params['summary'] ) ||
238 ( !is_null( $params['sectiontitle'] ) && $this->section
=== 'new' )
240 $result_array['parsedsummary'] = array();
241 ApiResult
::setContent( $result_array['parsedsummary'], $this->formatSummary( $titleObj, $params ) );
244 $result->addValue( null, $this->getModuleName(), $result_array );
249 // Not cached (save or load)
250 if ( $params['pst'] ) {
251 $p_result = $this->pstContent
->getParserOutput( $titleObj, null, $popts );
253 $p_result = $this->content
->getParserOutput( $titleObj, null, $popts );
257 $result_array = array();
259 $result_array['title'] = $titleObj->getPrefixedText();
261 if ( !is_null( $oldid ) ) {
262 $result_array['revid'] = intval( $oldid );
265 if ( $params['redirects'] && !is_null( $redirValues ) ) {
266 $result_array['redirects'] = $redirValues;
269 if ( $params['disabletoc'] ) {
270 $p_result->setTOCEnabled( false );
273 if ( isset( $prop['text'] ) ) {
274 $result_array['text'] = array();
275 ApiResult
::setContent( $result_array['text'], $p_result->getText() );
278 if ( !is_null( $params['summary'] ) ||
279 ( !is_null( $params['sectiontitle'] ) && $this->section
=== 'new' )
281 $result_array['parsedsummary'] = array();
282 ApiResult
::setContent( $result_array['parsedsummary'], $this->formatSummary( $titleObj, $params ) );
285 if ( isset( $prop['langlinks'] ) ) {
286 $langlinks = $p_result->getLanguageLinks();
288 if ( $params['effectivelanglinks'] ) {
289 // Link flags are ignored for now, but may in the future be
290 // included in the result.
291 $linkFlags = array();
292 Hooks
::run( 'LanguageLinks', array( $titleObj, &$langlinks, &$linkFlags ) );
298 if ( isset( $prop['langlinks'] ) ) {
299 $result_array['langlinks'] = $this->formatLangLinks( $langlinks );
301 if ( isset( $prop['categories'] ) ) {
302 $result_array['categories'] = $this->formatCategoryLinks( $p_result->getCategories() );
304 if ( isset( $prop['categorieshtml'] ) ) {
305 $categoriesHtml = $this->categoriesHtml( $p_result->getCategories() );
306 $result_array['categorieshtml'] = array();
307 ApiResult
::setContent( $result_array['categorieshtml'], $categoriesHtml );
309 if ( isset( $prop['links'] ) ) {
310 $result_array['links'] = $this->formatLinks( $p_result->getLinks() );
312 if ( isset( $prop['templates'] ) ) {
313 $result_array['templates'] = $this->formatLinks( $p_result->getTemplates() );
315 if ( isset( $prop['images'] ) ) {
316 $result_array['images'] = array_keys( $p_result->getImages() );
318 if ( isset( $prop['externallinks'] ) ) {
319 $result_array['externallinks'] = array_keys( $p_result->getExternalLinks() );
321 if ( isset( $prop['sections'] ) ) {
322 $result_array['sections'] = $p_result->getSections();
325 if ( isset( $prop['displaytitle'] ) ) {
326 $result_array['displaytitle'] = $p_result->getDisplayTitle() ?
327 $p_result->getDisplayTitle() :
328 $titleObj->getPrefixedText();
331 if ( isset( $prop['headitems'] ) ||
isset( $prop['headhtml'] ) ) {
332 $context = $this->getContext();
333 $context->setTitle( $titleObj );
334 $context->getOutput()->addParserOutputMetadata( $p_result );
336 if ( isset( $prop['headitems'] ) ) {
337 $headItems = $this->formatHeadItems( $p_result->getHeadItems() );
339 $css = $this->formatCss( $context->getOutput()->buildCssLinksArray() );
341 $scripts = array( $context->getOutput()->getHeadScripts() );
343 $result_array['headitems'] = array_merge( $headItems, $css, $scripts );
346 if ( isset( $prop['headhtml'] ) ) {
347 $result_array['headhtml'] = array();
348 ApiResult
::setContent(
349 $result_array['headhtml'],
350 $context->getOutput()->headElement( $context->getSkin() )
355 if ( isset( $prop['modules'] ) ) {
356 $result_array['modules'] = array_values( array_unique( $p_result->getModules() ) );
357 $result_array['modulescripts'] = array_values( array_unique( $p_result->getModuleScripts() ) );
358 $result_array['modulestyles'] = array_values( array_unique( $p_result->getModuleStyles() ) );
359 $result_array['modulemessages'] = array_values( array_unique( $p_result->getModuleMessages() ) );
362 if ( isset( $prop['indicators'] ) ) {
363 foreach ( $p_result->getIndicators() as $name => $content ) {
364 $indicator = array( 'name' => $name );
365 ApiResult
::setContent( $indicator, $content );
366 $result_array['indicators'][] = $indicator;
370 if ( isset( $prop['iwlinks'] ) ) {
371 $result_array['iwlinks'] = $this->formatIWLinks( $p_result->getInterwikiLinks() );
374 if ( isset( $prop['wikitext'] ) ) {
375 $result_array['wikitext'] = array();
376 ApiResult
::setContent( $result_array['wikitext'], $this->content
->serialize( $format ) );
377 if ( !is_null( $this->pstContent
) ) {
378 $result_array['psttext'] = array();
379 ApiResult
::setContent( $result_array['psttext'], $this->pstContent
->serialize( $format ) );
382 if ( isset( $prop['properties'] ) ) {
383 $result_array['properties'] = $this->formatProperties( $p_result->getProperties() );
386 if ( isset( $prop['limitreportdata'] ) ) {
387 $result_array['limitreportdata'] =
388 $this->formatLimitReportData( $p_result->getLimitReportData() );
390 if ( isset( $prop['limitreporthtml'] ) ) {
391 $limitreportHtml = EditPage
::getPreviewLimitReport( $p_result );
392 $result_array['limitreporthtml'] = array();
393 ApiResult
::setContent( $result_array['limitreporthtml'], $limitreportHtml );
396 if ( $params['generatexml'] ) {
397 if ( $this->content
->getModel() != CONTENT_MODEL_WIKITEXT
) {
398 $this->dieUsage( "generatexml is only supported for wikitext content", "notwikitext" );
401 $wgParser->startExternalParse( $titleObj, $popts, Parser
::OT_PREPROCESS
);
402 $dom = $wgParser->preprocessToDom( $this->content
->getNativeData() );
403 if ( is_callable( array( $dom, 'saveXML' ) ) ) {
404 $xml = $dom->saveXML();
406 $xml = $dom->__toString();
408 $result_array['parsetree'] = array();
409 ApiResult
::setContent( $result_array['parsetree'], $xml );
412 $result_mapping = array(
415 'categories' => 'cl',
419 'externallinks' => 'el',
424 'indicators' => 'ind',
425 'modulescripts' => 'm',
426 'modulestyles' => 'm',
427 'modulemessages' => 'm',
428 'properties' => 'pp',
429 'limitreportdata' => 'lr',
431 $this->setIndexedTagNames( $result_array, $result_mapping );
432 $result->addValue( null, $this->getModuleName(), $result_array );
436 * Constructs a ParserOptions object
438 * @param WikiPage $pageObj
439 * @param array $params
441 * @return ParserOptions
443 protected function makeParserOptions( WikiPage
$pageObj, array $params ) {
445 $popts = $pageObj->makeParserOptions( $this->getContext() );
446 $popts->enableLimitReport( !$params['disablepp'] );
447 $popts->setIsPreview( $params['preview'] ||
$params['sectionpreview'] );
448 $popts->setIsSectionPreview( $params['sectionpreview'] );
449 $popts->setEditSection( !$params['disableeditsection'] );
455 * @param WikiPage $page
456 * @param ParserOptions $popts
458 * @param bool $getWikitext
459 * @return ParserOutput
461 private function getParsedContent( WikiPage
$page, $popts, $pageId = null, $getWikitext = false ) {
462 $this->content
= $page->getContent( Revision
::RAW
); //XXX: really raw?
464 if ( $this->section
!== false && $this->content
!== null ) {
465 $this->content
= $this->getSectionContent(
467 !is_null( $pageId ) ?
'page id ' . $pageId : $page->getTitle()->getPrefixedText()
470 // Not cached (save or load)
471 return $this->content
->getParserOutput( $page->getTitle(), null, $popts );
474 // Try the parser cache first
475 // getParserOutput will save to Parser cache if able
476 $pout = $page->getParserOutput( $popts );
478 $this->dieUsage( "There is no revision ID {$page->getLatest()}", 'missingrev' );
480 if ( $getWikitext ) {
481 $this->content
= $page->getContent( Revision
::RAW
);
488 * @param Content $content
489 * @param string $what Identifies the content in error messages, e.g. page title.
490 * @return Content|bool
492 private function getSectionContent( Content
$content, $what ) {
493 // Not cached (save or load)
494 $section = $content->getSection( $this->section
);
495 if ( $section === false ) {
496 $this->dieUsage( "There is no section {$this->section} in " . $what, 'nosuchsection' );
498 if ( $section === null ) {
499 $this->dieUsage( "Sections are not supported by " . $what, 'nosuchsection' );
507 * This mimicks the behavior of EditPage in formatting a summary
509 * @param Title $title of the page being parsed
510 * @param Array $params the API parameters of the request
511 * @return Content|bool
513 private function formatSummary( $title, $params ) {
515 $summary = !is_null( $params['summary'] ) ?
$params['summary'] : '';
516 $sectionTitle = !is_null( $params['sectiontitle'] ) ?
$params['sectiontitle'] : '';
518 if ( $this->section
=== 'new' && ( $sectionTitle === '' ||
$summary === '' ) ) {
519 if( $sectionTitle !== '' ) {
520 $summary = $params['sectiontitle'];
522 if ( $summary !== '' ) {
523 $summary = wfMessage( 'newsectionsummary' )->rawParams( $wgParser->stripSectionName( $summary ) )
524 ->inContentLanguage()->text();
527 return Linker
::formatComment( $summary, $title, $this->section
=== 'new' );
530 private function formatLangLinks( $links ) {
532 foreach ( $links as $link ) {
534 $bits = explode( ':', $link, 2 );
535 $title = Title
::newFromText( $link );
537 $entry['lang'] = $bits[0];
539 $entry['url'] = wfExpandUrl( $title->getFullURL(), PROTO_CURRENT
);
540 // localised language name in 'uselang' language
541 $entry['langname'] = Language
::fetchLanguageName(
542 $title->getInterwiki(),
543 $this->getLanguage()->getCode()
546 // native language name
547 $entry['autonym'] = Language
::fetchLanguageName( $title->getInterwiki() );
549 ApiResult
::setContent( $entry, $bits[1] );
556 private function formatCategoryLinks( $links ) {
563 // Fetch hiddencat property
565 $lb->setArray( array( NS_CATEGORY
=> $links ) );
566 $db = $this->getDB();
567 $res = $db->select( array( 'page', 'page_props' ),
568 array( 'page_title', 'pp_propname' ),
569 $lb->constructSet( 'page', $db ),
572 array( 'page_props' => array(
573 'LEFT JOIN', array( 'pp_propname' => 'hiddencat', 'pp_page = page_id' )
576 $hiddencats = array();
577 foreach ( $res as $row ) {
578 $hiddencats[$row->page_title
] = isset( $row->pp_propname
);
581 foreach ( $links as $link => $sortkey ) {
583 $entry['sortkey'] = $sortkey;
584 ApiResult
::setContent( $entry, $link );
585 if ( !isset( $hiddencats[$link] ) ) {
586 $entry['missing'] = '';
587 } elseif ( $hiddencats[$link] ) {
588 $entry['hidden'] = '';
596 private function categoriesHtml( $categories ) {
597 $context = $this->getContext();
598 $context->getOutput()->addCategoryLinks( $categories );
600 return $context->getSkin()->getCategories();
603 private function formatLinks( $links ) {
605 foreach ( $links as $ns => $nslinks ) {
606 foreach ( $nslinks as $title => $id ) {
609 ApiResult
::setContent( $entry, Title
::makeTitle( $ns, $title )->getFullText() );
611 $entry['exists'] = '';
620 private function formatIWLinks( $iw ) {
622 foreach ( $iw as $prefix => $titles ) {
623 foreach ( array_keys( $titles ) as $title ) {
625 $entry['prefix'] = $prefix;
627 $title = Title
::newFromText( "{$prefix}:{$title}" );
629 $entry['url'] = wfExpandUrl( $title->getFullURL(), PROTO_CURRENT
);
632 ApiResult
::setContent( $entry, $title->getFullText() );
640 private function formatHeadItems( $headItems ) {
642 foreach ( $headItems as $tag => $content ) {
644 $entry['tag'] = $tag;
645 ApiResult
::setContent( $entry, $content );
652 private function formatProperties( $properties ) {
654 foreach ( $properties as $name => $value ) {
656 $entry['name'] = $name;
657 ApiResult
::setContent( $entry, $value );
664 private function formatCss( $css ) {
666 foreach ( $css as $file => $link ) {
668 $entry['file'] = $file;
669 ApiResult
::setContent( $entry, $link );
676 private function formatLimitReportData( $limitReportData ) {
678 $apiResult = $this->getResult();
680 foreach ( $limitReportData as $name => $value ) {
682 $entry['name'] = $name;
683 if ( !is_array( $value ) ) {
684 $value = array( $value );
686 $apiResult->setIndexedTagName( $value, 'param' );
687 $apiResult->setIndexedTagName_recursive( $value, 'param' );
688 $entry = array_merge( $entry, $value );
695 private function setIndexedTagNames( &$array, $mapping ) {
696 foreach ( $mapping as $key => $name ) {
697 if ( isset( $array[$key] ) ) {
698 $this->getResult()->setIndexedTagName( $array[$key], $name );
703 public function getAllowedParams() {
710 ApiBase
::PARAM_TYPE
=> 'integer',
712 'redirects' => false,
714 ApiBase
::PARAM_TYPE
=> 'integer',
717 ApiBase
::PARAM_DFLT
=> 'text|langlinks|categories|links|templates|' .
718 'images|externallinks|sections|revid|displaytitle|iwlinks|properties',
719 ApiBase
::PARAM_ISMULTI
=> true,
720 ApiBase
::PARAM_TYPE
=> array(
745 'effectivelanglinks' => false,
747 'sectiontitle' => array(
748 ApiBase
::PARAM_TYPE
=> 'string',
750 'disablepp' => false,
751 'disableeditsection' => false,
752 'generatexml' => array(
753 ApiBase
::PARAM_DFLT
=> false,
754 ApiBase
::PARAM_HELP_MSG
=> array(
755 'apihelp-parse-param-generatexml', CONTENT_MODEL_WIKITEXT
759 'sectionpreview' => false,
760 'disabletoc' => false,
761 'contentformat' => array(
762 ApiBase
::PARAM_TYPE
=> ContentHandler
::getAllContentFormats(),
764 'contentmodel' => array(
765 ApiBase
::PARAM_TYPE
=> ContentHandler
::getContentModels(),
770 protected function getExamplesMessages() {
772 'action=parse&page=Project:Sandbox'
773 => 'apihelp-parse-example-page',
774 'action=parse&text={{Project:Sandbox}}&contentmodel=wikitext'
775 => 'apihelp-parse-example-text',
776 'action=parse&text={{PAGENAME}}&title=Test'
777 => 'apihelp-parse-example-texttitle',
778 'action=parse&summary=Some+[[link]]&prop='
779 => 'apihelp-parse-example-summary',
783 public function getHelpUrls() {
784 return 'https://www.mediawiki.org/wiki/API:Parsing_wikitext#parse';