3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
20 use MediaWiki\Auth\AuthManager
;
21 use MediaWiki\Auth\PasswordAuthenticationRequest
;
22 use MediaWiki\MediaWikiServices
;
25 * We're now using the HTMLForm object with some customisation to generate the
26 * Preferences form. This object handles generic submission, CSRF protection,
27 * layout and other logic in a reusable manner. We subclass it as a PreferencesForm
28 * to make some minor customisations.
30 * In order to generate the form, the HTMLForm object needs an array structure
31 * detailing the form fields available, and that's what this class is for. Each
32 * element of the array is a basic property-list, including the type of field,
33 * the label it is to be given in the form, callbacks for validation and
34 * 'filtering', and other pertinent information. Note that the 'default' field
35 * is named for generic forms, and does not represent the preference's default
36 * (which is stored in $wgDefaultUserOptions), but the default for the form
37 * field, which should be whatever the user has set for that preference. There
38 * is no need to override it unless you have some special storage logic (for
39 * instance, those not presently stored as options, but which are best set from
40 * the user preferences view).
42 * Field types are implemented as subclasses of the generic HTMLFormField
43 * object, and typically implement at least getInputHTML, which generates the
44 * HTML for the input field to be placed in the table.
46 * Once fields have been retrieved and validated, submission logic is handed
47 * over to the tryUISubmit static method of this class.
51 protected static $saveFilters = [
52 'timecorrection' => [ 'Preferences', 'filterTimezoneInput' ],
53 'rclimit' => [ 'Preferences', 'filterIntval' ],
54 'wllimit' => [ 'Preferences', 'filterIntval' ],
55 'searchlimit' => [ 'Preferences', 'filterIntval' ],
58 // Stuff that shouldn't be saved as a preference.
59 private static $saveBlacklist = [
67 static function getSaveBlacklist() {
68 return self
::$saveBlacklist;
74 * @param IContextSource $context
77 static function getPreferences( $user, IContextSource
$context ) {
78 $defaultPreferences = [];
80 self
::profilePreferences( $user, $context, $defaultPreferences );
81 self
::skinPreferences( $user, $context, $defaultPreferences );
82 self
::datetimePreferences( $user, $context, $defaultPreferences );
83 self
::filesPreferences( $user, $context, $defaultPreferences );
84 self
::renderingPreferences( $user, $context, $defaultPreferences );
85 self
::editingPreferences( $user, $context, $defaultPreferences );
86 self
::rcPreferences( $user, $context, $defaultPreferences );
87 self
::watchlistPreferences( $user, $context, $defaultPreferences );
88 self
::searchPreferences( $user, $context, $defaultPreferences );
89 self
::miscPreferences( $user, $context, $defaultPreferences );
91 Hooks
::run( 'GetPreferences', [ $user, &$defaultPreferences ] );
93 self
::loadPreferenceValues( $user, $context, $defaultPreferences );
94 return $defaultPreferences;
98 * Loads existing values for a given array of preferences
101 * @param IContextSource $context
102 * @param array &$defaultPreferences Array to load values for
105 static function loadPreferenceValues( $user, $context, &$defaultPreferences ) {
106 # # Remove preferences that wikis don't want to use
107 foreach ( $context->getConfig()->get( 'HiddenPrefs' ) as $pref ) {
108 if ( isset( $defaultPreferences[$pref] ) ) {
109 unset( $defaultPreferences[$pref] );
113 # # Make sure that form fields have their parent set. See T43337.
114 $dummyForm = new HTMLForm( [], $context );
116 $disable = !$user->isAllowed( 'editmyoptions' );
118 $defaultOptions = User
::getDefaultOptions();
119 # # Prod in defaults from the user
120 foreach ( $defaultPreferences as $name => &$info ) {
121 $prefFromUser = self
::getOptionFromUser( $name, $info, $user );
122 if ( $disable && !in_array( $name, self
::$saveBlacklist ) ) {
123 $info['disabled'] = 'disabled';
125 $field = HTMLForm
::loadInputFromParameters( $name, $info, $dummyForm ); // For validation
126 $globalDefault = isset( $defaultOptions[$name] )
127 ?
$defaultOptions[$name]
130 // If it validates, set it as the default
131 if ( isset( $info['default'] ) ) {
132 // Already set, no problem
134 } elseif ( !is_null( $prefFromUser ) && // Make sure we're not just pulling nothing
135 $field->validate( $prefFromUser, $user->getOptions() ) === true ) {
136 $info['default'] = $prefFromUser;
137 } elseif ( $field->validate( $globalDefault, $user->getOptions() ) === true ) {
138 $info['default'] = $globalDefault;
140 throw new MWException( "Global default '$globalDefault' is invalid for field $name" );
144 return $defaultPreferences;
148 * Pull option from a user account. Handles stuff like array-type preferences.
150 * @param string $name
153 * @return array|string
155 static function getOptionFromUser( $name, $info, $user ) {
156 $val = $user->getOption( $name );
158 // Handling for multiselect preferences
159 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
160 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
161 $options = HTMLFormField
::flattenOptions( $info['options'] );
162 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
165 foreach ( $options as $value ) {
166 if ( $user->getOption( "$prefix$value" ) ) {
172 // Handling for checkmatrix preferences
173 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
174 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
175 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
176 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
177 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
180 foreach ( $columns as $column ) {
181 foreach ( $rows as $row ) {
182 if ( $user->getOption( "$prefix$column-$row" ) ) {
183 $val[] = "$column-$row";
194 * @param IContextSource $context
195 * @param array &$defaultPreferences
198 static function profilePreferences( $user, IContextSource
$context, &$defaultPreferences ) {
199 global $wgContLang, $wgParser;
201 $authManager = AuthManager
::singleton();
202 $config = $context->getConfig();
203 // retrieving user name for GENDER and misc.
204 $userName = $user->getName();
206 # # User info #####################################
208 $defaultPreferences['username'] = [
210 'label-message' => [ 'username', $userName ],
211 'default' => $userName,
212 'section' => 'personal/info',
215 $lang = $context->getLanguage();
217 # Get groups to which the user belongs
218 $userEffectiveGroups = $user->getEffectiveGroups();
219 $userGroupMemberships = $user->getGroupMemberships();
220 $userGroups = $userMembers = $userTempGroups = $userTempMembers = [];
221 foreach ( $userEffectiveGroups as $ueg ) {
223 // Skip the default * group, seems useless here
227 if ( isset( $userGroupMemberships[$ueg] ) ) {
228 $groupStringOrObject = $userGroupMemberships[$ueg];
230 $groupStringOrObject = $ueg;
233 $userG = UserGroupMembership
::getLink( $groupStringOrObject, $context, 'html' );
234 $userM = UserGroupMembership
::getLink( $groupStringOrObject, $context, 'html',
237 // Store expiring groups separately, so we can place them before non-expiring
238 // groups in the list. This is to avoid the ambiguity of something like
239 // "administrator, bureaucrat (until X date)" -- users might wonder whether the
240 // expiry date applies to both groups, or just the last one
241 if ( $groupStringOrObject instanceof UserGroupMembership
&&
242 $groupStringOrObject->getExpiry()
244 $userTempGroups[] = $userG;
245 $userTempMembers[] = $userM;
247 $userGroups[] = $userG;
248 $userMembers[] = $userM;
252 sort( $userMembers );
253 sort( $userTempGroups );
254 sort( $userTempMembers );
255 $userGroups = array_merge( $userTempGroups, $userGroups );
256 $userMembers = array_merge( $userTempMembers, $userMembers );
258 $defaultPreferences['usergroups'] = [
260 'label' => $context->msg( 'prefs-memberingroups' )->numParams(
261 count( $userGroups ) )->params( $userName )->parse(),
262 'default' => $context->msg( 'prefs-memberingroups-type' )
263 ->rawParams( $lang->commaList( $userGroups ), $lang->commaList( $userMembers ) )
266 'section' => 'personal/info',
269 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
271 $editCount = $linkRenderer->makeLink( SpecialPage
::getTitleFor( "Contributions", $userName ),
272 $lang->formatNum( $user->getEditCount() ) );
274 $defaultPreferences['editcount'] = [
277 'label-message' => 'prefs-edits',
278 'default' => $editCount,
279 'section' => 'personal/info',
282 if ( $user->getRegistration() ) {
283 $displayUser = $context->getUser();
284 $userRegistration = $user->getRegistration();
285 $defaultPreferences['registrationdate'] = [
287 'label-message' => 'prefs-registration',
288 'default' => $context->msg(
289 'prefs-registration-date-time',
290 $lang->userTimeAndDate( $userRegistration, $displayUser ),
291 $lang->userDate( $userRegistration, $displayUser ),
292 $lang->userTime( $userRegistration, $displayUser )
294 'section' => 'personal/info',
298 $canViewPrivateInfo = $user->isAllowed( 'viewmyprivateinfo' );
299 $canEditPrivateInfo = $user->isAllowed( 'editmyprivateinfo' );
301 // Actually changeable stuff
302 $defaultPreferences['realname'] = [
303 // (not really "private", but still shouldn't be edited without permission)
304 'type' => $canEditPrivateInfo && $authManager->allowsPropertyChange( 'realname' )
306 'default' => $user->getRealName(),
307 'section' => 'personal/info',
308 'label-message' => 'yourrealname',
309 'help-message' => 'prefs-help-realname',
312 if ( $canEditPrivateInfo && $authManager->allowsAuthenticationDataChange(
313 new PasswordAuthenticationRequest(), false )->isGood()
315 $link = $linkRenderer->makeLink( SpecialPage
::getTitleFor( 'ChangePassword' ),
316 $context->msg( 'prefs-resetpass' )->text(), [],
317 [ 'returnto' => SpecialPage
::getTitleFor( 'Preferences' )->getPrefixedText() ] );
319 $defaultPreferences['password'] = [
323 'label-message' => 'yourpassword',
324 'section' => 'personal/info',
327 // Only show prefershttps if secure login is turned on
328 if ( $config->get( 'SecureLogin' ) && wfCanIPUseHTTPS( $context->getRequest()->getIP() ) ) {
329 $defaultPreferences['prefershttps'] = [
331 'label-message' => 'tog-prefershttps',
332 'help-message' => 'prefs-help-prefershttps',
333 'section' => 'personal/info'
338 $languages = Language
::fetchLanguageNames( null, 'mw' );
339 $languageCode = $config->get( 'LanguageCode' );
340 if ( !array_key_exists( $languageCode, $languages ) ) {
341 $languages[$languageCode] = $languageCode;
346 foreach ( $languages as $code => $name ) {
347 $display = LanguageCode
::bcp47( $code ) . ' - ' . $name;
348 $options[$display] = $code;
350 $defaultPreferences['language'] = [
352 'section' => 'personal/i18n',
353 'options' => $options,
354 'label-message' => 'yourlanguage',
357 $defaultPreferences['gender'] = [
359 'section' => 'personal/i18n',
361 $context->msg( 'parentheses' )
362 ->params( $context->msg( 'gender-unknown' )->plain() )
363 ->escaped() => 'unknown',
364 $context->msg( 'gender-female' )->escaped() => 'female',
365 $context->msg( 'gender-male' )->escaped() => 'male',
367 'label-message' => 'yourgender',
368 'help-message' => 'prefs-help-gender',
371 // see if there are multiple language variants to choose from
372 if ( !$config->get( 'DisableLangConversion' ) ) {
373 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
374 if ( $langCode == $wgContLang->getCode() ) {
375 $variants = $wgContLang->getVariants();
377 if ( count( $variants ) <= 1 ) {
382 foreach ( $variants as $v ) {
383 $v = str_replace( '_', '-', strtolower( $v ) );
384 $variantArray[$v] = $lang->getVariantname( $v, false );
388 foreach ( $variantArray as $code => $name ) {
389 $display = LanguageCode
::bcp47( $code ) . ' - ' . $name;
390 $options[$display] = $code;
393 $defaultPreferences['variant'] = [
394 'label-message' => 'yourvariant',
396 'options' => $options,
397 'section' => 'personal/i18n',
398 'help-message' => 'prefs-help-variant',
401 $defaultPreferences["variant-$langCode"] = [
408 // Stuff from Language::getExtraUserToggles()
409 // FIXME is this dead code? $extraUserToggles doesn't seem to be defined for any language
410 $toggles = $wgContLang->getExtraUserToggles();
412 foreach ( $toggles as $toggle ) {
413 $defaultPreferences[$toggle] = [
415 'section' => 'personal/i18n',
416 'label-message' => "tog-$toggle",
420 // show a preview of the old signature first
421 $oldsigWikiText = $wgParser->preSaveTransform(
423 $context->getTitle(),
425 ParserOptions
::newFromContext( $context )
427 $oldsigHTML = $context->getOutput()->parseInline( $oldsigWikiText, true, true );
428 $defaultPreferences['oldsig'] = [
431 'label-message' => 'tog-oldsig',
432 'default' => $oldsigHTML,
433 'section' => 'personal/signature',
435 $defaultPreferences['nickname'] = [
436 'type' => $authManager->allowsPropertyChange( 'nickname' ) ?
'text' : 'info',
437 'maxlength' => $config->get( 'MaxSigChars' ),
438 'label-message' => 'yournick',
439 'validation-callback' => [ 'Preferences', 'validateSignature' ],
440 'section' => 'personal/signature',
441 'filter-callback' => [ 'Preferences', 'cleanSignature' ],
443 $defaultPreferences['fancysig'] = [
445 'label-message' => 'tog-fancysig',
446 // show general help about signature at the bottom of the section
447 'help-message' => 'prefs-help-signature',
448 'section' => 'personal/signature'
453 if ( $config->get( 'EnableEmail' ) ) {
454 if ( $canViewPrivateInfo ) {
455 $helpMessages[] = $config->get( 'EmailConfirmToEdit' )
456 ?
'prefs-help-email-required'
457 : 'prefs-help-email';
459 if ( $config->get( 'EnableUserEmail' ) ) {
460 // additional messages when users can send email to each other
461 $helpMessages[] = 'prefs-help-email-others';
464 $emailAddress = $user->getEmail() ?
htmlspecialchars( $user->getEmail() ) : '';
465 if ( $canEditPrivateInfo && $authManager->allowsPropertyChange( 'emailaddress' ) ) {
466 $link = $linkRenderer->makeLink(
467 SpecialPage
::getTitleFor( 'ChangeEmail' ),
468 $context->msg( $user->getEmail() ?
'prefs-changeemail' : 'prefs-setemail' )->text(),
470 [ 'returnto' => SpecialPage
::getTitleFor( 'Preferences' )->getPrefixedText() ] );
472 $emailAddress .= $emailAddress == '' ?
$link : (
473 $context->msg( 'word-separator' )->escaped()
474 . $context->msg( 'parentheses' )->rawParams( $link )->escaped()
478 $defaultPreferences['emailaddress'] = [
481 'default' => $emailAddress,
482 'label-message' => 'youremail',
483 'section' => 'personal/email',
484 'help-messages' => $helpMessages,
485 # 'cssclass' chosen below
489 $disableEmailPrefs = false;
491 if ( $config->get( 'EmailAuthentication' ) ) {
492 $emailauthenticationclass = 'mw-email-not-authenticated';
493 if ( $user->getEmail() ) {
494 if ( $user->getEmailAuthenticationTimestamp() ) {
495 // date and time are separate parameters to facilitate localisation.
496 // $time is kept for backward compat reasons.
497 // 'emailauthenticated' is also used in SpecialConfirmemail.php
498 $displayUser = $context->getUser();
499 $emailTimestamp = $user->getEmailAuthenticationTimestamp();
500 $time = $lang->userTimeAndDate( $emailTimestamp, $displayUser );
501 $d = $lang->userDate( $emailTimestamp, $displayUser );
502 $t = $lang->userTime( $emailTimestamp, $displayUser );
503 $emailauthenticated = $context->msg( 'emailauthenticated',
504 $time, $d, $t )->parse() . '<br />';
505 $disableEmailPrefs = false;
506 $emailauthenticationclass = 'mw-email-authenticated';
508 $disableEmailPrefs = true;
509 $emailauthenticated = $context->msg( 'emailnotauthenticated' )->parse() . '<br />' .
510 $linkRenderer->makeKnownLink(
511 SpecialPage
::getTitleFor( 'Confirmemail' ),
512 $context->msg( 'emailconfirmlink' )->text()
514 $emailauthenticationclass = "mw-email-not-authenticated";
517 $disableEmailPrefs = true;
518 $emailauthenticated = $context->msg( 'noemailprefs' )->escaped();
519 $emailauthenticationclass = 'mw-email-none';
522 if ( $canViewPrivateInfo ) {
523 $defaultPreferences['emailauthentication'] = [
526 'section' => 'personal/email',
527 'label-message' => 'prefs-emailconfirm-label',
528 'default' => $emailauthenticated,
529 # Apply the same CSS class used on the input to the message:
530 'cssclass' => $emailauthenticationclass,
535 if ( $config->get( 'EnableUserEmail' ) && $user->isAllowed( 'sendemail' ) ) {
536 $defaultPreferences['disablemail'] = [
539 'section' => 'personal/email',
540 'label-message' => 'allowemail',
541 'disabled' => $disableEmailPrefs,
543 $defaultPreferences['ccmeonemails'] = [
545 'section' => 'personal/email',
546 'label-message' => 'tog-ccmeonemails',
547 'disabled' => $disableEmailPrefs,
550 if ( $config->get( 'EnableUserEmailBlacklist' )
551 && !$disableEmailPrefs
552 && !(bool)$user->getOption( 'disablemail' )
554 $lookup = CentralIdLookup
::factory();
555 $ids = $user->getOption( 'email-blacklist', [] );
556 $names = $ids ?
$lookup->namesFromCentralIds( $ids, $user ) : [];
558 $defaultPreferences['email-blacklist'] = [
559 'type' => 'usersmultiselect',
560 'label-message' => 'email-blacklist-label',
561 'section' => 'personal/email',
562 'default' => implode( "\n", $names ),
567 if ( $config->get( 'EnotifWatchlist' ) ) {
568 $defaultPreferences['enotifwatchlistpages'] = [
570 'section' => 'personal/email',
571 'label-message' => 'tog-enotifwatchlistpages',
572 'disabled' => $disableEmailPrefs,
575 if ( $config->get( 'EnotifUserTalk' ) ) {
576 $defaultPreferences['enotifusertalkpages'] = [
578 'section' => 'personal/email',
579 'label-message' => 'tog-enotifusertalkpages',
580 'disabled' => $disableEmailPrefs,
583 if ( $config->get( 'EnotifUserTalk' ) ||
$config->get( 'EnotifWatchlist' ) ) {
584 if ( $config->get( 'EnotifMinorEdits' ) ) {
585 $defaultPreferences['enotifminoredits'] = [
587 'section' => 'personal/email',
588 'label-message' => 'tog-enotifminoredits',
589 'disabled' => $disableEmailPrefs,
593 if ( $config->get( 'EnotifRevealEditorAddress' ) ) {
594 $defaultPreferences['enotifrevealaddr'] = [
596 'section' => 'personal/email',
597 'label-message' => 'tog-enotifrevealaddr',
598 'disabled' => $disableEmailPrefs,
607 * @param IContextSource $context
608 * @param array &$defaultPreferences
611 static function skinPreferences( $user, IContextSource
$context, &$defaultPreferences ) {
612 # # Skin #####################################
614 // Skin selector, if there is at least one valid skin
615 $skinOptions = self
::generateSkinOptions( $user, $context );
616 if ( $skinOptions ) {
617 $defaultPreferences['skin'] = [
619 'options' => $skinOptions,
620 'section' => 'rendering/skin',
624 $config = $context->getConfig();
625 $allowUserCss = $config->get( 'AllowUserCss' );
626 $allowUserJs = $config->get( 'AllowUserJs' );
627 # Create links to user CSS/JS pages for all skins
628 # This code is basically copied from generateSkinOptions(). It'd
629 # be nice to somehow merge this back in there to avoid redundancy.
630 if ( $allowUserCss ||
$allowUserJs ) {
632 $userName = $user->getName();
634 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
635 if ( $allowUserCss ) {
636 $cssPage = Title
::makeTitleSafe( NS_USER
, $userName . '/common.css' );
637 $linkTools[] = $linkRenderer->makeLink( $cssPage, $context->msg( 'prefs-custom-css' )->text() );
640 if ( $allowUserJs ) {
641 $jsPage = Title
::makeTitleSafe( NS_USER
, $userName . '/common.js' );
642 $linkTools[] = $linkRenderer->makeLink( $jsPage, $context->msg( 'prefs-custom-js' )->text() );
645 $defaultPreferences['commoncssjs'] = [
648 'default' => $context->getLanguage()->pipeList( $linkTools ),
649 'label-message' => 'prefs-common-css-js',
650 'section' => 'rendering/skin',
657 * @param IContextSource $context
658 * @param array &$defaultPreferences
660 static function filesPreferences( $user, IContextSource
$context, &$defaultPreferences ) {
661 # # Files #####################################
662 $defaultPreferences['imagesize'] = [
664 'options' => self
::getImageSizes( $context ),
665 'label-message' => 'imagemaxsize',
666 'section' => 'rendering/files',
668 $defaultPreferences['thumbsize'] = [
670 'options' => self
::getThumbSizes( $context ),
671 'label-message' => 'thumbsize',
672 'section' => 'rendering/files',
678 * @param IContextSource $context
679 * @param array &$defaultPreferences
682 static function datetimePreferences( $user, IContextSource
$context, &$defaultPreferences ) {
683 # # Date and time #####################################
684 $dateOptions = self
::getDateOptions( $context );
685 if ( $dateOptions ) {
686 $defaultPreferences['date'] = [
688 'options' => $dateOptions,
689 'section' => 'rendering/dateformat',
694 $now = wfTimestampNow();
695 $lang = $context->getLanguage();
696 $nowlocal = Xml
::element( 'span', [ 'id' => 'wpLocalTime' ],
697 $lang->userTime( $now, $user ) );
698 $nowserver = $lang->userTime( $now, $user,
699 [ 'format' => false, 'timecorrection' => false ] ) .
700 Html
::hidden( 'wpServerTime', (int)substr( $now, 8, 2 ) * 60 +
(int)substr( $now, 10, 2 ) );
702 $defaultPreferences['nowserver'] = [
705 'label-message' => 'servertime',
706 'default' => $nowserver,
707 'section' => 'rendering/timeoffset',
710 $defaultPreferences['nowlocal'] = [
713 'label-message' => 'localtime',
714 'default' => $nowlocal,
715 'section' => 'rendering/timeoffset',
718 // Grab existing pref.
719 $tzOffset = $user->getOption( 'timecorrection' );
720 $tz = explode( '|', $tzOffset, 3 );
722 $tzOptions = self
::getTimezoneOptions( $context );
724 $tzSetting = $tzOffset;
725 if ( count( $tz ) > 1 && $tz[0] == 'ZoneInfo' &&
726 !in_array( $tzOffset, HTMLFormField
::flattenOptions( $tzOptions ) )
728 // Timezone offset can vary with DST
730 $userTZ = new DateTimeZone( $tz[2] );
731 $minDiff = floor( $userTZ->getOffset( new DateTime( 'now' ) ) / 60 );
732 $tzSetting = "ZoneInfo|$minDiff|{$tz[2]}";
733 } catch ( Exception
$e ) {
734 // User has an invalid time zone set. Fall back to just using the offset
738 if ( count( $tz ) > 1 && $tz[0] == 'Offset' ) {
740 $tzSetting = sprintf( '%+03d:%02d', floor( $minDiff / 60 ), abs( $minDiff ) %
60 );
743 $defaultPreferences['timecorrection'] = [
744 'class' => 'HTMLSelectOrOtherField',
745 'label-message' => 'timezonelegend',
746 'options' => $tzOptions,
747 'default' => $tzSetting,
749 'section' => 'rendering/timeoffset',
755 * @param IContextSource $context
756 * @param array &$defaultPreferences
758 static function renderingPreferences( $user, IContextSource
$context, &$defaultPreferences ) {
759 # # Diffs ####################################
760 $defaultPreferences['diffonly'] = [
762 'section' => 'rendering/diffs',
763 'label-message' => 'tog-diffonly',
765 $defaultPreferences['norollbackdiff'] = [
767 'section' => 'rendering/diffs',
768 'label-message' => 'tog-norollbackdiff',
771 # # Page Rendering ##############################
772 if ( $context->getConfig()->get( 'AllowUserCssPrefs' ) ) {
773 $defaultPreferences['underline'] = [
776 $context->msg( 'underline-never' )->text() => 0,
777 $context->msg( 'underline-always' )->text() => 1,
778 $context->msg( 'underline-default' )->text() => 2,
780 'label-message' => 'tog-underline',
781 'section' => 'rendering/advancedrendering',
785 $stubThresholdValues = [ 50, 100, 500, 1000, 2000, 5000, 10000 ];
786 $stubThresholdOptions = [ $context->msg( 'stub-threshold-disabled' )->text() => 0 ];
787 foreach ( $stubThresholdValues as $value ) {
788 $stubThresholdOptions[$context->msg( 'size-bytes', $value )->text()] = $value;
791 $defaultPreferences['stubthreshold'] = [
793 'section' => 'rendering/advancedrendering',
794 'options' => $stubThresholdOptions,
795 // This is not a raw HTML message; label-raw is needed for the manual <a></a>
796 'label-raw' => $context->msg( 'stub-threshold' )->rawParams(
797 '<a href="#" class="stub">' .
798 $context->msg( 'stub-threshold-sample-link' )->parse() .
802 $defaultPreferences['showhiddencats'] = [
804 'section' => 'rendering/advancedrendering',
805 'label-message' => 'tog-showhiddencats'
808 $defaultPreferences['numberheadings'] = [
810 'section' => 'rendering/advancedrendering',
811 'label-message' => 'tog-numberheadings',
817 * @param IContextSource $context
818 * @param array &$defaultPreferences
820 static function editingPreferences( $user, IContextSource
$context, &$defaultPreferences ) {
821 # # Editing #####################################
822 $defaultPreferences['editsectiononrightclick'] = [
824 'section' => 'editing/advancedediting',
825 'label-message' => 'tog-editsectiononrightclick',
827 $defaultPreferences['editondblclick'] = [
829 'section' => 'editing/advancedediting',
830 'label-message' => 'tog-editondblclick',
833 if ( $context->getConfig()->get( 'AllowUserCssPrefs' ) ) {
834 $defaultPreferences['editfont'] = [
836 'section' => 'editing/editor',
837 'label-message' => 'editfont-style',
839 $context->msg( 'editfont-monospace' )->text() => 'monospace',
840 $context->msg( 'editfont-sansserif' )->text() => 'sans-serif',
841 $context->msg( 'editfont-serif' )->text() => 'serif',
846 if ( $user->isAllowed( 'minoredit' ) ) {
847 $defaultPreferences['minordefault'] = [
849 'section' => 'editing/editor',
850 'label-message' => 'tog-minordefault',
854 $defaultPreferences['forceeditsummary'] = [
856 'section' => 'editing/editor',
857 'label-message' => 'tog-forceeditsummary',
859 $defaultPreferences['useeditwarning'] = [
861 'section' => 'editing/editor',
862 'label-message' => 'tog-useeditwarning',
864 $defaultPreferences['showtoolbar'] = [
866 'section' => 'editing/editor',
867 'label-message' => 'tog-showtoolbar',
870 $defaultPreferences['previewonfirst'] = [
872 'section' => 'editing/preview',
873 'label-message' => 'tog-previewonfirst',
875 $defaultPreferences['previewontop'] = [
877 'section' => 'editing/preview',
878 'label-message' => 'tog-previewontop',
880 $defaultPreferences['uselivepreview'] = [
882 'section' => 'editing/preview',
883 'label-message' => 'tog-uselivepreview',
889 * @param IContextSource $context
890 * @param array &$defaultPreferences
892 static function rcPreferences( $user, IContextSource
$context, &$defaultPreferences ) {
893 $config = $context->getConfig();
894 $rcMaxAge = $config->get( 'RCMaxAge' );
895 # # RecentChanges #####################################
896 $defaultPreferences['rcdays'] = [
898 'label-message' => 'recentchangesdays',
899 'section' => 'rc/displayrc',
901 'max' => ceil( $rcMaxAge / ( 3600 * 24 ) ),
902 'help' => $context->msg( 'recentchangesdays-max' )->numParams(
903 ceil( $rcMaxAge / ( 3600 * 24 ) ) )->escaped()
905 $defaultPreferences['rclimit'] = [
909 'label-message' => 'recentchangescount',
910 'help-message' => 'prefs-help-recentchangescount',
911 'section' => 'rc/displayrc',
913 $defaultPreferences['usenewrc'] = [
915 'label-message' => 'tog-usenewrc',
916 'section' => 'rc/advancedrc',
918 $defaultPreferences['hideminor'] = [
920 'label-message' => 'tog-hideminor',
921 'section' => 'rc/advancedrc',
923 $defaultPreferences['rcfilters-saved-queries'] = [
926 $defaultPreferences['rcfilters-wl-saved-queries'] = [
929 // Override RCFilters preferences for RecentChanges 'limit'
930 $defaultPreferences['rcfilters-limit'] = [
933 $defaultPreferences['rcfilters-saved-queries-versionbackup'] = [
936 $defaultPreferences['rcfilters-wl-saved-queries-versionbackup'] = [
939 if ( $config->get( 'RCWatchCategoryMembership' ) ) {
940 $defaultPreferences['hidecategorization'] = [
942 'label-message' => 'tog-hidecategorization',
943 'section' => 'rc/advancedrc',
947 if ( $user->useRCPatrol() ) {
948 $defaultPreferences['hidepatrolled'] = [
950 'section' => 'rc/advancedrc',
951 'label-message' => 'tog-hidepatrolled',
955 if ( $user->useNPPatrol() ) {
956 $defaultPreferences['newpageshidepatrolled'] = [
958 'section' => 'rc/advancedrc',
959 'label-message' => 'tog-newpageshidepatrolled',
963 if ( $config->get( 'RCShowWatchingUsers' ) ) {
964 $defaultPreferences['shownumberswatching'] = [
966 'section' => 'rc/advancedrc',
967 'label-message' => 'tog-shownumberswatching',
971 if ( $config->get( 'StructuredChangeFiltersShowPreference' ) ) {
972 $defaultPreferences['rcenhancedfilters-disable'] = [
974 'section' => 'rc/opt-out',
975 'label-message' => 'rcfilters-preference-label',
976 'help-message' => 'rcfilters-preference-help',
983 * @param IContextSource $context
984 * @param array &$defaultPreferences
986 static function watchlistPreferences( $user, IContextSource
$context, &$defaultPreferences ) {
987 $config = $context->getConfig();
988 $watchlistdaysMax = ceil( $config->get( 'RCMaxAge' ) / ( 3600 * 24 ) );
990 # # Watchlist #####################################
991 if ( $user->isAllowed( 'editmywatchlist' ) ) {
992 $editWatchlistLinks = [];
993 $editWatchlistModes = [
994 'edit' => [ 'EditWatchlist', false ],
995 'raw' => [ 'EditWatchlist', 'raw' ],
996 'clear' => [ 'EditWatchlist', 'clear' ],
998 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
999 foreach ( $editWatchlistModes as $editWatchlistMode => $mode ) {
1000 // Messages: prefs-editwatchlist-edit, prefs-editwatchlist-raw, prefs-editwatchlist-clear
1001 $editWatchlistLinks[] = $linkRenderer->makeKnownLink(
1002 SpecialPage
::getTitleFor( $mode[0], $mode[1] ),
1003 new HtmlArmor( $context->msg( "prefs-editwatchlist-{$editWatchlistMode}" )->parse() )
1007 $defaultPreferences['editwatchlist'] = [
1010 'default' => $context->getLanguage()->pipeList( $editWatchlistLinks ),
1011 'label-message' => 'prefs-editwatchlist-label',
1012 'section' => 'watchlist/editwatchlist',
1016 $defaultPreferences['watchlistdays'] = [
1019 'max' => $watchlistdaysMax,
1020 'section' => 'watchlist/displaywatchlist',
1021 'help' => $context->msg( 'prefs-watchlist-days-max' )->numParams(
1022 $watchlistdaysMax )->escaped(),
1023 'label-message' => 'prefs-watchlist-days',
1025 $defaultPreferences['wllimit'] = [
1029 'label-message' => 'prefs-watchlist-edits',
1030 'help' => $context->msg( 'prefs-watchlist-edits-max' )->escaped(),
1031 'section' => 'watchlist/displaywatchlist',
1033 $defaultPreferences['extendwatchlist'] = [
1035 'section' => 'watchlist/advancedwatchlist',
1036 'label-message' => 'tog-extendwatchlist',
1038 $defaultPreferences['watchlisthideminor'] = [
1040 'section' => 'watchlist/advancedwatchlist',
1041 'label-message' => 'tog-watchlisthideminor',
1043 $defaultPreferences['watchlisthidebots'] = [
1045 'section' => 'watchlist/advancedwatchlist',
1046 'label-message' => 'tog-watchlisthidebots',
1048 $defaultPreferences['watchlisthideown'] = [
1050 'section' => 'watchlist/advancedwatchlist',
1051 'label-message' => 'tog-watchlisthideown',
1053 $defaultPreferences['watchlisthideanons'] = [
1055 'section' => 'watchlist/advancedwatchlist',
1056 'label-message' => 'tog-watchlisthideanons',
1058 $defaultPreferences['watchlisthideliu'] = [
1060 'section' => 'watchlist/advancedwatchlist',
1061 'label-message' => 'tog-watchlisthideliu',
1063 $defaultPreferences['watchlistreloadautomatically'] = [
1065 'section' => 'watchlist/advancedwatchlist',
1066 'label-message' => 'tog-watchlistreloadautomatically',
1068 $defaultPreferences['watchlistunwatchlinks'] = [
1070 'section' => 'watchlist/advancedwatchlist',
1071 'label-message' => 'tog-watchlistunwatchlinks',
1074 if ( $config->get( 'RCWatchCategoryMembership' ) ) {
1075 $defaultPreferences['watchlisthidecategorization'] = [
1077 'section' => 'watchlist/advancedwatchlist',
1078 'label-message' => 'tog-watchlisthidecategorization',
1082 if ( $user->useRCPatrol() ) {
1083 $defaultPreferences['watchlisthidepatrolled'] = [
1085 'section' => 'watchlist/advancedwatchlist',
1086 'label-message' => 'tog-watchlisthidepatrolled',
1091 'edit' => 'watchdefault',
1092 'move' => 'watchmoves',
1093 'delete' => 'watchdeletion'
1097 if ( $user->isAllowed( 'createpage' ) ||
$user->isAllowed( 'createtalk' ) ) {
1098 $watchTypes['read'] = 'watchcreations';
1101 if ( $user->isAllowed( 'rollback' ) ) {
1102 $watchTypes['rollback'] = 'watchrollback';
1105 if ( $user->isAllowed( 'upload' ) ) {
1106 $watchTypes['upload'] = 'watchuploads';
1109 foreach ( $watchTypes as $action => $pref ) {
1110 if ( $user->isAllowed( $action ) ) {
1112 // tog-watchdefault, tog-watchmoves, tog-watchdeletion, tog-watchcreations, tog-watchuploads
1113 // tog-watchrollback
1114 $defaultPreferences[$pref] = [
1116 'section' => 'watchlist/advancedwatchlist',
1117 'label-message' => "tog-$pref",
1122 if ( $config->get( 'EnableAPI' ) ) {
1123 $defaultPreferences['watchlisttoken'] = [
1126 $defaultPreferences['watchlisttoken-info'] = [
1128 'section' => 'watchlist/tokenwatchlist',
1129 'label-message' => 'prefs-watchlist-token',
1130 'default' => $user->getTokenFromOption( 'watchlisttoken' ),
1131 'help-message' => 'prefs-help-watchlist-token2',
1138 * @param IContextSource $context
1139 * @param array &$defaultPreferences
1141 static function searchPreferences( $user, IContextSource
$context, &$defaultPreferences ) {
1142 foreach ( MWNamespace
::getValidNamespaces() as $n ) {
1143 $defaultPreferences['searchNs' . $n] = [
1150 * Dummy, kept for backwards-compatibility.
1152 * @param IContextSource $context
1153 * @param array &$defaultPreferences
1155 static function miscPreferences( $user, IContextSource
$context, &$defaultPreferences ) {
1159 * @param User $user The User object
1160 * @param IContextSource $context
1161 * @return array Text/links to display as key; $skinkey as value
1163 static function generateSkinOptions( $user, IContextSource
$context ) {
1166 $mptitle = Title
::newMainPage();
1167 $previewtext = $context->msg( 'skin-preview' )->escaped();
1169 $linkRenderer = MediaWikiServices
::getInstance()->getLinkRenderer();
1171 # Only show skins that aren't disabled in $wgSkipSkins
1172 $validSkinNames = Skin
::getAllowedSkins();
1174 foreach ( $validSkinNames as $skinkey => &$skinname ) {
1175 $msg = $context->msg( "skinname-{$skinkey}" );
1176 if ( $msg->exists() ) {
1177 $skinname = htmlspecialchars( $msg->text() );
1181 $config = $context->getConfig();
1182 $defaultSkin = $config->get( 'DefaultSkin' );
1183 $allowUserCss = $config->get( 'AllowUserCss' );
1184 $allowUserJs = $config->get( 'AllowUserJs' );
1186 # Sort by the internal name, so that the ordering is the same for each display language,
1187 # especially if some skin names are translated to use a different alphabet and some are not.
1188 uksort( $validSkinNames, function ( $a, $b ) use ( $defaultSkin ) {
1189 # Display the default first in the list by comparing it as lesser than any other.
1190 if ( strcasecmp( $a, $defaultSkin ) === 0 ) {
1193 if ( strcasecmp( $b, $defaultSkin ) === 0 ) {
1196 return strcasecmp( $a, $b );
1199 $foundDefault = false;
1200 foreach ( $validSkinNames as $skinkey => $sn ) {
1203 # Mark the default skin
1204 if ( strcasecmp( $skinkey, $defaultSkin ) === 0 ) {
1205 $linkTools[] = $context->msg( 'default' )->escaped();
1206 $foundDefault = true;
1209 # Create preview link
1210 $mplink = htmlspecialchars( $mptitle->getLocalURL( [ 'useskin' => $skinkey ] ) );
1211 $linkTools[] = "<a target='_blank' href=\"$mplink\">$previewtext</a>";
1213 # Create links to user CSS/JS pages
1214 if ( $allowUserCss ) {
1215 $cssPage = Title
::makeTitleSafe( NS_USER
, $user->getName() . '/' . $skinkey . '.css' );
1216 $linkTools[] = $linkRenderer->makeLink( $cssPage, $context->msg( 'prefs-custom-css' )->text() );
1219 if ( $allowUserJs ) {
1220 $jsPage = Title
::makeTitleSafe( NS_USER
, $user->getName() . '/' . $skinkey . '.js' );
1221 $linkTools[] = $linkRenderer->makeLink( $jsPage, $context->msg( 'prefs-custom-js' )->text() );
1224 $display = $sn . ' ' . $context->msg( 'parentheses' )
1225 ->rawParams( $context->getLanguage()->pipeList( $linkTools ) )
1227 $ret[$display] = $skinkey;
1230 if ( !$foundDefault ) {
1231 // If the default skin is not available, things are going to break horribly because the
1232 // default value for skin selector will not be a valid value. Let's just not show it then.
1240 * @param IContextSource $context
1243 static function getDateOptions( IContextSource
$context ) {
1244 $lang = $context->getLanguage();
1245 $dateopts = $lang->getDatePreferences();
1250 if ( !in_array( 'default', $dateopts ) ) {
1251 $dateopts[] = 'default'; // Make sure default is always valid T21237
1254 // FIXME KLUGE: site default might not be valid for user language
1255 global $wgDefaultUserOptions;
1256 if ( !in_array( $wgDefaultUserOptions['date'], $dateopts ) ) {
1257 $wgDefaultUserOptions['date'] = 'default';
1260 $epoch = wfTimestampNow();
1261 foreach ( $dateopts as $key ) {
1262 if ( $key == 'default' ) {
1263 $formatted = $context->msg( 'datedefault' )->escaped();
1265 $formatted = htmlspecialchars( $lang->timeanddate( $epoch, false, $key ) );
1267 $ret[$formatted] = $key;
1274 * @param IContextSource $context
1277 static function getImageSizes( IContextSource
$context ) {
1279 $pixels = $context->msg( 'unit-pixel' )->text();
1281 foreach ( $context->getConfig()->get( 'ImageLimits' ) as $index => $limits ) {
1282 // Note: A left-to-right marker (\u200e) is inserted, see T144386
1283 $display = "{$limits[0]}" . json_decode( '"\u200e"' ) . "×{$limits[1]}" . $pixels;
1284 $ret[$display] = $index;
1291 * @param IContextSource $context
1294 static function getThumbSizes( IContextSource
$context ) {
1296 $pixels = $context->msg( 'unit-pixel' )->text();
1298 foreach ( $context->getConfig()->get( 'ThumbLimits' ) as $index => $size ) {
1299 $display = $size . $pixels;
1300 $ret[$display] = $index;
1307 * @param string $signature
1308 * @param array $alldata
1309 * @param HTMLForm $form
1310 * @return bool|string
1312 static function validateSignature( $signature, $alldata, $form ) {
1314 $maxSigChars = $form->getConfig()->get( 'MaxSigChars' );
1315 if ( mb_strlen( $signature ) > $maxSigChars ) {
1316 return Xml
::element( 'span', [ 'class' => 'error' ],
1317 $form->msg( 'badsiglength' )->numParams( $maxSigChars )->text() );
1318 } elseif ( isset( $alldata['fancysig'] ) &&
1319 $alldata['fancysig'] &&
1320 $wgParser->validateSig( $signature ) === false
1322 return Xml
::element(
1324 [ 'class' => 'error' ],
1325 $form->msg( 'badsig' )->text()
1333 * @param string $signature
1334 * @param array $alldata
1335 * @param HTMLForm $form
1338 static function cleanSignature( $signature, $alldata, $form ) {
1339 if ( isset( $alldata['fancysig'] ) && $alldata['fancysig'] ) {
1341 $signature = $wgParser->cleanSig( $signature );
1343 // When no fancy sig used, make sure ~{3,5} get removed.
1344 $signature = Parser
::cleanSigInSig( $signature );
1352 * @param IContextSource $context
1353 * @param string $formClass
1354 * @param array $remove Array of items to remove
1355 * @return PreferencesForm|HTMLForm
1357 static function getFormObject(
1359 IContextSource
$context,
1360 $formClass = 'PreferencesForm',
1363 $formDescriptor = self
::getPreferences( $user, $context );
1364 if ( count( $remove ) ) {
1365 $removeKeys = array_flip( $remove );
1366 $formDescriptor = array_diff_key( $formDescriptor, $removeKeys );
1369 // Remove type=api preferences. They are not intended for rendering in the form.
1370 foreach ( $formDescriptor as $name => $info ) {
1371 if ( isset( $info['type'] ) && $info['type'] === 'api' ) {
1372 unset( $formDescriptor[$name] );
1377 * @var $htmlForm PreferencesForm
1379 $htmlForm = new $formClass( $formDescriptor, $context, 'prefs' );
1381 $htmlForm->setModifiedUser( $user );
1382 $htmlForm->setId( 'mw-prefs-form' );
1383 $htmlForm->setAutocomplete( 'off' );
1384 $htmlForm->setSubmitText( $context->msg( 'saveprefs' )->text() );
1385 # Used message keys: 'accesskey-preferences-save', 'tooltip-preferences-save'
1386 $htmlForm->setSubmitTooltip( 'preferences-save' );
1387 $htmlForm->setSubmitID( 'prefcontrol' );
1388 $htmlForm->setSubmitCallback( [ 'Preferences', 'tryFormSubmit' ] );
1394 * @param IContextSource $context
1397 static function getTimezoneOptions( IContextSource
$context ) {
1400 $localTZoffset = $context->getConfig()->get( 'LocalTZoffset' );
1401 $timeZoneList = self
::getTimeZoneList( $context->getLanguage() );
1403 $timestamp = MWTimestamp
::getLocalInstance();
1404 // Check that the LocalTZoffset is the same as the local time zone offset
1405 if ( $localTZoffset == $timestamp->format( 'Z' ) / 60 ) {
1406 $timezoneName = $timestamp->getTimezone()->getName();
1407 // Localize timezone
1408 if ( isset( $timeZoneList[$timezoneName] ) ) {
1409 $timezoneName = $timeZoneList[$timezoneName]['name'];
1411 $server_tz_msg = $context->msg(
1412 'timezoneuseserverdefault',
1416 $tzstring = sprintf(
1418 floor( $localTZoffset / 60 ),
1419 abs( $localTZoffset ) %
60
1421 $server_tz_msg = $context->msg( 'timezoneuseserverdefault', $tzstring )->text();
1423 $opt[$server_tz_msg] = "System|$localTZoffset";
1424 $opt[$context->msg( 'timezoneuseoffset' )->text()] = 'other';
1425 $opt[$context->msg( 'guesstimezone' )->text()] = 'guess';
1427 foreach ( $timeZoneList as $timeZoneInfo ) {
1428 $region = $timeZoneInfo['region'];
1429 if ( !isset( $opt[$region] ) ) {
1432 $opt[$region][$timeZoneInfo['name']] = $timeZoneInfo['timecorrection'];
1438 * @param string $value
1439 * @param array $alldata
1442 static function filterIntval( $value, $alldata ) {
1443 return intval( $value );
1448 * @param array $alldata
1451 static function filterTimezoneInput( $tz, $alldata ) {
1452 $data = explode( '|', $tz, 3 );
1453 switch ( $data[0] ) {
1457 if ( count( $data ) === 3 ) {
1458 // Make sure this timezone exists
1460 new DateTimeZone( $data[2] );
1461 // If the constructor didn't throw, we know it's valid
1463 } catch ( Exception
$e ) {
1464 // Not a valid timezone
1469 // If the supplied timezone doesn't exist, fall back to the encoded offset
1470 return 'Offset|' . intval( $tz[1] );
1476 $data = explode( ':', $tz, 2 );
1477 if ( count( $data ) == 2 ) {
1478 $data[0] = intval( $data[0] );
1479 $data[1] = intval( $data[1] );
1480 $minDiff = abs( $data[0] ) * 60 +
$data[1];
1481 if ( $data[0] < 0 ) {
1482 $minDiff = - $minDiff;
1485 $minDiff = intval( $data[0] ) * 60;
1488 # Max is +14:00 and min is -12:00, see:
1489 # https://en.wikipedia.org/wiki/Timezone
1490 $minDiff = min( $minDiff, 840 ); # 14:00
1491 $minDiff = max( $minDiff, -720 ); # -12:00
1492 return 'Offset|' . $minDiff;
1497 * Handle the form submission if everything validated properly
1499 * @param array $formData
1500 * @param PreferencesForm $form
1501 * @return bool|Status|string
1503 static function tryFormSubmit( $formData, $form ) {
1504 $user = $form->getModifiedUser();
1505 $hiddenPrefs = $form->getConfig()->get( 'HiddenPrefs' );
1508 if ( !$user->isAllowedAny( 'editmyprivateinfo', 'editmyoptions' ) ) {
1509 return Status
::newFatal( 'mypreferencesprotected' );
1513 foreach ( array_keys( $formData ) as $name ) {
1514 if ( isset( self
::$saveFilters[$name] ) ) {
1516 call_user_func( self
::$saveFilters[$name], $formData[$name], $formData );
1520 // Fortunately, the realname field is MUCH simpler
1521 // (not really "private", but still shouldn't be edited without permission)
1523 if ( !in_array( 'realname', $hiddenPrefs )
1524 && $user->isAllowed( 'editmyprivateinfo' )
1525 && array_key_exists( 'realname', $formData )
1527 $realName = $formData['realname'];
1528 $user->setRealName( $realName );
1531 if ( $user->isAllowed( 'editmyoptions' ) ) {
1532 $oldUserOptions = $user->getOptions();
1534 foreach ( self
::$saveBlacklist as $b ) {
1535 unset( $formData[$b] );
1538 # If users have saved a value for a preference which has subsequently been disabled
1539 # via $wgHiddenPrefs, we don't want to destroy that setting in case the preference
1540 # is subsequently re-enabled
1541 foreach ( $hiddenPrefs as $pref ) {
1542 # If the user has not set a non-default value here, the default will be returned
1543 # and subsequently discarded
1544 $formData[$pref] = $user->getOption( $pref, null, true );
1547 // If the user changed the rclimit preference, also change the rcfilters-rclimit preference
1549 isset( $formData['rclimit'] ) &&
1550 intval( $formData[ 'rclimit' ] ) !== $user->getIntOption( 'rclimit' )
1552 $formData['rcfilters-limit'] = $formData['rclimit'];
1555 // Keep old preferences from interfering due to back-compat code, etc.
1556 $user->resetOptions( 'unused', $form->getContext() );
1558 foreach ( $formData as $key => $value ) {
1559 $user->setOption( $key, $value );
1563 'PreferencesFormPreSave',
1564 [ $formData, $form, $user, &$result, $oldUserOptions ]
1568 MediaWiki\Auth\AuthManager
::callLegacyAuthPlugin( 'updateExternalDB', [ $user ] );
1569 $user->saveSettings();
1575 * @param array $formData
1576 * @param PreferencesForm $form
1579 public static function tryUISubmit( $formData, $form ) {
1580 $res = self
::tryFormSubmit( $formData, $form );
1585 if ( $res === 'eauth' ) {
1586 $urlOptions['eauth'] = 1;
1589 $urlOptions +
= $form->getExtraSuccessRedirectParameters();
1591 $url = $form->getTitle()->getFullURL( $urlOptions );
1593 $context = $form->getContext();
1594 // Set session data for the success message
1595 $context->getRequest()->getSession()->set( 'specialPreferencesSaveSuccess', 1 );
1597 $context->getOutput()->redirect( $url );
1600 return Status
::newGood();
1604 * Get a list of all time zones
1605 * @param Language $language Language used for the localized names
1606 * @return array A list of all time zones. The system name of the time zone is used as key and
1607 * the value is an array which contains localized name, the timecorrection value used for
1608 * preferences and the region
1611 public static function getTimeZoneList( Language
$language ) {
1612 $identifiers = DateTimeZone
::listIdentifiers();
1613 if ( $identifiers === false ) {
1616 sort( $identifiers );
1619 'Africa' => wfMessage( 'timezoneregion-africa' )->inLanguage( $language )->text(),
1620 'America' => wfMessage( 'timezoneregion-america' )->inLanguage( $language )->text(),
1621 'Antarctica' => wfMessage( 'timezoneregion-antarctica' )->inLanguage( $language )->text(),
1622 'Arctic' => wfMessage( 'timezoneregion-arctic' )->inLanguage( $language )->text(),
1623 'Asia' => wfMessage( 'timezoneregion-asia' )->inLanguage( $language )->text(),
1624 'Atlantic' => wfMessage( 'timezoneregion-atlantic' )->inLanguage( $language )->text(),
1625 'Australia' => wfMessage( 'timezoneregion-australia' )->inLanguage( $language )->text(),
1626 'Europe' => wfMessage( 'timezoneregion-europe' )->inLanguage( $language )->text(),
1627 'Indian' => wfMessage( 'timezoneregion-indian' )->inLanguage( $language )->text(),
1628 'Pacific' => wfMessage( 'timezoneregion-pacific' )->inLanguage( $language )->text(),
1630 asort( $tzRegions );
1634 $now = new DateTime();
1636 foreach ( $identifiers as $identifier ) {
1637 $parts = explode( '/', $identifier, 2 );
1639 // DateTimeZone::listIdentifiers() returns a number of
1640 // backwards-compatibility entries. This filters them out of the
1641 // list presented to the user.
1642 if ( count( $parts ) !== 2 ||
!array_key_exists( $parts[0], $tzRegions ) ) {
1647 $parts[0] = $tzRegions[$parts[0]];
1649 $dateTimeZone = new DateTimeZone( $identifier );
1650 $minDiff = floor( $dateTimeZone->getOffset( $now ) / 60 );
1652 $display = str_replace( '_', ' ', $parts[0] . '/' . $parts[1] );
1653 $value = "ZoneInfo|$minDiff|$identifier";
1655 $timeZoneList[$identifier] = [
1657 'timecorrection' => $value,
1658 'region' => $parts[0],
1662 return $timeZoneList;