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
21 namespace MediaWiki\Preferences
;
36 use LanguageConverter
;
37 use MediaWiki\Auth\AuthManager
;
38 use MediaWiki\Auth\PasswordAuthenticationRequest
;
39 use MediaWiki\Linker\LinkRenderer
;
40 use MediaWiki\MediaWikiServices
;
48 use Psr\Log\LoggerAwareTrait
;
49 use Psr\Log\NullLogger
;
55 use UserGroupMembership
;
59 * This is the default implementation of PreferencesFactory.
61 class DefaultPreferencesFactory
implements PreferencesFactory
{
67 /** @var Language The wiki's content language, equivalent to $wgContLang. */
70 /** @var AuthManager */
71 protected $authManager;
73 /** @var LinkRenderer */
74 protected $linkRenderer;
77 * @param Config $config
78 * @param Language $contLang
79 * @param AuthManager $authManager
80 * @param LinkRenderer $linkRenderer
82 public function __construct(
85 AuthManager
$authManager,
86 LinkRenderer
$linkRenderer
88 $this->config
= $config;
89 $this->contLang
= $contLang;
90 $this->authManager
= $authManager;
91 $this->linkRenderer
= $linkRenderer;
92 $this->logger
= new NullLogger();
98 protected function getSaveFilters() {
99 // Wrap intval() so that we can pass it multiple parameters and treat all filters the same.
100 $intvalFilter = function ( $value, $alldata ) {
101 return intval( $value );
104 'timecorrection' => [ $this, 'filterTimezoneInput' ],
105 'rclimit' => $intvalFilter,
106 'wllimit' => $intvalFilter,
107 'searchlimit' => $intvalFilter,
114 public function getSaveBlacklist() {
122 * @throws MWException
124 * @param IContextSource $context
127 public function getFormDescriptor( User
$user, IContextSource
$context ) {
130 $canIPUseHTTPS = wfCanIPUseHTTPS( $context->getRequest()->getIP() );
131 $this->profilePreferences( $user, $context, $preferences, $canIPUseHTTPS );
132 $this->skinPreferences( $user, $context, $preferences );
133 $this->datetimePreferences( $user, $context, $preferences );
134 $this->filesPreferences( $context, $preferences );
135 $this->renderingPreferences( $context, $preferences );
136 $this->editingPreferences( $user, $context, $preferences );
137 $this->rcPreferences( $user, $context, $preferences );
138 $this->watchlistPreferences( $user, $context, $preferences );
139 $this->searchPreferences( $preferences );
141 Hooks
::run( 'GetPreferences', [ $user, &$preferences ] );
143 $this->loadPreferenceValues( $user, $context, $preferences );
144 $this->logger
->debug( "Created form descriptor for user '{$user->getName()}'" );
149 * Loads existing values for a given array of preferences
150 * @throws MWException
152 * @param IContextSource $context
153 * @param array &$defaultPreferences Array to load values for
156 private function loadPreferenceValues(
157 User
$user, IContextSource
$context, &$defaultPreferences
159 # # Remove preferences that wikis don't want to use
160 foreach ( $this->config
->get( 'HiddenPrefs' ) as $pref ) {
161 if ( isset( $defaultPreferences[$pref] ) ) {
162 unset( $defaultPreferences[$pref] );
166 # # Make sure that form fields have their parent set. See T43337.
167 $dummyForm = new HTMLForm( [], $context );
169 $disable = !$user->isAllowed( 'editmyoptions' );
171 $defaultOptions = User
::getDefaultOptions();
172 # # Prod in defaults from the user
173 foreach ( $defaultPreferences as $name => &$info ) {
174 $prefFromUser = $this->getOptionFromUser( $name, $info, $user );
175 if ( $disable && !in_array( $name, $this->getSaveBlacklist() ) ) {
176 $info['disabled'] = 'disabled';
178 $field = HTMLForm
::loadInputFromParameters( $name, $info, $dummyForm ); // For validation
179 $globalDefault = isset( $defaultOptions[$name] )
180 ?
$defaultOptions[$name]
183 // If it validates, set it as the default
184 if ( isset( $info['default'] ) ) {
185 // Already set, no problem
187 } elseif ( !is_null( $prefFromUser ) && // Make sure we're not just pulling nothing
188 $field->validate( $prefFromUser, $user->getOptions() ) === true ) {
189 $info['default'] = $prefFromUser;
190 } elseif ( $field->validate( $globalDefault, $user->getOptions() ) === true ) {
191 $info['default'] = $globalDefault;
193 throw new MWException( "Global default '$globalDefault' is invalid for field $name" );
197 return $defaultPreferences;
201 * Pull option from a user account. Handles stuff like array-type preferences.
203 * @param string $name
206 * @return array|string
208 protected function getOptionFromUser( $name, $info, User
$user ) {
209 $val = $user->getOption( $name );
211 // Handling for multiselect preferences
212 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
213 ( isset( $info['class'] ) && $info['class'] == \HTMLMultiSelectField
::class ) ) {
214 $options = HTMLFormField
::flattenOptions( $info['options'] );
215 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
218 foreach ( $options as $value ) {
219 if ( $user->getOption( "$prefix$value" ) ) {
225 // Handling for checkmatrix preferences
226 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
227 ( isset( $info['class'] ) && $info['class'] == \HTMLCheckMatrix
::class ) ) {
228 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
229 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
230 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
233 foreach ( $columns as $column ) {
234 foreach ( $rows as $row ) {
235 if ( $user->getOption( "$prefix$column-$row" ) ) {
236 $val[] = "$column-$row";
246 * @todo Inject user Language instead of using context.
248 * @param IContextSource $context
249 * @param array &$defaultPreferences
250 * @param bool $canIPUseHTTPS Whether the user's IP is likely to be able to access the wiki
254 protected function profilePreferences(
255 User
$user, IContextSource
$context, &$defaultPreferences, $canIPUseHTTPS
257 // retrieving user name for GENDER and misc.
258 $userName = $user->getName();
260 # # User info #####################################
262 $defaultPreferences['username'] = [
264 'label-message' => [ 'username', $userName ],
265 'default' => $userName,
266 'section' => 'personal/info',
269 $lang = $context->getLanguage();
271 # Get groups to which the user belongs
272 $userEffectiveGroups = $user->getEffectiveGroups();
273 $userGroupMemberships = $user->getGroupMemberships();
274 $userGroups = $userMembers = $userTempGroups = $userTempMembers = [];
275 foreach ( $userEffectiveGroups as $ueg ) {
277 // Skip the default * group, seems useless here
281 if ( isset( $userGroupMemberships[$ueg] ) ) {
282 $groupStringOrObject = $userGroupMemberships[$ueg];
284 $groupStringOrObject = $ueg;
287 $userG = UserGroupMembership
::getLink( $groupStringOrObject, $context, 'html' );
288 $userM = UserGroupMembership
::getLink( $groupStringOrObject, $context, 'html',
291 // Store expiring groups separately, so we can place them before non-expiring
292 // groups in the list. This is to avoid the ambiguity of something like
293 // "administrator, bureaucrat (until X date)" -- users might wonder whether the
294 // expiry date applies to both groups, or just the last one
295 if ( $groupStringOrObject instanceof UserGroupMembership
&&
296 $groupStringOrObject->getExpiry()
298 $userTempGroups[] = $userG;
299 $userTempMembers[] = $userM;
301 $userGroups[] = $userG;
302 $userMembers[] = $userM;
306 sort( $userMembers );
307 sort( $userTempGroups );
308 sort( $userTempMembers );
309 $userGroups = array_merge( $userTempGroups, $userGroups );
310 $userMembers = array_merge( $userTempMembers, $userMembers );
312 $defaultPreferences['usergroups'] = [
314 'label' => $context->msg( 'prefs-memberingroups' )->numParams(
315 count( $userGroups ) )->params( $userName )->parse(),
316 'default' => $context->msg( 'prefs-memberingroups-type' )
317 ->rawParams( $lang->commaList( $userGroups ), $lang->commaList( $userMembers ) )
320 'section' => 'personal/info',
323 $contribTitle = SpecialPage
::getTitleFor( "Contributions", $userName );
324 $formattedEditCount = $lang->formatNum( $user->getEditCount() );
325 $editCount = $this->linkRenderer
->makeLink( $contribTitle, $formattedEditCount );
327 $defaultPreferences['editcount'] = [
330 'label-message' => 'prefs-edits',
331 'default' => $editCount,
332 'section' => 'personal/info',
335 if ( $user->getRegistration() ) {
336 $displayUser = $context->getUser();
337 $userRegistration = $user->getRegistration();
338 $defaultPreferences['registrationdate'] = [
340 'label-message' => 'prefs-registration',
341 'default' => $context->msg(
342 'prefs-registration-date-time',
343 $lang->userTimeAndDate( $userRegistration, $displayUser ),
344 $lang->userDate( $userRegistration, $displayUser ),
345 $lang->userTime( $userRegistration, $displayUser )
347 'section' => 'personal/info',
351 $canViewPrivateInfo = $user->isAllowed( 'viewmyprivateinfo' );
352 $canEditPrivateInfo = $user->isAllowed( 'editmyprivateinfo' );
354 // Actually changeable stuff
355 $defaultPreferences['realname'] = [
356 // (not really "private", but still shouldn't be edited without permission)
357 'type' => $canEditPrivateInfo && $this->authManager
->allowsPropertyChange( 'realname' )
359 'default' => $user->getRealName(),
360 'section' => 'personal/info',
361 'label-message' => 'yourrealname',
362 'help-message' => 'prefs-help-realname',
365 if ( $canEditPrivateInfo && $this->authManager
->allowsAuthenticationDataChange(
366 new PasswordAuthenticationRequest(), false )->isGood()
368 $link = $this->linkRenderer
->makeLink( SpecialPage
::getTitleFor( 'ChangePassword' ),
369 $context->msg( 'prefs-resetpass' )->text(), [],
370 [ 'returnto' => SpecialPage
::getTitleFor( 'Preferences' )->getPrefixedText() ] );
371 $defaultPreferences['password'] = [
375 'label-message' => 'yourpassword',
376 'section' => 'personal/info',
379 // Only show prefershttps if secure login is turned on
380 if ( $this->config
->get( 'SecureLogin' ) && $canIPUseHTTPS ) {
381 $defaultPreferences['prefershttps'] = [
383 'label-message' => 'tog-prefershttps',
384 'help-message' => 'prefs-help-prefershttps',
385 'section' => 'personal/info'
390 $languages = Language
::fetchLanguageNames( null, 'mw' );
391 $languageCode = $this->config
->get( 'LanguageCode' );
392 if ( !array_key_exists( $languageCode, $languages ) ) {
393 $languages[$languageCode] = $languageCode;
398 foreach ( $languages as $code => $name ) {
399 $display = LanguageCode
::bcp47( $code ) . ' - ' . $name;
400 $options[$display] = $code;
402 $defaultPreferences['language'] = [
404 'section' => 'personal/i18n',
405 'options' => $options,
406 'label-message' => 'yourlanguage',
409 $defaultPreferences['gender'] = [
411 'section' => 'personal/i18n',
413 $context->msg( 'parentheses' )
414 ->params( $context->msg( 'gender-unknown' )->plain() )
415 ->escaped() => 'unknown',
416 $context->msg( 'gender-female' )->escaped() => 'female',
417 $context->msg( 'gender-male' )->escaped() => 'male',
419 'label-message' => 'yourgender',
420 'help-message' => 'prefs-help-gender',
423 // see if there are multiple language variants to choose from
424 if ( !$this->config
->get( 'DisableLangConversion' ) ) {
425 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
426 if ( $langCode == $this->contLang
->getCode() ) {
427 $variants = $this->contLang
->getVariants();
429 if ( count( $variants ) <= 1 ) {
434 foreach ( $variants as $v ) {
435 $v = str_replace( '_', '-', strtolower( $v ) );
436 $variantArray[$v] = $lang->getVariantname( $v, false );
440 foreach ( $variantArray as $code => $name ) {
441 $display = LanguageCode
::bcp47( $code ) . ' - ' . $name;
442 $options[$display] = $code;
445 $defaultPreferences['variant'] = [
446 'label-message' => 'yourvariant',
448 'options' => $options,
449 'section' => 'personal/i18n',
450 'help-message' => 'prefs-help-variant',
453 $defaultPreferences["variant-$langCode"] = [
460 // Stuff from Language::getExtraUserToggles()
461 // FIXME is this dead code? $extraUserToggles doesn't seem to be defined for any language
462 $toggles = $this->contLang
->getExtraUserToggles();
464 foreach ( $toggles as $toggle ) {
465 $defaultPreferences[$toggle] = [
467 'section' => 'personal/i18n',
468 'label-message' => "tog-$toggle",
472 // show a preview of the old signature first
473 $oldsigWikiText = MediaWikiServices
::getInstance()->getParser()->preSaveTransform(
475 $context->getTitle(),
477 ParserOptions
::newFromContext( $context )
479 $oldsigHTML = $context->getOutput()->parseInline( $oldsigWikiText, true, true );
480 $defaultPreferences['oldsig'] = [
483 'label-message' => 'tog-oldsig',
484 'default' => $oldsigHTML,
485 'section' => 'personal/signature',
487 $defaultPreferences['nickname'] = [
488 'type' => $this->authManager
->allowsPropertyChange( 'nickname' ) ?
'text' : 'info',
489 'maxlength' => $this->config
->get( 'MaxSigChars' ),
490 'label-message' => 'yournick',
491 'validation-callback' => function ( $signature, $alldata, HTMLForm
$form ) {
492 return $this->validateSignature( $signature, $alldata, $form );
494 'section' => 'personal/signature',
495 'filter-callback' => function ( $signature, array $alldata, HTMLForm
$form ) {
496 return $this->cleanSignature( $signature, $alldata, $form );
499 $defaultPreferences['fancysig'] = [
501 'label-message' => 'tog-fancysig',
502 // show general help about signature at the bottom of the section
503 'help-message' => 'prefs-help-signature',
504 'section' => 'personal/signature'
509 if ( $this->config
->get( 'EnableEmail' ) ) {
510 if ( $canViewPrivateInfo ) {
511 $helpMessages[] = $this->config
->get( 'EmailConfirmToEdit' )
512 ?
'prefs-help-email-required'
513 : 'prefs-help-email';
515 if ( $this->config
->get( 'EnableUserEmail' ) ) {
516 // additional messages when users can send email to each other
517 $helpMessages[] = 'prefs-help-email-others';
520 $emailAddress = $user->getEmail() ?
htmlspecialchars( $user->getEmail() ) : '';
521 if ( $canEditPrivateInfo && $this->authManager
->allowsPropertyChange( 'emailaddress' ) ) {
522 $link = $this->linkRenderer
->makeLink(
523 SpecialPage
::getTitleFor( 'ChangeEmail' ),
524 $context->msg( $user->getEmail() ?
'prefs-changeemail' : 'prefs-setemail' )->text(),
526 [ 'returnto' => SpecialPage
::getTitleFor( 'Preferences' )->getPrefixedText() ] );
528 $emailAddress .= $emailAddress == '' ?
$link : (
529 $context->msg( 'word-separator' )->escaped()
530 . $context->msg( 'parentheses' )->rawParams( $link )->escaped()
534 $defaultPreferences['emailaddress'] = [
537 'default' => $emailAddress,
538 'label-message' => 'youremail',
539 'section' => 'personal/email',
540 'help-messages' => $helpMessages,
541 # 'cssclass' chosen below
545 $disableEmailPrefs = false;
547 if ( $this->config
->get( 'EmailAuthentication' ) ) {
548 $emailauthenticationclass = 'mw-email-not-authenticated';
549 if ( $user->getEmail() ) {
550 if ( $user->getEmailAuthenticationTimestamp() ) {
551 // date and time are separate parameters to facilitate localisation.
552 // $time is kept for backward compat reasons.
553 // 'emailauthenticated' is also used in SpecialConfirmemail.php
554 $displayUser = $context->getUser();
555 $emailTimestamp = $user->getEmailAuthenticationTimestamp();
556 $time = $lang->userTimeAndDate( $emailTimestamp, $displayUser );
557 $d = $lang->userDate( $emailTimestamp, $displayUser );
558 $t = $lang->userTime( $emailTimestamp, $displayUser );
559 $emailauthenticated = $context->msg( 'emailauthenticated',
560 $time, $d, $t )->parse() . '<br />';
561 $disableEmailPrefs = false;
562 $emailauthenticationclass = 'mw-email-authenticated';
564 $disableEmailPrefs = true;
565 $emailauthenticated = $context->msg( 'emailnotauthenticated' )->parse() . '<br />' .
566 $this->linkRenderer
->makeKnownLink(
567 SpecialPage
::getTitleFor( 'Confirmemail' ),
568 $context->msg( 'emailconfirmlink' )->text()
570 $emailauthenticationclass = "mw-email-not-authenticated";
573 $disableEmailPrefs = true;
574 $emailauthenticated = $context->msg( 'noemailprefs' )->escaped();
575 $emailauthenticationclass = 'mw-email-none';
578 if ( $canViewPrivateInfo ) {
579 $defaultPreferences['emailauthentication'] = [
582 'section' => 'personal/email',
583 'label-message' => 'prefs-emailconfirm-label',
584 'default' => $emailauthenticated,
585 # Apply the same CSS class used on the input to the message:
586 'cssclass' => $emailauthenticationclass,
591 if ( $this->config
->get( 'EnableUserEmail' ) && $user->isAllowed( 'sendemail' ) ) {
592 $defaultPreferences['disablemail'] = [
593 'id' => 'wpAllowEmail',
596 'section' => 'personal/email',
597 'label-message' => 'allowemail',
598 'disabled' => $disableEmailPrefs,
601 $defaultPreferences['email-allow-new-users'] = [
602 'id' => 'wpAllowEmailFromNewUsers',
604 'section' => 'personal/email',
605 'label-message' => 'email-allow-new-users-label',
606 'disabled' => $disableEmailPrefs,
609 $defaultPreferences['ccmeonemails'] = [
611 'section' => 'personal/email',
612 'label-message' => 'tog-ccmeonemails',
613 'disabled' => $disableEmailPrefs,
616 if ( $this->config
->get( 'EnableUserEmailBlacklist' ) ) {
617 $lookup = CentralIdLookup
::factory();
618 $ids = $user->getOption( 'email-blacklist', [] );
619 $names = $ids ?
$lookup->namesFromCentralIds( $ids, $user ) : [];
621 $defaultPreferences['email-blacklist'] = [
622 'type' => 'usersmultiselect',
623 'label-message' => 'email-blacklist-label',
624 'section' => 'personal/email',
625 'default' => implode( "\n", $names ),
626 'disabled' => $disableEmailPrefs,
631 if ( $this->config
->get( 'EnotifWatchlist' ) ) {
632 $defaultPreferences['enotifwatchlistpages'] = [
634 'section' => 'personal/email',
635 'label-message' => 'tog-enotifwatchlistpages',
636 'disabled' => $disableEmailPrefs,
639 if ( $this->config
->get( 'EnotifUserTalk' ) ) {
640 $defaultPreferences['enotifusertalkpages'] = [
642 'section' => 'personal/email',
643 'label-message' => 'tog-enotifusertalkpages',
644 'disabled' => $disableEmailPrefs,
647 if ( $this->config
->get( 'EnotifUserTalk' ) ||
$this->config
->get( 'EnotifWatchlist' ) ) {
648 if ( $this->config
->get( 'EnotifMinorEdits' ) ) {
649 $defaultPreferences['enotifminoredits'] = [
651 'section' => 'personal/email',
652 'label-message' => 'tog-enotifminoredits',
653 'disabled' => $disableEmailPrefs,
657 if ( $this->config
->get( 'EnotifRevealEditorAddress' ) ) {
658 $defaultPreferences['enotifrevealaddr'] = [
660 'section' => 'personal/email',
661 'label-message' => 'tog-enotifrevealaddr',
662 'disabled' => $disableEmailPrefs,
671 * @param IContextSource $context
672 * @param array &$defaultPreferences
675 protected function skinPreferences( User
$user, IContextSource
$context, &$defaultPreferences ) {
676 # # Skin #####################################
678 // Skin selector, if there is at least one valid skin
679 $skinOptions = $this->generateSkinOptions( $user, $context );
680 if ( $skinOptions ) {
681 $defaultPreferences['skin'] = [
683 'options' => $skinOptions,
684 'section' => 'rendering/skin',
688 $allowUserCss = $this->config
->get( 'AllowUserCss' );
689 $allowUserJs = $this->config
->get( 'AllowUserJs' );
690 # Create links to user CSS/JS pages for all skins
691 # This code is basically copied from generateSkinOptions(). It'd
692 # be nice to somehow merge this back in there to avoid redundancy.
693 if ( $allowUserCss ||
$allowUserJs ) {
695 $userName = $user->getName();
697 if ( $allowUserCss ) {
698 $cssPage = Title
::makeTitleSafe( NS_USER
, $userName . '/common.css' );
699 $cssLinkText = $context->msg( 'prefs-custom-css' )->text();
700 $linkTools[] = $this->linkRenderer
->makeLink( $cssPage, $cssLinkText );
703 if ( $allowUserJs ) {
704 $jsPage = Title
::makeTitleSafe( NS_USER
, $userName . '/common.js' );
705 $jsLinkText = $context->msg( 'prefs-custom-js' )->text();
706 $linkTools[] = $this->linkRenderer
->makeLink( $jsPage, $jsLinkText );
709 $defaultPreferences['commoncssjs'] = [
712 'default' => $context->getLanguage()->pipeList( $linkTools ),
713 'label-message' => 'prefs-common-config',
714 'section' => 'rendering/skin',
720 * @param IContextSource $context
721 * @param array &$defaultPreferences
723 protected function filesPreferences( IContextSource
$context, &$defaultPreferences ) {
724 # # Files #####################################
725 $defaultPreferences['imagesize'] = [
727 'options' => $this->getImageSizes( $context ),
728 'label-message' => 'imagemaxsize',
729 'section' => 'rendering/files',
731 $defaultPreferences['thumbsize'] = [
733 'options' => $this->getThumbSizes( $context ),
734 'label-message' => 'thumbsize',
735 'section' => 'rendering/files',
741 * @param IContextSource $context
742 * @param array &$defaultPreferences
745 protected function datetimePreferences( $user, IContextSource
$context, &$defaultPreferences ) {
746 # # Date and time #####################################
747 $dateOptions = $this->getDateOptions( $context );
748 if ( $dateOptions ) {
749 $defaultPreferences['date'] = [
751 'options' => $dateOptions,
752 'section' => 'rendering/dateformat',
757 $now = wfTimestampNow();
758 $lang = $context->getLanguage();
759 $nowlocal = Xml
::element( 'span', [ 'id' => 'wpLocalTime' ],
760 $lang->userTime( $now, $user ) );
761 $nowserver = $lang->userTime( $now, $user,
762 [ 'format' => false, 'timecorrection' => false ] ) .
763 Html
::hidden( 'wpServerTime', (int)substr( $now, 8, 2 ) * 60 +
(int)substr( $now, 10, 2 ) );
765 $defaultPreferences['nowserver'] = [
768 'label-message' => 'servertime',
769 'default' => $nowserver,
770 'section' => 'rendering/timeoffset',
773 $defaultPreferences['nowlocal'] = [
776 'label-message' => 'localtime',
777 'default' => $nowlocal,
778 'section' => 'rendering/timeoffset',
781 // Grab existing pref.
782 $tzOffset = $user->getOption( 'timecorrection' );
783 $tz = explode( '|', $tzOffset, 3 );
785 $tzOptions = $this->getTimezoneOptions( $context );
787 $tzSetting = $tzOffset;
788 if ( count( $tz ) > 1 && $tz[0] == 'ZoneInfo' &&
789 !in_array( $tzOffset, HTMLFormField
::flattenOptions( $tzOptions ) )
791 // Timezone offset can vary with DST
793 $userTZ = new DateTimeZone( $tz[2] );
794 $minDiff = floor( $userTZ->getOffset( new DateTime( 'now' ) ) / 60 );
795 $tzSetting = "ZoneInfo|$minDiff|{$tz[2]}";
796 } catch ( Exception
$e ) {
797 // User has an invalid time zone set. Fall back to just using the offset
801 if ( count( $tz ) > 1 && $tz[0] == 'Offset' ) {
803 $tzSetting = sprintf( '%+03d:%02d', floor( $minDiff / 60 ), abs( $minDiff ) %
60 );
806 $defaultPreferences['timecorrection'] = [
807 'class' => \HTMLSelectOrOtherField
::class,
808 'label-message' => 'timezonelegend',
809 'options' => $tzOptions,
810 'default' => $tzSetting,
812 'section' => 'rendering/timeoffset',
817 * @param MessageLocalizer $l10n
818 * @param array &$defaultPreferences
820 protected function renderingPreferences( MessageLocalizer
$l10n, &$defaultPreferences ) {
821 # # Diffs ####################################
822 $defaultPreferences['diffonly'] = [
824 'section' => 'rendering/diffs',
825 'label-message' => 'tog-diffonly',
827 $defaultPreferences['norollbackdiff'] = [
829 'section' => 'rendering/diffs',
830 'label-message' => 'tog-norollbackdiff',
833 # # Page Rendering ##############################
834 if ( $this->config
->get( 'AllowUserCssPrefs' ) ) {
835 $defaultPreferences['underline'] = [
838 $l10n->msg( 'underline-never' )->text() => 0,
839 $l10n->msg( 'underline-always' )->text() => 1,
840 $l10n->msg( 'underline-default' )->text() => 2,
842 'label-message' => 'tog-underline',
843 'section' => 'rendering/advancedrendering',
847 $stubThresholdValues = [ 50, 100, 500, 1000, 2000, 5000, 10000 ];
848 $stubThresholdOptions = [ $l10n->msg( 'stub-threshold-disabled' )->text() => 0 ];
849 foreach ( $stubThresholdValues as $value ) {
850 $stubThresholdOptions[$l10n->msg( 'size-bytes', $value )->text()] = $value;
853 $defaultPreferences['stubthreshold'] = [
855 'section' => 'rendering/advancedrendering',
856 'options' => $stubThresholdOptions,
857 // This is not a raw HTML message; label-raw is needed for the manual <a></a>
858 'label-raw' => $l10n->msg( 'stub-threshold' )->rawParams(
859 '<a href="#" class="stub">' .
860 $l10n->msg( 'stub-threshold-sample-link' )->parse() .
864 $defaultPreferences['showhiddencats'] = [
866 'section' => 'rendering/advancedrendering',
867 'label-message' => 'tog-showhiddencats'
870 $defaultPreferences['numberheadings'] = [
872 'section' => 'rendering/advancedrendering',
873 'label-message' => 'tog-numberheadings',
879 * @param MessageLocalizer $l10n
880 * @param array &$defaultPreferences
882 protected function editingPreferences( User
$user, MessageLocalizer
$l10n, &$defaultPreferences ) {
883 # # Editing #####################################
884 $defaultPreferences['editsectiononrightclick'] = [
886 'section' => 'editing/advancedediting',
887 'label-message' => 'tog-editsectiononrightclick',
889 $defaultPreferences['editondblclick'] = [
891 'section' => 'editing/advancedediting',
892 'label-message' => 'tog-editondblclick',
895 if ( $this->config
->get( 'AllowUserCssPrefs' ) ) {
896 $defaultPreferences['editfont'] = [
898 'section' => 'editing/editor',
899 'label-message' => 'editfont-style',
901 $l10n->msg( 'editfont-monospace' )->text() => 'monospace',
902 $l10n->msg( 'editfont-sansserif' )->text() => 'sans-serif',
903 $l10n->msg( 'editfont-serif' )->text() => 'serif',
908 if ( $user->isAllowed( 'minoredit' ) ) {
909 $defaultPreferences['minordefault'] = [
911 'section' => 'editing/editor',
912 'label-message' => 'tog-minordefault',
916 $defaultPreferences['forceeditsummary'] = [
918 'section' => 'editing/editor',
919 'label-message' => 'tog-forceeditsummary',
921 $defaultPreferences['useeditwarning'] = [
923 'section' => 'editing/editor',
924 'label-message' => 'tog-useeditwarning',
926 $defaultPreferences['showtoolbar'] = [
928 'section' => 'editing/editor',
929 'label-message' => 'tog-showtoolbar',
932 $defaultPreferences['previewonfirst'] = [
934 'section' => 'editing/preview',
935 'label-message' => 'tog-previewonfirst',
937 $defaultPreferences['previewontop'] = [
939 'section' => 'editing/preview',
940 'label-message' => 'tog-previewontop',
942 $defaultPreferences['uselivepreview'] = [
944 'section' => 'editing/preview',
945 'label-message' => 'tog-uselivepreview',
951 * @param MessageLocalizer $l10n
952 * @param array &$defaultPreferences
954 protected function rcPreferences( User
$user, MessageLocalizer
$l10n, &$defaultPreferences ) {
955 $rcMaxAge = $this->config
->get( 'RCMaxAge' );
956 # # RecentChanges #####################################
957 $defaultPreferences['rcdays'] = [
959 'label-message' => 'recentchangesdays',
960 'section' => 'rc/displayrc',
962 'max' => ceil( $rcMaxAge / ( 3600 * 24 ) ),
963 'help' => $l10n->msg( 'recentchangesdays-max' )->numParams(
964 ceil( $rcMaxAge / ( 3600 * 24 ) ) )->escaped()
966 $defaultPreferences['rclimit'] = [
970 'label-message' => 'recentchangescount',
971 'help-message' => 'prefs-help-recentchangescount',
972 'section' => 'rc/displayrc',
974 $defaultPreferences['usenewrc'] = [
976 'label-message' => 'tog-usenewrc',
977 'section' => 'rc/advancedrc',
979 $defaultPreferences['hideminor'] = [
981 'label-message' => 'tog-hideminor',
982 'section' => 'rc/advancedrc',
984 $defaultPreferences['rcfilters-saved-queries'] = [
987 $defaultPreferences['rcfilters-wl-saved-queries'] = [
990 // Override RCFilters preferences for RecentChanges 'limit'
991 $defaultPreferences['rcfilters-limit'] = [
994 $defaultPreferences['rcfilters-saved-queries-versionbackup'] = [
997 $defaultPreferences['rcfilters-wl-saved-queries-versionbackup'] = [
1001 if ( $this->config
->get( 'RCWatchCategoryMembership' ) ) {
1002 $defaultPreferences['hidecategorization'] = [
1004 'label-message' => 'tog-hidecategorization',
1005 'section' => 'rc/advancedrc',
1009 if ( $user->useRCPatrol() ) {
1010 $defaultPreferences['hidepatrolled'] = [
1012 'section' => 'rc/advancedrc',
1013 'label-message' => 'tog-hidepatrolled',
1017 if ( $user->useNPPatrol() ) {
1018 $defaultPreferences['newpageshidepatrolled'] = [
1020 'section' => 'rc/advancedrc',
1021 'label-message' => 'tog-newpageshidepatrolled',
1025 if ( $this->config
->get( 'RCShowWatchingUsers' ) ) {
1026 $defaultPreferences['shownumberswatching'] = [
1028 'section' => 'rc/advancedrc',
1029 'label-message' => 'tog-shownumberswatching',
1033 if ( $this->config
->get( 'StructuredChangeFiltersShowPreference' ) ) {
1034 $defaultPreferences['rcenhancedfilters-disable'] = [
1036 'section' => 'rc/opt-out',
1037 'label-message' => 'rcfilters-preference-label',
1038 'help-message' => 'rcfilters-preference-help',
1045 * @param IContextSource $context
1046 * @param array &$defaultPreferences
1048 protected function watchlistPreferences(
1049 User
$user, IContextSource
$context, &$defaultPreferences
1051 $watchlistdaysMax = ceil( $this->config
->get( 'RCMaxAge' ) / ( 3600 * 24 ) );
1053 # # Watchlist #####################################
1054 if ( $user->isAllowed( 'editmywatchlist' ) ) {
1055 $editWatchlistLinks = [];
1056 $editWatchlistModes = [
1057 'edit' => [ 'EditWatchlist', false ],
1058 'raw' => [ 'EditWatchlist', 'raw' ],
1059 'clear' => [ 'EditWatchlist', 'clear' ],
1061 foreach ( $editWatchlistModes as $editWatchlistMode => $mode ) {
1062 // Messages: prefs-editwatchlist-edit, prefs-editwatchlist-raw, prefs-editwatchlist-clear
1063 $editWatchlistLinks[] = $this->linkRenderer
->makeKnownLink(
1064 SpecialPage
::getTitleFor( $mode[0], $mode[1] ),
1065 new HtmlArmor( $context->msg( "prefs-editwatchlist-{$editWatchlistMode}" )->parse() )
1069 $defaultPreferences['editwatchlist'] = [
1072 'default' => $context->getLanguage()->pipeList( $editWatchlistLinks ),
1073 'label-message' => 'prefs-editwatchlist-label',
1074 'section' => 'watchlist/editwatchlist',
1078 $defaultPreferences['watchlistdays'] = [
1081 'max' => $watchlistdaysMax,
1082 'section' => 'watchlist/displaywatchlist',
1083 'help' => $context->msg( 'prefs-watchlist-days-max' )->numParams(
1084 $watchlistdaysMax )->escaped(),
1085 'label-message' => 'prefs-watchlist-days',
1087 $defaultPreferences['wllimit'] = [
1091 'label-message' => 'prefs-watchlist-edits',
1092 'help' => $context->msg( 'prefs-watchlist-edits-max' )->escaped(),
1093 'section' => 'watchlist/displaywatchlist',
1095 $defaultPreferences['extendwatchlist'] = [
1097 'section' => 'watchlist/advancedwatchlist',
1098 'label-message' => 'tog-extendwatchlist',
1100 $defaultPreferences['watchlisthideminor'] = [
1102 'section' => 'watchlist/advancedwatchlist',
1103 'label-message' => 'tog-watchlisthideminor',
1105 $defaultPreferences['watchlisthidebots'] = [
1107 'section' => 'watchlist/advancedwatchlist',
1108 'label-message' => 'tog-watchlisthidebots',
1110 $defaultPreferences['watchlisthideown'] = [
1112 'section' => 'watchlist/advancedwatchlist',
1113 'label-message' => 'tog-watchlisthideown',
1115 $defaultPreferences['watchlisthideanons'] = [
1117 'section' => 'watchlist/advancedwatchlist',
1118 'label-message' => 'tog-watchlisthideanons',
1120 $defaultPreferences['watchlisthideliu'] = [
1122 'section' => 'watchlist/advancedwatchlist',
1123 'label-message' => 'tog-watchlisthideliu',
1126 if ( !\SpecialWatchlist
::checkStructuredFilterUiEnabled(
1130 $defaultPreferences['watchlistreloadautomatically'] = [
1132 'section' => 'watchlist/advancedwatchlist',
1133 'label-message' => 'tog-watchlistreloadautomatically',
1137 $defaultPreferences['watchlistunwatchlinks'] = [
1139 'section' => 'watchlist/advancedwatchlist',
1140 'label-message' => 'tog-watchlistunwatchlinks',
1143 if ( $this->config
->get( 'RCWatchCategoryMembership' ) ) {
1144 $defaultPreferences['watchlisthidecategorization'] = [
1146 'section' => 'watchlist/advancedwatchlist',
1147 'label-message' => 'tog-watchlisthidecategorization',
1151 if ( $user->useRCPatrol() ) {
1152 $defaultPreferences['watchlisthidepatrolled'] = [
1154 'section' => 'watchlist/advancedwatchlist',
1155 'label-message' => 'tog-watchlisthidepatrolled',
1160 'edit' => 'watchdefault',
1161 'move' => 'watchmoves',
1162 'delete' => 'watchdeletion'
1166 if ( $user->isAllowed( 'createpage' ) ||
$user->isAllowed( 'createtalk' ) ) {
1167 $watchTypes['read'] = 'watchcreations';
1170 if ( $user->isAllowed( 'rollback' ) ) {
1171 $watchTypes['rollback'] = 'watchrollback';
1174 if ( $user->isAllowed( 'upload' ) ) {
1175 $watchTypes['upload'] = 'watchuploads';
1178 foreach ( $watchTypes as $action => $pref ) {
1179 if ( $user->isAllowed( $action ) ) {
1181 // tog-watchdefault, tog-watchmoves, tog-watchdeletion, tog-watchcreations, tog-watchuploads
1182 // tog-watchrollback
1183 $defaultPreferences[$pref] = [
1185 'section' => 'watchlist/advancedwatchlist',
1186 'label-message' => "tog-$pref",
1191 $defaultPreferences['watchlisttoken'] = [
1194 $defaultPreferences['watchlisttoken-info'] = [
1196 'section' => 'watchlist/tokenwatchlist',
1197 'label-message' => 'prefs-watchlist-token',
1198 'default' => $user->getTokenFromOption( 'watchlisttoken' ),
1199 'help-message' => 'prefs-help-watchlist-token2',
1204 * @param array &$defaultPreferences
1206 protected function searchPreferences( &$defaultPreferences ) {
1207 foreach ( MWNamespace
::getValidNamespaces() as $n ) {
1208 $defaultPreferences['searchNs' . $n] = [
1215 * @param User $user The User object
1216 * @param IContextSource $context
1217 * @return array Text/links to display as key; $skinkey as value
1219 protected function generateSkinOptions( User
$user, IContextSource
$context ) {
1222 $mptitle = Title
::newMainPage();
1223 $previewtext = $context->msg( 'skin-preview' )->escaped();
1225 # Only show skins that aren't disabled in $wgSkipSkins
1226 $validSkinNames = Skin
::getAllowedSkins();
1228 foreach ( $validSkinNames as $skinkey => &$skinname ) {
1229 $msg = $context->msg( "skinname-{$skinkey}" );
1230 if ( $msg->exists() ) {
1231 $skinname = htmlspecialchars( $msg->text() );
1235 $defaultSkin = $this->config
->get( 'DefaultSkin' );
1236 $allowUserCss = $this->config
->get( 'AllowUserCss' );
1237 $allowUserJs = $this->config
->get( 'AllowUserJs' );
1239 # Sort by the internal name, so that the ordering is the same for each display language,
1240 # especially if some skin names are translated to use a different alphabet and some are not.
1241 uksort( $validSkinNames, function ( $a, $b ) use ( $defaultSkin ) {
1242 # Display the default first in the list by comparing it as lesser than any other.
1243 if ( strcasecmp( $a, $defaultSkin ) === 0 ) {
1246 if ( strcasecmp( $b, $defaultSkin ) === 0 ) {
1249 return strcasecmp( $a, $b );
1252 $foundDefault = false;
1253 foreach ( $validSkinNames as $skinkey => $sn ) {
1256 # Mark the default skin
1257 if ( strcasecmp( $skinkey, $defaultSkin ) === 0 ) {
1258 $linkTools[] = $context->msg( 'default' )->escaped();
1259 $foundDefault = true;
1262 # Create preview link
1263 $mplink = htmlspecialchars( $mptitle->getLocalURL( [ 'useskin' => $skinkey ] ) );
1264 $linkTools[] = "<a target='_blank' href=\"$mplink\">$previewtext</a>";
1266 # Create links to user CSS/JS pages
1267 if ( $allowUserCss ) {
1268 $cssPage = Title
::makeTitleSafe( NS_USER
, $user->getName() . '/' . $skinkey . '.css' );
1269 $cssLinkText = $context->msg( 'prefs-custom-css' )->text();
1270 $linkTools[] = $this->linkRenderer
->makeLink( $cssPage, $cssLinkText );
1273 if ( $allowUserJs ) {
1274 $jsPage = Title
::makeTitleSafe( NS_USER
, $user->getName() . '/' . $skinkey . '.js' );
1275 $jsLinkText = $context->msg( 'prefs-custom-js' )->text();
1276 $linkTools[] = $this->linkRenderer
->makeLink( $jsPage, $jsLinkText );
1279 $display = $sn . ' ' . $context->msg( 'parentheses' )
1280 ->rawParams( $context->getLanguage()->pipeList( $linkTools ) )
1282 $ret[$display] = $skinkey;
1285 if ( !$foundDefault ) {
1286 // If the default skin is not available, things are going to break horribly because the
1287 // default value for skin selector will not be a valid value. Let's just not show it then.
1295 * @param IContextSource $context
1298 protected function getDateOptions( IContextSource
$context ) {
1299 $lang = $context->getLanguage();
1300 $dateopts = $lang->getDatePreferences();
1305 if ( !in_array( 'default', $dateopts ) ) {
1306 $dateopts[] = 'default'; // Make sure default is always valid T21237
1309 // FIXME KLUGE: site default might not be valid for user language
1310 global $wgDefaultUserOptions;
1311 if ( !in_array( $wgDefaultUserOptions['date'], $dateopts ) ) {
1312 $wgDefaultUserOptions['date'] = 'default';
1315 $epoch = wfTimestampNow();
1316 foreach ( $dateopts as $key ) {
1317 if ( $key == 'default' ) {
1318 $formatted = $context->msg( 'datedefault' )->escaped();
1320 $formatted = htmlspecialchars( $lang->timeanddate( $epoch, false, $key ) );
1322 $ret[$formatted] = $key;
1329 * @param MessageLocalizer $l10n
1332 protected function getImageSizes( MessageLocalizer
$l10n ) {
1334 $pixels = $l10n->msg( 'unit-pixel' )->text();
1336 foreach ( $this->config
->get( 'ImageLimits' ) as $index => $limits ) {
1337 // Note: A left-to-right marker (\u200e) is inserted, see T144386
1338 $display = "{$limits[0]}" . json_decode( '"\u200e"' ) . "×{$limits[1]}" . $pixels;
1339 $ret[$display] = $index;
1346 * @param MessageLocalizer $l10n
1349 protected function getThumbSizes( MessageLocalizer
$l10n ) {
1351 $pixels = $l10n->msg( 'unit-pixel' )->text();
1353 foreach ( $this->config
->get( 'ThumbLimits' ) as $index => $size ) {
1354 $display = $size . $pixels;
1355 $ret[$display] = $index;
1362 * @param string $signature
1363 * @param array $alldata
1364 * @param HTMLForm $form
1365 * @return bool|string
1367 protected function validateSignature( $signature, $alldata, HTMLForm
$form ) {
1368 $maxSigChars = $this->config
->get( 'MaxSigChars' );
1369 if ( mb_strlen( $signature ) > $maxSigChars ) {
1370 return Xml
::element( 'span', [ 'class' => 'error' ],
1371 $form->msg( 'badsiglength' )->numParams( $maxSigChars )->text() );
1372 } elseif ( isset( $alldata['fancysig'] ) &&
1373 $alldata['fancysig'] &&
1374 MediaWikiServices
::getInstance()->getParser()->validateSig( $signature ) === false
1376 return Xml
::element(
1378 [ 'class' => 'error' ],
1379 $form->msg( 'badsig' )->text()
1387 * @param string $signature
1388 * @param array $alldata
1389 * @param HTMLForm $form
1392 protected function cleanSignature( $signature, $alldata, HTMLForm
$form ) {
1393 $parser = MediaWikiServices
::getInstance()->getParser();
1394 if ( isset( $alldata['fancysig'] ) && $alldata['fancysig'] ) {
1395 $signature = $parser->cleanSig( $signature );
1397 // When no fancy sig used, make sure ~{3,5} get removed.
1398 $signature = Parser
::cleanSigInSig( $signature );
1406 * @param IContextSource $context
1407 * @param string $formClass
1408 * @param array $remove Array of items to remove
1409 * @return PreferencesForm|HTMLForm
1411 public function getForm(
1413 IContextSource
$context,
1414 $formClass = PreferencesForm
::class,
1417 $formDescriptor = $this->getFormDescriptor( $user, $context );
1418 if ( count( $remove ) ) {
1419 $removeKeys = array_flip( $remove );
1420 $formDescriptor = array_diff_key( $formDescriptor, $removeKeys );
1423 // Remove type=api preferences. They are not intended for rendering in the form.
1424 foreach ( $formDescriptor as $name => $info ) {
1425 if ( isset( $info['type'] ) && $info['type'] === 'api' ) {
1426 unset( $formDescriptor[$name] );
1431 * @var $htmlForm PreferencesForm
1433 $htmlForm = new $formClass( $formDescriptor, $context, 'prefs' );
1435 $htmlForm->setModifiedUser( $user );
1436 $htmlForm->setId( 'mw-prefs-form' );
1437 $htmlForm->setAutocomplete( 'off' );
1438 $htmlForm->setSubmitText( $context->msg( 'saveprefs' )->text() );
1439 # Used message keys: 'accesskey-preferences-save', 'tooltip-preferences-save'
1440 $htmlForm->setSubmitTooltip( 'preferences-save' );
1441 $htmlForm->setSubmitID( 'prefcontrol' );
1442 $htmlForm->setSubmitCallback( function ( array $formData, PreferencesForm
$form ) {
1443 return $this->submitForm( $formData, $form );
1450 * @param IContextSource $context
1453 protected function getTimezoneOptions( IContextSource
$context ) {
1456 $localTZoffset = $this->config
->get( 'LocalTZoffset' );
1457 $timeZoneList = $this->getTimeZoneList( $context->getLanguage() );
1459 $timestamp = MWTimestamp
::getLocalInstance();
1460 // Check that the LocalTZoffset is the same as the local time zone offset
1461 if ( $localTZoffset == $timestamp->format( 'Z' ) / 60 ) {
1462 $timezoneName = $timestamp->getTimezone()->getName();
1463 // Localize timezone
1464 if ( isset( $timeZoneList[$timezoneName] ) ) {
1465 $timezoneName = $timeZoneList[$timezoneName]['name'];
1467 $server_tz_msg = $context->msg(
1468 'timezoneuseserverdefault',
1472 $tzstring = sprintf(
1474 floor( $localTZoffset / 60 ),
1475 abs( $localTZoffset ) %
60
1477 $server_tz_msg = $context->msg( 'timezoneuseserverdefault', $tzstring )->text();
1479 $opt[$server_tz_msg] = "System|$localTZoffset";
1480 $opt[$context->msg( 'timezoneuseoffset' )->text()] = 'other';
1481 $opt[$context->msg( 'guesstimezone' )->text()] = 'guess';
1483 foreach ( $timeZoneList as $timeZoneInfo ) {
1484 $region = $timeZoneInfo['region'];
1485 if ( !isset( $opt[$region] ) ) {
1488 $opt[$region][$timeZoneInfo['name']] = $timeZoneInfo['timecorrection'];
1495 * @param array $alldata
1498 protected function filterTimezoneInput( $tz, array $alldata ) {
1499 $data = explode( '|', $tz, 3 );
1500 switch ( $data[0] ) {
1504 if ( count( $data ) === 3 ) {
1505 // Make sure this timezone exists
1507 new DateTimeZone( $data[2] );
1508 // If the constructor didn't throw, we know it's valid
1510 } catch ( Exception
$e ) {
1511 // Not a valid timezone
1516 // If the supplied timezone doesn't exist, fall back to the encoded offset
1517 return 'Offset|' . intval( $tz[1] );
1523 $data = explode( ':', $tz, 2 );
1524 if ( count( $data ) == 2 ) {
1525 $data[0] = intval( $data[0] );
1526 $data[1] = intval( $data[1] );
1527 $minDiff = abs( $data[0] ) * 60 +
$data[1];
1528 if ( $data[0] < 0 ) {
1529 $minDiff = - $minDiff;
1532 $minDiff = intval( $data[0] ) * 60;
1535 # Max is +14:00 and min is -12:00, see:
1536 # https://en.wikipedia.org/wiki/Timezone
1537 $minDiff = min( $minDiff, 840 ); # 14:00
1538 $minDiff = max( $minDiff, -720 ); # -12:00
1539 return 'Offset|' . $minDiff;
1544 * Handle the form submission if everything validated properly
1546 * @param array $formData
1547 * @param PreferencesForm $form
1548 * @return bool|Status|string
1550 protected function saveFormData( $formData, PreferencesForm
$form ) {
1551 $user = $form->getModifiedUser();
1552 $hiddenPrefs = $this->config
->get( 'HiddenPrefs' );
1555 if ( !$user->isAllowedAny( 'editmyprivateinfo', 'editmyoptions' ) ) {
1556 return Status
::newFatal( 'mypreferencesprotected' );
1560 foreach ( array_keys( $formData ) as $name ) {
1561 $filters = $this->getSaveFilters();
1562 if ( isset( $filters[$name] ) ) {
1563 $formData[$name] = call_user_func( $filters[$name], $formData[$name], $formData );
1567 // Fortunately, the realname field is MUCH simpler
1568 // (not really "private", but still shouldn't be edited without permission)
1570 if ( !in_array( 'realname', $hiddenPrefs )
1571 && $user->isAllowed( 'editmyprivateinfo' )
1572 && array_key_exists( 'realname', $formData )
1574 $realName = $formData['realname'];
1575 $user->setRealName( $realName );
1578 if ( $user->isAllowed( 'editmyoptions' ) ) {
1579 $oldUserOptions = $user->getOptions();
1581 foreach ( $this->getSaveBlacklist() as $b ) {
1582 unset( $formData[$b] );
1585 # If users have saved a value for a preference which has subsequently been disabled
1586 # via $wgHiddenPrefs, we don't want to destroy that setting in case the preference
1587 # is subsequently re-enabled
1588 foreach ( $hiddenPrefs as $pref ) {
1589 # If the user has not set a non-default value here, the default will be returned
1590 # and subsequently discarded
1591 $formData[$pref] = $user->getOption( $pref, null, true );
1594 // If the user changed the rclimit preference, also change the rcfilters-rclimit preference
1596 isset( $formData['rclimit'] ) &&
1597 intval( $formData[ 'rclimit' ] ) !== $user->getIntOption( 'rclimit' )
1599 $formData['rcfilters-limit'] = $formData['rclimit'];
1602 // Keep old preferences from interfering due to back-compat code, etc.
1603 $user->resetOptions( 'unused', $form->getContext() );
1605 foreach ( $formData as $key => $value ) {
1606 $user->setOption( $key, $value );
1610 'PreferencesFormPreSave',
1611 [ $formData, $form, $user, &$result, $oldUserOptions ]
1615 AuthManager
::callLegacyAuthPlugin( 'updateExternalDB', [ $user ] );
1616 $user->saveSettings();
1622 * DO NOT USE. Temporary function to punch hole for the Preferences class.
1624 * @deprecated since 1.31, its inception
1626 * @param array $formData
1627 * @param PreferencesForm $form
1628 * @return bool|Status|string
1630 public function legacySaveFormData( $formData, PreferencesForm
$form ) {
1631 return $this->saveFormData( $formData, $form );
1635 * Save the form data and reload the page
1637 * @param array $formData
1638 * @param PreferencesForm $form
1641 protected function submitForm( array $formData, PreferencesForm
$form ) {
1642 $res = $this->saveFormData( $formData, $form );
1647 if ( $res === 'eauth' ) {
1648 $urlOptions['eauth'] = 1;
1651 $urlOptions +
= $form->getExtraSuccessRedirectParameters();
1653 $url = $form->getTitle()->getFullURL( $urlOptions );
1655 $context = $form->getContext();
1656 // Set session data for the success message
1657 $context->getRequest()->getSession()->set( 'specialPreferencesSaveSuccess', 1 );
1659 $context->getOutput()->redirect( $url );
1662 return Status
::newGood();
1666 * DO NOT USE. Temporary function to punch hole for the Preferences class.
1668 * @deprecated since 1.31, its inception
1670 * @param array $formData
1671 * @param PreferencesForm $form
1674 public function legacySubmitForm( array $formData, PreferencesForm
$form ) {
1675 return $this->submitForm( $formData, $form );
1679 * Get a list of all time zones
1680 * @param Language $language Language used for the localized names
1681 * @return array A list of all time zones. The system name of the time zone is used as key and
1682 * the value is an array which contains localized name, the timecorrection value used for
1683 * preferences and the region
1686 protected function getTimeZoneList( Language
$language ) {
1687 $identifiers = DateTimeZone
::listIdentifiers();
1688 if ( $identifiers === false ) {
1691 sort( $identifiers );
1694 'Africa' => wfMessage( 'timezoneregion-africa' )->inLanguage( $language )->text(),
1695 'America' => wfMessage( 'timezoneregion-america' )->inLanguage( $language )->text(),
1696 'Antarctica' => wfMessage( 'timezoneregion-antarctica' )->inLanguage( $language )->text(),
1697 'Arctic' => wfMessage( 'timezoneregion-arctic' )->inLanguage( $language )->text(),
1698 'Asia' => wfMessage( 'timezoneregion-asia' )->inLanguage( $language )->text(),
1699 'Atlantic' => wfMessage( 'timezoneregion-atlantic' )->inLanguage( $language )->text(),
1700 'Australia' => wfMessage( 'timezoneregion-australia' )->inLanguage( $language )->text(),
1701 'Europe' => wfMessage( 'timezoneregion-europe' )->inLanguage( $language )->text(),
1702 'Indian' => wfMessage( 'timezoneregion-indian' )->inLanguage( $language )->text(),
1703 'Pacific' => wfMessage( 'timezoneregion-pacific' )->inLanguage( $language )->text(),
1705 asort( $tzRegions );
1709 $now = new DateTime();
1711 foreach ( $identifiers as $identifier ) {
1712 $parts = explode( '/', $identifier, 2 );
1714 // DateTimeZone::listIdentifiers() returns a number of
1715 // backwards-compatibility entries. This filters them out of the
1716 // list presented to the user.
1717 if ( count( $parts ) !== 2 ||
!array_key_exists( $parts[0], $tzRegions ) ) {
1722 $parts[0] = $tzRegions[$parts[0]];
1724 $dateTimeZone = new DateTimeZone( $identifier );
1725 $minDiff = floor( $dateTimeZone->getOffset( $now ) / 60 );
1727 $display = str_replace( '_', ' ', $parts[0] . '/' . $parts[1] );
1728 $value = "ZoneInfo|$minDiff|$identifier";
1730 $timeZoneList[$identifier] = [
1732 'timecorrection' => $value,
1733 'region' => $parts[0],
1737 return $timeZoneList;