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 # Sort by UI skin name. First though need to update validSkinNames as sometimes
1175 # the skinkey & UI skinname differ (e.g. "standard" skinkey is "Classic" in the UI).
1176 foreach ( $validSkinNames as $skinkey => &$skinname ) {
1177 $msg = $context->msg( "skinname-{$skinkey}" );
1178 if ( $msg->exists() ) {
1179 $skinname = htmlspecialchars( $msg->text() );
1182 asort( $validSkinNames );
1184 $config = $context->getConfig();
1185 $defaultSkin = $config->get( 'DefaultSkin' );
1186 $allowUserCss = $config->get( 'AllowUserCss' );
1187 $allowUserJs = $config->get( 'AllowUserJs' );
1189 $foundDefault = false;
1190 foreach ( $validSkinNames as $skinkey => $sn ) {
1193 # Mark the default skin
1194 if ( strcasecmp( $skinkey, $defaultSkin ) === 0 ) {
1195 $linkTools[] = $context->msg( 'default' )->escaped();
1196 $foundDefault = true;
1199 # Create preview link
1200 $mplink = htmlspecialchars( $mptitle->getLocalURL( [ 'useskin' => $skinkey ] ) );
1201 $linkTools[] = "<a target='_blank' href=\"$mplink\">$previewtext</a>";
1203 # Create links to user CSS/JS pages
1204 if ( $allowUserCss ) {
1205 $cssPage = Title
::makeTitleSafe( NS_USER
, $user->getName() . '/' . $skinkey . '.css' );
1206 $linkTools[] = $linkRenderer->makeLink( $cssPage, $context->msg( 'prefs-custom-css' )->text() );
1209 if ( $allowUserJs ) {
1210 $jsPage = Title
::makeTitleSafe( NS_USER
, $user->getName() . '/' . $skinkey . '.js' );
1211 $linkTools[] = $linkRenderer->makeLink( $jsPage, $context->msg( 'prefs-custom-js' )->text() );
1214 $display = $sn . ' ' . $context->msg( 'parentheses' )
1215 ->rawParams( $context->getLanguage()->pipeList( $linkTools ) )
1217 $ret[$display] = $skinkey;
1220 if ( !$foundDefault ) {
1221 // If the default skin is not available, things are going to break horribly because the
1222 // default value for skin selector will not be a valid value. Let's just not show it then.
1230 * @param IContextSource $context
1233 static function getDateOptions( IContextSource
$context ) {
1234 $lang = $context->getLanguage();
1235 $dateopts = $lang->getDatePreferences();
1240 if ( !in_array( 'default', $dateopts ) ) {
1241 $dateopts[] = 'default'; // Make sure default is always valid T21237
1244 // FIXME KLUGE: site default might not be valid for user language
1245 global $wgDefaultUserOptions;
1246 if ( !in_array( $wgDefaultUserOptions['date'], $dateopts ) ) {
1247 $wgDefaultUserOptions['date'] = 'default';
1250 $epoch = wfTimestampNow();
1251 foreach ( $dateopts as $key ) {
1252 if ( $key == 'default' ) {
1253 $formatted = $context->msg( 'datedefault' )->escaped();
1255 $formatted = htmlspecialchars( $lang->timeanddate( $epoch, false, $key ) );
1257 $ret[$formatted] = $key;
1264 * @param IContextSource $context
1267 static function getImageSizes( IContextSource
$context ) {
1269 $pixels = $context->msg( 'unit-pixel' )->text();
1271 foreach ( $context->getConfig()->get( 'ImageLimits' ) as $index => $limits ) {
1272 // Note: A left-to-right marker (\u200e) is inserted, see T144386
1273 $display = "{$limits[0]}" . json_decode( '"\u200e"' ) . "×{$limits[1]}" . $pixels;
1274 $ret[$display] = $index;
1281 * @param IContextSource $context
1284 static function getThumbSizes( IContextSource
$context ) {
1286 $pixels = $context->msg( 'unit-pixel' )->text();
1288 foreach ( $context->getConfig()->get( 'ThumbLimits' ) as $index => $size ) {
1289 $display = $size . $pixels;
1290 $ret[$display] = $index;
1297 * @param string $signature
1298 * @param array $alldata
1299 * @param HTMLForm $form
1300 * @return bool|string
1302 static function validateSignature( $signature, $alldata, $form ) {
1304 $maxSigChars = $form->getConfig()->get( 'MaxSigChars' );
1305 if ( mb_strlen( $signature ) > $maxSigChars ) {
1306 return Xml
::element( 'span', [ 'class' => 'error' ],
1307 $form->msg( 'badsiglength' )->numParams( $maxSigChars )->text() );
1308 } elseif ( isset( $alldata['fancysig'] ) &&
1309 $alldata['fancysig'] &&
1310 $wgParser->validateSig( $signature ) === false
1312 return Xml
::element(
1314 [ 'class' => 'error' ],
1315 $form->msg( 'badsig' )->text()
1323 * @param string $signature
1324 * @param array $alldata
1325 * @param HTMLForm $form
1328 static function cleanSignature( $signature, $alldata, $form ) {
1329 if ( isset( $alldata['fancysig'] ) && $alldata['fancysig'] ) {
1331 $signature = $wgParser->cleanSig( $signature );
1333 // When no fancy sig used, make sure ~{3,5} get removed.
1334 $signature = Parser
::cleanSigInSig( $signature );
1342 * @param IContextSource $context
1343 * @param string $formClass
1344 * @param array $remove Array of items to remove
1345 * @return PreferencesForm|HTMLForm
1347 static function getFormObject(
1349 IContextSource
$context,
1350 $formClass = 'PreferencesForm',
1353 $formDescriptor = self
::getPreferences( $user, $context );
1354 if ( count( $remove ) ) {
1355 $removeKeys = array_flip( $remove );
1356 $formDescriptor = array_diff_key( $formDescriptor, $removeKeys );
1359 // Remove type=api preferences. They are not intended for rendering in the form.
1360 foreach ( $formDescriptor as $name => $info ) {
1361 if ( isset( $info['type'] ) && $info['type'] === 'api' ) {
1362 unset( $formDescriptor[$name] );
1367 * @var $htmlForm PreferencesForm
1369 $htmlForm = new $formClass( $formDescriptor, $context, 'prefs' );
1371 $htmlForm->setModifiedUser( $user );
1372 $htmlForm->setId( 'mw-prefs-form' );
1373 $htmlForm->setAutocomplete( 'off' );
1374 $htmlForm->setSubmitText( $context->msg( 'saveprefs' )->text() );
1375 # Used message keys: 'accesskey-preferences-save', 'tooltip-preferences-save'
1376 $htmlForm->setSubmitTooltip( 'preferences-save' );
1377 $htmlForm->setSubmitID( 'prefcontrol' );
1378 $htmlForm->setSubmitCallback( [ 'Preferences', 'tryFormSubmit' ] );
1384 * @param IContextSource $context
1387 static function getTimezoneOptions( IContextSource
$context ) {
1390 $localTZoffset = $context->getConfig()->get( 'LocalTZoffset' );
1391 $timeZoneList = self
::getTimeZoneList( $context->getLanguage() );
1393 $timestamp = MWTimestamp
::getLocalInstance();
1394 // Check that the LocalTZoffset is the same as the local time zone offset
1395 if ( $localTZoffset == $timestamp->format( 'Z' ) / 60 ) {
1396 $timezoneName = $timestamp->getTimezone()->getName();
1397 // Localize timezone
1398 if ( isset( $timeZoneList[$timezoneName] ) ) {
1399 $timezoneName = $timeZoneList[$timezoneName]['name'];
1401 $server_tz_msg = $context->msg(
1402 'timezoneuseserverdefault',
1406 $tzstring = sprintf(
1408 floor( $localTZoffset / 60 ),
1409 abs( $localTZoffset ) %
60
1411 $server_tz_msg = $context->msg( 'timezoneuseserverdefault', $tzstring )->text();
1413 $opt[$server_tz_msg] = "System|$localTZoffset";
1414 $opt[$context->msg( 'timezoneuseoffset' )->text()] = 'other';
1415 $opt[$context->msg( 'guesstimezone' )->text()] = 'guess';
1417 foreach ( $timeZoneList as $timeZoneInfo ) {
1418 $region = $timeZoneInfo['region'];
1419 if ( !isset( $opt[$region] ) ) {
1422 $opt[$region][$timeZoneInfo['name']] = $timeZoneInfo['timecorrection'];
1428 * @param string $value
1429 * @param array $alldata
1432 static function filterIntval( $value, $alldata ) {
1433 return intval( $value );
1438 * @param array $alldata
1441 static function filterTimezoneInput( $tz, $alldata ) {
1442 $data = explode( '|', $tz, 3 );
1443 switch ( $data[0] ) {
1447 if ( count( $data ) === 3 ) {
1448 // Make sure this timezone exists
1450 new DateTimeZone( $data[2] );
1451 // If the constructor didn't throw, we know it's valid
1453 } catch ( Exception
$e ) {
1454 // Not a valid timezone
1459 // If the supplied timezone doesn't exist, fall back to the encoded offset
1460 return 'Offset|' . intval( $tz[1] );
1466 $data = explode( ':', $tz, 2 );
1467 if ( count( $data ) == 2 ) {
1468 $data[0] = intval( $data[0] );
1469 $data[1] = intval( $data[1] );
1470 $minDiff = abs( $data[0] ) * 60 +
$data[1];
1471 if ( $data[0] < 0 ) {
1472 $minDiff = - $minDiff;
1475 $minDiff = intval( $data[0] ) * 60;
1478 # Max is +14:00 and min is -12:00, see:
1479 # https://en.wikipedia.org/wiki/Timezone
1480 $minDiff = min( $minDiff, 840 ); # 14:00
1481 $minDiff = max( $minDiff, -720 ); # -12:00
1482 return 'Offset|' . $minDiff;
1487 * Handle the form submission if everything validated properly
1489 * @param array $formData
1490 * @param PreferencesForm $form
1491 * @return bool|Status|string
1493 static function tryFormSubmit( $formData, $form ) {
1494 $user = $form->getModifiedUser();
1495 $hiddenPrefs = $form->getConfig()->get( 'HiddenPrefs' );
1498 if ( !$user->isAllowedAny( 'editmyprivateinfo', 'editmyoptions' ) ) {
1499 return Status
::newFatal( 'mypreferencesprotected' );
1503 foreach ( array_keys( $formData ) as $name ) {
1504 if ( isset( self
::$saveFilters[$name] ) ) {
1506 call_user_func( self
::$saveFilters[$name], $formData[$name], $formData );
1510 // Fortunately, the realname field is MUCH simpler
1511 // (not really "private", but still shouldn't be edited without permission)
1513 if ( !in_array( 'realname', $hiddenPrefs )
1514 && $user->isAllowed( 'editmyprivateinfo' )
1515 && array_key_exists( 'realname', $formData )
1517 $realName = $formData['realname'];
1518 $user->setRealName( $realName );
1521 if ( $user->isAllowed( 'editmyoptions' ) ) {
1522 $oldUserOptions = $user->getOptions();
1524 foreach ( self
::$saveBlacklist as $b ) {
1525 unset( $formData[$b] );
1528 # If users have saved a value for a preference which has subsequently been disabled
1529 # via $wgHiddenPrefs, we don't want to destroy that setting in case the preference
1530 # is subsequently re-enabled
1531 foreach ( $hiddenPrefs as $pref ) {
1532 # If the user has not set a non-default value here, the default will be returned
1533 # and subsequently discarded
1534 $formData[$pref] = $user->getOption( $pref, null, true );
1537 // If the user changed the rclimit preference, also change the rcfilters-rclimit preference
1539 isset( $formData['rclimit'] ) &&
1540 intval( $formData[ 'rclimit' ] ) !== $user->getIntOption( 'rclimit' )
1542 $formData['rcfilters-limit'] = $formData['rclimit'];
1545 // Keep old preferences from interfering due to back-compat code, etc.
1546 $user->resetOptions( 'unused', $form->getContext() );
1548 foreach ( $formData as $key => $value ) {
1549 $user->setOption( $key, $value );
1553 'PreferencesFormPreSave',
1554 [ $formData, $form, $user, &$result, $oldUserOptions ]
1558 MediaWiki\Auth\AuthManager
::callLegacyAuthPlugin( 'updateExternalDB', [ $user ] );
1559 $user->saveSettings();
1565 * @param array $formData
1566 * @param PreferencesForm $form
1569 public static function tryUISubmit( $formData, $form ) {
1570 $res = self
::tryFormSubmit( $formData, $form );
1575 if ( $res === 'eauth' ) {
1576 $urlOptions['eauth'] = 1;
1579 $urlOptions +
= $form->getExtraSuccessRedirectParameters();
1581 $url = $form->getTitle()->getFullURL( $urlOptions );
1583 $context = $form->getContext();
1584 // Set session data for the success message
1585 $context->getRequest()->getSession()->set( 'specialPreferencesSaveSuccess', 1 );
1587 $context->getOutput()->redirect( $url );
1590 return Status
::newGood();
1594 * Get a list of all time zones
1595 * @param Language $language Language used for the localized names
1596 * @return array A list of all time zones. The system name of the time zone is used as key and
1597 * the value is an array which contains localized name, the timecorrection value used for
1598 * preferences and the region
1601 public static function getTimeZoneList( Language
$language ) {
1602 $identifiers = DateTimeZone
::listIdentifiers();
1603 if ( $identifiers === false ) {
1606 sort( $identifiers );
1609 'Africa' => wfMessage( 'timezoneregion-africa' )->inLanguage( $language )->text(),
1610 'America' => wfMessage( 'timezoneregion-america' )->inLanguage( $language )->text(),
1611 'Antarctica' => wfMessage( 'timezoneregion-antarctica' )->inLanguage( $language )->text(),
1612 'Arctic' => wfMessage( 'timezoneregion-arctic' )->inLanguage( $language )->text(),
1613 'Asia' => wfMessage( 'timezoneregion-asia' )->inLanguage( $language )->text(),
1614 'Atlantic' => wfMessage( 'timezoneregion-atlantic' )->inLanguage( $language )->text(),
1615 'Australia' => wfMessage( 'timezoneregion-australia' )->inLanguage( $language )->text(),
1616 'Europe' => wfMessage( 'timezoneregion-europe' )->inLanguage( $language )->text(),
1617 'Indian' => wfMessage( 'timezoneregion-indian' )->inLanguage( $language )->text(),
1618 'Pacific' => wfMessage( 'timezoneregion-pacific' )->inLanguage( $language )->text(),
1620 asort( $tzRegions );
1624 $now = new DateTime();
1626 foreach ( $identifiers as $identifier ) {
1627 $parts = explode( '/', $identifier, 2 );
1629 // DateTimeZone::listIdentifiers() returns a number of
1630 // backwards-compatibility entries. This filters them out of the
1631 // list presented to the user.
1632 if ( count( $parts ) !== 2 ||
!array_key_exists( $parts[0], $tzRegions ) ) {
1637 $parts[0] = $tzRegions[$parts[0]];
1639 $dateTimeZone = new DateTimeZone( $identifier );
1640 $minDiff = floor( $dateTimeZone->getOffset( $now ) / 60 );
1642 $display = str_replace( '_', ' ', $parts[0] . '/' . $parts[1] );
1643 $value = "ZoneInfo|$minDiff|$identifier";
1645 $timeZoneList[$identifier] = [
1647 'timecorrection' => $value,
1648 'region' => $parts[0],
1652 return $timeZoneList;