MediaWiki  master
ApiQueryAllMessages.php
Go to the documentation of this file.
1 <?php
27 
34 
36  private $contentLanguage;
37 
39  private $languageFactory;
40 
42  private $languageNameUtils;
43 
45  private $localisationCache;
46 
48  private $messageCache;
49 
59  public function __construct(
60  ApiQuery $query,
61  $moduleName,
62  Language $contentLanguage,
63  LanguageFactory $languageFactory,
64  LanguageNameUtils $languageNameUtils,
65  LocalisationCache $localisationCache,
66  MessageCache $messageCache
67  ) {
68  parent::__construct( $query, $moduleName, 'am' );
69  $this->contentLanguage = $contentLanguage;
70  $this->languageFactory = $languageFactory;
71  $this->languageNameUtils = $languageNameUtils;
72  $this->localisationCache = $localisationCache;
73  $this->messageCache = $messageCache;
74  }
75 
76  public function execute() {
77  $params = $this->extractRequestParams();
78  if ( $params['lang'] === null ) {
79  $langObj = $this->getLanguage();
80  } elseif ( !$this->languageNameUtils->isValidCode( $params['lang'] ) ) {
81  $this->dieWithError(
82  [ 'apierror-invalidlang', $this->encodeParamName( 'lang' ) ], 'invalidlang'
83  );
84  } else {
85  $langObj = $this->languageFactory->getLanguage( $params['lang'] );
86  }
87 
88  if ( $params['enableparser'] ) {
89  if ( $params['title'] !== null ) {
90  $title = Title::newFromText( $params['title'] );
91  if ( !$title || $title->isExternal() ) {
92  $this->dieWithError( [ 'apierror-invalidtitle', wfEscapeWikiText( $params['title'] ) ] );
93  }
94  } else {
95  $title = Title::newFromText( 'API' );
96  }
97  }
98 
99  $prop = array_fill_keys( (array)$params['prop'], true );
100 
101  // Determine which messages should we print
102  if ( in_array( '*', $params['messages'] ) ) {
103  $message_names = $this->localisationCache->getSubitemList( $langObj->getCode(), 'messages' ) ?? [];
104  if ( $params['includelocal'] ) {
105  $message_names = array_unique( array_merge(
106  $message_names,
107  // Pass in the content language code so we get local messages that have a
108  // MediaWiki:msgkey page. We might theoretically miss messages that have no
109  // MediaWiki:msgkey page but do have a MediaWiki:msgkey/lang page, but that's
110  // just a stupid case.
111  $this->messageCache->getAllMessageKeys( $this->contentLanguage->getCode() )
112  ) );
113  }
114  sort( $message_names );
115  $messages_target = $message_names;
116  } else {
117  $messages_target = $params['messages'];
118  }
119 
120  // Filter messages that have the specified prefix
121  // Because we sorted the message array earlier, they will appear in a clump:
122  if ( isset( $params['prefix'] ) ) {
123  $skip = false;
124  $messages_filtered = [];
125  foreach ( $messages_target as $message ) {
126  if ( str_starts_with( $message, $params['prefix'] ) ) {
127  if ( !$skip ) {
128  $skip = true;
129  }
130  $messages_filtered[] = $message;
131  } elseif ( $skip ) {
132  break;
133  }
134  }
135  $messages_target = $messages_filtered;
136  }
137 
138  // Filter messages that contain specified string
139  if ( isset( $params['filter'] ) ) {
140  $messages_filtered = [];
141  foreach ( $messages_target as $message ) {
142  if ( str_contains( $message, $params['filter'] ) ) {
143  $messages_filtered[] = $message;
144  }
145  }
146  $messages_target = $messages_filtered;
147  }
148 
149  // Whether we have any sort of message customisation filtering
150  $customiseFilterEnabled = $params['customised'] !== 'all';
151  if ( $customiseFilterEnabled ) {
152  $customisedMessages = AllMessagesTablePager::getCustomisedStatuses(
153  array_map(
154  [ $langObj, 'ucfirst' ],
155  $messages_target
156  ),
157  $langObj->getCode(),
158  !$langObj->equals( $this->contentLanguage ),
159  $this->getDB()
160  );
161 
162  $customised = $params['customised'] === 'modified';
163  }
164 
165  // Get all requested messages and print the result
166  $skip = $params['from'] !== null;
167  $useto = $params['to'] !== null;
168  $result = $this->getResult();
169  foreach ( $messages_target as $message ) {
170  // Skip all messages up to $params['from']
171  if ( $skip && $message === $params['from'] ) {
172  $skip = false;
173  }
174 
175  if ( $useto && $message > $params['to'] ) {
176  break;
177  }
178 
179  if ( !$skip ) {
180  $a = [
181  'name' => $message,
182  'normalizedname' => MessageCache::normalizeKey( $message ),
183  ];
184 
185  $args = [];
186  if ( isset( $params['args'] ) && count( $params['args'] ) != 0 ) {
187  $args = $params['args'];
188  }
189 
190  if ( $customiseFilterEnabled ) {
191  $messageIsCustomised = isset( $customisedMessages['pages'][$langObj->ucfirst( $message )] );
192  // @phan-suppress-next-line PhanPossiblyUndeclaredVariable customised is set when used
193  if ( $customised === $messageIsCustomised ) {
194  // @phan-suppress-next-line PhanPossiblyUndeclaredVariable customised is set when used
195  if ( $customised ) {
196  $a['customised'] = true;
197  }
198  } else {
199  continue;
200  }
201  }
202 
203  $msg = $this->msg( $message, $args )->inLanguage( $langObj );
204 
205  if ( !$msg->exists() ) {
206  $a['missing'] = true;
207  } else {
208  // Check if the parser is enabled:
209  if ( $params['enableparser'] ) {
210  // @phan-suppress-next-line PhanPossiblyUndeclaredVariable title is set when used
211  $msgString = $msg->page( $title )->text();
212  } else {
213  $msgString = $msg->plain();
214  }
215  if ( !$params['nocontent'] ) {
216  ApiResult::setContentValue( $a, 'content', $msgString );
217  }
218  if ( isset( $prop['default'] ) ) {
219  $default = $this->msg( $message )->inLanguage( $langObj )->useDatabase( false );
220  if ( !$default->exists() ) {
221  $a['defaultmissing'] = true;
222  } elseif ( $default->plain() != $msgString ) {
223  $a['default'] = $default->plain();
224  }
225  }
226  }
227  $fit = $result->addValue( [ 'query', $this->getModuleName() ], null, $a );
228  if ( !$fit ) {
229  $this->setContinueEnumParameter( 'from', $message );
230  break;
231  }
232  }
233  }
234  $result->addIndexedTagName( [ 'query', $this->getModuleName() ], 'message' );
235  }
236 
237  public function getCacheMode( $params ) {
238  if ( $params['lang'] === null ) {
239  // Language not specified, will be fetched from preferences
240  return 'anon-public-user-private';
241  } elseif ( $params['enableparser'] ) {
242  // User-specific parser options will be used
243  return 'anon-public-user-private';
244  } else {
245  // OK to cache
246  return 'public';
247  }
248  }
249 
250  public function getAllowedParams() {
251  return [
252  'messages' => [
253  ParamValidator::PARAM_DEFAULT => '*',
254  ParamValidator::PARAM_ISMULTI => true,
255  ],
256  'prop' => [
257  ParamValidator::PARAM_ISMULTI => true,
258  ParamValidator::PARAM_TYPE => [
259  'default'
260  ]
261  ],
262  'enableparser' => false,
263  'nocontent' => false,
264  'includelocal' => false,
265  'args' => [
266  ParamValidator::PARAM_ISMULTI => true,
267  ParamValidator::PARAM_ALLOW_DUPLICATES => true,
268  ],
269  'filter' => [],
270  'customised' => [
271  ParamValidator::PARAM_DEFAULT => 'all',
272  ParamValidator::PARAM_TYPE => [
273  'all',
274  'modified',
275  'unmodified'
276  ]
277  ],
278  'lang' => null,
279  'from' => null,
280  'to' => null,
281  'title' => null,
282  'prefix' => null,
283  ];
284  }
285 
286  protected function getExamplesMessages() {
287  return [
288  'action=query&meta=allmessages&amprefix=ipb-'
289  => 'apihelp-query+allmessages-example-ipb',
290  'action=query&meta=allmessages&ammessages=august|mainpage&amlang=de'
291  => 'apihelp-query+allmessages-example-de',
292  ];
293  }
294 
295  public function getHelpUrls() {
296  return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Allmessages';
297  }
298 }
wfEscapeWikiText( $text)
Escapes the given text so that it may be output using addWikiText() without any linking,...
static getCustomisedStatuses( $messageNames, $langcode='en', $foreign=false, IDatabase $dbr=null)
Determine which of the MediaWiki and MediaWiki_talk namespace pages exist.
dieWithError( $msg, $code=null, $data=null, $httpCode=0)
Abort execution with an error.
Definition: ApiBase.php:1460
encodeParamName( $paramName)
This method mangles parameter name based on the prefix supplied to the constructor.
Definition: ApiBase.php:751
getResult()
Get the result object.
Definition: ApiBase.php:637
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition: ApiBase.php:773
getModuleName()
Get the name of the module being executed by this instance.
Definition: ApiBase.php:506
A query action to return messages from site message cache.
execute()
Evaluates the parameters, performs the requested query, and sets up the result.
getAllowedParams()
Returns an array of allowed parameters (parameter name) => (default value) or (parameter name) => (ar...
getCacheMode( $params)
Get the cache mode for the data generated by this module.
getHelpUrls()
Return links to more detailed help pages about the module.
__construct(ApiQuery $query, $moduleName, Language $contentLanguage, LanguageFactory $languageFactory, LanguageNameUtils $languageNameUtils, LocalisationCache $localisationCache, MessageCache $messageCache)
getExamplesMessages()
Returns usage examples for this module.
This is a base class for all Query modules.
setContinueEnumParameter( $paramName, $paramValue)
Set a query-continue value.
This is the main query class.
Definition: ApiQuery.php:42
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:467
msg( $key,... $params)
Get a Message object with context set Parameters are the same as wfMessage()
Base class for language-specific code.
Definition: Language.php:56
Caching for the contents of localisation files.
Internationalisation code See https://www.mediawiki.org/wiki/Special:MyLanguage/Localisation for more...
A service that provides utilities to do with language names and codes.
Represents a title within MediaWiki.
Definition: Title.php:82
Cache messages that are defined by MediaWiki-namespace pages or by hooks.
static normalizeKey( $key)
Normalize message key input.
Service for formatting and validating API parameters.