MediaWiki  1.28.0
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->dieUsage( 'Anonymous users cannot change preferences', 'notloggedin' );
40  } elseif ( !$this->getUser()->isAllowed( 'editmyoptions' ) ) {
41  $this->dieUsage( "You don't have permission to edit your options", 'permissiondenied' );
42  }
43 
44  $params = $this->extractRequestParams();
45  $changed = false;
46 
47  if ( isset( $params['optionvalue'] ) && !isset( $params['optionname'] ) ) {
48  $this->dieUsageMsg( [ '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->dieUsage( 'Anonymous users cannot change preferences', 'notloggedin' );
55  }
56 
57  if ( $params['reset'] ) {
58  $user->resetOptions( $params['resetkinds'], $this->getContext() );
59  $changed = true;
60  }
61 
62  $changes = [];
63  if ( count( $params['change'] ) ) {
64  foreach ( $params['change'] as $entry ) {
65  $array = explode( '=', $entry, 2 );
66  $changes[$array[0]] = isset( $array[1] ) ? $array[1] : null;
67  }
68  }
69  if ( isset( $params['optionname'] ) ) {
70  $newValue = isset( $params['optionvalue'] ) ? $params['optionvalue'] : null;
71  $changes[$params['optionname']] = $newValue;
72  }
73  if ( !$changed && !count( $changes ) ) {
74  $this->dieUsage( 'No changes were requested', 'nochanges' );
75  }
76 
77  $prefs = Preferences::getPreferences( $user, $this->getContext() );
78  $prefsKinds = $user->getOptionKinds( $this->getContext(), $changes );
79 
80  $htmlForm = null;
81  foreach ( $changes as $key => $value ) {
82  switch ( $prefsKinds[$key] ) {
83  case 'registered':
84  // Regular option.
85  if ( $htmlForm === null ) {
86  // We need a dummy HTMLForm for the validate callback...
87  $htmlForm = new HTMLForm( [], $this );
88  }
89  $field = HTMLForm::loadInputFromParameters( $key, $prefs[$key], $htmlForm );
90  $validation = $field->validate( $value, $user->getOptions() );
91  break;
92  case 'registered-multiselect':
93  case 'registered-checkmatrix':
94  // A key for a multiselect or checkmatrix option.
95  $validation = true;
96  $value = $value !== null ? (bool)$value : null;
97  break;
98  case 'userjs':
99  // Allow non-default preferences prefixed with 'userjs-', to be set by user scripts
100  if ( strlen( $key ) > 255 ) {
101  $validation = 'key too long (no more than 255 bytes allowed)';
102  } elseif ( preg_match( '/[^a-zA-Z0-9_-]/', $key ) !== 0 ) {
103  $validation = 'invalid key (only a-z, A-Z, 0-9, _, - allowed)';
104  } else {
105  $validation = true;
106  }
107  break;
108  case 'special':
109  $validation = 'cannot be set by this module';
110  break;
111  case 'unused':
112  default:
113  $validation = 'not a valid preference';
114  break;
115  }
116  if ( $validation === true ) {
117  $user->setOption( $key, $value );
118  $changed = true;
119  } else {
120  $this->setWarning( "Validation error for '$key': $validation" );
121  }
122  }
123 
124  if ( $changed ) {
125  // Commit changes
126  $user->saveSettings();
127  }
128 
129  $this->getResult()->addValue( null, $this->getModuleName(), 'success' );
130  }
131 
132  public function mustBePosted() {
133  return true;
134  }
135 
136  public function isWriteMode() {
137  return true;
138  }
139 
140  public function getAllowedParams() {
141  $optionKinds = User::listOptionKinds();
142  $optionKinds[] = 'all';
143 
144  return [
145  'reset' => false,
146  'resetkinds' => [
147  ApiBase::PARAM_TYPE => $optionKinds,
148  ApiBase::PARAM_DFLT => 'all',
150  ],
151  'change' => [
152  ApiBase::PARAM_ISMULTI => true,
153  ],
154  'optionname' => [
155  ApiBase::PARAM_TYPE => 'string',
156  ],
157  'optionvalue' => [
158  ApiBase::PARAM_TYPE => 'string',
159  ],
160  ];
161  }
162 
163  public function needsToken() {
164  return 'csrf';
165  }
166 
167  public function getHelpUrls() {
168  return 'https://www.mediawiki.org/wiki/API:Options';
169  }
170 
171  protected function getExamplesMessages() {
172  return [
173  'action=options&reset=&token=123ABC'
174  => 'apihelp-options-example-reset',
175  'action=options&change=skin=vector|hideminor=1&token=123ABC'
176  => 'apihelp-options-example-change',
177  'action=options&reset=&change=skin=monobook&optionname=nickname&' .
178  'optionvalue=[[User:Beau|Beau]]%20([[User_talk:Beau|talk]])&token=123ABC'
179  => 'apihelp-options-example-complex',
180  ];
181  }
182 }
const PARAM_TYPE
(string|string[]) Either an array of allowed value strings, or a string type as described below...
Definition: ApiBase.php:88
execute()
Changes preferences of the current user.
Definition: ApiOptions.php:37
getResult()
Get the result object.
Definition: ApiBase.php:577
const PARAM_DFLT
(null|boolean|integer|string) Default value of the parameter.
Definition: ApiBase.php:50
getAllowedParams()
Definition: ApiOptions.php:140
extractRequestParams($parseLimit=true)
Using getAllowedParams(), this function makes an array of the values provided by the user...
Definition: ApiBase.php:678
$value
static getPreferences($user, IContextSource $context)
Definition: Preferences.php:83
static listOptionKinds()
Return a list of the types of user options currently returned by User::getOptionKinds().
Definition: User.php:2936
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:1936
getContext()
Get the base IContextSource object.
$params
Object handling generic submission, CSRF protection, layout and other logic for UI forms...
Definition: HTMLForm.php:128
getModuleName()
Get the name of the module being executed by this instance.
Definition: ApiBase.php:457
setWarning($warning)
Set warning section for this module.
Definition: ApiBase.php:1543
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
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:242
static loadInputFromParameters($fieldname, $descriptor, HTMLForm $parent=null)
Initialise a new Object for the field.
Definition: HTMLForm.php:478
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's preferences.
Definition: ApiOptions.php:33
const PARAM_ISMULTI
(boolean) Accept multiple pipe-separated values for this parameter (e.g.
Definition: ApiBase.php:53
getExamplesMessages()
Definition: ApiOptions.php:171
dieUsage($description, $errorCode, $httpRespCode=0, $extradata=null)
Throw a UsageException, which will (if uncaught) call the main module's error handler and die with an...
Definition: ApiBase.php:1574
This abstract class implements many basic API functions, and is the base of all API classes...
Definition: ApiBase.php:39
getUser()
Get the User object.
dieUsageMsg($error)
Output the error message related to a certain array.
Definition: ApiBase.php:2192