MediaWiki  REL1_31
ApiOptions.php
Go to the documentation of this file.
1 <?php
24 
31 class ApiOptions extends ApiBase {
35  public function execute() {
36  if ( $this->getUser()->isAnon() ) {
37  $this->dieWithError(
38  [ 'apierror-mustbeloggedin', $this->msg( 'action-editmyoptions' ) ], 'notloggedin'
39  );
40  }
41 
42  $this->checkUserRightsAny( 'editmyoptions' );
43 
44  $params = $this->extractRequestParams();
45  $changed = false;
46 
47  if ( isset( $params['optionvalue'] ) && !isset( $params['optionname'] ) ) {
48  $this->dieWithError( [ 'apierror-missingparam', 'optionname' ] );
49  }
50 
51  // Load the user from the master to reduce CAS errors on double post (T95839)
52  $user = $this->getUser()->getInstanceForUpdate();
53  if ( !$user ) {
54  $this->dieWithError(
55  [ 'apierror-mustbeloggedin', $this->msg( 'action-editmyoptions' ) ], 'notloggedin'
56  );
57  }
58 
59  if ( $params['reset'] ) {
60  $user->resetOptions( $params['resetkinds'], $this->getContext() );
61  $changed = true;
62  }
63 
64  $changes = [];
65  if ( $params['change'] ) {
66  foreach ( $params['change'] as $entry ) {
67  $array = explode( '=', $entry, 2 );
68  $changes[$array[0]] = isset( $array[1] ) ? $array[1] : null;
69  }
70  }
71  if ( isset( $params['optionname'] ) ) {
72  $newValue = isset( $params['optionvalue'] ) ? $params['optionvalue'] : null;
73  $changes[$params['optionname']] = $newValue;
74  }
75  if ( !$changed && !count( $changes ) ) {
76  $this->dieWithError( 'apierror-nochanges' );
77  }
78 
79  $preferencesFactory = MediaWikiServices::getInstance()->getPreferencesFactory();
80  $prefs = $preferencesFactory->getFormDescriptor( $user, $this->getContext() );
81  $prefsKinds = $user->getOptionKinds( $this->getContext(), $changes );
82 
83  $htmlForm = null;
84  foreach ( $changes as $key => $value ) {
85  switch ( $prefsKinds[$key] ) {
86  case 'registered':
87  // Regular option.
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  break;
95  case 'registered-multiselect':
96  case 'registered-checkmatrix':
97  // A key for a multiselect or checkmatrix option.
98  $validation = true;
99  $value = $value !== null ? (bool)$value : null;
100  break;
101  case 'userjs':
102  // Allow non-default preferences prefixed with 'userjs-', to be set by user scripts
103  if ( strlen( $key ) > 255 ) {
104  $validation = $this->msg( 'apiwarn-validationfailed-keytoolong', Message::numParam( 255 ) );
105  } elseif ( preg_match( '/[^a-zA-Z0-9_-]/', $key ) !== 0 ) {
106  $validation = $this->msg( 'apiwarn-validationfailed-badchars' );
107  } else {
108  $validation = true;
109  }
110  break;
111  case 'special':
112  $validation = $this->msg( 'apiwarn-validationfailed-cannotset' );
113  break;
114  case 'unused':
115  default:
116  $validation = $this->msg( 'apiwarn-validationfailed-badpref' );
117  break;
118  }
119  if ( $validation === true ) {
120  $user->setOption( $key, $value );
121  $changed = true;
122  } else {
123  $this->addWarning( [ 'apiwarn-validationfailed', wfEscapeWikiText( $key ), $validation ] );
124  }
125  }
126 
127  if ( $changed ) {
128  // Commit changes
129  $user->saveSettings();
130  }
131 
132  $this->getResult()->addValue( null, $this->getModuleName(), 'success' );
133  }
134 
135  public function mustBePosted() {
136  return true;
137  }
138 
139  public function isWriteMode() {
140  return true;
141  }
142 
143  public function getAllowedParams() {
144  $optionKinds = User::listOptionKinds();
145  $optionKinds[] = 'all';
146 
147  return [
148  'reset' => false,
149  'resetkinds' => [
150  ApiBase::PARAM_TYPE => $optionKinds,
151  ApiBase::PARAM_DFLT => 'all',
153  ],
154  'change' => [
155  ApiBase::PARAM_ISMULTI => true,
156  ],
157  'optionname' => [
158  ApiBase::PARAM_TYPE => 'string',
159  ],
160  'optionvalue' => [
161  ApiBase::PARAM_TYPE => 'string',
162  ],
163  ];
164  }
165 
166  public function needsToken() {
167  return 'csrf';
168  }
169 
170  public function getHelpUrls() {
171  return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Options';
172  }
173 
174  protected function getExamplesMessages() {
175  return [
176  'action=options&reset=&token=123ABC'
177  => 'apihelp-options-example-reset',
178  'action=options&change=skin=vector|hideminor=1&token=123ABC'
179  => 'apihelp-options-example-change',
180  'action=options&reset=&change=skin=monobook&optionname=nickname&' .
181  'optionvalue=[[User:Beau|Beau]]%20([[User_talk:Beau|talk]])&token=123ABC'
182  => 'apihelp-options-example-complex',
183  ];
184  }
185 }
$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:247
Message\numParam
static numParam( $num)
Definition: Message.php:1028
ContextSource\getContext
getContext()
Get the base IContextSource object.
Definition: ContextSource.php:40
ApiBase\addWarning
addWarning( $msg, $code=null, $data=null)
Add a warning for this module.
Definition: ApiBase.php:1819
use
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
Definition: APACHE-LICENSE-2.0.txt:10
ApiBase\dieWithError
dieWithError( $msg, $code=null, $data=null, $httpCode=null)
Abort execution with an error.
Definition: ApiBase.php:1895
ApiOptions\isWriteMode
isWriteMode()
Indicates whether this module requires write mode.
Definition: ApiOptions.php:139
ContextSource\msg
msg( $key)
Get a Message object with context set Parameters are the same as wfMessage()
Definition: ContextSource.php:168
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:87
ApiBase\getResult
getResult()
Get the result object.
Definition: ApiBase.php:641
ApiBase\checkUserRightsAny
checkUserRightsAny( $rights, $user=null)
Helper function for permission-denied errors.
Definition: ApiBase.php:2006
$params
$params
Definition: styleTest.css.php:40
ContextSource\getUser
getUser()
Definition: ContextSource.php:120
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:2006
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:37
ApiBase
This abstract class implements many basic API functions, and is the base of all API classes.
Definition: ApiBase.php:37
ApiOptions\getAllowedParams
getAllowedParams()
Returns an array of allowed parameters (parameter name) => (default value) or (parameter name) => (ar...
Definition: ApiOptions.php:143
ApiOptions\execute
execute()
Changes preferences of the current user.
Definition: ApiOptions.php:35
ApiOptions\getExamplesMessages
getExamplesMessages()
Returns usage examples for this module.
Definition: ApiOptions.php:174
ApiOptions\mustBePosted
mustBePosted()
Indicates whether this module must be called with a POST request.
Definition: ApiOptions.php:135
HTMLForm\loadInputFromParameters
static loadInputFromParameters( $fieldname, $descriptor, HTMLForm $parent=null)
Initialise a new Object for the field.
Definition: HTMLForm.php:477
ApiOptions
API module that facilitates the changing of user's preferences.
Definition: ApiOptions.php:31
ApiBase\extractRequestParams
extractRequestParams( $parseLimit=true)
Using getAllowedParams(), this function makes an array of the values provided by the user,...
Definition: ApiBase.php:749
ApiOptions\needsToken
needsToken()
Returns the token type this module requires in order to execute.
Definition: ApiOptions.php:166
$value
$value
Definition: styleTest.css.php:45
wfEscapeWikiText
wfEscapeWikiText( $text)
Escapes the given text so that it may be output using addWikiText() without any linking,...
Definition: GlobalFunctions.php:1643
ApiBase\PARAM_DFLT
const PARAM_DFLT
(null|boolean|integer|string) Default value of the parameter.
Definition: ApiBase.php:48
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:22
ApiBase\getModuleName
getModuleName()
Get the name of the module being executed by this instance.
Definition: ApiBase.php:521
ApiBase\PARAM_ISMULTI
const PARAM_ISMULTI
(boolean) Accept multiple pipe-separated values for this parameter (e.g.
Definition: ApiBase.php:51
MediaWikiServices
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:25
ApiOptions\getHelpUrls
getHelpUrls()
Return links to more detailed help pages about the module.
Definition: ApiOptions.php:170
User\listOptionKinds
static listOptionKinds()
Return a list of the types of user options currently returned by User::getOptionKinds().
Definition: User.php:3324
HTMLForm
Object handling generic submission, CSRF protection, layout and other logic for UI forms.
Definition: HTMLForm.php:130