MediaWiki  1.29.1
ApiOptions.php
Go to the documentation of this file.
1 <?php
33 class ApiOptions extends ApiBase {
37  public function execute() {
38  if ( $this->getUser()->isAnon() ) {
39  $this->dieWithError(
40  [ 'apierror-mustbeloggedin', $this->msg( 'action-editmyoptions' ) ], 'notloggedin'
41  );
42  }
43 
44  $this->checkUserRightsAny( 'editmyoptions' );
45 
46  $params = $this->extractRequestParams();
47  $changed = false;
48 
49  if ( isset( $params['optionvalue'] ) && !isset( $params['optionname'] ) ) {
50  $this->dieWithError( [ 'apierror-missingparam', 'optionname' ] );
51  }
52 
53  // Load the user from the master to reduce CAS errors on double post (T95839)
54  $user = $this->getUser()->getInstanceForUpdate();
55  if ( !$user ) {
56  $this->dieWithError(
57  [ 'apierror-mustbeloggedin', $this->msg( 'action-editmyoptions' ) ], 'notloggedin'
58  );
59  }
60 
61  if ( $params['reset'] ) {
62  $user->resetOptions( $params['resetkinds'], $this->getContext() );
63  $changed = true;
64  }
65 
66  $changes = [];
67  if ( count( $params['change'] ) ) {
68  foreach ( $params['change'] as $entry ) {
69  $array = explode( '=', $entry, 2 );
70  $changes[$array[0]] = isset( $array[1] ) ? $array[1] : null;
71  }
72  }
73  if ( isset( $params['optionname'] ) ) {
74  $newValue = isset( $params['optionvalue'] ) ? $params['optionvalue'] : null;
75  $changes[$params['optionname']] = $newValue;
76  }
77  if ( !$changed && !count( $changes ) ) {
78  $this->dieWithError( 'apierror-nochanges' );
79  }
80 
81  $prefs = Preferences::getPreferences( $user, $this->getContext() );
82  $prefsKinds = $user->getOptionKinds( $this->getContext(), $changes );
83 
84  $htmlForm = null;
85  foreach ( $changes as $key => $value ) {
86  switch ( $prefsKinds[$key] ) {
87  case 'registered':
88  // Regular option.
89  if ( $htmlForm === null ) {
90  // We need a dummy HTMLForm for the validate callback...
91  $htmlForm = new HTMLForm( [], $this );
92  }
93  $field = HTMLForm::loadInputFromParameters( $key, $prefs[$key], $htmlForm );
94  $validation = $field->validate( $value, $user->getOptions() );
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  $user->setOption( $key, $value );
122  $changed = true;
123  } else {
124  $this->addWarning( [ 'apiwarn-validationfailed', wfEscapeWikitext( $key ), $validation ] );
125  }
126  }
127 
128  if ( $changed ) {
129  // Commit changes
130  $user->saveSettings();
131  }
132 
133  $this->getResult()->addValue( null, $this->getModuleName(), 'success' );
134  }
135 
136  public function mustBePosted() {
137  return true;
138  }
139 
140  public function isWriteMode() {
141  return true;
142  }
143 
144  public function getAllowedParams() {
145  $optionKinds = User::listOptionKinds();
146  $optionKinds[] = 'all';
147 
148  return [
149  'reset' => false,
150  'resetkinds' => [
151  ApiBase::PARAM_TYPE => $optionKinds,
152  ApiBase::PARAM_DFLT => 'all',
154  ],
155  'change' => [
156  ApiBase::PARAM_ISMULTI => true,
157  ],
158  'optionname' => [
159  ApiBase::PARAM_TYPE => 'string',
160  ],
161  'optionvalue' => [
162  ApiBase::PARAM_TYPE => 'string',
163  ],
164  ];
165  }
166 
167  public function needsToken() {
168  return 'csrf';
169  }
170 
171  public function getHelpUrls() {
172  return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Options';
173  }
174 
175  protected function getExamplesMessages() {
176  return [
177  'action=options&reset=&token=123ABC'
178  => 'apihelp-options-example-reset',
179  'action=options&change=skin=vector|hideminor=1&token=123ABC'
180  => 'apihelp-options-example-change',
181  'action=options&reset=&change=skin=monobook&optionname=nickname&' .
182  'optionvalue=[[User:Beau|Beau]]%20([[User_talk:Beau|talk]])&token=123ABC'
183  => 'apihelp-options-example-complex',
184  ];
185  }
186 }
Preferences\getPreferences
static getPreferences( $user, IContextSource $context)
Definition: Preferences.php:82
ContextSource\getContext
getContext()
Get the base IContextSource object.
Definition: ContextSource.php:41
ApiBase\addWarning
addWarning( $msg, $code=null, $data=null)
Add a warning for this module.
Definition: ApiBase.php:1720
ContextSource\msg
msg()
Get a Message object with context set Parameters are the same as wfMessage()
Definition: ContextSource.php:187
captcha-old.count
count
Definition: captcha-old.py:225
ApiBase\dieWithError
dieWithError( $msg, $code=null, $data=null, $httpCode=null)
Abort execution with an error.
Definition: ApiBase.php:1796
ApiOptions\isWriteMode
isWriteMode()
Indicates whether this module requires write mode.
Definition: ApiOptions.php:140
ApiBase\PARAM_TYPE
const PARAM_TYPE
(string|string[]) Either an array of allowed value strings, or a string type as described below.
Definition: ApiBase.php:91
ApiBase\getResult
getResult()
Get the result object.
Definition: ApiBase.php:610
$user
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 account $user
Definition: hooks.txt:246
ApiBase\checkUserRightsAny
checkUserRightsAny( $rights, $user=null)
Helper function for permission-denied errors.
Definition: ApiBase.php:1890
$params
$params
Definition: styleTest.css.php:40
ContextSource\getUser
getUser()
Get the User object.
Definition: ContextSource.php:133
php
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
ApiBase
This abstract class implements many basic API functions, and is the base of all API classes.
Definition: ApiBase.php:41
ApiOptions\getAllowedParams
getAllowedParams()
Returns an array of allowed parameters (parameter name) => (default value) or (parameter name) => (ar...
Definition: ApiOptions.php:144
ApiOptions\execute
execute()
Changes preferences of the current user.
Definition: ApiOptions.php:37
ApiOptions\getExamplesMessages
getExamplesMessages()
Returns usage examples for this module.
Definition: ApiOptions.php:175
ApiOptions\mustBePosted
mustBePosted()
Indicates whether this module must be called with a POST request.
Definition: ApiOptions.php:136
HTMLForm\loadInputFromParameters
static loadInputFromParameters( $fieldname, $descriptor, HTMLForm $parent=null)
Initialise a new Object for the field.
Definition: HTMLForm.php:480
ApiOptions
API module that facilitates the changing of user's preferences.
Definition: ApiOptions.php:33
ApiBase\extractRequestParams
extractRequestParams( $parseLimit=true)
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition: ApiBase.php:718
ApiOptions\needsToken
needsToken()
Returns the token type this module requires in order to execute.
Definition: ApiOptions.php:167
$value
$value
Definition: styleTest.css.php:45
ApiBase\PARAM_DFLT
const PARAM_DFLT
(null|boolean|integer|string) Default value of the parameter.
Definition: ApiBase.php:52
as
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
ApiBase\getModuleName
getModuleName()
Get the name of the module being executed by this instance.
Definition: ApiBase.php:490
ApiBase\PARAM_ISMULTI
const PARAM_ISMULTI
(boolean) Accept multiple pipe-separated values for this parameter (e.g.
Definition: ApiBase.php:55
true
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:1956
ApiOptions\getHelpUrls
getHelpUrls()
Return links to more detailed help pages about the module.
Definition: ApiOptions.php:171
User\listOptionKinds
static listOptionKinds()
Return a list of the types of user options currently returned by User::getOptionKinds().
Definition: User.php:3027
HTMLForm
Object handling generic submission, CSRF protection, layout and other logic for UI forms.
Definition: HTMLForm.php:128