Merge "Fix 'Tags' padding to keep it farther from the edge and document the source...
[lhc/web/wiklou.git] / includes / api / ApiOptions.php
1 <?php
2 /**
3 * Copyright © 2012 Szymon Świerkosz beau@adres.pl
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 */
22
23 use MediaWiki\MediaWikiServices;
24
25 /**
26 * API module that facilitates the changing of user's preferences.
27 * Requires API write mode to be enabled.
28 *
29 * @ingroup API
30 */
31 class ApiOptions extends ApiBase {
32 /** @var User User account to modify */
33 private $userForUpdates;
34
35 /**
36 * Changes preferences of the current user.
37 */
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
129 /**
130 * Load the user from the master to reduce CAS errors on double post (T95839)
131 *
132 * @return null|User
133 */
134 protected function getUserForUpdates() {
135 if ( !$this->userForUpdates ) {
136 $this->userForUpdates = $this->getUser()->getInstanceForUpdate();
137 }
138
139 return $this->userForUpdates;
140 }
141
142 /**
143 * Returns preferences form descriptor
144 * @return mixed[][]
145 */
146 protected function getPreferences() {
147 $preferencesFactory = MediaWikiServices::getInstance()->getPreferencesFactory();
148 return $preferencesFactory->getFormDescriptor( $this->getUserForUpdates(),
149 $this->getContext() );
150 }
151
152 /**
153 * @param string[] $kinds One or more types returned by User::listOptionKinds() or 'all'
154 */
155 protected function resetPreferences( array $kinds ) {
156 $this->getUserForUpdates()->resetOptions( $kinds, $this->getContext() );
157 }
158
159 /**
160 * Sets one user preference to be applied by commitChanges()
161 *
162 * @param string $preference
163 * @param mixed $value
164 */
165 protected function setPreference( $preference, $value ) {
166 $this->getUserForUpdates()->setOption( $preference, $value );
167 }
168
169 /**
170 * Applies changes to user preferences
171 */
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',
193 ApiBase::PARAM_ISMULTI => true
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 }