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
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
;
35 * The base class for core's ApiOptions and two modules in the GlobalPreferences
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 */
50 /** @var HTMLForm|null */
53 /** @var string[]|null */
59 public function __construct(
62 UserOptionsManager
$userOptionsManager,
63 PreferencesFactory
$preferencesFactory
65 parent
::__construct( $main, $action );
66 $this->userOptionsManager
= $userOptionsManager;
67 $this->preferencesFactory
= $preferencesFactory;
71 * Changes preferences of the current user.
73 public function execute() {
74 $user = $this->getUserForUpdatesOrNull();
75 if ( !$user ||
!$user->isNamed() ) {
77 [ 'apierror-mustbeloggedin', $this->msg( 'action-editmyoptions' ) ], 'notloggedin'
81 $this->checkUserRightsAny( 'editmyoptions' );
83 $params = $this->extractRequestParams();
86 if ( isset( $params['optionvalue'] ) && !isset( $params['optionname'] ) ) {
87 $this->dieWithError( [ 'apierror-missingparam', 'optionname' ] );
90 $resetKinds = $params['resetkinds'];
91 if ( !$params['reset'] ) {
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 );
110 $this->resetPreferences( $resetKinds );
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 ) ) {
124 $validation = $this->validate( $key, $value );
125 if ( $validation === true ) {
126 $this->setPreference( $key, $value );
129 $this->addWarning( [ 'apiwarn-validationfailed', wfEscapeWikiText( $key ), $validation ] );
134 $this->commitChanges();
137 $this->getResult()->addValue( null, $this->getModuleName(), 'success' );
141 * Run the ApiOptions hook if applicable
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.
158 protected function shouldIgnoreKey( $key ) {
163 * Get the preference kinds for the current user's options.
164 * This can only be called after $this->prefsKinds is set in execute()
168 protected function getPrefsKinds(): array {
169 return $this->prefsKinds
;
173 * Get the HTMLForm for the user's preferences
177 protected function getHtmlForm() {
178 if ( !$this->htmlForm
) {
179 $this->htmlForm
= new HTMLForm(
180 DefaultPreferencesFactory
::simplifyFormDescriptor( $this->getPreferences() ),
184 return $this->htmlForm
;
188 * Validate a proposed change
191 * @param mixed &$value
192 * @return bool|\MediaWiki\Message\Message|string
194 protected function validate( $key, &$value ) {
195 switch ( $this->getPrefsKinds()[$key] ) {
198 if ( $value === null ) {
203 $field = $this->getHtmlForm()->getField( $key );
204 $validation = $field->validate(
206 $this->userOptionsManager
->getOptions( $this->getUserForUpdates() )
210 case 'registered-multiselect':
211 case 'registered-checkmatrix':
212 // A key for a multiselect or checkmatrix option.
213 // TODO: Apply validation properly.
215 $value = $value !== null ?
(bool)$value : null;
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' );
227 LoggerFactory
::getInstance( 'api-warning' )->info(
228 'ApiOptions: Setting userjs option',
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' )
242 $validation = $this->msg( 'apiwarn-validationfailed-cannotset' );
246 $validation = $this->msg( 'apiwarn-validationfailed-badpref' );
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
)
261 * Load the user from the primary to reduce CAS errors on double post (T95839)
262 * Will throw if the user is anonymous.
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
276 protected function getUserForUpdatesOrNull(): ?User
{
277 if ( !$this->userForUpdates
) {
278 $this->userForUpdates
= $this->getUser()->getInstanceForUpdate();
281 return $this->userForUpdates
;
285 * Returns preferences form descriptor
288 protected function getPreferences() {
289 if ( !$this->preferences
) {
290 $this->preferences
= $this->preferencesFactory
->getFormDescriptor(
291 $this->getUserForUpdates(),
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() {
330 public function isWriteMode() {
334 public function getAllowedParams() {
335 $optionKinds = $this->preferencesFactory
->listResetKinds();
336 $optionKinds[] = 'all';
341 ParamValidator
::PARAM_TYPE
=> $optionKinds,
342 ParamValidator
::PARAM_DEFAULT
=> 'all',
343 ParamValidator
::PARAM_ISMULTI
=> true
346 ParamValidator
::PARAM_ISMULTI
=> true,
349 ParamValidator
::PARAM_TYPE
=> 'string',
352 ParamValidator
::PARAM_TYPE
=> 'string',
357 public function needsToken() {
362 /** @deprecated class alias since 1.43 */
363 class_alias( ApiOptionsBase
::class, 'ApiOptionsBase' );