MediaWiki  master
ApiOptions.php
Go to the documentation of this file.
1 <?php
24 
31 class ApiOptions extends ApiBase {
33  private $userForUpdates;
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 
48  $params = $this->extractRequestParams();
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 ( $htmlForm === null ) {
84  // We need a dummy HTMLForm for the validate callback...
85  $htmlForm = new HTMLForm( [], $this );
86  }
87  $field = HTMLForm::loadInputFromParameters( $key, $prefs[$key], $htmlForm );
88  $validation = $field->validate( $value, $user->getOptions() );
89  break;
90  case 'registered-multiselect':
91  case 'registered-checkmatrix':
92  // A key for a multiselect or checkmatrix option.
93  $validation = true;
94  $value = $value !== null ? (bool)$value : null;
95  break;
96  case 'userjs':
97  // Allow non-default preferences prefixed with 'userjs-', to be set by user scripts
98  if ( strlen( $key ) > 255 ) {
99  $validation = $this->msg( 'apiwarn-validationfailed-keytoolong', Message::numParam( 255 ) );
100  } elseif ( preg_match( '/[^a-zA-Z0-9_-]/', $key ) !== 0 ) {
101  $validation = $this->msg( 'apiwarn-validationfailed-badchars' );
102  } else {
103  $validation = true;
104  }
105  break;
106  case 'special':
107  $validation = $this->msg( 'apiwarn-validationfailed-cannotset' );
108  break;
109  case 'unused':
110  default:
111  $validation = $this->msg( 'apiwarn-validationfailed-badpref' );
112  break;
113  }
114  if ( $validation === true ) {
115  $this->setPreference( $key, $value );
116  $changed = true;
117  } else {
118  $this->addWarning( [ 'apiwarn-validationfailed', wfEscapeWikiText( $key ), $validation ] );
119  }
120  }
121 
122  if ( $changed ) {
123  $this->commitChanges();
124  }
125 
126  $this->getResult()->addValue( null, $this->getModuleName(), 'success' );
127  }
128 
134  protected function getUserForUpdates() {
135  if ( !$this->userForUpdates ) {
136  $this->userForUpdates = $this->getUser()->getInstanceForUpdate();
137  }
138 
139  return $this->userForUpdates;
140  }
141 
146  protected function getPreferences() {
147  $preferencesFactory = MediaWikiServices::getInstance()->getPreferencesFactory();
148  return $preferencesFactory->getFormDescriptor( $this->getUserForUpdates(),
149  $this->getContext() );
150  }
151 
155  protected function resetPreferences( array $kinds ) {
156  $this->getUserForUpdates()->resetOptions( $kinds, $this->getContext() );
157  }
158 
165  protected function setPreference( $preference, $value ) {
166  $this->getUserForUpdates()->setOption( $preference, $value );
167  }
168 
172  protected function commitChanges() {
173  $this->getUserForUpdates()->saveSettings();
174  }
175 
176  public function mustBePosted() {
177  return true;
178  }
179 
180  public function isWriteMode() {
181  return true;
182  }
183 
184  public function getAllowedParams() {
185  $optionKinds = User::listOptionKinds();
186  $optionKinds[] = 'all';
187 
188  return [
189  'reset' => false,
190  'resetkinds' => [
191  ApiBase::PARAM_TYPE => $optionKinds,
192  ApiBase::PARAM_DFLT => 'all',
194  ],
195  'change' => [
196  ApiBase::PARAM_ISMULTI => true,
197  ],
198  'optionname' => [
199  ApiBase::PARAM_TYPE => 'string',
200  ],
201  'optionvalue' => [
202  ApiBase::PARAM_TYPE => 'string',
203  ],
204  ];
205  }
206 
207  public function needsToken() {
208  return 'csrf';
209  }
210 
211  public function getHelpUrls() {
212  return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Options';
213  }
214 
215  protected function getExamplesMessages() {
216  return [
217  'action=options&reset=&token=123ABC'
218  => 'apihelp-options-example-reset',
219  'action=options&change=skin=vector|hideminor=1&token=123ABC'
220  => 'apihelp-options-example-change',
221  'action=options&reset=&change=skin=monobook&optionname=nickname&' .
222  'optionvalue=[[User:Beau|Beau]]%20([[User_talk:Beau|talk]])&token=123ABC'
223  => 'apihelp-options-example-complex',
224  ];
225  }
226 }
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))
const PARAM_TYPE
(string|string[]) Either an array of allowed value strings, or a string type as described below...
Definition: ApiBase.php:87
wfEscapeWikiText( $text)
Escapes the given text so that it may be output using addWikiText() without any linking, formatting, etc.
execute()
Changes preferences of the current user.
Definition: ApiOptions.php:38
getResult()
Get the result object.
Definition: ApiBase.php:659
setPreference( $preference, $value)
Sets one user preference to be applied by commitChanges()
Definition: ApiOptions.php:165
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
const PARAM_DFLT
(null|boolean|integer|string) Default value of the parameter.
Definition: ApiBase.php:48
getAllowedParams()
Definition: ApiOptions.php:184
$value
dieWithError( $msg, $code=null, $data=null, $httpCode=null)
Abort execution with an error.
Definition: ApiBase.php:1972
extractRequestParams( $options=[])
Using getAllowedParams(), this function makes an array of the values provided by the user...
Definition: ApiBase.php:770
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency MediaWikiServices
Definition: injection.txt:23
msg( $key)
Get a Message object with context set Parameters are the same as wfMessage()
static numParam( $num)
Definition: Message.php:1037
static listOptionKinds()
Return a list of the types of user options currently returned by User::getOptionKinds().
Definition: User.php:3320
User $userForUpdates
User account to modify.
Definition: ApiOptions.php:33
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:2041
static loadInputFromParameters( $fieldname, $descriptor, HTMLForm $parent=null)
Initialise a new Object for the field.
Definition: HTMLForm.php:482
commitChanges()
Applies changes to user preferences.
Definition: ApiOptions.php:172
getUserForUpdates()
Load the user from the master to reduce CAS errors on double post (T95839)
Definition: ApiOptions.php:134
getContext()
Get the base IContextSource object.
$params
getModuleName()
Get the name of the module being executed by this instance.
Definition: ApiBase.php:539
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
resetPreferences(array $kinds)
Definition: ApiOptions.php:155
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
API module that facilitates the changing of user&#39;s preferences.
Definition: ApiOptions.php:31
addWarning( $msg, $code=null, $data=null)
Add a warning for this module.
Definition: ApiBase.php:1896
const PARAM_ISMULTI
(boolean) Accept multiple pipe-separated values for this parameter (e.g.
Definition: ApiBase.php:51
getExamplesMessages()
Definition: ApiOptions.php:215
getPreferences()
Returns preferences form descriptor.
Definition: ApiOptions.php:146
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:2080
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a local account $user
Definition: hooks.txt:244