MediaWiki  1.29.2
ApiQueryAllMessages.php
Go to the documentation of this file.
1 <?php
33 
34  public function __construct( ApiQuery $query, $moduleName ) {
35  parent::__construct( $query, $moduleName, 'am' );
36  }
37 
38  public function execute() {
39  $params = $this->extractRequestParams();
40 
41  if ( is_null( $params['lang'] ) ) {
42  $langObj = $this->getLanguage();
43  } elseif ( !Language::isValidCode( $params['lang'] ) ) {
44  $this->dieWithError(
45  [ 'apierror-invalidlang', $this->encodeParamName( 'lang' ) ], 'invalidlang'
46  );
47  } else {
48  $langObj = Language::factory( $params['lang'] );
49  }
50 
51  if ( $params['enableparser'] ) {
52  if ( !is_null( $params['title'] ) ) {
53  $title = Title::newFromText( $params['title'] );
54  if ( !$title || $title->isExternal() ) {
55  $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $params['title'] ) ] );
56  }
57  } else {
58  $title = Title::newFromText( 'API' );
59  }
60  }
61 
62  $prop = array_flip( (array)$params['prop'] );
63 
64  // Determine which messages should we print
65  if ( in_array( '*', $params['messages'] ) ) {
66  $message_names = Language::getMessageKeysFor( $langObj->getCode() );
67  if ( $params['includelocal'] ) {
68  $message_names = array_unique( array_merge(
69  $message_names,
70  // Pass in the content language code so we get local messages that have a
71  // MediaWiki:msgkey page. We might theoretically miss messages that have no
72  // MediaWiki:msgkey page but do have a MediaWiki:msgkey/lang page, but that's
73  // just a stupid case.
74  MessageCache::singleton()->getAllMessageKeys( $this->getConfig()->get( 'LanguageCode' ) )
75  ) );
76  }
77  sort( $message_names );
78  $messages_target = $message_names;
79  } else {
80  $messages_target = $params['messages'];
81  }
82 
83  // Filter messages that have the specified prefix
84  // Because we sorted the message array earlier, they will appear in a clump:
85  if ( isset( $params['prefix'] ) ) {
86  $skip = false;
87  $messages_filtered = [];
88  foreach ( $messages_target as $message ) {
89  // === 0: must be at beginning of string (position 0)
90  if ( strpos( $message, $params['prefix'] ) === 0 ) {
91  if ( !$skip ) {
92  $skip = true;
93  }
94  $messages_filtered[] = $message;
95  } elseif ( $skip ) {
96  break;
97  }
98  }
99  $messages_target = $messages_filtered;
100  }
101 
102  // Filter messages that contain specified string
103  if ( isset( $params['filter'] ) ) {
104  $messages_filtered = [];
105  foreach ( $messages_target as $message ) {
106  // !== is used because filter can be at the beginning of the string
107  if ( strpos( $message, $params['filter'] ) !== false ) {
108  $messages_filtered[] = $message;
109  }
110  }
111  $messages_target = $messages_filtered;
112  }
113 
114  // Whether we have any sort of message customisation filtering
115  $customiseFilterEnabled = $params['customised'] !== 'all';
116  if ( $customiseFilterEnabled ) {
118 
119  $customisedMessages = AllMessagesTablePager::getCustomisedStatuses(
120  array_map(
121  [ $langObj, 'ucfirst' ],
122  $messages_target
123  ),
124  $langObj->getCode(),
125  !$langObj->equals( $wgContLang )
126  );
127 
128  $customised = $params['customised'] === 'modified';
129  }
130 
131  // Get all requested messages and print the result
132  $skip = !is_null( $params['from'] );
133  $useto = !is_null( $params['to'] );
134  $result = $this->getResult();
135  foreach ( $messages_target as $message ) {
136  // Skip all messages up to $params['from']
137  if ( $skip && $message === $params['from'] ) {
138  $skip = false;
139  }
140 
141  if ( $useto && $message > $params['to'] ) {
142  break;
143  }
144 
145  if ( !$skip ) {
146  $a = [
147  'name' => $message,
148  'normalizedname' => MessageCache::normalizeKey( $message ),
149  ];
150 
151  $args = [];
152  if ( isset( $params['args'] ) && count( $params['args'] ) != 0 ) {
153  $args = $params['args'];
154  }
155 
156  if ( $customiseFilterEnabled ) {
157  $messageIsCustomised = isset( $customisedMessages['pages'][$langObj->ucfirst( $message )] );
158  if ( $customised === $messageIsCustomised ) {
159  if ( $customised ) {
160  $a['customised'] = true;
161  }
162  } else {
163  continue;
164  }
165  }
166 
167  $msg = wfMessage( $message, $args )->inLanguage( $langObj );
168 
169  if ( !$msg->exists() ) {
170  $a['missing'] = true;
171  } else {
172  // Check if the parser is enabled:
173  if ( $params['enableparser'] ) {
174  $msgString = $msg->title( $title )->text();
175  } else {
176  $msgString = $msg->plain();
177  }
178  if ( !$params['nocontent'] ) {
179  ApiResult::setContentValue( $a, 'content', $msgString );
180  }
181  if ( isset( $prop['default'] ) ) {
182  $default = wfMessage( $message )->inLanguage( $langObj )->useDatabase( false );
183  if ( !$default->exists() ) {
184  $a['defaultmissing'] = true;
185  } elseif ( $default->plain() != $msgString ) {
186  $a['default'] = $default->plain();
187  }
188  }
189  }
190  $fit = $result->addValue( [ 'query', $this->getModuleName() ], null, $a );
191  if ( !$fit ) {
192  $this->setContinueEnumParameter( 'from', $message );
193  break;
194  }
195  }
196  }
197  $result->addIndexedTagName( [ 'query', $this->getModuleName() ], 'message' );
198  }
199 
200  public function getCacheMode( $params ) {
201  if ( is_null( $params['lang'] ) ) {
202  // Language not specified, will be fetched from preferences
203  return 'anon-public-user-private';
204  } elseif ( $params['enableparser'] ) {
205  // User-specific parser options will be used
206  return 'anon-public-user-private';
207  } else {
208  // OK to cache
209  return 'public';
210  }
211  }
212 
213  public function getAllowedParams() {
214  return [
215  'messages' => [
216  ApiBase::PARAM_DFLT => '*',
217  ApiBase::PARAM_ISMULTI => true,
218  ],
219  'prop' => [
220  ApiBase::PARAM_ISMULTI => true,
222  'default'
223  ]
224  ],
225  'enableparser' => false,
226  'nocontent' => false,
227  'includelocal' => false,
228  'args' => [
229  ApiBase::PARAM_ISMULTI => true,
231  ],
232  'filter' => [],
233  'customised' => [
234  ApiBase::PARAM_DFLT => 'all',
236  'all',
237  'modified',
238  'unmodified'
239  ]
240  ],
241  'lang' => null,
242  'from' => null,
243  'to' => null,
244  'title' => null,
245  'prefix' => null,
246  ];
247  }
248 
249  protected function getExamplesMessages() {
250  return [
251  'action=query&meta=allmessages&amprefix=ipb-'
252  => 'apihelp-query+allmessages-example-ipb',
253  'action=query&meta=allmessages&ammessages=august|mainpage&amlang=de'
254  => 'apihelp-query+allmessages-example-de',
255  ];
256  }
257 
258  public function getHelpUrls() {
259  return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Allmessages';
260  }
261 }
ContextSource\getConfig
getConfig()
Get the Config object.
Definition: ContextSource.php:68
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:265
ApiQuery
This is the main query class.
Definition: ApiQuery.php:40
ApiQueryAllMessages\getExamplesMessages
getExamplesMessages()
Returns usage examples for this module.
Definition: ApiQueryAllMessages.php:249
MessageCache\normalizeKey
static normalizeKey( $key)
Normalize message key input.
Definition: MessageCache.php:145
ApiQueryAllMessages\getHelpUrls
getHelpUrls()
Return links to more detailed help pages about the module.
Definition: ApiQueryAllMessages.php:258
captcha-old.count
count
Definition: captcha-old.py:225
ApiBase\dieWithError
dieWithError( $msg, $code=null, $data=null, $httpCode=null)
Abort execution with an error.
Definition: ApiBase.php:1796
$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. Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page. Return false to stop further processing of the tag $reader:XMLReader object & $pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports. & $fullInterwikiPrefix:Interwiki prefix, may contain colons. & $pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable. Can be used to lazy-load the import sources list. & $importSources:The value of $wgImportSources. Modify as necessary. See the comment in DefaultSettings.php for the detail of how to structure this array. '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 '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 '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 '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. '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 IP::isTrustedProxy() & $ip:IP being check & $result:Change this value to override the result of IP::isTrustedProxy() '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 Sanitizer::validateEmail(), 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. '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) '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 '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:Array with elements of the form "language:title" in the order that they will be output. & $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. 'LanguageSelector':Hook to change the language selector available on a page. $out:The output page. $cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED! Use HtmlPageLinkRendererBegin instead. 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:1954
ApiBase\PARAM_TYPE
const PARAM_TYPE
(string|string[]) Either an array of allowed value strings, or a string type as described below.
Definition: ApiBase.php:91
ApiBase\getResult
getResult()
Get the result object.
Definition: ApiBase.php:610
ApiQueryAllMessages\__construct
__construct(ApiQuery $query, $moduleName)
Definition: ApiQueryAllMessages.php:34
$params
$params
Definition: styleTest.css.php:40
ApiBase\PARAM_ALLOW_DUPLICATES
const PARAM_ALLOW_DUPLICATES
(boolean) Allow the same value to be set more than once when PARAM_ISMULTI is true?
Definition: ApiBase.php:106
php
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
ContextSource\getLanguage
getLanguage()
Get the Language object.
Definition: ContextSource.php:143
ApiQueryAllMessages\execute
execute()
Evaluates the parameters, performs the requested query, and sets up the result.
Definition: ApiQueryAllMessages.php:38
ApiResult\setContentValue
static setContentValue(array &$arr, $name, $value, $flags=0)
Add an output value to the array by name and mark as META_CONTENT.
Definition: ApiResult.php:478
$query
null for the wiki Added should default to null in handler for backwards compatibility add a value to it if you want to add a cookie that have to vary cache options can modify $query
Definition: hooks.txt:1572
AllMessagesTablePager\getCustomisedStatuses
static getCustomisedStatuses( $messageNames, $langcode='en', $foreign=false)
Determine which of the MediaWiki and MediaWiki_talk namespace pages exist.
Definition: AllMessagesTablePager.php:200
$title
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:934
ApiQueryBase
This is a base class for all Query modules.
Definition: ApiQueryBase.php:37
ApiQueryAllMessages\getCacheMode
getCacheMode( $params)
Get the cache mode for the data generated by this module.
Definition: ApiQueryAllMessages.php:200
global
when a variable name is used in a it is silently declared as a new masking the global
Definition: design.txt:93
MessageCache\singleton
static singleton()
Get the signleton instance of this class.
Definition: MessageCache.php:113
ApiBase\extractRequestParams
extractRequestParams( $parseLimit=true)
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition: ApiBase.php:718
ApiBase\encodeParamName
encodeParamName( $paramName)
This method mangles parameter name based on the prefix supplied to the constructor.
Definition: ApiBase.php:699
ApiQueryAllMessages
A query action to return messages from site message cache.
Definition: ApiQueryAllMessages.php:32
wfEscapeWikiText
wfEscapeWikiText( $text)
Escapes the given text so that it may be output using addWikiText() without any linking,...
Definition: GlobalFunctions.php:1657
Language\isValidCode
static isValidCode( $code)
Returns true if a language code string is of a valid form, whether or not it exists.
Definition: Language.php:337
$args
if( $line===false) $args
Definition: cdb.php:63
ApiQueryAllMessages\getAllowedParams
getAllowedParams()
Returns an array of allowed parameters (parameter name) => (default value) or (parameter name) => (ar...
Definition: ApiQueryAllMessages.php:213
ApiBase\PARAM_DFLT
const PARAM_DFLT
(null|boolean|integer|string) Default value of the parameter.
Definition: ApiBase.php:52
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:490
ApiBase\PARAM_ISMULTI
const PARAM_ISMULTI
(boolean) Accept multiple pipe-separated values for this parameter (e.g.
Definition: ApiBase.php:55
Language\getMessageKeysFor
static getMessageKeysFor( $code)
Get all message keys for a given language.
Definition: Language.php:4488
Language\factory
static factory( $code)
Get a cached or new language object for a given language code.
Definition: Language.php:183
wfMessage
either a unescaped string or a HtmlArmor object after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation 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
ApiQueryBase\setContinueEnumParameter
setContinueEnumParameter( $paramName, $paramValue)
Set a query-continue value.
Definition: ApiQueryBase.php:535
array
the array() calling protocol came about after MediaWiki 1.4rc1.
$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