MediaWiki REL1_32
ApiOptions.php
Go to the documentation of this file.
1<?php
24
31class ApiOptions extends ApiBase {
34
38 public function execute() {
39 $user = $this->getUserForUpdates();
40 if ( !$user || $user->isAnon() ) {
41 $this->dieWithError(
42 [ 'apierror-mustbeloggedin', $this->msg( 'action-editmyoptions' ) ], 'notloggedin'
43 );
44 }
45
46 $this->checkUserRightsAny( 'editmyoptions' );
47
49 $changed = false;
50
51 if ( isset( $params['optionvalue'] ) && !isset( $params['optionname'] ) ) {
52 $this->dieWithError( [ 'apierror-missingparam', 'optionname' ] );
53 }
54
55 if ( $params['reset'] ) {
56 $this->resetPreferences( $params['resetkinds'] );
57 $changed = true;
58 }
59
60 $changes = [];
61 if ( $params['change'] ) {
62 foreach ( $params['change'] as $entry ) {
63 $array = explode( '=', $entry, 2 );
64 $changes[$array[0]] = $array[1] ?? null;
65 }
66 }
67 if ( isset( $params['optionname'] ) ) {
68 $newValue = $params['optionvalue'] ?? null;
69 $changes[$params['optionname']] = $newValue;
70 }
71 if ( !$changed && !count( $changes ) ) {
72 $this->dieWithError( 'apierror-nochanges' );
73 }
74
75 $prefs = $this->getPreferences();
76 $prefsKinds = $user->getOptionKinds( $this->getContext(), $changes );
77
78 $htmlForm = null;
79 foreach ( $changes as $key => $value ) {
80 switch ( $prefsKinds[$key] ) {
81 case 'registered':
82 // Regular option.
83 if ( $value === null ) {
84 // Reset it
85 $validation = true;
86 } else {
87 // Validate
88 if ( $htmlForm === null ) {
89 // We need a dummy HTMLForm for the validate callback...
90 $htmlForm = new HTMLForm( [], $this );
91 }
92 $field = HTMLForm::loadInputFromParameters( $key, $prefs[$key], $htmlForm );
93 $validation = $field->validate( $value, $user->getOptions() );
94 }
95 break;
96 case 'registered-multiselect':
97 case 'registered-checkmatrix':
98 // A key for a multiselect or checkmatrix option.
99 $validation = true;
100 $value = $value !== null ? (bool)$value : null;
101 break;
102 case 'userjs':
103 // Allow non-default preferences prefixed with 'userjs-', to be set by user scripts
104 if ( strlen( $key ) > 255 ) {
105 $validation = $this->msg( 'apiwarn-validationfailed-keytoolong', Message::numParam( 255 ) );
106 } elseif ( preg_match( '/[^a-zA-Z0-9_-]/', $key ) !== 0 ) {
107 $validation = $this->msg( 'apiwarn-validationfailed-badchars' );
108 } else {
109 $validation = true;
110 }
111 break;
112 case 'special':
113 $validation = $this->msg( 'apiwarn-validationfailed-cannotset' );
114 break;
115 case 'unused':
116 default:
117 $validation = $this->msg( 'apiwarn-validationfailed-badpref' );
118 break;
119 }
120 if ( $validation === true ) {
121 $this->setPreference( $key, $value );
122 $changed = true;
123 } else {
124 $this->addWarning( [ 'apiwarn-validationfailed', wfEscapeWikiText( $key ), $validation ] );
125 }
126 }
127
128 if ( $changed ) {
129 $this->commitChanges();
130 }
131
132 $this->getResult()->addValue( null, $this->getModuleName(), 'success' );
133 }
134
140 protected function getUserForUpdates() {
141 if ( !$this->userForUpdates ) {
142 $this->userForUpdates = $this->getUser()->getInstanceForUpdate();
143 }
144
146 }
147
152 protected function getPreferences() {
153 $preferencesFactory = MediaWikiServices::getInstance()->getPreferencesFactory();
154 return $preferencesFactory->getFormDescriptor( $this->getUserForUpdates(),
155 $this->getContext() );
156 }
157
161 protected function resetPreferences( array $kinds ) {
162 $this->getUserForUpdates()->resetOptions( $kinds, $this->getContext() );
163 }
164
171 protected function setPreference( $preference, $value ) {
172 $this->getUserForUpdates()->setOption( $preference, $value );
173 }
174
178 protected function commitChanges() {
179 $this->getUserForUpdates()->saveSettings();
180 }
181
182 public function mustBePosted() {
183 return true;
184 }
185
186 public function isWriteMode() {
187 return true;
188 }
189
190 public function getAllowedParams() {
191 $optionKinds = User::listOptionKinds();
192 $optionKinds[] = 'all';
193
194 return [
195 'reset' => false,
196 'resetkinds' => [
197 ApiBase::PARAM_TYPE => $optionKinds,
198 ApiBase::PARAM_DFLT => 'all',
200 ],
201 'change' => [
203 ],
204 'optionname' => [
205 ApiBase::PARAM_TYPE => 'string',
206 ],
207 'optionvalue' => [
208 ApiBase::PARAM_TYPE => 'string',
209 ],
210 ];
211 }
212
213 public function needsToken() {
214 return 'csrf';
215 }
216
217 public function getHelpUrls() {
218 return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Options';
219 }
220
221 protected function getExamplesMessages() {
222 return [
223 'action=options&reset=&token=123ABC'
224 => 'apihelp-options-example-reset',
225 'action=options&change=skin=vector|hideminor=1&token=123ABC'
226 => 'apihelp-options-example-change',
227 'action=options&reset=&change=skin=monobook&optionname=nickname&' .
228 'optionvalue=[[User:Beau|Beau]]%20([[User_talk:Beau|talk]])&token=123ABC'
229 => 'apihelp-options-example-complex',
230 ];
231 }
232}
wfEscapeWikiText( $text)
Escapes the given text so that it may be output using addWikiText() without any linking,...
This abstract class implements many basic API functions, and is the base of all API classes.
Definition ApiBase.php:37
checkUserRightsAny( $rights, $user=null)
Helper function for permission-denied errors.
Definition ApiBase.php:2095
dieWithError( $msg, $code=null, $data=null, $httpCode=null)
Abort execution with an error.
Definition ApiBase.php:1987
const PARAM_TYPE
(string|string[]) Either an array of allowed value strings, or a string type as described below.
Definition ApiBase.php:87
const PARAM_DFLT
(null|boolean|integer|string) Default value of the parameter.
Definition ApiBase.php:48
getResult()
Get the result object.
Definition ApiBase.php:659
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition ApiBase.php:770
addWarning( $msg, $code=null, $data=null)
Add a warning for this module.
Definition ApiBase.php:1906
getModuleName()
Get the name of the module being executed by this instance.
Definition ApiBase.php:539
const PARAM_ISMULTI
(boolean) Accept multiple pipe-separated values for this parameter (e.g.
Definition ApiBase.php:51
API module that facilitates the changing of user's preferences.
resetPreferences(array $kinds)
commitChanges()
Applies changes to user preferences.
isWriteMode()
Indicates whether this module requires write mode.
getExamplesMessages()
Returns usage examples for this module.
setPreference( $preference, $value)
Sets one user preference to be applied by commitChanges()
needsToken()
Returns the token type this module requires in order to execute.
getHelpUrls()
Return links to more detailed help pages about the module.
User $userForUpdates
User account to modify.
execute()
Changes preferences of the current user.
getAllowedParams()
Returns an array of allowed parameters (parameter name) => (default value) or (parameter name) => (ar...
getPreferences()
Returns preferences form descriptor.
mustBePosted()
Indicates whether this module must be called with a POST request.
getUserForUpdates()
Load the user from the master to reduce CAS errors on double post (T95839)
msg( $key)
Get a Message object with context set Parameters are the same as wfMessage()
getContext()
Get the base IContextSource object.
Object handling generic submission, CSRF protection, layout and other logic for UI forms.
Definition HTMLForm.php:136
MediaWikiServices is the service locator for the application scope of MediaWiki.
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition User.php:47
static listOptionKinds()
Return a list of the types of user options currently returned by User::getOptionKinds().
Definition User.php:3341
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return true
Definition hooks.txt:2055
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
$params