Localisation updates from https://translatewiki.net.
[mediawiki.git] / includes / api / ApiOptionsBase.php
blobdd0e4d28c48948f8a6a0f5e00296a0819ef05b1c
1 <?php
2 /**
3 * Copyright © 2012 Szymon Świerkosz beau@adres.pl
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
20 * @file
23 namespace MediaWiki\Api;
25 use MediaWiki\HTMLForm\HTMLForm;
26 use MediaWiki\Logger\LoggerFactory;
27 use MediaWiki\Message\Message;
28 use MediaWiki\Preferences\DefaultPreferencesFactory;
29 use MediaWiki\Preferences\PreferencesFactory;
30 use MediaWiki\User\Options\UserOptionsManager;
31 use MediaWiki\User\User;
32 use Wikimedia\ParamValidator\ParamValidator;
34 /**
35 * The base class for core's ApiOptions and two modules in the GlobalPreferences
36 * extension.
38 * @ingroup API
40 abstract class ApiOptionsBase extends ApiBase {
41 /** @var User User account to modify */
42 private $userForUpdates;
44 private UserOptionsManager $userOptionsManager;
45 private PreferencesFactory $preferencesFactory;
47 /** @var mixed[][]|null */
48 private $preferences;
50 /** @var HTMLForm|null */
51 private $htmlForm;
53 /** @var string[]|null */
54 private $prefsKinds;
56 /** @var array */
57 private $params;
59 public function __construct(
60 ApiMain $main,
61 string $action,
62 UserOptionsManager $userOptionsManager,
63 PreferencesFactory $preferencesFactory
64 ) {
65 parent::__construct( $main, $action );
66 $this->userOptionsManager = $userOptionsManager;
67 $this->preferencesFactory = $preferencesFactory;
70 /**
71 * Changes preferences of the current user.
73 public function execute() {
74 $user = $this->getUserForUpdatesOrNull();
75 if ( !$user || !$user->isNamed() ) {
76 $this->dieWithError(
77 [ 'apierror-mustbeloggedin', $this->msg( 'action-editmyoptions' ) ], 'notloggedin'
81 $this->checkUserRightsAny( 'editmyoptions' );
83 $params = $this->extractRequestParams();
84 $changed = false;
86 if ( isset( $params['optionvalue'] ) && !isset( $params['optionname'] ) ) {
87 $this->dieWithError( [ 'apierror-missingparam', 'optionname' ] );
90 $resetKinds = $params['resetkinds'];
91 if ( !$params['reset'] ) {
92 $resetKinds = [];
95 $changes = [];
96 if ( $params['change'] ) {
97 foreach ( $params['change'] as $entry ) {
98 $array = explode( '=', $entry, 2 );
99 $changes[$array[0]] = $array[1] ?? null;
102 if ( isset( $params['optionname'] ) ) {
103 $newValue = $params['optionvalue'] ?? null;
104 $changes[$params['optionname']] = $newValue;
107 $this->runHook( $user, $changes, $resetKinds );
109 if ( $resetKinds ) {
110 $this->resetPreferences( $resetKinds );
111 $changed = true;
114 if ( !$changed && !count( $changes ) ) {
115 $this->dieWithError( 'apierror-nochanges' );
118 $this->prefsKinds = $this->preferencesFactory->getResetKinds( $user, $this->getContext(), $changes );
120 foreach ( $changes as $key => $value ) {
121 if ( $this->shouldIgnoreKey( $key ) ) {
122 continue;
124 $validation = $this->validate( $key, $value );
125 if ( $validation === true ) {
126 $this->setPreference( $key, $value );
127 $changed = true;
128 } else {
129 $this->addWarning( [ 'apiwarn-validationfailed', wfEscapeWikiText( $key ), $validation ] );
133 if ( $changed ) {
134 $this->commitChanges();
137 $this->getResult()->addValue( null, $this->getModuleName(), 'success' );
141 * Run the ApiOptions hook if applicable
143 * @param User $user
144 * @param string[] $changes
145 * @param string[] $resetKinds
147 protected function runHook( $user, $changes, $resetKinds ) {
151 * Check whether a key should be ignored.
153 * This may be overridden to emit a warning as well as returning true.
155 * @param string $key
156 * @return bool
158 protected function shouldIgnoreKey( $key ) {
159 return false;
163 * Get the preference kinds for the current user's options.
164 * This can only be called after $this->prefsKinds is set in execute()
166 * @return string[]
168 protected function getPrefsKinds(): array {
169 return $this->prefsKinds;
173 * Get the HTMLForm for the user's preferences
175 * @return HTMLForm
177 protected function getHtmlForm() {
178 if ( !$this->htmlForm ) {
179 $this->htmlForm = new HTMLForm(
180 DefaultPreferencesFactory::simplifyFormDescriptor( $this->getPreferences() ),
181 $this
184 return $this->htmlForm;
188 * Validate a proposed change
190 * @param string $key
191 * @param mixed &$value
192 * @return bool|\MediaWiki\Message\Message|string
194 protected function validate( $key, &$value ) {
195 switch ( $this->getPrefsKinds()[$key] ) {
196 case 'registered':
197 // Regular option.
198 if ( $value === null ) {
199 // Reset it
200 $validation = true;
201 } else {
202 // Validate
203 $field = $this->getHtmlForm()->getField( $key );
204 $validation = $field->validate(
205 $value,
206 $this->userOptionsManager->getOptions( $this->getUserForUpdates() )
209 break;
210 case 'registered-multiselect':
211 case 'registered-checkmatrix':
212 // A key for a multiselect or checkmatrix option.
213 // TODO: Apply validation properly.
214 $validation = true;
215 $value = $value !== null ? (bool)$value : null;
216 break;
217 case 'userjs':
218 // Allow non-default preferences prefixed with 'userjs-', to be set by user scripts
219 if ( strlen( $key ) > 255 ) {
220 $validation = $this->msg( 'apiwarn-validationfailed-keytoolong', Message::numParam( 255 ) );
221 } elseif ( preg_match( '/[^a-zA-Z0-9_-]/', $key ) !== 0 ) {
222 $validation = $this->msg( 'apiwarn-validationfailed-badchars' );
223 } else {
224 $validation = true;
227 LoggerFactory::getInstance( 'api-warning' )->info(
228 'ApiOptions: Setting userjs option',
230 'phab' => 'T259073',
231 'OptionName' => substr( $key, 0, 255 ),
232 'OptionValue' => substr( $value ?? '', 0, 255 ),
233 'OptionSize' => strlen( $value ?? '' ),
234 'OptionValidation' => $validation,
235 'UserId' => $this->getUserForUpdates()->getId(),
236 'RequestIP' => $this->getRequest()->getIP(),
237 'RequestUA' => $this->getRequest()->getHeader( 'User-Agent' )
240 break;
241 case 'special':
242 $validation = $this->msg( 'apiwarn-validationfailed-cannotset' );
243 break;
244 case 'unused':
245 default:
246 $validation = $this->msg( 'apiwarn-validationfailed-badpref' );
247 break;
249 if ( $validation === true && is_string( $value ) &&
250 strlen( $value ) > UserOptionsManager::MAX_BYTES_OPTION_VALUE
252 $validation = $this->msg(
253 'apiwarn-validationfailed-valuetoolong',
254 Message::numParam( UserOptionsManager::MAX_BYTES_OPTION_VALUE )
257 return $validation;
261 * Load the user from the primary to reduce CAS errors on double post (T95839)
262 * Will throw if the user is anonymous.
264 * @return User
266 protected function getUserForUpdates(): User {
267 // @phan-suppress-next-line PhanTypeMismatchReturnNullable
268 return $this->getUserForUpdatesOrNull();
272 * Get the user for updates, or null if the user is anonymous
274 * @return User|null
276 protected function getUserForUpdatesOrNull(): ?User {
277 if ( !$this->userForUpdates ) {
278 $this->userForUpdates = $this->getUser()->getInstanceForUpdate();
281 return $this->userForUpdates;
285 * Returns preferences form descriptor
286 * @return mixed[][]
288 protected function getPreferences() {
289 if ( !$this->preferences ) {
290 $this->preferences = $this->preferencesFactory->getFormDescriptor(
291 $this->getUserForUpdates(),
292 $this->getContext()
295 return $this->preferences;
298 protected function getUserOptionsManager(): UserOptionsManager {
299 return $this->userOptionsManager;
302 protected function getPreferencesFactory(): PreferencesFactory {
303 return $this->preferencesFactory;
307 * Reset preferences of the specified kinds
309 * @param string[] $kinds One or more types returned by UserOptionsManager::listOptionKinds() or 'all'
311 abstract protected function resetPreferences( array $kinds );
314 * Sets one user preference to be applied by commitChanges()
316 * @param string $preference
317 * @param mixed $value
319 abstract protected function setPreference( $preference, $value );
322 * Applies changes to user preferences
324 abstract protected function commitChanges();
326 public function mustBePosted() {
327 return true;
330 public function isWriteMode() {
331 return true;
334 public function getAllowedParams() {
335 $optionKinds = $this->preferencesFactory->listResetKinds();
336 $optionKinds[] = 'all';
338 return [
339 'reset' => false,
340 'resetkinds' => [
341 ParamValidator::PARAM_TYPE => $optionKinds,
342 ParamValidator::PARAM_DEFAULT => 'all',
343 ParamValidator::PARAM_ISMULTI => true
345 'change' => [
346 ParamValidator::PARAM_ISMULTI => true,
348 'optionname' => [
349 ParamValidator::PARAM_TYPE => 'string',
351 'optionvalue' => [
352 ParamValidator::PARAM_TYPE => 'string',
357 public function needsToken() {
358 return 'csrf';
362 /** @deprecated class alias since 1.43 */
363 class_alias( ApiOptionsBase::class, 'ApiOptionsBase' );