wiki.techinc.nl/includes/api/ApiExpandTemplates.php

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

262 lines
8.4 KiB
PHP
Raw Normal View History

2007-10-10 00:15:51 +00:00
<?php
/**
* Copyright © 2007 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
2007-10-10 00:15:51 +00:00
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
2007-10-10 00:15:51 +00:00
* http://www.gnu.org/copyleft/gpl.html
*
* @file
2007-10-10 00:15:51 +00:00
*/
namespace MediaWiki\Api;
use MediaWiki\Json\FormatJson;
use MediaWiki\Parser\Parser;
use MediaWiki\Parser\ParserFactory;
use MediaWiki\Parser\ParserOptions;
use MediaWiki\Revision\RevisionStore;
use MediaWiki\Title\Title;
use Wikimedia\ParamValidator\ParamValidator;
2007-10-10 00:15:51 +00:00
/**
2008-01-12 07:08:17 +00:00
* API module that functions as a shortcut to the wikitext preprocessor. Expands
* any templates in a provided string, and returns the result of this expansion
* to the caller.
*
* @ingroup API
2007-10-10 00:15:51 +00:00
*/
class ApiExpandTemplates extends ApiBase {
private RevisionStore $revisionStore;
private ParserFactory $parserFactory;
public function __construct(
ApiMain $main,
string $action,
RevisionStore $revisionStore,
ParserFactory $parserFactory
) {
parent::__construct( $main, $action );
$this->revisionStore = $revisionStore;
$this->parserFactory = $parserFactory;
}
2007-10-10 00:15:51 +00:00
public function execute() {
// Cache may vary on the user because ParserOptions gets data from it
$this->getMain()->setCacheMode( 'anon-public-user-private' );
2007-10-10 00:15:51 +00:00
// Get parameters
$params = $this->extractRequestParams();
$this->requireMaxOneParameter( $params, 'prop', 'generatexml' );
$title = $params['title'];
if ( $title === null ) {
$titleProvided = false;
// A title is needed for parsing, so arbitrarily choose one
$title = 'API';
} else {
$titleProvided = true;
}
if ( $params['prop'] === null ) {
$this->addDeprecation(
[ 'apiwarn-deprecation-missingparam', 'prop' ], 'action=expandtemplates&!prop'
);
$prop = [];
} else {
$prop = array_fill_keys( $params['prop'], true );
}
2007-10-10 00:15:51 +00:00
$titleObj = Title::newFromText( $title );
if ( !$titleObj || $titleObj->isExternal() ) {
$this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $params['title'] ) ] );
}
// Get title and revision ID for parser
$revid = $params['revid'];
if ( $revid !== null ) {
$rev = $this->revisionStore->getRevisionById( $revid );
if ( !$rev ) {
$this->dieWithError( [ 'apierror-nosuchrevid', $revid ] );
}
$pTitleObj = $titleObj;
$titleObj = Title::newFromLinkTarget( $rev->getPageAsLinkTarget() );
if ( $titleProvided && !$titleObj->equals( $pTitleObj ) ) {
$this->addWarning( [ 'apierror-revwrongpage', $rev->getId(),
wfEscapeWikiText( $pTitleObj->getPrefixedText() ) ] );
}
}
$result = $this->getResult();
2007-10-10 00:15:51 +00:00
// Parse text
$options = ParserOptions::newFromContext( $this->getContext() );
if ( $params['includecomments'] ) {
$options->setRemoveComments( false );
}
$reset = null;
$suppressCache = false;
Hooks::run() call site migration Migrate all callers of Hooks::run() to use the new HookContainer/HookRunner system. General principles: * Use DI if it is already used. We're not changing the way state is managed in this patch. * HookContainer is always injected, not HookRunner. HookContainer is a service, it's a more generic interface, it is the only thing that provides isRegistered() which is needed in some cases, and a HookRunner can be efficiently constructed from it (confirmed by benchmark). Because HookContainer is needed for object construction, it is also needed by all factories. * "Ask your friendly local base class". Big hierarchies like SpecialPage and ApiBase have getHookContainer() and getHookRunner() methods in the base class, and classes that extend that base class are not expected to know or care where the base class gets its HookContainer from. * ProtectedHookAccessorTrait provides protected getHookContainer() and getHookRunner() methods, getting them from the global service container. The point of this is to ease migration to DI by ensuring that call sites ask their local friendly base class rather than getting a HookRunner from the service container directly. * Private $this->hookRunner. In some smaller classes where accessor methods did not seem warranted, there is a private HookRunner property which is accessed directly. Very rarely (two cases), there is a protected property, for consistency with code that conventionally assumes protected=private, but in cases where the class might actually be overridden, a protected accessor is preferred over a protected property. * The last resort: Hooks::runner(). Mostly for static, file-scope and global code. In a few cases it was used for objects with broken construction schemes, out of horror or laziness. Constructors with new required arguments: * AuthManager * BadFileLookup * BlockManager * ClassicInterwikiLookup * ContentHandlerFactory * ContentSecurityPolicy * DefaultOptionsManager * DerivedPageDataUpdater * FullSearchResultWidget * HtmlCacheUpdater * LanguageFactory * LanguageNameUtils * LinkRenderer * LinkRendererFactory * LocalisationCache * MagicWordFactory * MessageCache * NamespaceInfo * PageEditStash * PageHandlerFactory * PageUpdater * ParserFactory * PermissionManager * RevisionStore * RevisionStoreFactory * SearchEngineConfig * SearchEngineFactory * SearchFormWidget * SearchNearMatcher * SessionBackend * SpecialPageFactory * UserNameUtils * UserOptionsManager * WatchedItemQueryService * WatchedItemStore Constructors with new optional arguments: * DefaultPreferencesFactory * Language * LinkHolderArray * MovePage * Parser * ParserCache * PasswordReset * Router setHookContainer() now required after construction: * AuthenticationProvider * ResourceLoaderModule * SearchEngine Change-Id: Id442b0dbe43aba84bd5cf801d86dedc768b082c7
2020-03-19 02:42:09 +00:00
$this->getHookRunner()->onApiMakeParserOptions(
$options, $titleObj, $params, $this, $reset, $suppressCache );
$retval = [];
if ( isset( $prop['parsetree'] ) || $params['generatexml'] ) {
$parser = $this->parserFactory->getInstance();
$parser->startExternalParse( $titleObj, $options, Parser::OT_PREPROCESS );
$dom = $parser->preprocessToDom( $params['text'] );
// @phan-suppress-next-line PhanUndeclaredMethodInCallable
if ( is_callable( [ $dom, 'saveXML' ] ) ) {
// @phan-suppress-next-line PhanUndeclaredMethod
$xml = $dom->saveXML();
} else {
// @phan-suppress-next-line PhanUndeclaredMethod
$xml = $dom->__toString();
}
if ( isset( $prop['parsetree'] ) ) {
unset( $prop['parsetree'] );
$retval['parsetree'] = $xml;
} else {
// the old way
$result->addValue( null, 'parsetree', $xml );
$result->addValue( null, ApiResult::META_BC_SUBELEMENTS, [ 'parsetree' ] );
}
}
2007-10-10 00:15:51 +00:00
// if they didn't want any output except (probably) the parse tree,
// then don't bother actually fully expanding it
if ( $prop || $params['prop'] === null ) {
$parser = $this->parserFactory->getInstance();
$parser->startExternalParse( $titleObj, $options, Parser::OT_PREPROCESS );
$frame = $parser->getPreprocessor()->newFrame();
$wikitext = $parser->preprocess( $params['text'], $titleObj, $options, $revid, $frame );
if ( $params['prop'] === null ) {
// the old way
API: Overhaul ApiResult, make format=xml not throw, and add json formatversion ApiResult was a mess: some methods could only be used with an array reference instead of manipulating the stored data, methods that had both array-ref and internal-data versions had names that didn't at all correspond, some methods that worked on an array reference were annoyingly non-static, and then the whole mess with setIndexedTagName. ApiFormatXml is also entirely annoying to deal with, as it liked to throw exceptions if certain metadata wasn't provided that no other formatter required. Its legacy also means we have this silly convention of using empty-string rather than boolean true, annoying restrictions on keys (leading to things that should be hashes being arrays of key-value object instead), '*' used as a key all over the place, and so on. So, changes here: * ApiResult is no longer an ApiBase or a ContextSource. * Wherever sensible, ApiResult provides a static method working on an arrayref and a non-static method working on internal data. * Metadata is now always added to ApiResult's internal data structure. Formatters are responsible for stripping it if necessary. "raw mode" is deprecated. * New metadata to replace the '*' key, solve the array() => '[]' vs '{}' question, and so on. * New class for formatting warnings and errors using i18n messages, and support for multiple errors and a more machine-readable format for warnings. For the moment, though, the actual output will not be changing yet (see T47843 for future plans). * New formatversion parameter for format=json and format=php, to select between BC mode and the modern output. * In BC mode, booleans will be converted to empty-string presence style; modules currently returning booleans will need to use ApiResult::META_BC_BOOLS to preserve their current output. Actual changes to the API modules' output (e.g. actually returning booleans for the new formatversion) beyond the use of ApiResult::setContentValue() are left for a future change. Bug: T76728 Bug: T57371 Bug: T33629 Change-Id: I7b37295e8862b188d1f3b0cd07f66ac34629678f
2014-12-03 22:14:22 +00:00
ApiResult::setContentValue( $retval, 'wikitext', $wikitext );
} else {
$p_output = $parser->getOutput();
if ( isset( $prop['categories'] ) ) {
$categories = $p_output->getCategoryNames();
if ( $categories ) {
$defaultSortKey = $p_output->getPageProperty( 'defaultsort' ) ?? '';
$categories_result = [];
foreach ( $categories as $category ) {
$entry = [
// Note that ::getCategorySortKey() returns
// the empty string '' to mean
// "use the default sort key"
'sortkey' => $p_output->getCategorySortKey( $category ) ?: $defaultSortKey,
];
ApiResult::setContentValue( $entry, 'category', $category );
$categories_result[] = $entry;
}
API: Overhaul ApiResult, make format=xml not throw, and add json formatversion ApiResult was a mess: some methods could only be used with an array reference instead of manipulating the stored data, methods that had both array-ref and internal-data versions had names that didn't at all correspond, some methods that worked on an array reference were annoyingly non-static, and then the whole mess with setIndexedTagName. ApiFormatXml is also entirely annoying to deal with, as it liked to throw exceptions if certain metadata wasn't provided that no other formatter required. Its legacy also means we have this silly convention of using empty-string rather than boolean true, annoying restrictions on keys (leading to things that should be hashes being arrays of key-value object instead), '*' used as a key all over the place, and so on. So, changes here: * ApiResult is no longer an ApiBase or a ContextSource. * Wherever sensible, ApiResult provides a static method working on an arrayref and a non-static method working on internal data. * Metadata is now always added to ApiResult's internal data structure. Formatters are responsible for stripping it if necessary. "raw mode" is deprecated. * New metadata to replace the '*' key, solve the array() => '[]' vs '{}' question, and so on. * New class for formatting warnings and errors using i18n messages, and support for multiple errors and a more machine-readable format for warnings. For the moment, though, the actual output will not be changing yet (see T47843 for future plans). * New formatversion parameter for format=json and format=php, to select between BC mode and the modern output. * In BC mode, booleans will be converted to empty-string presence style; modules currently returning booleans will need to use ApiResult::META_BC_BOOLS to preserve their current output. Actual changes to the API modules' output (e.g. actually returning booleans for the new formatversion) beyond the use of ApiResult::setContentValue() are left for a future change. Bug: T76728 Bug: T57371 Bug: T33629 Change-Id: I7b37295e8862b188d1f3b0cd07f66ac34629678f
2014-12-03 22:14:22 +00:00
ApiResult::setIndexedTagName( $categories_result, 'category' );
$retval['categories'] = $categories_result;
}
}
if ( isset( $prop['properties'] ) ) {
$properties = $p_output->getPageProperties();
if ( $properties ) {
ApiResult::setArrayType( $properties, 'BCkvp', 'name' );
ApiResult::setIndexedTagName( $properties, 'property' );
$retval['properties'] = $properties;
}
}
if ( isset( $prop['volatile'] ) ) {
$retval['volatile'] = $frame->isVolatile();
}
if ( isset( $prop['ttl'] ) && $frame->getTTL() !== null ) {
$retval['ttl'] = $frame->getTTL();
}
if ( isset( $prop['wikitext'] ) ) {
$retval['wikitext'] = $wikitext;
}
if ( isset( $prop['modules'] ) ) {
$retval['modules'] = array_values( array_unique( $p_output->getModules() ) );
// Deprecated since 1.32 (T188689)
$retval['modulescripts'] = [];
$retval['modulestyles'] = array_values( array_unique( $p_output->getModuleStyles() ) );
}
if ( isset( $prop['jsconfigvars'] ) ) {
$showStrategyKeys = (bool)( $params['showstrategykeys'] );
$retval['jsconfigvars'] =
ApiResult::addMetadataToResultVars( $p_output->getJsConfigVars( $showStrategyKeys ) );
}
if ( isset( $prop['encodedjsconfigvars'] ) ) {
$retval['encodedjsconfigvars'] = FormatJson::encode(
$p_output->getJsConfigVars(), false, FormatJson::ALL_OK
);
$retval[ApiResult::META_SUBELEMENTS][] = 'encodedjsconfigvars';
}
if ( isset( $prop['modules'] ) &&
!isset( $prop['jsconfigvars'] ) && !isset( $prop['encodedjsconfigvars'] ) ) {
$this->addWarning( 'apiwarn-moduleswithoutvars' );
}
}
}
ApiResult::setSubelementsList( $retval, [ 'wikitext', 'parsetree' ] );
$result->addValue( null, $this->getModuleName(), $retval );
2007-10-10 00:15:51 +00:00
}
public function getAllowedParams() {
return [
'title' => null,
'text' => [
ParamValidator::PARAM_TYPE => 'text',
ParamValidator::PARAM_REQUIRED => true,
],
'revid' => [
ParamValidator::PARAM_TYPE => 'integer',
],
'prop' => [
ParamValidator::PARAM_TYPE => [
'wikitext',
'categories',
'properties',
'volatile',
'ttl',
'modules',
'jsconfigvars',
'encodedjsconfigvars',
'parsetree',
],
ParamValidator::PARAM_ISMULTI => true,
ApiBase::PARAM_HELP_MSG_PER_VALUE => [],
],
'includecomments' => false,
'showstrategykeys' => false,
'generatexml' => [
ParamValidator::PARAM_TYPE => 'boolean',
ParamValidator::PARAM_DEPRECATED => true,
],
];
2007-10-10 00:15:51 +00:00
}
protected function getExamplesMessages() {
return [
'action=expandtemplates&text={{Project:Sandbox}}'
=> 'apihelp-expandtemplates-example-simple',
];
2007-10-10 00:15:51 +00:00
}
public function getHelpUrls() {
return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Expandtemplates';
}
2007-10-10 00:15:51 +00:00
}
/** @deprecated class alias since 1.43 */
class_alias( ApiExpandTemplates::class, 'ApiExpandTemplates' );