Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 134
0.00% covered (danger)
0.00%
0 / 16
CRAP
0.00% covered (danger)
0.00%
0 / 1
ApiOptionsBase
0.00% covered (danger)
0.00%
0 / 133
0.00% covered (danger)
0.00%
0 / 16
2352
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 execute
0.00% covered (danger)
0.00%
0 / 39
0.00% covered (danger)
0.00%
0 / 1
272
 runHook
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 shouldIgnoreKey
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getPrefsKinds
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getHtmlForm
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
6
 validate
0.00% covered (danger)
0.00%
0 / 48
0.00% covered (danger)
0.00%
0 / 1
240
 getUserForUpdates
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getUserForUpdatesOrNull
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
6
 getPreferences
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
6
 getUserOptionsManager
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getPreferencesFactory
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 resetPreferences
n/a
0 / 0
n/a
0 / 0
0
 setPreference
n/a
0 / 0
n/a
0 / 0
0
 commitChanges
n/a
0 / 0
n/a
0 / 0
0
 mustBePosted
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 isWriteMode
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 getAllowedParams
0.00% covered (danger)
0.00%
0 / 19
0.00% covered (danger)
0.00%
0 / 1
2
 needsToken
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
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
23namespace MediaWiki\Api;
24
25use MediaWiki\HTMLForm\HTMLForm;
26use MediaWiki\Logger\LoggerFactory;
27use MediaWiki\Message\Message;
28use MediaWiki\Preferences\DefaultPreferencesFactory;
29use MediaWiki\Preferences\PreferencesFactory;
30use MediaWiki\User\Options\UserOptionsManager;
31use MediaWiki\User\User;
32use Wikimedia\ParamValidator\ParamValidator;
33
34/**
35 * The base class for core's ApiOptions and two modules in the GlobalPreferences
36 * extension.
37 *
38 * @ingroup API
39 */
40abstract class ApiOptionsBase extends ApiBase {
41    /** @var User User account to modify */
42    private $userForUpdates;
43
44    private UserOptionsManager $userOptionsManager;
45    private PreferencesFactory $preferencesFactory;
46
47    /** @var mixed[][]|null */
48    private $preferences;
49
50    /** @var HTMLForm|null */
51    private $htmlForm;
52
53    /** @var string[]|null */
54    private $prefsKinds;
55
56    /** @var array */
57    private $params;
58
59    public function __construct(
60        ApiMain $main,
61        string $action,
62        UserOptionsManager $userOptionsManager,
63        PreferencesFactory $preferencesFactory
64    ) {
65        parent::__construct( $main, $action );
66        $this->userOptionsManager = $userOptionsManager;
67        $this->preferencesFactory = $preferencesFactory;
68    }
69
70    /**
71     * Changes preferences of the current user.
72     */
73    public function execute() {
74        $user = $this->getUserForUpdatesOrNull();
75        if ( !$user || !$user->isNamed() ) {
76            $this->dieWithError(
77                [ 'apierror-mustbeloggedin', $this->msg( 'action-editmyoptions' ) ], 'notloggedin'
78            );
79        }
80
81        $this->checkUserRightsAny( 'editmyoptions' );
82
83        $params = $this->extractRequestParams();
84        $changed = false;
85
86        if ( isset( $params['optionvalue'] ) && !isset( $params['optionname'] ) ) {
87            $this->dieWithError( [ 'apierror-missingparam', 'optionname' ] );
88        }
89
90        $resetKinds = $params['resetkinds'];
91        if ( !$params['reset'] ) {
92            $resetKinds = [];
93        }
94
95        $changes = [];
96        if ( $params['change'] ) {
97            foreach ( $params['change'] as $entry ) {
98                $array = explode( '=', $entry, 2 );
99                $changes[$array[0]] = $array[1] ?? null;
100            }
101        }
102        if ( isset( $params['optionname'] ) ) {
103            $newValue = $params['optionvalue'] ?? null;
104            $changes[$params['optionname']] = $newValue;
105        }
106
107        $this->runHook( $user, $changes, $resetKinds );
108
109        if ( $resetKinds ) {
110            $this->resetPreferences( $resetKinds );
111            $changed = true;
112        }
113
114        if ( !$changed && !count( $changes ) ) {
115            $this->dieWithError( 'apierror-nochanges' );
116        }
117
118        $this->prefsKinds = $this->preferencesFactory->getResetKinds( $user, $this->getContext(), $changes );
119
120        foreach ( $changes as $key => $value ) {
121            if ( $this->shouldIgnoreKey( $key ) ) {
122                continue;
123            }
124            $validation = $this->validate( $key, $value );
125            if ( $validation === true ) {
126                $this->setPreference( $key, $value );
127                $changed = true;
128            } else {
129                $this->addWarning( [ 'apiwarn-validationfailed', wfEscapeWikiText( $key ), $validation ] );
130            }
131        }
132
133        if ( $changed ) {
134            $this->commitChanges();
135        }
136
137        $this->getResult()->addValue( null, $this->getModuleName(), 'success' );
138    }
139
140    /**
141     * Run the ApiOptions hook if applicable
142     *
143     * @param User $user
144     * @param string[] $changes
145     * @param string[] $resetKinds
146     */
147    protected function runHook( $user, $changes, $resetKinds ) {
148    }
149
150    /**
151     * Check whether a key should be ignored.
152     *
153     * This may be overridden to emit a warning as well as returning true.
154     *
155     * @param string $key
156     * @return bool
157     */
158    protected function shouldIgnoreKey( $key ) {
159        return false;
160    }
161
162    /**
163     * Get the preference kinds for the current user's options.
164     * This can only be called after $this->prefsKinds is set in execute()
165     *
166     * @return string[]
167     */
168    protected function getPrefsKinds(): array {
169        return $this->prefsKinds;
170    }
171
172    /**
173     * Get the HTMLForm for the user's preferences
174     *
175     * @return HTMLForm
176     */
177    protected function getHtmlForm() {
178        if ( !$this->htmlForm ) {
179            $this->htmlForm = new HTMLForm(
180                DefaultPreferencesFactory::simplifyFormDescriptor( $this->getPreferences() ),
181                $this
182            );
183        }
184        return $this->htmlForm;
185    }
186
187    /**
188     * Validate a proposed change
189     *
190     * @param string $key
191     * @param mixed &$value
192     * @return bool|\MediaWiki\Message\Message|string
193     */
194    protected function validate( $key, &$value ) {
195        switch ( $this->getPrefsKinds()[$key] ) {
196            case 'registered':
197                // Regular option.
198                if ( $value === null ) {
199                    // Reset it
200                    $validation = true;
201                } else {
202                    // Validate
203                    $field = $this->getHtmlForm()->getField( $key );
204                    $validation = $field->validate(
205                        $value,
206                        $this->userOptionsManager->getOptions( $this->getUserForUpdates() )
207                    );
208                }
209                break;
210            case 'registered-multiselect':
211            case 'registered-checkmatrix':
212                // A key for a multiselect or checkmatrix option.
213                // TODO: Apply validation properly.
214                $validation = true;
215                $value = $value !== null ? (bool)$value : null;
216                break;
217            case 'userjs':
218                // Allow non-default preferences prefixed with 'userjs-', to be set by user scripts
219                if ( strlen( $key ) > 255 ) {
220                    $validation = $this->msg( 'apiwarn-validationfailed-keytoolong', Message::numParam( 255 ) );
221                } elseif ( preg_match( '/[^a-zA-Z0-9_-]/', $key ) !== 0 ) {
222                    $validation = $this->msg( 'apiwarn-validationfailed-badchars' );
223                } else {
224                    $validation = true;
225                }
226
227                LoggerFactory::getInstance( 'api-warning' )->info(
228                    'ApiOptions: Setting userjs option',
229                    [
230                        'phab' => 'T259073',
231                        'OptionName' => substr( $key, 0, 255 ),
232                        'OptionValue' => substr( $value ?? '', 0, 255 ),
233                        'OptionSize' => strlen( $value ?? '' ),
234                        'OptionValidation' => $validation,
235                        'UserId' => $this->getUserForUpdates()->getId(),
236                        'RequestIP' => $this->getRequest()->getIP(),
237                        'RequestUA' => $this->getRequest()->getHeader( 'User-Agent' )
238                    ]
239                );
240                break;
241            case 'special':
242                $validation = $this->msg( 'apiwarn-validationfailed-cannotset' );
243                break;
244            case 'unused':
245            default:
246                $validation = $this->msg( 'apiwarn-validationfailed-badpref' );
247                break;
248        }
249        if ( $validation === true && is_string( $value ) &&
250            strlen( $value ) > UserOptionsManager::MAX_BYTES_OPTION_VALUE
251        ) {
252            $validation = $this->msg(
253                'apiwarn-validationfailed-valuetoolong',
254                Message::numParam( UserOptionsManager::MAX_BYTES_OPTION_VALUE )
255            );
256        }
257        return $validation;
258    }
259
260    /**
261     * Load the user from the primary to reduce CAS errors on double post (T95839)
262     * Will throw if the user is anonymous.
263     *
264     * @return User
265     */
266    protected function getUserForUpdates(): User {
267        // @phan-suppress-next-line PhanTypeMismatchReturnNullable
268        return $this->getUserForUpdatesOrNull();
269    }
270
271    /**
272     * Get the user for updates, or null if the user is anonymous
273     *
274     * @return User|null
275     */
276    protected function getUserForUpdatesOrNull(): ?User {
277        if ( !$this->userForUpdates ) {
278            $this->userForUpdates = $this->getUser()->getInstanceForUpdate();
279        }
280
281        return $this->userForUpdates;
282    }
283
284    /**
285     * Returns preferences form descriptor
286     * @return mixed[][]
287     */
288    protected function getPreferences() {
289        if ( !$this->preferences ) {
290            $this->preferences = $this->preferencesFactory->getFormDescriptor(
291                $this->getUserForUpdates(),
292                $this->getContext()
293            );
294        }
295        return $this->preferences;
296    }
297
298    protected function getUserOptionsManager(): UserOptionsManager {
299        return $this->userOptionsManager;
300    }
301
302    protected function getPreferencesFactory(): PreferencesFactory {
303        return $this->preferencesFactory;
304    }
305
306    /**
307     * Reset preferences of the specified kinds
308     *
309     * @param string[] $kinds One or more types returned by UserOptionsManager::listOptionKinds() or 'all'
310     */
311    abstract protected function resetPreferences( array $kinds );
312
313    /**
314     * Sets one user preference to be applied by commitChanges()
315     *
316     * @param string $preference
317     * @param mixed $value
318     */
319    abstract protected function setPreference( $preference, $value );
320
321    /**
322     * Applies changes to user preferences
323     */
324    abstract protected function commitChanges();
325
326    public function mustBePosted() {
327        return true;
328    }
329
330    public function isWriteMode() {
331        return true;
332    }
333
334    public function getAllowedParams() {
335        $optionKinds = $this->preferencesFactory->listResetKinds();
336        $optionKinds[] = 'all';
337
338        return [
339            'reset' => false,
340            'resetkinds' => [
341                ParamValidator::PARAM_TYPE => $optionKinds,
342                ParamValidator::PARAM_DEFAULT => 'all',
343                ParamValidator::PARAM_ISMULTI => true
344            ],
345            'change' => [
346                ParamValidator::PARAM_ISMULTI => true,
347            ],
348            'optionname' => [
349                ParamValidator::PARAM_TYPE => 'string',
350            ],
351            'optionvalue' => [
352                ParamValidator::PARAM_TYPE => 'string',
353            ],
354        ];
355    }
356
357    public function needsToken() {
358        return 'csrf';
359    }
360}
361
362/** @deprecated class alias since 1.43 */
363class_alias( ApiOptionsBase::class, 'ApiOptionsBase' );