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