Translate extension for MediaWiki
Loading...
Searching...
No Matches
AggregateGroupsActionApi.php
1<?php
2declare( strict_types = 1 );
3
4namespace MediaWiki\Extension\Translate\MessageGroupProcessing;
5
6use MediaWiki\Api\ApiBase;
7use MediaWiki\Api\ApiMain;
8use MediaWiki\Extension\Translate\LogNames;
9use MediaWiki\Extension\Translate\MessageGroups\AggregateMessageGroup;
10use MediaWiki\Extension\Translate\MessageLoading\RebuildMessageIndexJob;
11use MediaWiki\Extension\Translate\MessageProcessing\MessageGroupMetadata;
12use MediaWiki\JobQueue\JobQueueGroup;
13use MediaWiki\Logger\LoggerFactory;
14use MediaWiki\Logging\ManualLogEntry;
15use Wikimedia\ParamValidator\ParamValidator;
16
27class AggregateGroupsActionApi extends ApiBase {
28
29 protected static string $right = 'translate-manage';
30
31 public function __construct(
32 ApiMain $main,
33 string $action,
34 private readonly JobQueueGroup $jobQueueGroup,
35 private readonly MessageGroupMetadata $messageGroupMetadata,
36 private readonly AggregateGroupManager $aggregateGroupManager,
37 ) {
38 parent::__construct( $main, $action );
39 }
40
41 public function execute(): void {
42 $this->checkUserRightsAny( self::$right );
43 $block = $this->getUser()->getBlock();
44 if ( $block && $block->isSitewide() ) {
45 $this->dieBlocked( $block );
46 }
47
48 $params = $this->extractRequestParams();
49 $action = $params['do'];
50 $output = [];
51 if ( $action === 'associate' || $action === 'dissociate' ) {
52 // Groups is mandatory only for these two actions
53 if ( !isset( $params['groups'] ) ) {
54 $this->dieWithError( [ 'apierror-missingparam', 'groups' ] );
55 }
56
57 $subgroupIds = array_map( 'trim', $params['groups'] );
58
59 if ( !isset( $params['aggregategroup'] ) ) {
60 $this->dieWithError( [ 'apierror-missingparam', 'aggregategroup' ] );
61 }
62
63 $aggregateGroupId = $params['aggregategroup'];
64
65 try {
66 if ( $action === 'associate' ) {
67 // Not all subgroups passed maybe added, as some may already be part of the aggregate group
68 $groupIdsToLog = $this->aggregateGroupManager->associate( $aggregateGroupId, $subgroupIds );
69 $output[ 'groupUrls'] = [];
70 foreach ( $groupIdsToLog as $subgroupId ) {
71 $output[ 'groupUrls'][ $subgroupId ] =
72 $this->aggregateGroupManager->getTargetTitleByGroupId( $subgroupId )->getFullURL();
73 }
74 } else {
75 $groupIdsToLog = $this->aggregateGroupManager->disassociate( $aggregateGroupId, $subgroupIds );
76 }
77 } catch (
81 ) {
82 $this->dieWithException( $e );
83 }
84
85 $logParams = [
86 'aggregategroup' => $this->messageGroupMetadata->get( $aggregateGroupId, 'name' ),
87 'aggregategroup-id' => $aggregateGroupId,
88 ];
89
90 foreach ( $groupIdsToLog as $subgroupId ) {
91 $title = $this->aggregateGroupManager->getTargetTitleByGroupId( $subgroupId );
92 $entry = new ManualLogEntry( 'pagetranslation', $action );
93 $entry->setPerformer( $this->getUser() );
94 $entry->setTarget( $title );
95 $entry->setParameters( $logParams );
96
97 $logId = $entry->insert();
98 $entry->publish( $logId );
99 }
100 } elseif ( $action === 'remove' ) {
101 if ( !isset( $params['aggregategroup'] ) ) {
102 $this->dieWithError( [ 'apierror-missingparam', 'aggregategroup' ] );
103 }
104
105 $aggregateGroupId = $params['aggregategroup'];
106 $group = MessageGroups::getGroup( $aggregateGroupId );
107 if ( !( $group instanceof AggregateMessageGroup ) ) {
108 $this->dieWithError(
109 'apierror-translate-invalidaggregategroupname',
110 'invalidaggregategroupname'
111 );
112 }
113
114 $this->messageGroupMetadata->deleteGroup( $params['aggregategroup'] );
115 $logger = LoggerFactory::getInstance( LogNames::MAIN );
116 $logger->info(
117 'Aggregate group {groupId} has been deleted.',
118 [ 'groupId' => $aggregateGroupId ]
119 );
120 } elseif ( $action === 'add' ) {
121 if ( !isset( $params['groupname'] ) ) {
122 $this->dieWithError( [ 'apierror-missingparam', 'groupname' ] );
123 }
124 $name = trim( $params['groupname'] );
125 if ( strlen( $name ) === 0 ) {
126 $this->dieWithError(
127 'apierror-translate-invalidaggregategroupname',
128 'invalidaggregategroupname'
129 );
130 }
131
132 $desc = trim( $params['groupdescription'] );
133 $languageCode = trim( $params['groupsourcelanguagecode'] );
134 $languageCode = $languageCode === AggregateMessageGroup::UNDETERMINED_LANGUAGE_CODE ?
135 null : $languageCode;
136 try {
137 $aggregateGroupId = $this->aggregateGroupManager->add( $name, $desc, $languageCode );
138 } catch ( DuplicateAggregateGroupException $e ) {
139 $this->dieWithException( $e );
140 }
141
142 // Once a new aggregate group is added, we need to show all the pages that can be added to that.
143 $output['groups'] = $this->getIncludableGroups();
144 $output['aggregategroupId'] = $aggregateGroupId;
145 // @todo Logging
146 } elseif ( $action === 'update' ) {
147 if ( !isset( $params['groupname'] ) ) {
148 $this->dieWithError( [ 'apierror-missingparam', 'groupname' ] );
149 }
150 $name = trim( $params['groupname'] );
151 if ( strlen( $name ) === 0 ) {
152 $this->dieWithError(
153 'apierror-translate-invalidaggregategroupname',
154 'invalidaggregategroupname'
155 );
156 }
157
158 $aggregateGroupId = $params['aggregategroup'];
159 $oldName = $this->messageGroupMetadata->get( $aggregateGroupId, 'name' );
160
161 // Error if the label exists already
162 $exists = MessageGroups::labelExists( $name );
163 if ( $exists && $oldName !== $name ) {
164 $this->dieWithException( new DuplicateAggregateGroupException( $name ) );
165 }
166
167 $desc = trim( $params['groupdescription'] );
168
169 $newLanguageCode = trim( $params['groupsourcelanguagecode'] );
170
171 $oldDesc = $this->messageGroupMetadata->get( $aggregateGroupId, 'description' );
172 $currentLanguageCode = $this->messageGroupMetadata->get( $aggregateGroupId, 'sourcelanguagecode' );
173
174 if (
175 $newLanguageCode !== AggregateMessageGroup::UNDETERMINED_LANGUAGE_CODE &&
176 $newLanguageCode !== $currentLanguageCode
177 ) {
178 $groupsWithDifferentLanguage =
179 $this->getGroupsWithDifferentLanguage( $aggregateGroupId, $newLanguageCode );
180
181 if ( count( $groupsWithDifferentLanguage ) ) {
182 $this->dieWithError( [
183 'translate-error-aggregategroup-source-language-mismatch',
184 implode( ', ', $groupsWithDifferentLanguage ),
185 $newLanguageCode,
186 count( $groupsWithDifferentLanguage )
187 ] );
188 }
189 }
190
191 if (
192 $oldName === $name
193 && $oldDesc === $desc
194 && $newLanguageCode === $currentLanguageCode
195 ) {
196 $this->dieWithError( 'apierror-translate-invalidupdate', 'invalidupdate' );
197 }
198 $this->messageGroupMetadata->set( $aggregateGroupId, 'name', $name );
199 $this->messageGroupMetadata->set( $aggregateGroupId, 'description', $desc );
200 if ( $newLanguageCode === AggregateMessageGroup::UNDETERMINED_LANGUAGE_CODE ) {
201 $this->messageGroupMetadata->clearMetadata( $aggregateGroupId, [ 'sourcelanguagecode' ] );
202 } else {
203 $this->messageGroupMetadata->set( $aggregateGroupId, 'sourcelanguagecode', $newLanguageCode );
204 }
205 }
206
207 // If we got this far, nothing has failed
208 $output['result'] = 'ok';
209 $this->getResult()->addValue( null, $this->getModuleName(), $output );
210 // Cache needs to be cleared after any changes to groups
211 MessageGroups::singleton()->recache();
212 $this->jobQueueGroup->push( RebuildMessageIndexJob::newJob() );
213 }
214
222 private function getGroupsWithDifferentLanguage(
223 string $aggregateGroupId,
224 string $sourceLanguageCode
225 ): array {
226 $groupsWithDifferentLanguage = [];
227 $subgroups = $this->messageGroupMetadata->getSubgroups( $aggregateGroupId );
228 foreach ( $subgroups as $group ) {
229 $messageGroup = MessageGroups::getGroup( $group );
230 $messageGroupLanguage = $messageGroup->getSourceLanguage();
231 if ( $messageGroupLanguage !== $sourceLanguageCode ) {
232 $groupsWithDifferentLanguage[] = $messageGroup->getLabel();
233 }
234 }
235
236 return $groupsWithDifferentLanguage;
237 }
238
239 public function isWriteMode(): bool {
240 return true;
241 }
242
243 public function needsToken(): string {
244 return 'csrf';
245 }
246
247 protected function getAllowedParams(): array {
248 return [
249 'do' => [
250 ParamValidator::PARAM_TYPE => [ 'associate', 'dissociate', 'remove', 'add', 'update' ],
251 ParamValidator::PARAM_REQUIRED => true,
252 ],
253 'aggregategroup' => [
254 ParamValidator::PARAM_TYPE => 'string',
255 ],
256 'groups' => [
257 // Not providing a list of values to allow dissociation of unknown groups
258 ParamValidator::PARAM_TYPE => 'string',
259 ParamValidator::PARAM_ISMULTI => true,
260 ],
261 'groupname' => [
262 ParamValidator::PARAM_TYPE => 'string',
263 ],
264 'groupdescription' => [
265 ParamValidator::PARAM_TYPE => 'string',
266 ParamValidator::PARAM_DEFAULT => '',
267 ],
268 'groupsourcelanguagecode' => [
269 ParamValidator::PARAM_TYPE => 'string',
270 ParamValidator::PARAM_DEFAULT => AggregateMessageGroup::UNDETERMINED_LANGUAGE_CODE,
271 ],
272 ];
273 }
274
275 protected function getExamplesMessages(): array {
276 return [
277 'action=aggregategroups&do=associate&groups=groupId1|groupId2&aggregategroup=aggregateGroupId'
278 => 'apihelp-aggregategroups-example-1',
279 ];
280 }
281
283 private function getIncludableGroups(): array {
284 $groups = MessageGroups::getAllGroups();
285 $pages = [];
286 foreach ( $groups as $group ) {
287 if ( $this->aggregateGroupManager->supportsAggregation( $group ) ) {
288 $pages[$group->getId()] = $group->getLabel( $this->getContext() );
289 }
290 }
291
292 return $pages;
293 }
294}
const MAIN
Default log channel for the extension.
Definition LogNames.php:15
Exception thrown when a message group could not be associated to an aggregate group.
Exception thrown when message group languages do not match the aggregate message group's language.
Contains logic to manage aggregate groups and their subgroups.
API module for managing aggregate message groups Only supports aggregate message groups defined insid...
Exception thrown when a duplicate aggregate group with the given name is found.
static labelExists(string $name)
Check if a particular aggregate group label exists.
Groups multiple message groups together as one group.
getGroup()
Get the primary MessageGroup this message belongs to.
Offers functionality for reading and updating Translate group related metadata.