89982a61e8d1c11ff677613b7dfb8ff73b7ef0f8
[lhc/web/wiklou.git] / includes / Preferences.php
1 <?php
2 /**
3 * Form to edit user preferences.
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 use MediaWiki\Auth\AuthManager;
23 use MediaWiki\Auth\PasswordAuthenticationRequest;
24 use MediaWiki\MediaWikiServices;
25
26 /**
27 * We're now using the HTMLForm object with some customisation to generate the
28 * Preferences form. This object handles generic submission, CSRF protection,
29 * layout and other logic in a reusable manner. We subclass it as a PreferencesForm
30 * to make some minor customisations.
31 *
32 * In order to generate the form, the HTMLForm object needs an array structure
33 * detailing the form fields available, and that's what this class is for. Each
34 * element of the array is a basic property-list, including the type of field,
35 * the label it is to be given in the form, callbacks for validation and
36 * 'filtering', and other pertinent information. Note that the 'default' field
37 * is named for generic forms, and does not represent the preference's default
38 * (which is stored in $wgDefaultUserOptions), but the default for the form
39 * field, which should be whatever the user has set for that preference. There
40 * is no need to override it unless you have some special storage logic (for
41 * instance, those not presently stored as options, but which are best set from
42 * the user preferences view).
43 *
44 * Field types are implemented as subclasses of the generic HTMLFormField
45 * object, and typically implement at least getInputHTML, which generates the
46 * HTML for the input field to be placed in the table.
47 *
48 * Once fields have been retrieved and validated, submission logic is handed
49 * over to the tryUISubmit static method of this class.
50 */
51 class Preferences {
52 /** @var array */
53 protected static $defaultPreferences = null;
54
55 /** @var array */
56 protected static $saveFilters = [
57 'timecorrection' => [ 'Preferences', 'filterTimezoneInput' ],
58 'rclimit' => [ 'Preferences', 'filterIntval' ],
59 'wllimit' => [ 'Preferences', 'filterIntval' ],
60 'searchlimit' => [ 'Preferences', 'filterIntval' ],
61 ];
62
63 // Stuff that shouldn't be saved as a preference.
64 private static $saveBlacklist = [
65 'realname',
66 'emailaddress',
67 ];
68
69 /**
70 * @return array
71 */
72 static function getSaveBlacklist() {
73 return self::$saveBlacklist;
74 }
75
76 /**
77 * @throws MWException
78 * @param User $user
79 * @param IContextSource $context
80 * @return array|null
81 */
82 static function getPreferences( $user, IContextSource $context ) {
83 if ( self::$defaultPreferences ) {
84 return self::$defaultPreferences;
85 }
86
87 $defaultPreferences = [];
88
89 self::profilePreferences( $user, $context, $defaultPreferences );
90 self::skinPreferences( $user, $context, $defaultPreferences );
91 self::datetimePreferences( $user, $context, $defaultPreferences );
92 self::filesPreferences( $user, $context, $defaultPreferences );
93 self::renderingPreferences( $user, $context, $defaultPreferences );
94 self::editingPreferences( $user, $context, $defaultPreferences );
95 self::rcPreferences( $user, $context, $defaultPreferences );
96 self::watchlistPreferences( $user, $context, $defaultPreferences );
97 self::searchPreferences( $user, $context, $defaultPreferences );
98 self::miscPreferences( $user, $context, $defaultPreferences );
99
100 Hooks::run( 'GetPreferences', [ $user, &$defaultPreferences ] );
101
102 self::loadPreferenceValues( $user, $context, $defaultPreferences );
103 self::$defaultPreferences = $defaultPreferences;
104 return $defaultPreferences;
105 }
106
107 /**
108 * Loads existing values for a given array of preferences
109 * @throws MWException
110 * @param User $user
111 * @param IContextSource $context
112 * @param array $defaultPreferences Array to load values for
113 * @return array|null
114 */
115 static function loadPreferenceValues( $user, $context, &$defaultPreferences ) {
116 # # Remove preferences that wikis don't want to use
117 foreach ( $context->getConfig()->get( 'HiddenPrefs' ) as $pref ) {
118 if ( isset( $defaultPreferences[$pref] ) ) {
119 unset( $defaultPreferences[$pref] );
120 }
121 }
122
123 # # Make sure that form fields have their parent set. See bug 41337.
124 $dummyForm = new HTMLForm( [], $context );
125
126 $disable = !$user->isAllowed( 'editmyoptions' );
127
128 $defaultOptions = User::getDefaultOptions();
129 # # Prod in defaults from the user
130 foreach ( $defaultPreferences as $name => &$info ) {
131 $prefFromUser = self::getOptionFromUser( $name, $info, $user );
132 if ( $disable && !in_array( $name, self::$saveBlacklist ) ) {
133 $info['disabled'] = 'disabled';
134 }
135 $field = HTMLForm::loadInputFromParameters( $name, $info, $dummyForm ); // For validation
136 $globalDefault = isset( $defaultOptions[$name] )
137 ? $defaultOptions[$name]
138 : null;
139
140 // If it validates, set it as the default
141 if ( isset( $info['default'] ) ) {
142 // Already set, no problem
143 continue;
144 } elseif ( !is_null( $prefFromUser ) && // Make sure we're not just pulling nothing
145 $field->validate( $prefFromUser, $user->getOptions() ) === true ) {
146 $info['default'] = $prefFromUser;
147 } elseif ( $field->validate( $globalDefault, $user->getOptions() ) === true ) {
148 $info['default'] = $globalDefault;
149 } else {
150 throw new MWException( "Global default '$globalDefault' is invalid for field $name" );
151 }
152 }
153
154 return $defaultPreferences;
155 }
156
157 /**
158 * Pull option from a user account. Handles stuff like array-type preferences.
159 *
160 * @param string $name
161 * @param array $info
162 * @param User $user
163 * @return array|string
164 */
165 static function getOptionFromUser( $name, $info, $user ) {
166 $val = $user->getOption( $name );
167
168 // Handling for multiselect preferences
169 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
170 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
171 $options = HTMLFormField::flattenOptions( $info['options'] );
172 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name;
173 $val = [];
174
175 foreach ( $options as $value ) {
176 if ( $user->getOption( "$prefix$value" ) ) {
177 $val[] = $value;
178 }
179 }
180 }
181
182 // Handling for checkmatrix preferences
183 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
184 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
185 $columns = HTMLFormField::flattenOptions( $info['columns'] );
186 $rows = HTMLFormField::flattenOptions( $info['rows'] );
187 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name;
188 $val = [];
189
190 foreach ( $columns as $column ) {
191 foreach ( $rows as $row ) {
192 if ( $user->getOption( "$prefix$column-$row" ) ) {
193 $val[] = "$column-$row";
194 }
195 }
196 }
197 }
198
199 return $val;
200 }
201
202 /**
203 * @param User $user
204 * @param IContextSource $context
205 * @param array $defaultPreferences
206 * @return void
207 */
208 static function profilePreferences( $user, IContextSource $context, &$defaultPreferences ) {
209 global $wgContLang, $wgParser;
210
211 $authManager = AuthManager::singleton();
212 $config = $context->getConfig();
213 // retrieving user name for GENDER and misc.
214 $userName = $user->getName();
215
216 # # User info #####################################
217 // Information panel
218 $defaultPreferences['username'] = [
219 'type' => 'info',
220 'label-message' => [ 'username', $userName ],
221 'default' => $userName,
222 'section' => 'personal/info',
223 ];
224
225 # Get groups to which the user belongs
226 $userEffectiveGroups = $user->getEffectiveGroups();
227 $userGroups = $userMembers = [];
228 foreach ( $userEffectiveGroups as $ueg ) {
229 if ( $ueg == '*' ) {
230 // Skip the default * group, seems useless here
231 continue;
232 }
233 $groupName = User::getGroupName( $ueg );
234 $userGroups[] = User::makeGroupLinkHTML( $ueg, $groupName );
235
236 $memberName = User::getGroupMember( $ueg, $userName );
237 $userMembers[] = User::makeGroupLinkHTML( $ueg, $memberName );
238 }
239 asort( $userGroups );
240 asort( $userMembers );
241
242 $lang = $context->getLanguage();
243
244 $defaultPreferences['usergroups'] = [
245 'type' => 'info',
246 'label' => $context->msg( 'prefs-memberingroups' )->numParams(
247 count( $userGroups ) )->params( $userName )->parse(),
248 'default' => $context->msg( 'prefs-memberingroups-type' )
249 ->rawParams( $lang->commaList( $userGroups ), $lang->commaList( $userMembers ) )
250 ->escaped(),
251 'raw' => true,
252 'section' => 'personal/info',
253 ];
254
255 $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
256
257 $editCount = $linkRenderer->makeLink( SpecialPage::getTitleFor( "Contributions", $userName ),
258 $lang->formatNum( $user->getEditCount() ) );
259
260 $defaultPreferences['editcount'] = [
261 'type' => 'info',
262 'raw' => true,
263 'label-message' => 'prefs-edits',
264 'default' => $editCount,
265 'section' => 'personal/info',
266 ];
267
268 if ( $user->getRegistration() ) {
269 $displayUser = $context->getUser();
270 $userRegistration = $user->getRegistration();
271 $defaultPreferences['registrationdate'] = [
272 'type' => 'info',
273 'label-message' => 'prefs-registration',
274 'default' => $context->msg(
275 'prefs-registration-date-time',
276 $lang->userTimeAndDate( $userRegistration, $displayUser ),
277 $lang->userDate( $userRegistration, $displayUser ),
278 $lang->userTime( $userRegistration, $displayUser )
279 )->parse(),
280 'section' => 'personal/info',
281 ];
282 }
283
284 $canViewPrivateInfo = $user->isAllowed( 'viewmyprivateinfo' );
285 $canEditPrivateInfo = $user->isAllowed( 'editmyprivateinfo' );
286
287 // Actually changeable stuff
288 $defaultPreferences['realname'] = [
289 // (not really "private", but still shouldn't be edited without permission)
290 'type' => $canEditPrivateInfo && $authManager->allowsPropertyChange( 'realname' )
291 ? 'text' : 'info',
292 'default' => $user->getRealName(),
293 'section' => 'personal/info',
294 'label-message' => 'yourrealname',
295 'help-message' => 'prefs-help-realname',
296 ];
297
298 if ( $canEditPrivateInfo && $authManager->allowsAuthenticationDataChange(
299 new PasswordAuthenticationRequest(), false )->isGood()
300 ) {
301 $link = $linkRenderer->makeLink( SpecialPage::getTitleFor( 'ChangePassword' ),
302 $context->msg( 'prefs-resetpass' )->text(), [],
303 [ 'returnto' => SpecialPage::getTitleFor( 'Preferences' )->getPrefixedText() ] );
304
305 $defaultPreferences['password'] = [
306 'type' => 'info',
307 'raw' => true,
308 'default' => $link,
309 'label-message' => 'yourpassword',
310 'section' => 'personal/info',
311 ];
312 }
313 // Only show prefershttps if secure login is turned on
314 if ( $config->get( 'SecureLogin' ) && wfCanIPUseHTTPS( $context->getRequest()->getIP() ) ) {
315 $defaultPreferences['prefershttps'] = [
316 'type' => 'toggle',
317 'label-message' => 'tog-prefershttps',
318 'help-message' => 'prefs-help-prefershttps',
319 'section' => 'personal/info'
320 ];
321 }
322
323 // Language
324 $languages = Language::fetchLanguageNames( null, 'mw' );
325 $languageCode = $config->get( 'LanguageCode' );
326 if ( !array_key_exists( $languageCode, $languages ) ) {
327 $languages[$languageCode] = $languageCode;
328 }
329 ksort( $languages );
330
331 $options = [];
332 foreach ( $languages as $code => $name ) {
333 $display = wfBCP47( $code ) . ' - ' . $name;
334 $options[$display] = $code;
335 }
336 $defaultPreferences['language'] = [
337 'type' => 'select',
338 'section' => 'personal/i18n',
339 'options' => $options,
340 'label-message' => 'yourlanguage',
341 ];
342
343 $defaultPreferences['gender'] = [
344 'type' => 'radio',
345 'section' => 'personal/i18n',
346 'options' => [
347 $context->msg( 'parentheses' )
348 ->params( $context->msg( 'gender-unknown' )->plain() )
349 ->escaped() => 'unknown',
350 $context->msg( 'gender-female' )->escaped() => 'female',
351 $context->msg( 'gender-male' )->escaped() => 'male',
352 ],
353 'label-message' => 'yourgender',
354 'help-message' => 'prefs-help-gender',
355 ];
356
357 // see if there are multiple language variants to choose from
358 if ( !$config->get( 'DisableLangConversion' ) ) {
359 foreach ( LanguageConverter::$languagesWithVariants as $langCode ) {
360 if ( $langCode == $wgContLang->getCode() ) {
361 $variants = $wgContLang->getVariants();
362
363 if ( count( $variants ) <= 1 ) {
364 continue;
365 }
366
367 $variantArray = [];
368 foreach ( $variants as $v ) {
369 $v = str_replace( '_', '-', strtolower( $v ) );
370 $variantArray[$v] = $lang->getVariantname( $v, false );
371 }
372
373 $options = [];
374 foreach ( $variantArray as $code => $name ) {
375 $display = wfBCP47( $code ) . ' - ' . $name;
376 $options[$display] = $code;
377 }
378
379 $defaultPreferences['variant'] = [
380 'label-message' => 'yourvariant',
381 'type' => 'select',
382 'options' => $options,
383 'section' => 'personal/i18n',
384 'help-message' => 'prefs-help-variant',
385 ];
386 } else {
387 $defaultPreferences["variant-$langCode"] = [
388 'type' => 'api',
389 ];
390 }
391 }
392 }
393
394 // Stuff from Language::getExtraUserToggles()
395 // FIXME is this dead code? $extraUserToggles doesn't seem to be defined for any language
396 $toggles = $wgContLang->getExtraUserToggles();
397
398 foreach ( $toggles as $toggle ) {
399 $defaultPreferences[$toggle] = [
400 'type' => 'toggle',
401 'section' => 'personal/i18n',
402 'label-message' => "tog-$toggle",
403 ];
404 }
405
406 // show a preview of the old signature first
407 $oldsigWikiText = $wgParser->preSaveTransform(
408 '~~~',
409 $context->getTitle(),
410 $user,
411 ParserOptions::newFromContext( $context )
412 );
413 $oldsigHTML = $context->getOutput()->parseInline( $oldsigWikiText, true, true );
414 $defaultPreferences['oldsig'] = [
415 'type' => 'info',
416 'raw' => true,
417 'label-message' => 'tog-oldsig',
418 'default' => $oldsigHTML,
419 'section' => 'personal/signature',
420 ];
421 $defaultPreferences['nickname'] = [
422 'type' => $authManager->allowsPropertyChange( 'nickname' ) ? 'text' : 'info',
423 'maxlength' => $config->get( 'MaxSigChars' ),
424 'label-message' => 'yournick',
425 'validation-callback' => [ 'Preferences', 'validateSignature' ],
426 'section' => 'personal/signature',
427 'filter-callback' => [ 'Preferences', 'cleanSignature' ],
428 ];
429 $defaultPreferences['fancysig'] = [
430 'type' => 'toggle',
431 'label-message' => 'tog-fancysig',
432 // show general help about signature at the bottom of the section
433 'help-message' => 'prefs-help-signature',
434 'section' => 'personal/signature'
435 ];
436
437 # # Email stuff
438
439 if ( $config->get( 'EnableEmail' ) ) {
440 if ( $canViewPrivateInfo ) {
441 $helpMessages[] = $config->get( 'EmailConfirmToEdit' )
442 ? 'prefs-help-email-required'
443 : 'prefs-help-email';
444
445 if ( $config->get( 'EnableUserEmail' ) ) {
446 // additional messages when users can send email to each other
447 $helpMessages[] = 'prefs-help-email-others';
448 }
449
450 $emailAddress = $user->getEmail() ? htmlspecialchars( $user->getEmail() ) : '';
451 if ( $canEditPrivateInfo && $authManager->allowsPropertyChange( 'emailaddress' ) ) {
452 $link = $linkRenderer->makeLink(
453 SpecialPage::getTitleFor( 'ChangeEmail' ),
454 $context->msg( $user->getEmail() ? 'prefs-changeemail' : 'prefs-setemail' )->text(),
455 [],
456 [ 'returnto' => SpecialPage::getTitleFor( 'Preferences' )->getPrefixedText() ] );
457
458 $emailAddress .= $emailAddress == '' ? $link : (
459 $context->msg( 'word-separator' )->escaped()
460 . $context->msg( 'parentheses' )->rawParams( $link )->escaped()
461 );
462 }
463
464 $defaultPreferences['emailaddress'] = [
465 'type' => 'info',
466 'raw' => true,
467 'default' => $emailAddress,
468 'label-message' => 'youremail',
469 'section' => 'personal/email',
470 'help-messages' => $helpMessages,
471 # 'cssclass' chosen below
472 ];
473 }
474
475 $disableEmailPrefs = false;
476
477 if ( $config->get( 'EmailAuthentication' ) ) {
478 $emailauthenticationclass = 'mw-email-not-authenticated';
479 if ( $user->getEmail() ) {
480 if ( $user->getEmailAuthenticationTimestamp() ) {
481 // date and time are separate parameters to facilitate localisation.
482 // $time is kept for backward compat reasons.
483 // 'emailauthenticated' is also used in SpecialConfirmemail.php
484 $displayUser = $context->getUser();
485 $emailTimestamp = $user->getEmailAuthenticationTimestamp();
486 $time = $lang->userTimeAndDate( $emailTimestamp, $displayUser );
487 $d = $lang->userDate( $emailTimestamp, $displayUser );
488 $t = $lang->userTime( $emailTimestamp, $displayUser );
489 $emailauthenticated = $context->msg( 'emailauthenticated',
490 $time, $d, $t )->parse() . '<br />';
491 $disableEmailPrefs = false;
492 $emailauthenticationclass = 'mw-email-authenticated';
493 } else {
494 $disableEmailPrefs = true;
495 $emailauthenticated = $context->msg( 'emailnotauthenticated' )->parse() . '<br />' .
496 Linker::linkKnown(
497 SpecialPage::getTitleFor( 'Confirmemail' ),
498 $context->msg( 'emailconfirmlink' )->escaped()
499 ) . '<br />';
500 $emailauthenticationclass = "mw-email-not-authenticated";
501 }
502 } else {
503 $disableEmailPrefs = true;
504 $emailauthenticated = $context->msg( 'noemailprefs' )->escaped();
505 $emailauthenticationclass = 'mw-email-none';
506 }
507
508 if ( $canViewPrivateInfo ) {
509 $defaultPreferences['emailauthentication'] = [
510 'type' => 'info',
511 'raw' => true,
512 'section' => 'personal/email',
513 'label-message' => 'prefs-emailconfirm-label',
514 'default' => $emailauthenticated,
515 # Apply the same CSS class used on the input to the message:
516 'cssclass' => $emailauthenticationclass,
517 ];
518 }
519 }
520
521 if ( $config->get( 'EnableUserEmail' ) && $user->isAllowed( 'sendemail' ) ) {
522 $defaultPreferences['disablemail'] = [
523 'type' => 'toggle',
524 'invert' => true,
525 'section' => 'personal/email',
526 'label-message' => 'allowemail',
527 'disabled' => $disableEmailPrefs,
528 ];
529 $defaultPreferences['ccmeonemails'] = [
530 'type' => 'toggle',
531 'section' => 'personal/email',
532 'label-message' => 'tog-ccmeonemails',
533 'disabled' => $disableEmailPrefs,
534 ];
535 }
536
537 if ( $config->get( 'EnotifWatchlist' ) ) {
538 $defaultPreferences['enotifwatchlistpages'] = [
539 'type' => 'toggle',
540 'section' => 'personal/email',
541 'label-message' => 'tog-enotifwatchlistpages',
542 'disabled' => $disableEmailPrefs,
543 ];
544 }
545 if ( $config->get( 'EnotifUserTalk' ) ) {
546 $defaultPreferences['enotifusertalkpages'] = [
547 'type' => 'toggle',
548 'section' => 'personal/email',
549 'label-message' => 'tog-enotifusertalkpages',
550 'disabled' => $disableEmailPrefs,
551 ];
552 }
553 if ( $config->get( 'EnotifUserTalk' ) || $config->get( 'EnotifWatchlist' ) ) {
554 if ( $config->get( 'EnotifMinorEdits' ) ) {
555 $defaultPreferences['enotifminoredits'] = [
556 'type' => 'toggle',
557 'section' => 'personal/email',
558 'label-message' => 'tog-enotifminoredits',
559 'disabled' => $disableEmailPrefs,
560 ];
561 }
562
563 if ( $config->get( 'EnotifRevealEditorAddress' ) ) {
564 $defaultPreferences['enotifrevealaddr'] = [
565 'type' => 'toggle',
566 'section' => 'personal/email',
567 'label-message' => 'tog-enotifrevealaddr',
568 'disabled' => $disableEmailPrefs,
569 ];
570 }
571 }
572 }
573 }
574
575 /**
576 * @param User $user
577 * @param IContextSource $context
578 * @param array $defaultPreferences
579 * @return void
580 */
581 static function skinPreferences( $user, IContextSource $context, &$defaultPreferences ) {
582 # # Skin #####################################
583
584 // Skin selector, if there is at least one valid skin
585 $skinOptions = self::generateSkinOptions( $user, $context );
586 if ( $skinOptions ) {
587 $defaultPreferences['skin'] = [
588 'type' => 'radio',
589 'options' => $skinOptions,
590 'label' => '&#160;',
591 'section' => 'rendering/skin',
592 ];
593 }
594
595 $config = $context->getConfig();
596 $allowUserCss = $config->get( 'AllowUserCss' );
597 $allowUserJs = $config->get( 'AllowUserJs' );
598 # Create links to user CSS/JS pages for all skins
599 # This code is basically copied from generateSkinOptions(). It'd
600 # be nice to somehow merge this back in there to avoid redundancy.
601 if ( $allowUserCss || $allowUserJs ) {
602 $linkTools = [];
603 $userName = $user->getName();
604
605 $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
606 if ( $allowUserCss ) {
607 $cssPage = Title::makeTitleSafe( NS_USER, $userName . '/common.css' );
608 $linkTools[] = $linkRenderer->makeLink( $cssPage, $context->msg( 'prefs-custom-css' )->text() );
609 }
610
611 if ( $allowUserJs ) {
612 $jsPage = Title::makeTitleSafe( NS_USER, $userName . '/common.js' );
613 $linkTools[] = $linkRenderer->makeLink( $jsPage, $context->msg( 'prefs-custom-js' )->text() );
614 }
615
616 $defaultPreferences['commoncssjs'] = [
617 'type' => 'info',
618 'raw' => true,
619 'default' => $context->getLanguage()->pipeList( $linkTools ),
620 'label-message' => 'prefs-common-css-js',
621 'section' => 'rendering/skin',
622 ];
623 }
624 }
625
626 /**
627 * @param User $user
628 * @param IContextSource $context
629 * @param array $defaultPreferences
630 */
631 static function filesPreferences( $user, IContextSource $context, &$defaultPreferences ) {
632 # # Files #####################################
633 $defaultPreferences['imagesize'] = [
634 'type' => 'select',
635 'options' => self::getImageSizes( $context ),
636 'label-message' => 'imagemaxsize',
637 'section' => 'rendering/files',
638 ];
639 $defaultPreferences['thumbsize'] = [
640 'type' => 'select',
641 'options' => self::getThumbSizes( $context ),
642 'label-message' => 'thumbsize',
643 'section' => 'rendering/files',
644 ];
645 }
646
647 /**
648 * @param User $user
649 * @param IContextSource $context
650 * @param array $defaultPreferences
651 * @return void
652 */
653 static function datetimePreferences( $user, IContextSource $context, &$defaultPreferences ) {
654 # # Date and time #####################################
655 $dateOptions = self::getDateOptions( $context );
656 if ( $dateOptions ) {
657 $defaultPreferences['date'] = [
658 'type' => 'radio',
659 'options' => $dateOptions,
660 'label' => '&#160;',
661 'section' => 'rendering/dateformat',
662 ];
663 }
664
665 // Info
666 $now = wfTimestampNow();
667 $lang = $context->getLanguage();
668 $nowlocal = Xml::element( 'span', [ 'id' => 'wpLocalTime' ],
669 $lang->userTime( $now, $user ) );
670 $nowserver = $lang->userTime( $now, $user,
671 [ 'format' => false, 'timecorrection' => false ] ) .
672 Html::hidden( 'wpServerTime', (int)substr( $now, 8, 2 ) * 60 + (int)substr( $now, 10, 2 ) );
673
674 $defaultPreferences['nowserver'] = [
675 'type' => 'info',
676 'raw' => 1,
677 'label-message' => 'servertime',
678 'default' => $nowserver,
679 'section' => 'rendering/timeoffset',
680 ];
681
682 $defaultPreferences['nowlocal'] = [
683 'type' => 'info',
684 'raw' => 1,
685 'label-message' => 'localtime',
686 'default' => $nowlocal,
687 'section' => 'rendering/timeoffset',
688 ];
689
690 // Grab existing pref.
691 $tzOffset = $user->getOption( 'timecorrection' );
692 $tz = explode( '|', $tzOffset, 3 );
693
694 $tzOptions = self::getTimezoneOptions( $context );
695
696 $tzSetting = $tzOffset;
697 if ( count( $tz ) > 1 && $tz[0] == 'ZoneInfo' &&
698 !in_array( $tzOffset, HTMLFormField::flattenOptions( $tzOptions ) )
699 ) {
700 // Timezone offset can vary with DST
701 try {
702 $userTZ = new DateTimeZone( $tz[2] );
703 $minDiff = floor( $userTZ->getOffset( new DateTime( 'now' ) ) / 60 );
704 $tzSetting = "ZoneInfo|$minDiff|{$tz[2]}";
705 } catch ( Exception $e ) {
706 // User has an invalid time zone set. Fall back to just using the offset
707 $tz[0] = 'Offset';
708 }
709 }
710 if ( count( $tz ) > 1 && $tz[0] == 'Offset' ) {
711 $minDiff = $tz[1];
712 $tzSetting = sprintf( '%+03d:%02d', floor( $minDiff / 60 ), abs( $minDiff ) % 60 );
713 }
714
715 $defaultPreferences['timecorrection'] = [
716 'class' => 'HTMLSelectOrOtherField',
717 'label-message' => 'timezonelegend',
718 'options' => $tzOptions,
719 'default' => $tzSetting,
720 'size' => 20,
721 'section' => 'rendering/timeoffset',
722 ];
723 }
724
725 /**
726 * @param User $user
727 * @param IContextSource $context
728 * @param array $defaultPreferences
729 */
730 static function renderingPreferences( $user, IContextSource $context, &$defaultPreferences ) {
731 # # Diffs ####################################
732 $defaultPreferences['diffonly'] = [
733 'type' => 'toggle',
734 'section' => 'rendering/diffs',
735 'label-message' => 'tog-diffonly',
736 ];
737 $defaultPreferences['norollbackdiff'] = [
738 'type' => 'toggle',
739 'section' => 'rendering/diffs',
740 'label-message' => 'tog-norollbackdiff',
741 ];
742
743 # # Page Rendering ##############################
744 if ( $context->getConfig()->get( 'AllowUserCssPrefs' ) ) {
745 $defaultPreferences['underline'] = [
746 'type' => 'select',
747 'options' => [
748 $context->msg( 'underline-never' )->text() => 0,
749 $context->msg( 'underline-always' )->text() => 1,
750 $context->msg( 'underline-default' )->text() => 2,
751 ],
752 'label-message' => 'tog-underline',
753 'section' => 'rendering/advancedrendering',
754 ];
755 }
756
757 $stubThresholdValues = [ 50, 100, 500, 1000, 2000, 5000, 10000 ];
758 $stubThresholdOptions = [ $context->msg( 'stub-threshold-disabled' )->text() => 0 ];
759 foreach ( $stubThresholdValues as $value ) {
760 $stubThresholdOptions[$context->msg( 'size-bytes', $value )->text()] = $value;
761 }
762
763 $defaultPreferences['stubthreshold'] = [
764 'type' => 'select',
765 'section' => 'rendering/advancedrendering',
766 'options' => $stubThresholdOptions,
767 // This is not a raw HTML message; label-raw is needed for the manual <a></a>
768 'label-raw' => $context->msg( 'stub-threshold' )->rawParams(
769 '<a href="#" class="stub">' .
770 $context->msg( 'stub-threshold-sample-link' )->parse() .
771 '</a>' )->parse(),
772 ];
773
774 $defaultPreferences['showhiddencats'] = [
775 'type' => 'toggle',
776 'section' => 'rendering/advancedrendering',
777 'label-message' => 'tog-showhiddencats'
778 ];
779
780 $defaultPreferences['numberheadings'] = [
781 'type' => 'toggle',
782 'section' => 'rendering/advancedrendering',
783 'label-message' => 'tog-numberheadings',
784 ];
785 }
786
787 /**
788 * @param User $user
789 * @param IContextSource $context
790 * @param array $defaultPreferences
791 */
792 static function editingPreferences( $user, IContextSource $context, &$defaultPreferences ) {
793 # # Editing #####################################
794 $defaultPreferences['editsectiononrightclick'] = [
795 'type' => 'toggle',
796 'section' => 'editing/advancedediting',
797 'label-message' => 'tog-editsectiononrightclick',
798 ];
799 $defaultPreferences['editondblclick'] = [
800 'type' => 'toggle',
801 'section' => 'editing/advancedediting',
802 'label-message' => 'tog-editondblclick',
803 ];
804
805 if ( $context->getConfig()->get( 'AllowUserCssPrefs' ) ) {
806 $defaultPreferences['editfont'] = [
807 'type' => 'select',
808 'section' => 'editing/editor',
809 'label-message' => 'editfont-style',
810 'options' => [
811 $context->msg( 'editfont-default' )->text() => 'default',
812 $context->msg( 'editfont-monospace' )->text() => 'monospace',
813 $context->msg( 'editfont-sansserif' )->text() => 'sans-serif',
814 $context->msg( 'editfont-serif' )->text() => 'serif',
815 ]
816 ];
817 }
818
819 if ( $user->isAllowed( 'minoredit' ) ) {
820 $defaultPreferences['minordefault'] = [
821 'type' => 'toggle',
822 'section' => 'editing/editor',
823 'label-message' => 'tog-minordefault',
824 ];
825 }
826
827 $defaultPreferences['forceeditsummary'] = [
828 'type' => 'toggle',
829 'section' => 'editing/editor',
830 'label-message' => 'tog-forceeditsummary',
831 ];
832 $defaultPreferences['useeditwarning'] = [
833 'type' => 'toggle',
834 'section' => 'editing/editor',
835 'label-message' => 'tog-useeditwarning',
836 ];
837 $defaultPreferences['showtoolbar'] = [
838 'type' => 'toggle',
839 'section' => 'editing/editor',
840 'label-message' => 'tog-showtoolbar',
841 ];
842
843 $defaultPreferences['previewonfirst'] = [
844 'type' => 'toggle',
845 'section' => 'editing/preview',
846 'label-message' => 'tog-previewonfirst',
847 ];
848 $defaultPreferences['previewontop'] = [
849 'type' => 'toggle',
850 'section' => 'editing/preview',
851 'label-message' => 'tog-previewontop',
852 ];
853 $defaultPreferences['uselivepreview'] = [
854 'type' => 'toggle',
855 'section' => 'editing/preview',
856 'label-message' => 'tog-uselivepreview',
857 ];
858 }
859
860 /**
861 * @param User $user
862 * @param IContextSource $context
863 * @param array $defaultPreferences
864 */
865 static function rcPreferences( $user, IContextSource $context, &$defaultPreferences ) {
866 $config = $context->getConfig();
867 $rcMaxAge = $config->get( 'RCMaxAge' );
868 # # RecentChanges #####################################
869 $defaultPreferences['rcdays'] = [
870 'type' => 'float',
871 'label-message' => 'recentchangesdays',
872 'section' => 'rc/displayrc',
873 'min' => 1,
874 'max' => ceil( $rcMaxAge / ( 3600 * 24 ) ),
875 'help' => $context->msg( 'recentchangesdays-max' )->numParams(
876 ceil( $rcMaxAge / ( 3600 * 24 ) ) )->escaped()
877 ];
878 $defaultPreferences['rclimit'] = [
879 'type' => 'int',
880 'label-message' => 'recentchangescount',
881 'help-message' => 'prefs-help-recentchangescount',
882 'section' => 'rc/displayrc',
883 ];
884 $defaultPreferences['usenewrc'] = [
885 'type' => 'toggle',
886 'label-message' => 'tog-usenewrc',
887 'section' => 'rc/advancedrc',
888 ];
889 $defaultPreferences['hideminor'] = [
890 'type' => 'toggle',
891 'label-message' => 'tog-hideminor',
892 'section' => 'rc/advancedrc',
893 ];
894
895 if ( $config->get( 'RCWatchCategoryMembership' ) ) {
896 $defaultPreferences['hidecategorization'] = [
897 'type' => 'toggle',
898 'label-message' => 'tog-hidecategorization',
899 'section' => 'rc/advancedrc',
900 ];
901 }
902
903 if ( $user->useRCPatrol() ) {
904 $defaultPreferences['hidepatrolled'] = [
905 'type' => 'toggle',
906 'section' => 'rc/advancedrc',
907 'label-message' => 'tog-hidepatrolled',
908 ];
909 }
910
911 if ( $user->useNPPatrol() ) {
912 $defaultPreferences['newpageshidepatrolled'] = [
913 'type' => 'toggle',
914 'section' => 'rc/advancedrc',
915 'label-message' => 'tog-newpageshidepatrolled',
916 ];
917 }
918
919 if ( $config->get( 'RCShowWatchingUsers' ) ) {
920 $defaultPreferences['shownumberswatching'] = [
921 'type' => 'toggle',
922 'section' => 'rc/advancedrc',
923 'label-message' => 'tog-shownumberswatching',
924 ];
925 }
926 }
927
928 /**
929 * @param User $user
930 * @param IContextSource $context
931 * @param array $defaultPreferences
932 */
933 static function watchlistPreferences( $user, IContextSource $context, &$defaultPreferences ) {
934 $config = $context->getConfig();
935 $watchlistdaysMax = ceil( $config->get( 'RCMaxAge' ) / ( 3600 * 24 ) );
936
937 # # Watchlist #####################################
938 if ( $user->isAllowed( 'editmywatchlist' ) ) {
939 $editWatchlistLinks = [];
940 $editWatchlistModes = [
941 'edit' => [ 'EditWatchlist', false ],
942 'raw' => [ 'EditWatchlist', 'raw' ],
943 'clear' => [ 'EditWatchlist', 'clear' ],
944 ];
945 foreach ( $editWatchlistModes as $editWatchlistMode => $mode ) {
946 // Messages: prefs-editwatchlist-edit, prefs-editwatchlist-raw, prefs-editwatchlist-clear
947 $editWatchlistLinks[] = Linker::linkKnown(
948 SpecialPage::getTitleFor( $mode[0], $mode[1] ),
949 $context->msg( "prefs-editwatchlist-{$editWatchlistMode}" )->parse()
950 );
951 }
952
953 $defaultPreferences['editwatchlist'] = [
954 'type' => 'info',
955 'raw' => true,
956 'default' => $context->getLanguage()->pipeList( $editWatchlistLinks ),
957 'label-message' => 'prefs-editwatchlist-label',
958 'section' => 'watchlist/editwatchlist',
959 ];
960 }
961
962 $defaultPreferences['watchlistdays'] = [
963 'type' => 'float',
964 'min' => 0,
965 'max' => $watchlistdaysMax,
966 'section' => 'watchlist/displaywatchlist',
967 'help' => $context->msg( 'prefs-watchlist-days-max' )->numParams(
968 $watchlistdaysMax )->escaped(),
969 'label-message' => 'prefs-watchlist-days',
970 ];
971 $defaultPreferences['wllimit'] = [
972 'type' => 'int',
973 'min' => 0,
974 'max' => 1000,
975 'label-message' => 'prefs-watchlist-edits',
976 'help' => $context->msg( 'prefs-watchlist-edits-max' )->escaped(),
977 'section' => 'watchlist/displaywatchlist',
978 ];
979 $defaultPreferences['extendwatchlist'] = [
980 'type' => 'toggle',
981 'section' => 'watchlist/advancedwatchlist',
982 'label-message' => 'tog-extendwatchlist',
983 ];
984 $defaultPreferences['watchlisthideminor'] = [
985 'type' => 'toggle',
986 'section' => 'watchlist/advancedwatchlist',
987 'label-message' => 'tog-watchlisthideminor',
988 ];
989 $defaultPreferences['watchlisthidebots'] = [
990 'type' => 'toggle',
991 'section' => 'watchlist/advancedwatchlist',
992 'label-message' => 'tog-watchlisthidebots',
993 ];
994 $defaultPreferences['watchlisthideown'] = [
995 'type' => 'toggle',
996 'section' => 'watchlist/advancedwatchlist',
997 'label-message' => 'tog-watchlisthideown',
998 ];
999 $defaultPreferences['watchlisthideanons'] = [
1000 'type' => 'toggle',
1001 'section' => 'watchlist/advancedwatchlist',
1002 'label-message' => 'tog-watchlisthideanons',
1003 ];
1004 $defaultPreferences['watchlisthideliu'] = [
1005 'type' => 'toggle',
1006 'section' => 'watchlist/advancedwatchlist',
1007 'label-message' => 'tog-watchlisthideliu',
1008 ];
1009 $defaultPreferences['watchlistreloadautomatically'] = [
1010 'type' => 'toggle',
1011 'section' => 'watchlist/advancedwatchlist',
1012 'label-message' => 'tog-watchlistreloadautomatically',
1013 ];
1014
1015 if ( $config->get( 'RCWatchCategoryMembership' ) ) {
1016 $defaultPreferences['watchlisthidecategorization'] = [
1017 'type' => 'toggle',
1018 'section' => 'watchlist/advancedwatchlist',
1019 'label-message' => 'tog-watchlisthidecategorization',
1020 ];
1021 }
1022
1023 if ( $user->useRCPatrol() ) {
1024 $defaultPreferences['watchlisthidepatrolled'] = [
1025 'type' => 'toggle',
1026 'section' => 'watchlist/advancedwatchlist',
1027 'label-message' => 'tog-watchlisthidepatrolled',
1028 ];
1029 }
1030
1031 $watchTypes = [
1032 'edit' => 'watchdefault',
1033 'move' => 'watchmoves',
1034 'delete' => 'watchdeletion'
1035 ];
1036
1037 // Kinda hacky
1038 if ( $user->isAllowed( 'createpage' ) || $user->isAllowed( 'createtalk' ) ) {
1039 $watchTypes['read'] = 'watchcreations';
1040 }
1041
1042 if ( $user->isAllowed( 'rollback' ) ) {
1043 $watchTypes['rollback'] = 'watchrollback';
1044 }
1045
1046 if ( $user->isAllowed( 'upload' ) ) {
1047 $watchTypes['upload'] = 'watchuploads';
1048 }
1049
1050 foreach ( $watchTypes as $action => $pref ) {
1051 if ( $user->isAllowed( $action ) ) {
1052 // Messages:
1053 // tog-watchdefault, tog-watchmoves, tog-watchdeletion, tog-watchcreations, tog-watchuploads
1054 // tog-watchrollback
1055 $defaultPreferences[$pref] = [
1056 'type' => 'toggle',
1057 'section' => 'watchlist/advancedwatchlist',
1058 'label-message' => "tog-$pref",
1059 ];
1060 }
1061 }
1062
1063 if ( $config->get( 'EnableAPI' ) ) {
1064 $defaultPreferences['watchlisttoken'] = [
1065 'type' => 'api',
1066 ];
1067 $defaultPreferences['watchlisttoken-info'] = [
1068 'type' => 'info',
1069 'section' => 'watchlist/tokenwatchlist',
1070 'label-message' => 'prefs-watchlist-token',
1071 'default' => $user->getTokenFromOption( 'watchlisttoken' ),
1072 'help-message' => 'prefs-help-watchlist-token2',
1073 ];
1074 }
1075 }
1076
1077 /**
1078 * @param User $user
1079 * @param IContextSource $context
1080 * @param array $defaultPreferences
1081 */
1082 static function searchPreferences( $user, IContextSource $context, &$defaultPreferences ) {
1083 foreach ( MWNamespace::getValidNamespaces() as $n ) {
1084 $defaultPreferences['searchNs' . $n] = [
1085 'type' => 'api',
1086 ];
1087 }
1088 }
1089
1090 /**
1091 * Dummy, kept for backwards-compatibility.
1092 */
1093 static function miscPreferences( $user, IContextSource $context, &$defaultPreferences ) {
1094 }
1095
1096 /**
1097 * @param User $user The User object
1098 * @param IContextSource $context
1099 * @return array Text/links to display as key; $skinkey as value
1100 */
1101 static function generateSkinOptions( $user, IContextSource $context ) {
1102 $ret = [];
1103
1104 $mptitle = Title::newMainPage();
1105 $previewtext = $context->msg( 'skin-preview' )->escaped();
1106
1107 $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
1108
1109 # Only show skins that aren't disabled in $wgSkipSkins
1110 $validSkinNames = Skin::getAllowedSkins();
1111
1112 # Sort by UI skin name. First though need to update validSkinNames as sometimes
1113 # the skinkey & UI skinname differ (e.g. "standard" skinkey is "Classic" in the UI).
1114 foreach ( $validSkinNames as $skinkey => &$skinname ) {
1115 $msg = $context->msg( "skinname-{$skinkey}" );
1116 if ( $msg->exists() ) {
1117 $skinname = htmlspecialchars( $msg->text() );
1118 }
1119 }
1120 asort( $validSkinNames );
1121
1122 $config = $context->getConfig();
1123 $defaultSkin = $config->get( 'DefaultSkin' );
1124 $allowUserCss = $config->get( 'AllowUserCss' );
1125 $allowUserJs = $config->get( 'AllowUserJs' );
1126
1127 $foundDefault = false;
1128 foreach ( $validSkinNames as $skinkey => $sn ) {
1129 $linkTools = [];
1130
1131 # Mark the default skin
1132 if ( strcasecmp( $skinkey, $defaultSkin ) === 0 ) {
1133 $linkTools[] = $context->msg( 'default' )->escaped();
1134 $foundDefault = true;
1135 }
1136
1137 # Create preview link
1138 $mplink = htmlspecialchars( $mptitle->getLocalURL( [ 'useskin' => $skinkey ] ) );
1139 $linkTools[] = "<a target='_blank' href=\"$mplink\">$previewtext</a>";
1140
1141 # Create links to user CSS/JS pages
1142 if ( $allowUserCss ) {
1143 $cssPage = Title::makeTitleSafe( NS_USER, $user->getName() . '/' . $skinkey . '.css' );
1144 $linkTools[] = $linkRenderer->makeLink( $cssPage, $context->msg( 'prefs-custom-css' )->text() );
1145 }
1146
1147 if ( $allowUserJs ) {
1148 $jsPage = Title::makeTitleSafe( NS_USER, $user->getName() . '/' . $skinkey . '.js' );
1149 $linkTools[] = $linkRenderer->makeLink( $jsPage, $context->msg( 'prefs-custom-js' )->text() );
1150 }
1151
1152 $display = $sn . ' ' . $context->msg( 'parentheses' )
1153 ->rawParams( $context->getLanguage()->pipeList( $linkTools ) )
1154 ->escaped();
1155 $ret[$display] = $skinkey;
1156 }
1157
1158 if ( !$foundDefault ) {
1159 // If the default skin is not available, things are going to break horribly because the
1160 // default value for skin selector will not be a valid value. Let's just not show it then.
1161 return [];
1162 }
1163
1164 return $ret;
1165 }
1166
1167 /**
1168 * @param IContextSource $context
1169 * @return array
1170 */
1171 static function getDateOptions( IContextSource $context ) {
1172 $lang = $context->getLanguage();
1173 $dateopts = $lang->getDatePreferences();
1174
1175 $ret = [];
1176
1177 if ( $dateopts ) {
1178 if ( !in_array( 'default', $dateopts ) ) {
1179 $dateopts[] = 'default'; // Make sure default is always valid
1180 // Bug 19237
1181 }
1182
1183 // FIXME KLUGE: site default might not be valid for user language
1184 global $wgDefaultUserOptions;
1185 if ( !in_array( $wgDefaultUserOptions['date'], $dateopts ) ) {
1186 $wgDefaultUserOptions['date'] = 'default';
1187 }
1188
1189 $epoch = wfTimestampNow();
1190 foreach ( $dateopts as $key ) {
1191 if ( $key == 'default' ) {
1192 $formatted = $context->msg( 'datedefault' )->escaped();
1193 } else {
1194 $formatted = htmlspecialchars( $lang->timeanddate( $epoch, false, $key ) );
1195 }
1196 $ret[$formatted] = $key;
1197 }
1198 }
1199 return $ret;
1200 }
1201
1202 /**
1203 * @param IContextSource $context
1204 * @return array
1205 */
1206 static function getImageSizes( IContextSource $context ) {
1207 $ret = [];
1208 $pixels = $context->msg( 'unit-pixel' )->text();
1209
1210 foreach ( $context->getConfig()->get( 'ImageLimits' ) as $index => $limits ) {
1211 // Note: A left-to-right marker (\u200e) is inserted, see T144386
1212 $display = "{$limits[0]}" . json_decode( '"\u200e"' ) . "×{$limits[1]}" . $pixels;
1213 $ret[$display] = $index;
1214 }
1215
1216 return $ret;
1217 }
1218
1219 /**
1220 * @param IContextSource $context
1221 * @return array
1222 */
1223 static function getThumbSizes( IContextSource $context ) {
1224 $ret = [];
1225 $pixels = $context->msg( 'unit-pixel' )->text();
1226
1227 foreach ( $context->getConfig()->get( 'ThumbLimits' ) as $index => $size ) {
1228 $display = $size . $pixels;
1229 $ret[$display] = $index;
1230 }
1231
1232 return $ret;
1233 }
1234
1235 /**
1236 * @param string $signature
1237 * @param array $alldata
1238 * @param HTMLForm $form
1239 * @return bool|string
1240 */
1241 static function validateSignature( $signature, $alldata, $form ) {
1242 global $wgParser;
1243 $maxSigChars = $form->getConfig()->get( 'MaxSigChars' );
1244 if ( mb_strlen( $signature ) > $maxSigChars ) {
1245 return Xml::element( 'span', [ 'class' => 'error' ],
1246 $form->msg( 'badsiglength' )->numParams( $maxSigChars )->text() );
1247 } elseif ( isset( $alldata['fancysig'] ) &&
1248 $alldata['fancysig'] &&
1249 $wgParser->validateSig( $signature ) === false
1250 ) {
1251 return Xml::element(
1252 'span',
1253 [ 'class' => 'error' ],
1254 $form->msg( 'badsig' )->text()
1255 );
1256 } else {
1257 return true;
1258 }
1259 }
1260
1261 /**
1262 * @param string $signature
1263 * @param array $alldata
1264 * @param HTMLForm $form
1265 * @return string
1266 */
1267 static function cleanSignature( $signature, $alldata, $form ) {
1268 if ( isset( $alldata['fancysig'] ) && $alldata['fancysig'] ) {
1269 global $wgParser;
1270 $signature = $wgParser->cleanSig( $signature );
1271 } else {
1272 // When no fancy sig used, make sure ~{3,5} get removed.
1273 $signature = Parser::cleanSigInSig( $signature );
1274 }
1275
1276 return $signature;
1277 }
1278
1279 /**
1280 * @param User $user
1281 * @param IContextSource $context
1282 * @param string $formClass
1283 * @param array $remove Array of items to remove
1284 * @return PreferencesForm|HtmlForm
1285 */
1286 static function getFormObject(
1287 $user,
1288 IContextSource $context,
1289 $formClass = 'PreferencesForm',
1290 array $remove = []
1291 ) {
1292 $formDescriptor = Preferences::getPreferences( $user, $context );
1293 if ( count( $remove ) ) {
1294 $removeKeys = array_flip( $remove );
1295 $formDescriptor = array_diff_key( $formDescriptor, $removeKeys );
1296 }
1297
1298 // Remove type=api preferences. They are not intended for rendering in the form.
1299 foreach ( $formDescriptor as $name => $info ) {
1300 if ( isset( $info['type'] ) && $info['type'] === 'api' ) {
1301 unset( $formDescriptor[$name] );
1302 }
1303 }
1304
1305 /**
1306 * @var $htmlForm PreferencesForm
1307 */
1308 $htmlForm = new $formClass( $formDescriptor, $context, 'prefs' );
1309
1310 $htmlForm->setModifiedUser( $user );
1311 $htmlForm->setId( 'mw-prefs-form' );
1312 $htmlForm->setAutocomplete( 'off' );
1313 $htmlForm->setSubmitText( $context->msg( 'saveprefs' )->text() );
1314 # Used message keys: 'accesskey-preferences-save', 'tooltip-preferences-save'
1315 $htmlForm->setSubmitTooltip( 'preferences-save' );
1316 $htmlForm->setSubmitID( 'prefsubmit' );
1317 $htmlForm->setSubmitCallback( [ 'Preferences', 'tryFormSubmit' ] );
1318
1319 return $htmlForm;
1320 }
1321
1322 /**
1323 * @param IContextSource $context
1324 * @return array
1325 */
1326 static function getTimezoneOptions( IContextSource $context ) {
1327 $opt = [];
1328
1329 $localTZoffset = $context->getConfig()->get( 'LocalTZoffset' );
1330 $timeZoneList = self::getTimeZoneList( $context->getLanguage() );
1331
1332 $timestamp = MWTimestamp::getLocalInstance();
1333 // Check that the LocalTZoffset is the same as the local time zone offset
1334 if ( $localTZoffset == $timestamp->format( 'Z' ) / 60 ) {
1335 $timezoneName = $timestamp->getTimezone()->getName();
1336 // Localize timezone
1337 if ( isset( $timeZoneList[$timezoneName] ) ) {
1338 $timezoneName = $timeZoneList[$timezoneName]['name'];
1339 }
1340 $server_tz_msg = $context->msg(
1341 'timezoneuseserverdefault',
1342 $timezoneName
1343 )->text();
1344 } else {
1345 $tzstring = sprintf(
1346 '%+03d:%02d',
1347 floor( $localTZoffset / 60 ),
1348 abs( $localTZoffset ) % 60
1349 );
1350 $server_tz_msg = $context->msg( 'timezoneuseserverdefault', $tzstring )->text();
1351 }
1352 $opt[$server_tz_msg] = "System|$localTZoffset";
1353 $opt[$context->msg( 'timezoneuseoffset' )->text()] = 'other';
1354 $opt[$context->msg( 'guesstimezone' )->text()] = 'guess';
1355
1356 foreach ( $timeZoneList as $timeZoneInfo ) {
1357 $region = $timeZoneInfo['region'];
1358 if ( !isset( $opt[$region] ) ) {
1359 $opt[$region] = [];
1360 }
1361 $opt[$region][$timeZoneInfo['name']] = $timeZoneInfo['timecorrection'];
1362 }
1363 return $opt;
1364 }
1365
1366 /**
1367 * @param string $value
1368 * @param array $alldata
1369 * @return int
1370 */
1371 static function filterIntval( $value, $alldata ) {
1372 return intval( $value );
1373 }
1374
1375 /**
1376 * @param string $tz
1377 * @param array $alldata
1378 * @return string
1379 */
1380 static function filterTimezoneInput( $tz, $alldata ) {
1381 $data = explode( '|', $tz, 3 );
1382 switch ( $data[0] ) {
1383 case 'ZoneInfo':
1384 $valid = false;
1385
1386 if ( count( $data ) === 3 ) {
1387 // Make sure this timezone exists
1388 try {
1389 new DateTimeZone( $data[2] );
1390 // If the constructor didn't throw, we know it's valid
1391 $valid = true;
1392 } catch ( Exception $e ) {
1393 // Not a valid timezone
1394 }
1395 }
1396
1397 if ( !$valid ) {
1398 // If the supplied timezone doesn't exist, fall back to the encoded offset
1399 return 'Offset|' . intval( $tz[1] );
1400 }
1401 return $tz;
1402 case 'System':
1403 return $tz;
1404 default:
1405 $data = explode( ':', $tz, 2 );
1406 if ( count( $data ) == 2 ) {
1407 $data[0] = intval( $data[0] );
1408 $data[1] = intval( $data[1] );
1409 $minDiff = abs( $data[0] ) * 60 + $data[1];
1410 if ( $data[0] < 0 ) {
1411 $minDiff = - $minDiff;
1412 }
1413 } else {
1414 $minDiff = intval( $data[0] ) * 60;
1415 }
1416
1417 # Max is +14:00 and min is -12:00, see:
1418 # https://en.wikipedia.org/wiki/Timezone
1419 $minDiff = min( $minDiff, 840 ); # 14:00
1420 $minDiff = max( $minDiff, -720 ); # -12:00
1421 return 'Offset|' . $minDiff;
1422 }
1423 }
1424
1425 /**
1426 * Handle the form submission if everything validated properly
1427 *
1428 * @param array $formData
1429 * @param PreferencesForm $form
1430 * @return bool|Status|string
1431 */
1432 static function tryFormSubmit( $formData, $form ) {
1433 $user = $form->getModifiedUser();
1434 $hiddenPrefs = $form->getConfig()->get( 'HiddenPrefs' );
1435 $result = true;
1436
1437 if ( !$user->isAllowedAny( 'editmyprivateinfo', 'editmyoptions' ) ) {
1438 return Status::newFatal( 'mypreferencesprotected' );
1439 }
1440
1441 // Filter input
1442 foreach ( array_keys( $formData ) as $name ) {
1443 if ( isset( self::$saveFilters[$name] ) ) {
1444 $formData[$name] =
1445 call_user_func( self::$saveFilters[$name], $formData[$name], $formData );
1446 }
1447 }
1448
1449 // Fortunately, the realname field is MUCH simpler
1450 // (not really "private", but still shouldn't be edited without permission)
1451
1452 if ( !in_array( 'realname', $hiddenPrefs )
1453 && $user->isAllowed( 'editmyprivateinfo' )
1454 && array_key_exists( 'realname', $formData )
1455 ) {
1456 $realName = $formData['realname'];
1457 $user->setRealName( $realName );
1458 }
1459
1460 if ( $user->isAllowed( 'editmyoptions' ) ) {
1461 foreach ( self::$saveBlacklist as $b ) {
1462 unset( $formData[$b] );
1463 }
1464
1465 # If users have saved a value for a preference which has subsequently been disabled
1466 # via $wgHiddenPrefs, we don't want to destroy that setting in case the preference
1467 # is subsequently re-enabled
1468 foreach ( $hiddenPrefs as $pref ) {
1469 # If the user has not set a non-default value here, the default will be returned
1470 # and subsequently discarded
1471 $formData[$pref] = $user->getOption( $pref, null, true );
1472 }
1473
1474 // Keep old preferences from interfering due to back-compat code, etc.
1475 $user->resetOptions( 'unused', $form->getContext() );
1476
1477 foreach ( $formData as $key => $value ) {
1478 $user->setOption( $key, $value );
1479 }
1480
1481 Hooks::run( 'PreferencesFormPreSave', [ $formData, $form, $user, &$result ] );
1482 }
1483
1484 MediaWiki\Auth\AuthManager::callLegacyAuthPlugin( 'updateExternalDB', [ $user ] );
1485 $user->saveSettings();
1486
1487 return $result;
1488 }
1489
1490 /**
1491 * @param array $formData
1492 * @param PreferencesForm $form
1493 * @return Status
1494 */
1495 public static function tryUISubmit( $formData, $form ) {
1496 $res = self::tryFormSubmit( $formData, $form );
1497
1498 if ( $res ) {
1499 $urlOptions = [];
1500
1501 if ( $res === 'eauth' ) {
1502 $urlOptions['eauth'] = 1;
1503 }
1504
1505 $urlOptions += $form->getExtraSuccessRedirectParameters();
1506
1507 $url = $form->getTitle()->getFullURL( $urlOptions );
1508
1509 $context = $form->getContext();
1510 // Set session data for the success message
1511 $context->getRequest()->getSession()->set( 'specialPreferencesSaveSuccess', 1 );
1512
1513 $context->getOutput()->redirect( $url );
1514 }
1515
1516 return Status::newGood();
1517 }
1518
1519 /**
1520 * Get a list of all time zones
1521 * @param Language $language Language used for the localized names
1522 * @return array A list of all time zones. The system name of the time zone is used as key and
1523 * the value is an array which contains localized name, the timecorrection value used for
1524 * preferences and the region
1525 * @since 1.26
1526 */
1527 public static function getTimeZoneList( Language $language ) {
1528 $identifiers = DateTimeZone::listIdentifiers();
1529 if ( $identifiers === false ) {
1530 return [];
1531 }
1532 sort( $identifiers );
1533
1534 $tzRegions = [
1535 'Africa' => wfMessage( 'timezoneregion-africa' )->inLanguage( $language )->text(),
1536 'America' => wfMessage( 'timezoneregion-america' )->inLanguage( $language )->text(),
1537 'Antarctica' => wfMessage( 'timezoneregion-antarctica' )->inLanguage( $language )->text(),
1538 'Arctic' => wfMessage( 'timezoneregion-arctic' )->inLanguage( $language )->text(),
1539 'Asia' => wfMessage( 'timezoneregion-asia' )->inLanguage( $language )->text(),
1540 'Atlantic' => wfMessage( 'timezoneregion-atlantic' )->inLanguage( $language )->text(),
1541 'Australia' => wfMessage( 'timezoneregion-australia' )->inLanguage( $language )->text(),
1542 'Europe' => wfMessage( 'timezoneregion-europe' )->inLanguage( $language )->text(),
1543 'Indian' => wfMessage( 'timezoneregion-indian' )->inLanguage( $language )->text(),
1544 'Pacific' => wfMessage( 'timezoneregion-pacific' )->inLanguage( $language )->text(),
1545 ];
1546 asort( $tzRegions );
1547
1548 $timeZoneList = [];
1549
1550 $now = new DateTime();
1551
1552 foreach ( $identifiers as $identifier ) {
1553 $parts = explode( '/', $identifier, 2 );
1554
1555 // DateTimeZone::listIdentifiers() returns a number of
1556 // backwards-compatibility entries. This filters them out of the
1557 // list presented to the user.
1558 if ( count( $parts ) !== 2 || !array_key_exists( $parts[0], $tzRegions ) ) {
1559 continue;
1560 }
1561
1562 // Localize region
1563 $parts[0] = $tzRegions[$parts[0]];
1564
1565 $dateTimeZone = new DateTimeZone( $identifier );
1566 $minDiff = floor( $dateTimeZone->getOffset( $now ) / 60 );
1567
1568 $display = str_replace( '_', ' ', $parts[0] . '/' . $parts[1] );
1569 $value = "ZoneInfo|$minDiff|$identifier";
1570
1571 $timeZoneList[$identifier] = [
1572 'name' => $display,
1573 'timecorrection' => $value,
1574 'region' => $parts[0],
1575 ];
1576 }
1577
1578 return $timeZoneList;
1579 }
1580 }
1581
1582 /** Some tweaks to allow js prefs to work */
1583 class PreferencesForm extends HTMLForm {
1584 // Override default value from HTMLForm
1585 protected $mSubSectionBeforeFields = false;
1586
1587 private $modifiedUser;
1588
1589 /**
1590 * @param User $user
1591 */
1592 public function setModifiedUser( $user ) {
1593 $this->modifiedUser = $user;
1594 }
1595
1596 /**
1597 * @return User
1598 */
1599 public function getModifiedUser() {
1600 if ( $this->modifiedUser === null ) {
1601 return $this->getUser();
1602 } else {
1603 return $this->modifiedUser;
1604 }
1605 }
1606
1607 /**
1608 * Get extra parameters for the query string when redirecting after
1609 * successful save.
1610 *
1611 * @return array
1612 */
1613 public function getExtraSuccessRedirectParameters() {
1614 return [];
1615 }
1616
1617 /**
1618 * @param string $html
1619 * @return string
1620 */
1621 function wrapForm( $html ) {
1622 $html = Xml::tags( 'div', [ 'id' => 'preferences' ], $html );
1623
1624 return parent::wrapForm( $html );
1625 }
1626
1627 /**
1628 * @return string
1629 */
1630 function getButtons() {
1631 $attrs = [ 'id' => 'mw-prefs-restoreprefs' ];
1632
1633 if ( !$this->getModifiedUser()->isAllowedAny( 'editmyprivateinfo', 'editmyoptions' ) ) {
1634 return '';
1635 }
1636
1637 $html = parent::getButtons();
1638
1639 if ( $this->getModifiedUser()->isAllowed( 'editmyoptions' ) ) {
1640 $t = SpecialPage::getTitleFor( 'Preferences', 'reset' );
1641
1642 $linkRenderer = MediaWikiServices::getInstance()->getLinkRenderer();
1643 $html .= "\n" . $linkRenderer->makeLink( $t, $this->msg( 'restoreprefs' )->text(),
1644 Html::buttonAttributes( $attrs, [ 'mw-ui-quiet' ] ) );
1645
1646 $html = Xml::tags( 'div', [ 'class' => 'mw-prefs-buttons' ], $html );
1647 }
1648
1649 return $html;
1650 }
1651
1652 /**
1653 * Separate multi-option preferences into multiple preferences, since we
1654 * have to store them separately
1655 * @param array $data
1656 * @return array
1657 */
1658 function filterDataForSubmit( $data ) {
1659 foreach ( $this->mFlatFields as $fieldname => $field ) {
1660 if ( $field instanceof HTMLNestedFilterable ) {
1661 $info = $field->mParams;
1662 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $fieldname;
1663 foreach ( $field->filterDataForSubmit( $data[$fieldname] ) as $key => $value ) {
1664 $data["$prefix$key"] = $value;
1665 }
1666 unset( $data[$fieldname] );
1667 }
1668 }
1669
1670 return $data;
1671 }
1672
1673 /**
1674 * Get the whole body of the form.
1675 * @return string
1676 */
1677 function getBody() {
1678 return $this->displaySection( $this->mFieldTree, '', 'mw-prefsection-' );
1679 }
1680
1681 /**
1682 * Get the "<legend>" for a given section key. Normally this is the
1683 * prefs-$key message but we'll allow extensions to override it.
1684 * @param string $key
1685 * @return string
1686 */
1687 function getLegend( $key ) {
1688 $legend = parent::getLegend( $key );
1689 Hooks::run( 'PreferencesGetLegend', [ $this, $key, &$legend ] );
1690 return $legend;
1691 }
1692
1693 /**
1694 * Get the keys of each top level preference section.
1695 * @return array of section keys
1696 */
1697 function getPreferenceSections() {
1698 return array_keys( array_filter( $this->mFieldTree, 'is_array' ) );
1699 }
1700 }