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
;
53 use UserGroupMembership
;
57 * This is the default implementation of PreferencesFactory.
59 class DefaultPreferencesFactory
implements PreferencesFactory
{
64 /** @var Language The wiki's content language, equivalent to $wgContLang. */
67 /** @var AuthManager */
68 protected $authManager;
70 /** @var LinkRenderer */
71 protected $linkRenderer;
73 public function __construct(
76 AuthManager
$authManager,
77 LinkRenderer
$linkRenderer
79 $this->config
= $config;
80 $this->contLang
= $contLang;
81 $this->authManager
= $authManager;
82 $this->linkRenderer
= $linkRenderer;
88 protected function getSaveFilters() {
89 // Wrap intval() so that we can pass it multiple parameters and treat all filters the same.
90 $intvalFilter = function ( $value, $alldata ) {
91 return intval( $value );
94 'timecorrection' => [ $this, 'filterTimezoneInput' ],
95 'rclimit' => $intvalFilter,
96 'wllimit' => $intvalFilter,
97 'searchlimit' => $intvalFilter,
104 public function getSaveBlacklist() {
112 * @throws MWException
114 * @param IContextSource $context
117 public function getFormDescriptor( User
$user, IContextSource
$context ) {
120 $canIPUseHTTPS = wfCanIPUseHTTPS( $context->getRequest()->getIP() );
121 $this->profilePreferences( $user, $context, $preferences, $canIPUseHTTPS );
122 $this->skinPreferences( $user, $context, $preferences );
123 $this->datetimePreferences( $user, $context, $preferences );
124 $this->filesPreferences( $context, $preferences );
125 $this->renderingPreferences( $context, $preferences );
126 $this->editingPreferences( $user, $context, $preferences );
127 $this->rcPreferences( $user, $context, $preferences );
128 $this->watchlistPreferences( $user, $context, $preferences );
129 $this->searchPreferences( $preferences );
131 Hooks
::run( 'GetPreferences', [ $user, &$preferences ] );
133 $this->loadPreferenceValues( $user, $context, $preferences );
138 * Loads existing values for a given array of preferences
139 * @throws MWException
141 * @param IContextSource $context
142 * @param array &$defaultPreferences Array to load values for
145 private function loadPreferenceValues(
146 User
$user, IContextSource
$context, &$defaultPreferences
148 # # Remove preferences that wikis don't want to use
149 foreach ( $this->config
->get( 'HiddenPrefs' ) as $pref ) {
150 if ( isset( $defaultPreferences[$pref] ) ) {
151 unset( $defaultPreferences[$pref] );
155 # # Make sure that form fields have their parent set. See T43337.
156 $dummyForm = new HTMLForm( [], $context );
158 $disable = !$user->isAllowed( 'editmyoptions' );
160 $defaultOptions = User
::getDefaultOptions();
161 # # Prod in defaults from the user
162 foreach ( $defaultPreferences as $name => &$info ) {
163 $prefFromUser = $this->getOptionFromUser( $name, $info, $user );
164 if ( $disable && !in_array( $name, $this->getSaveBlacklist() ) ) {
165 $info['disabled'] = 'disabled';
167 $field = HTMLForm
::loadInputFromParameters( $name, $info, $dummyForm ); // For validation
168 $globalDefault = isset( $defaultOptions[$name] )
169 ?
$defaultOptions[$name]
172 // If it validates, set it as the default
173 if ( isset( $info['default'] ) ) {
174 // Already set, no problem
176 } elseif ( !is_null( $prefFromUser ) && // Make sure we're not just pulling nothing
177 $field->validate( $prefFromUser, $user->getOptions() ) === true ) {
178 $info['default'] = $prefFromUser;
179 } elseif ( $field->validate( $globalDefault, $user->getOptions() ) === true ) {
180 $info['default'] = $globalDefault;
182 throw new MWException( "Global default '$globalDefault' is invalid for field $name" );
186 return $defaultPreferences;
190 * Pull option from a user account. Handles stuff like array-type preferences.
192 * @param string $name
195 * @return array|string
197 protected function getOptionFromUser( $name, $info, User
$user ) {
198 $val = $user->getOption( $name );
200 // Handling for multiselect preferences
201 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
202 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
203 $options = HTMLFormField
::flattenOptions( $info['options'] );
204 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
207 foreach ( $options as $value ) {
208 if ( $user->getOption( "$prefix$value" ) ) {
214 // Handling for checkmatrix preferences
215 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
216 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
217 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
218 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
219 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
222 foreach ( $columns as $column ) {
223 foreach ( $rows as $row ) {
224 if ( $user->getOption( "$prefix$column-$row" ) ) {
225 $val[] = "$column-$row";
235 * @todo Inject user Language instead of using context.
237 * @param IContextSource $context
238 * @param array &$defaultPreferences
239 * @param bool $canIPUseHTTPS Whether the user's IP is likely to be able to access the wiki
243 protected function profilePreferences(
244 User
$user, IContextSource
$context, &$defaultPreferences, $canIPUseHTTPS
246 // retrieving user name for GENDER and misc.
247 $userName = $user->getName();
249 # # User info #####################################
251 $defaultPreferences['username'] = [
253 'label-message' => [ 'username', $userName ],
254 'default' => $userName,
255 'section' => 'personal/info',
258 $lang = $context->getLanguage();
260 # Get groups to which the user belongs
261 $userEffectiveGroups = $user->getEffectiveGroups();
262 $userGroupMemberships = $user->getGroupMemberships();
263 $userGroups = $userMembers = $userTempGroups = $userTempMembers = [];
264 foreach ( $userEffectiveGroups as $ueg ) {
266 // Skip the default * group, seems useless here
270 if ( isset( $userGroupMemberships[$ueg] ) ) {
271 $groupStringOrObject = $userGroupMemberships[$ueg];
273 $groupStringOrObject = $ueg;
276 $userG = UserGroupMembership
::getLink( $groupStringOrObject, $context, 'html' );
277 $userM = UserGroupMembership
::getLink( $groupStringOrObject, $context, 'html',
280 // Store expiring groups separately, so we can place them before non-expiring
281 // groups in the list. This is to avoid the ambiguity of something like
282 // "administrator, bureaucrat (until X date)" -- users might wonder whether the
283 // expiry date applies to both groups, or just the last one
284 if ( $groupStringOrObject instanceof UserGroupMembership
&&
285 $groupStringOrObject->getExpiry()
287 $userTempGroups[] = $userG;
288 $userTempMembers[] = $userM;
290 $userGroups[] = $userG;
291 $userMembers[] = $userM;
295 sort( $userMembers );
296 sort( $userTempGroups );
297 sort( $userTempMembers );
298 $userGroups = array_merge( $userTempGroups, $userGroups );
299 $userMembers = array_merge( $userTempMembers, $userMembers );
301 $defaultPreferences['usergroups'] = [
303 'label' => $context->msg( 'prefs-memberingroups' )->numParams(
304 count( $userGroups ) )->params( $userName )->parse(),
305 'default' => $context->msg( 'prefs-memberingroups-type' )
306 ->rawParams( $lang->commaList( $userGroups ), $lang->commaList( $userMembers ) )
309 'section' => 'personal/info',
312 $contribTitle = SpecialPage
::getTitleFor( "Contributions", $userName );
313 $formattedEditCount = $lang->formatNum( $user->getEditCount() );
314 $editCount = $this->linkRenderer
->makeLink( $contribTitle, $formattedEditCount );
316 $defaultPreferences['editcount'] = [
319 'label-message' => 'prefs-edits',
320 'default' => $editCount,
321 'section' => 'personal/info',
324 if ( $user->getRegistration() ) {
325 $displayUser = $context->getUser();
326 $userRegistration = $user->getRegistration();
327 $defaultPreferences['registrationdate'] = [
329 'label-message' => 'prefs-registration',
330 'default' => $context->msg(
331 'prefs-registration-date-time',
332 $lang->userTimeAndDate( $userRegistration, $displayUser ),
333 $lang->userDate( $userRegistration, $displayUser ),
334 $lang->userTime( $userRegistration, $displayUser )
336 'section' => 'personal/info',
340 $canViewPrivateInfo = $user->isAllowed( 'viewmyprivateinfo' );
341 $canEditPrivateInfo = $user->isAllowed( 'editmyprivateinfo' );
343 // Actually changeable stuff
344 $defaultPreferences['realname'] = [
345 // (not really "private", but still shouldn't be edited without permission)
346 'type' => $canEditPrivateInfo && $this->authManager
->allowsPropertyChange( 'realname' )
348 'default' => $user->getRealName(),
349 'section' => 'personal/info',
350 'label-message' => 'yourrealname',
351 'help-message' => 'prefs-help-realname',
354 if ( $canEditPrivateInfo && $this->authManager
->allowsAuthenticationDataChange(
355 new PasswordAuthenticationRequest(), false )->isGood()
357 $link = $this->linkRenderer
->makeLink( SpecialPage
::getTitleFor( 'ChangePassword' ),
358 $context->msg( 'prefs-resetpass' )->text(), [],
359 [ 'returnto' => SpecialPage
::getTitleFor( 'Preferences' )->getPrefixedText() ] );
360 $defaultPreferences['password'] = [
364 'label-message' => 'yourpassword',
365 'section' => 'personal/info',
368 // Only show prefershttps if secure login is turned on
369 if ( $this->config
->get( 'SecureLogin' ) && $canIPUseHTTPS ) {
370 $defaultPreferences['prefershttps'] = [
372 'label-message' => 'tog-prefershttps',
373 'help-message' => 'prefs-help-prefershttps',
374 'section' => 'personal/info'
379 $languages = Language
::fetchLanguageNames( null, 'mw' );
380 $languageCode = $this->config
->get( 'LanguageCode' );
381 if ( !array_key_exists( $languageCode, $languages ) ) {
382 $languages[$languageCode] = $languageCode;
387 foreach ( $languages as $code => $name ) {
388 $display = LanguageCode
::bcp47( $code ) . ' - ' . $name;
389 $options[$display] = $code;
391 $defaultPreferences['language'] = [
393 'section' => 'personal/i18n',
394 'options' => $options,
395 'label-message' => 'yourlanguage',
398 $defaultPreferences['gender'] = [
400 'section' => 'personal/i18n',
402 $context->msg( 'parentheses' )
403 ->params( $context->msg( 'gender-unknown' )->plain() )
404 ->escaped() => 'unknown',
405 $context->msg( 'gender-female' )->escaped() => 'female',
406 $context->msg( 'gender-male' )->escaped() => 'male',
408 'label-message' => 'yourgender',
409 'help-message' => 'prefs-help-gender',
412 // see if there are multiple language variants to choose from
413 if ( !$this->config
->get( 'DisableLangConversion' ) ) {
414 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
415 if ( $langCode == $this->contLang
->getCode() ) {
416 $variants = $this->contLang
->getVariants();
418 if ( count( $variants ) <= 1 ) {
423 foreach ( $variants as $v ) {
424 $v = str_replace( '_', '-', strtolower( $v ) );
425 $variantArray[$v] = $lang->getVariantname( $v, false );
429 foreach ( $variantArray as $code => $name ) {
430 $display = LanguageCode
::bcp47( $code ) . ' - ' . $name;
431 $options[$display] = $code;
434 $defaultPreferences['variant'] = [
435 'label-message' => 'yourvariant',
437 'options' => $options,
438 'section' => 'personal/i18n',
439 'help-message' => 'prefs-help-variant',
442 $defaultPreferences["variant-$langCode"] = [
449 // Stuff from Language::getExtraUserToggles()
450 // FIXME is this dead code? $extraUserToggles doesn't seem to be defined for any language
451 $toggles = $this->contLang
->getExtraUserToggles();
453 foreach ( $toggles as $toggle ) {
454 $defaultPreferences[$toggle] = [
456 'section' => 'personal/i18n',
457 'label-message' => "tog-$toggle",
461 // show a preview of the old signature first
462 $oldsigWikiText = MediaWikiServices
::getInstance()->getParser()->preSaveTransform(
464 $context->getTitle(),
466 ParserOptions
::newFromContext( $context )
468 $oldsigHTML = $context->getOutput()->parseInline( $oldsigWikiText, true, true );
469 $defaultPreferences['oldsig'] = [
472 'label-message' => 'tog-oldsig',
473 'default' => $oldsigHTML,
474 'section' => 'personal/signature',
476 $defaultPreferences['nickname'] = [
477 'type' => $this->authManager
->allowsPropertyChange( 'nickname' ) ?
'text' : 'info',
478 'maxlength' => $this->config
->get( 'MaxSigChars' ),
479 'label-message' => 'yournick',
480 'validation-callback' => function ( $signature, $alldata, HTMLForm
$form ) {
481 return $this->validateSignature( $signature, $alldata, $form );
483 'section' => 'personal/signature',
484 'filter-callback' => function ( $signature, array $alldata, HTMLForm
$form ) {
485 return $this->cleanSignature( $signature, $alldata, $form );
488 $defaultPreferences['fancysig'] = [
490 'label-message' => 'tog-fancysig',
491 // show general help about signature at the bottom of the section
492 'help-message' => 'prefs-help-signature',
493 'section' => 'personal/signature'
498 if ( $this->config
->get( 'EnableEmail' ) ) {
499 if ( $canViewPrivateInfo ) {
500 $helpMessages[] = $this->config
->get( 'EmailConfirmToEdit' )
501 ?
'prefs-help-email-required'
502 : 'prefs-help-email';
504 if ( $this->config
->get( 'EnableUserEmail' ) ) {
505 // additional messages when users can send email to each other
506 $helpMessages[] = 'prefs-help-email-others';
509 $emailAddress = $user->getEmail() ?
htmlspecialchars( $user->getEmail() ) : '';
510 if ( $canEditPrivateInfo && $this->authManager
->allowsPropertyChange( 'emailaddress' ) ) {
511 $link = $this->linkRenderer
->makeLink(
512 SpecialPage
::getTitleFor( 'ChangeEmail' ),
513 $context->msg( $user->getEmail() ?
'prefs-changeemail' : 'prefs-setemail' )->text(),
515 [ 'returnto' => SpecialPage
::getTitleFor( 'Preferences' )->getPrefixedText() ] );
517 $emailAddress .= $emailAddress == '' ?
$link : (
518 $context->msg( 'word-separator' )->escaped()
519 . $context->msg( 'parentheses' )->rawParams( $link )->escaped()
523 $defaultPreferences['emailaddress'] = [
526 'default' => $emailAddress,
527 'label-message' => 'youremail',
528 'section' => 'personal/email',
529 'help-messages' => $helpMessages,
530 # 'cssclass' chosen below
534 $disableEmailPrefs = false;
536 if ( $this->config
->get( 'EmailAuthentication' ) ) {
537 $emailauthenticationclass = 'mw-email-not-authenticated';
538 if ( $user->getEmail() ) {
539 if ( $user->getEmailAuthenticationTimestamp() ) {
540 // date and time are separate parameters to facilitate localisation.
541 // $time is kept for backward compat reasons.
542 // 'emailauthenticated' is also used in SpecialConfirmemail.php
543 $displayUser = $context->getUser();
544 $emailTimestamp = $user->getEmailAuthenticationTimestamp();
545 $time = $lang->userTimeAndDate( $emailTimestamp, $displayUser );
546 $d = $lang->userDate( $emailTimestamp, $displayUser );
547 $t = $lang->userTime( $emailTimestamp, $displayUser );
548 $emailauthenticated = $context->msg( 'emailauthenticated',
549 $time, $d, $t )->parse() . '<br />';
550 $disableEmailPrefs = false;
551 $emailauthenticationclass = 'mw-email-authenticated';
553 $disableEmailPrefs = true;
554 $emailauthenticated = $context->msg( 'emailnotauthenticated' )->parse() . '<br />' .
555 $this->linkRenderer
->makeKnownLink(
556 SpecialPage
::getTitleFor( 'Confirmemail' ),
557 $context->msg( 'emailconfirmlink' )->text()
559 $emailauthenticationclass = "mw-email-not-authenticated";
562 $disableEmailPrefs = true;
563 $emailauthenticated = $context->msg( 'noemailprefs' )->escaped();
564 $emailauthenticationclass = 'mw-email-none';
567 if ( $canViewPrivateInfo ) {
568 $defaultPreferences['emailauthentication'] = [
571 'section' => 'personal/email',
572 'label-message' => 'prefs-emailconfirm-label',
573 'default' => $emailauthenticated,
574 # Apply the same CSS class used on the input to the message:
575 'cssclass' => $emailauthenticationclass,
580 if ( $this->config
->get( 'EnableUserEmail' ) && $user->isAllowed( 'sendemail' ) ) {
581 $defaultPreferences['disablemail'] = [
582 'id' => 'wpAllowEmail',
585 'section' => 'personal/email',
586 'label-message' => 'allowemail',
587 'disabled' => $disableEmailPrefs,
590 $defaultPreferences['email-allow-new-users'] = [
591 'id' => 'wpAllowEmailFromNewUsers',
593 'section' => 'personal/email',
594 'label-message' => 'email-allow-new-users-label',
595 'disabled' => $disableEmailPrefs,
598 $defaultPreferences['ccmeonemails'] = [
600 'section' => 'personal/email',
601 'label-message' => 'tog-ccmeonemails',
602 'disabled' => $disableEmailPrefs,
605 if ( $this->config
->get( 'EnableUserEmailBlacklist' ) ) {
606 $lookup = CentralIdLookup
::factory();
607 $ids = $user->getOption( 'email-blacklist', [] );
608 $names = $ids ?
$lookup->namesFromCentralIds( $ids, $user ) : [];
610 $defaultPreferences['email-blacklist'] = [
611 'type' => 'usersmultiselect',
612 'label-message' => 'email-blacklist-label',
613 'section' => 'personal/email',
614 'default' => implode( "\n", $names ),
615 'disabled' => $disableEmailPrefs,
620 if ( $this->config
->get( 'EnotifWatchlist' ) ) {
621 $defaultPreferences['enotifwatchlistpages'] = [
623 'section' => 'personal/email',
624 'label-message' => 'tog-enotifwatchlistpages',
625 'disabled' => $disableEmailPrefs,
628 if ( $this->config
->get( 'EnotifUserTalk' ) ) {
629 $defaultPreferences['enotifusertalkpages'] = [
631 'section' => 'personal/email',
632 'label-message' => 'tog-enotifusertalkpages',
633 'disabled' => $disableEmailPrefs,
636 if ( $this->config
->get( 'EnotifUserTalk' ) ||
$this->config
->get( 'EnotifWatchlist' ) ) {
637 if ( $this->config
->get( 'EnotifMinorEdits' ) ) {
638 $defaultPreferences['enotifminoredits'] = [
640 'section' => 'personal/email',
641 'label-message' => 'tog-enotifminoredits',
642 'disabled' => $disableEmailPrefs,
646 if ( $this->config
->get( 'EnotifRevealEditorAddress' ) ) {
647 $defaultPreferences['enotifrevealaddr'] = [
649 'section' => 'personal/email',
650 'label-message' => 'tog-enotifrevealaddr',
651 'disabled' => $disableEmailPrefs,
660 * @param IContextSource $context
661 * @param array &$defaultPreferences
664 protected function skinPreferences( User
$user, IContextSource
$context, &$defaultPreferences ) {
665 # # Skin #####################################
667 // Skin selector, if there is at least one valid skin
668 $skinOptions = $this->generateSkinOptions( $user, $context );
669 if ( $skinOptions ) {
670 $defaultPreferences['skin'] = [
672 'options' => $skinOptions,
673 'section' => 'rendering/skin',
677 $allowUserCss = $this->config
->get( 'AllowUserCss' );
678 $allowUserJs = $this->config
->get( 'AllowUserJs' );
679 # Create links to user CSS/JS pages for all skins
680 # This code is basically copied from generateSkinOptions(). It'd
681 # be nice to somehow merge this back in there to avoid redundancy.
682 if ( $allowUserCss ||
$allowUserJs ) {
684 $userName = $user->getName();
686 if ( $allowUserCss ) {
687 $cssPage = Title
::makeTitleSafe( NS_USER
, $userName . '/common.css' );
688 $cssLinkText = $context->msg( 'prefs-custom-css' )->text();
689 $linkTools[] = $this->linkRenderer
->makeLink( $cssPage, $cssLinkText );
692 if ( $allowUserJs ) {
693 $jsPage = Title
::makeTitleSafe( NS_USER
, $userName . '/common.js' );
694 $jsLinkText = $context->msg( 'prefs-custom-js' )->text();
695 $linkTools[] = $this->linkRenderer
->makeLink( $jsPage, $jsLinkText );
698 $defaultPreferences['commoncssjs'] = [
701 'default' => $context->getLanguage()->pipeList( $linkTools ),
702 'label-message' => 'prefs-common-css-js',
703 'section' => 'rendering/skin',
709 * @param IContextSource $context
710 * @param array &$defaultPreferences
712 protected function filesPreferences( IContextSource
$context, &$defaultPreferences ) {
713 # # Files #####################################
714 $defaultPreferences['imagesize'] = [
716 'options' => $this->getImageSizes( $context ),
717 'label-message' => 'imagemaxsize',
718 'section' => 'rendering/files',
720 $defaultPreferences['thumbsize'] = [
722 'options' => $this->getThumbSizes( $context ),
723 'label-message' => 'thumbsize',
724 'section' => 'rendering/files',
730 * @param IContextSource $context
731 * @param array &$defaultPreferences
734 protected function datetimePreferences( $user, IContextSource
$context, &$defaultPreferences ) {
735 # # Date and time #####################################
736 $dateOptions = $this->getDateOptions( $context );
737 if ( $dateOptions ) {
738 $defaultPreferences['date'] = [
740 'options' => $dateOptions,
741 'section' => 'rendering/dateformat',
746 $now = wfTimestampNow();
747 $lang = $context->getLanguage();
748 $nowlocal = Xml
::element( 'span', [ 'id' => 'wpLocalTime' ],
749 $lang->userTime( $now, $user ) );
750 $nowserver = $lang->userTime( $now, $user,
751 [ 'format' => false, 'timecorrection' => false ] ) .
752 Html
::hidden( 'wpServerTime', (int)substr( $now, 8, 2 ) * 60 +
(int)substr( $now, 10, 2 ) );
754 $defaultPreferences['nowserver'] = [
757 'label-message' => 'servertime',
758 'default' => $nowserver,
759 'section' => 'rendering/timeoffset',
762 $defaultPreferences['nowlocal'] = [
765 'label-message' => 'localtime',
766 'default' => $nowlocal,
767 'section' => 'rendering/timeoffset',
770 // Grab existing pref.
771 $tzOffset = $user->getOption( 'timecorrection' );
772 $tz = explode( '|', $tzOffset, 3 );
774 $tzOptions = $this->getTimezoneOptions( $context );
776 $tzSetting = $tzOffset;
777 if ( count( $tz ) > 1 && $tz[0] == 'ZoneInfo' &&
778 !in_array( $tzOffset, HTMLFormField
::flattenOptions( $tzOptions ) )
780 // Timezone offset can vary with DST
782 $userTZ = new DateTimeZone( $tz[2] );
783 $minDiff = floor( $userTZ->getOffset( new DateTime( 'now' ) ) / 60 );
784 $tzSetting = "ZoneInfo|$minDiff|{$tz[2]}";
785 } catch ( Exception
$e ) {
786 // User has an invalid time zone set. Fall back to just using the offset
790 if ( count( $tz ) > 1 && $tz[0] == 'Offset' ) {
792 $tzSetting = sprintf( '%+03d:%02d', floor( $minDiff / 60 ), abs( $minDiff ) %
60 );
795 $defaultPreferences['timecorrection'] = [
796 'class' => 'HTMLSelectOrOtherField',
797 'label-message' => 'timezonelegend',
798 'options' => $tzOptions,
799 'default' => $tzSetting,
801 'section' => 'rendering/timeoffset',
806 * @param MessageLocalizer $l10n
807 * @param array &$defaultPreferences
809 protected function renderingPreferences( MessageLocalizer
$l10n, &$defaultPreferences ) {
810 # # Diffs ####################################
811 $defaultPreferences['diffonly'] = [
813 'section' => 'rendering/diffs',
814 'label-message' => 'tog-diffonly',
816 $defaultPreferences['norollbackdiff'] = [
818 'section' => 'rendering/diffs',
819 'label-message' => 'tog-norollbackdiff',
822 # # Page Rendering ##############################
823 if ( $this->config
->get( 'AllowUserCssPrefs' ) ) {
824 $defaultPreferences['underline'] = [
827 $l10n->msg( 'underline-never' )->text() => 0,
828 $l10n->msg( 'underline-always' )->text() => 1,
829 $l10n->msg( 'underline-default' )->text() => 2,
831 'label-message' => 'tog-underline',
832 'section' => 'rendering/advancedrendering',
836 $stubThresholdValues = [ 50, 100, 500, 1000, 2000, 5000, 10000 ];
837 $stubThresholdOptions = [ $l10n->msg( 'stub-threshold-disabled' )->text() => 0 ];
838 foreach ( $stubThresholdValues as $value ) {
839 $stubThresholdOptions[$l10n->msg( 'size-bytes', $value )->text()] = $value;
842 $defaultPreferences['stubthreshold'] = [
844 'section' => 'rendering/advancedrendering',
845 'options' => $stubThresholdOptions,
846 // This is not a raw HTML message; label-raw is needed for the manual <a></a>
847 'label-raw' => $l10n->msg( 'stub-threshold' )->rawParams(
848 '<a href="#" class="stub">' .
849 $l10n->msg( 'stub-threshold-sample-link' )->parse() .
853 $defaultPreferences['showhiddencats'] = [
855 'section' => 'rendering/advancedrendering',
856 'label-message' => 'tog-showhiddencats'
859 $defaultPreferences['numberheadings'] = [
861 'section' => 'rendering/advancedrendering',
862 'label-message' => 'tog-numberheadings',
868 * @param MessageLocalizer $l10n
869 * @param array &$defaultPreferences
871 protected function editingPreferences( User
$user, MessageLocalizer
$l10n, &$defaultPreferences ) {
872 # # Editing #####################################
873 $defaultPreferences['editsectiononrightclick'] = [
875 'section' => 'editing/advancedediting',
876 'label-message' => 'tog-editsectiononrightclick',
878 $defaultPreferences['editondblclick'] = [
880 'section' => 'editing/advancedediting',
881 'label-message' => 'tog-editondblclick',
884 if ( $this->config
->get( 'AllowUserCssPrefs' ) ) {
885 $defaultPreferences['editfont'] = [
887 'section' => 'editing/editor',
888 'label-message' => 'editfont-style',
890 $l10n->msg( 'editfont-monospace' )->text() => 'monospace',
891 $l10n->msg( 'editfont-sansserif' )->text() => 'sans-serif',
892 $l10n->msg( 'editfont-serif' )->text() => 'serif',
897 if ( $user->isAllowed( 'minoredit' ) ) {
898 $defaultPreferences['minordefault'] = [
900 'section' => 'editing/editor',
901 'label-message' => 'tog-minordefault',
905 $defaultPreferences['forceeditsummary'] = [
907 'section' => 'editing/editor',
908 'label-message' => 'tog-forceeditsummary',
910 $defaultPreferences['useeditwarning'] = [
912 'section' => 'editing/editor',
913 'label-message' => 'tog-useeditwarning',
915 $defaultPreferences['showtoolbar'] = [
917 'section' => 'editing/editor',
918 'label-message' => 'tog-showtoolbar',
921 $defaultPreferences['previewonfirst'] = [
923 'section' => 'editing/preview',
924 'label-message' => 'tog-previewonfirst',
926 $defaultPreferences['previewontop'] = [
928 'section' => 'editing/preview',
929 'label-message' => 'tog-previewontop',
931 $defaultPreferences['uselivepreview'] = [
933 'section' => 'editing/preview',
934 'label-message' => 'tog-uselivepreview',
940 * @param MessageLocalizer $l10n
941 * @param array &$defaultPreferences
943 protected function rcPreferences( User
$user, MessageLocalizer
$l10n, &$defaultPreferences ) {
944 $rcMaxAge = $this->config
->get( 'RCMaxAge' );
945 # # RecentChanges #####################################
946 $defaultPreferences['rcdays'] = [
948 'label-message' => 'recentchangesdays',
949 'section' => 'rc/displayrc',
951 'max' => ceil( $rcMaxAge / ( 3600 * 24 ) ),
952 'help' => $l10n->msg( 'recentchangesdays-max' )->numParams(
953 ceil( $rcMaxAge / ( 3600 * 24 ) ) )->escaped()
955 $defaultPreferences['rclimit'] = [
959 'label-message' => 'recentchangescount',
960 'help-message' => 'prefs-help-recentchangescount',
961 'section' => 'rc/displayrc',
963 $defaultPreferences['usenewrc'] = [
965 'label-message' => 'tog-usenewrc',
966 'section' => 'rc/advancedrc',
968 $defaultPreferences['hideminor'] = [
970 'label-message' => 'tog-hideminor',
971 'section' => 'rc/advancedrc',
973 $defaultPreferences['rcfilters-saved-queries'] = [
976 $defaultPreferences['rcfilters-wl-saved-queries'] = [
979 // Override RCFilters preferences for RecentChanges 'limit'
980 $defaultPreferences['rcfilters-limit'] = [
983 $defaultPreferences['rcfilters-saved-queries-versionbackup'] = [
986 $defaultPreferences['rcfilters-wl-saved-queries-versionbackup'] = [
990 if ( $this->config
->get( 'RCWatchCategoryMembership' ) ) {
991 $defaultPreferences['hidecategorization'] = [
993 'label-message' => 'tog-hidecategorization',
994 'section' => 'rc/advancedrc',
998 if ( $user->useRCPatrol() ) {
999 $defaultPreferences['hidepatrolled'] = [
1001 'section' => 'rc/advancedrc',
1002 'label-message' => 'tog-hidepatrolled',
1006 if ( $user->useNPPatrol() ) {
1007 $defaultPreferences['newpageshidepatrolled'] = [
1009 'section' => 'rc/advancedrc',
1010 'label-message' => 'tog-newpageshidepatrolled',
1014 if ( $this->config
->get( 'RCShowWatchingUsers' ) ) {
1015 $defaultPreferences['shownumberswatching'] = [
1017 'section' => 'rc/advancedrc',
1018 'label-message' => 'tog-shownumberswatching',
1022 if ( $this->config
->get( 'StructuredChangeFiltersShowPreference' ) ) {
1023 $defaultPreferences['rcenhancedfilters-disable'] = [
1025 'section' => 'rc/opt-out',
1026 'label-message' => 'rcfilters-preference-label',
1027 'help-message' => 'rcfilters-preference-help',
1034 * @param IContextSource $context
1035 * @param array &$defaultPreferences
1037 protected function watchlistPreferences(
1038 User
$user, IContextSource
$context, &$defaultPreferences
1040 $watchlistdaysMax = ceil( $this->config
->get( 'RCMaxAge' ) / ( 3600 * 24 ) );
1042 # # Watchlist #####################################
1043 if ( $user->isAllowed( 'editmywatchlist' ) ) {
1044 $editWatchlistLinks = [];
1045 $editWatchlistModes = [
1046 'edit' => [ 'EditWatchlist', false ],
1047 'raw' => [ 'EditWatchlist', 'raw' ],
1048 'clear' => [ 'EditWatchlist', 'clear' ],
1050 foreach ( $editWatchlistModes as $editWatchlistMode => $mode ) {
1051 // Messages: prefs-editwatchlist-edit, prefs-editwatchlist-raw, prefs-editwatchlist-clear
1052 $editWatchlistLinks[] = $this->linkRenderer
->makeKnownLink(
1053 SpecialPage
::getTitleFor( $mode[0], $mode[1] ),
1054 new HtmlArmor( $context->msg( "prefs-editwatchlist-{$editWatchlistMode}" )->parse() )
1058 $defaultPreferences['editwatchlist'] = [
1061 'default' => $context->getLanguage()->pipeList( $editWatchlistLinks ),
1062 'label-message' => 'prefs-editwatchlist-label',
1063 'section' => 'watchlist/editwatchlist',
1067 $defaultPreferences['watchlistdays'] = [
1070 'max' => $watchlistdaysMax,
1071 'section' => 'watchlist/displaywatchlist',
1072 'help' => $context->msg( 'prefs-watchlist-days-max' )->numParams(
1073 $watchlistdaysMax )->escaped(),
1074 'label-message' => 'prefs-watchlist-days',
1076 $defaultPreferences['wllimit'] = [
1080 'label-message' => 'prefs-watchlist-edits',
1081 'help' => $context->msg( 'prefs-watchlist-edits-max' )->escaped(),
1082 'section' => 'watchlist/displaywatchlist',
1084 $defaultPreferences['extendwatchlist'] = [
1086 'section' => 'watchlist/advancedwatchlist',
1087 'label-message' => 'tog-extendwatchlist',
1089 $defaultPreferences['watchlisthideminor'] = [
1091 'section' => 'watchlist/advancedwatchlist',
1092 'label-message' => 'tog-watchlisthideminor',
1094 $defaultPreferences['watchlisthidebots'] = [
1096 'section' => 'watchlist/advancedwatchlist',
1097 'label-message' => 'tog-watchlisthidebots',
1099 $defaultPreferences['watchlisthideown'] = [
1101 'section' => 'watchlist/advancedwatchlist',
1102 'label-message' => 'tog-watchlisthideown',
1104 $defaultPreferences['watchlisthideanons'] = [
1106 'section' => 'watchlist/advancedwatchlist',
1107 'label-message' => 'tog-watchlisthideanons',
1109 $defaultPreferences['watchlisthideliu'] = [
1111 'section' => 'watchlist/advancedwatchlist',
1112 'label-message' => 'tog-watchlisthideliu',
1114 $defaultPreferences['watchlistreloadautomatically'] = [
1116 'section' => 'watchlist/advancedwatchlist',
1117 'label-message' => 'tog-watchlistreloadautomatically',
1119 $defaultPreferences['watchlistunwatchlinks'] = [
1121 'section' => 'watchlist/advancedwatchlist',
1122 'label-message' => 'tog-watchlistunwatchlinks',
1125 if ( $this->config
->get( 'RCWatchCategoryMembership' ) ) {
1126 $defaultPreferences['watchlisthidecategorization'] = [
1128 'section' => 'watchlist/advancedwatchlist',
1129 'label-message' => 'tog-watchlisthidecategorization',
1133 if ( $user->useRCPatrol() ) {
1134 $defaultPreferences['watchlisthidepatrolled'] = [
1136 'section' => 'watchlist/advancedwatchlist',
1137 'label-message' => 'tog-watchlisthidepatrolled',
1142 'edit' => 'watchdefault',
1143 'move' => 'watchmoves',
1144 'delete' => 'watchdeletion'
1148 if ( $user->isAllowed( 'createpage' ) ||
$user->isAllowed( 'createtalk' ) ) {
1149 $watchTypes['read'] = 'watchcreations';
1152 if ( $user->isAllowed( 'rollback' ) ) {
1153 $watchTypes['rollback'] = 'watchrollback';
1156 if ( $user->isAllowed( 'upload' ) ) {
1157 $watchTypes['upload'] = 'watchuploads';
1160 foreach ( $watchTypes as $action => $pref ) {
1161 if ( $user->isAllowed( $action ) ) {
1163 // tog-watchdefault, tog-watchmoves, tog-watchdeletion, tog-watchcreations, tog-watchuploads
1164 // tog-watchrollback
1165 $defaultPreferences[$pref] = [
1167 'section' => 'watchlist/advancedwatchlist',
1168 'label-message' => "tog-$pref",
1173 if ( $this->config
->get( 'EnableAPI' ) ) {
1174 $defaultPreferences['watchlisttoken'] = [
1177 $defaultPreferences['watchlisttoken-info'] = [
1179 'section' => 'watchlist/tokenwatchlist',
1180 'label-message' => 'prefs-watchlist-token',
1181 'default' => $user->getTokenFromOption( 'watchlisttoken' ),
1182 'help-message' => 'prefs-help-watchlist-token2',
1188 * @param array &$defaultPreferences
1190 protected function searchPreferences( &$defaultPreferences ) {
1191 foreach ( MWNamespace
::getValidNamespaces() as $n ) {
1192 $defaultPreferences['searchNs' . $n] = [
1199 * @param User $user The User object
1200 * @param IContextSource $context
1201 * @return array Text/links to display as key; $skinkey as value
1203 protected function generateSkinOptions( User
$user, IContextSource
$context ) {
1206 $mptitle = Title
::newMainPage();
1207 $previewtext = $context->msg( 'skin-preview' )->escaped();
1209 # Only show skins that aren't disabled in $wgSkipSkins
1210 $validSkinNames = Skin
::getAllowedSkins();
1212 foreach ( $validSkinNames as $skinkey => &$skinname ) {
1213 $msg = $context->msg( "skinname-{$skinkey}" );
1214 if ( $msg->exists() ) {
1215 $skinname = htmlspecialchars( $msg->text() );
1219 $defaultSkin = $this->config
->get( 'DefaultSkin' );
1220 $allowUserCss = $this->config
->get( 'AllowUserCss' );
1221 $allowUserJs = $this->config
->get( 'AllowUserJs' );
1223 # Sort by the internal name, so that the ordering is the same for each display language,
1224 # especially if some skin names are translated to use a different alphabet and some are not.
1225 uksort( $validSkinNames, function ( $a, $b ) use ( $defaultSkin ) {
1226 # Display the default first in the list by comparing it as lesser than any other.
1227 if ( strcasecmp( $a, $defaultSkin ) === 0 ) {
1230 if ( strcasecmp( $b, $defaultSkin ) === 0 ) {
1233 return strcasecmp( $a, $b );
1236 $foundDefault = false;
1237 foreach ( $validSkinNames as $skinkey => $sn ) {
1240 # Mark the default skin
1241 if ( strcasecmp( $skinkey, $defaultSkin ) === 0 ) {
1242 $linkTools[] = $context->msg( 'default' )->escaped();
1243 $foundDefault = true;
1246 # Create preview link
1247 $mplink = htmlspecialchars( $mptitle->getLocalURL( [ 'useskin' => $skinkey ] ) );
1248 $linkTools[] = "<a target='_blank' href=\"$mplink\">$previewtext</a>";
1250 # Create links to user CSS/JS pages
1251 if ( $allowUserCss ) {
1252 $cssPage = Title
::makeTitleSafe( NS_USER
, $user->getName() . '/' . $skinkey . '.css' );
1253 $cssLinkText = $context->msg( 'prefs-custom-css' )->text();
1254 $linkTools[] = $this->linkRenderer
->makeLink( $cssPage, $cssLinkText );
1257 if ( $allowUserJs ) {
1258 $jsPage = Title
::makeTitleSafe( NS_USER
, $user->getName() . '/' . $skinkey . '.js' );
1259 $jsLinkText = $context->msg( 'prefs-custom-js' )->text();
1260 $linkTools[] = $this->linkRenderer
->makeLink( $jsPage, $jsLinkText );
1263 $display = $sn . ' ' . $context->msg( 'parentheses' )
1264 ->rawParams( $context->getLanguage()->pipeList( $linkTools ) )
1266 $ret[$display] = $skinkey;
1269 if ( !$foundDefault ) {
1270 // If the default skin is not available, things are going to break horribly because the
1271 // default value for skin selector will not be a valid value. Let's just not show it then.
1279 * @param IContextSource $context
1282 protected function getDateOptions( IContextSource
$context ) {
1283 $lang = $context->getLanguage();
1284 $dateopts = $lang->getDatePreferences();
1289 if ( !in_array( 'default', $dateopts ) ) {
1290 $dateopts[] = 'default'; // Make sure default is always valid T21237
1293 // FIXME KLUGE: site default might not be valid for user language
1294 global $wgDefaultUserOptions;
1295 if ( !in_array( $wgDefaultUserOptions['date'], $dateopts ) ) {
1296 $wgDefaultUserOptions['date'] = 'default';
1299 $epoch = wfTimestampNow();
1300 foreach ( $dateopts as $key ) {
1301 if ( $key == 'default' ) {
1302 $formatted = $context->msg( 'datedefault' )->escaped();
1304 $formatted = htmlspecialchars( $lang->timeanddate( $epoch, false, $key ) );
1306 $ret[$formatted] = $key;
1313 * @param MessageLocalizer $l10n
1316 protected function getImageSizes( MessageLocalizer
$l10n ) {
1318 $pixels = $l10n->msg( 'unit-pixel' )->text();
1320 foreach ( $this->config
->get( 'ImageLimits' ) as $index => $limits ) {
1321 // Note: A left-to-right marker (\u200e) is inserted, see T144386
1322 $display = "{$limits[0]}" . json_decode( '"\u200e"' ) . "×{$limits[1]}" . $pixels;
1323 $ret[$display] = $index;
1330 * @param MessageLocalizer $l10n
1333 protected function getThumbSizes( MessageLocalizer
$l10n ) {
1335 $pixels = $l10n->msg( 'unit-pixel' )->text();
1337 foreach ( $this->config
->get( 'ThumbLimits' ) as $index => $size ) {
1338 $display = $size . $pixels;
1339 $ret[$display] = $index;
1346 * @param string $signature
1347 * @param array $alldata
1348 * @param HTMLForm $form
1349 * @return bool|string
1351 protected function validateSignature( $signature, $alldata, HTMLForm
$form ) {
1352 $maxSigChars = $this->config
->get( 'MaxSigChars' );
1353 if ( mb_strlen( $signature ) > $maxSigChars ) {
1354 return Xml
::element( 'span', [ 'class' => 'error' ],
1355 $form->msg( 'badsiglength' )->numParams( $maxSigChars )->text() );
1356 } elseif ( isset( $alldata['fancysig'] ) &&
1357 $alldata['fancysig'] &&
1358 MediaWikiServices
::getInstance()->getParser()->validateSig( $signature ) === false
1360 return Xml
::element(
1362 [ 'class' => 'error' ],
1363 $form->msg( 'badsig' )->text()
1371 * @param string $signature
1372 * @param array $alldata
1373 * @param HTMLForm $form
1376 protected function cleanSignature( $signature, $alldata, HTMLForm
$form ) {
1377 $parser = MediaWikiServices
::getInstance()->getParser();
1378 if ( isset( $alldata['fancysig'] ) && $alldata['fancysig'] ) {
1379 $signature = $parser->cleanSig( $signature );
1381 // When no fancy sig used, make sure ~{3,5} get removed.
1382 $signature = Parser
::cleanSigInSig( $signature );
1390 * @param IContextSource $context
1391 * @param string $formClass
1392 * @param array $remove Array of items to remove
1393 * @return PreferencesForm|HTMLForm
1395 public function getForm(
1397 IContextSource
$context,
1398 $formClass = 'PreferencesForm',
1401 $formDescriptor = $this->getFormDescriptor( $user, $context );
1402 if ( count( $remove ) ) {
1403 $removeKeys = array_flip( $remove );
1404 $formDescriptor = array_diff_key( $formDescriptor, $removeKeys );
1407 // Remove type=api preferences. They are not intended for rendering in the form.
1408 foreach ( $formDescriptor as $name => $info ) {
1409 if ( isset( $info['type'] ) && $info['type'] === 'api' ) {
1410 unset( $formDescriptor[$name] );
1415 * @var $htmlForm PreferencesForm
1417 $htmlForm = new $formClass( $formDescriptor, $context, 'prefs' );
1419 $htmlForm->setModifiedUser( $user );
1420 $htmlForm->setId( 'mw-prefs-form' );
1421 $htmlForm->setAutocomplete( 'off' );
1422 $htmlForm->setSubmitText( $context->msg( 'saveprefs' )->text() );
1423 # Used message keys: 'accesskey-preferences-save', 'tooltip-preferences-save'
1424 $htmlForm->setSubmitTooltip( 'preferences-save' );
1425 $htmlForm->setSubmitID( 'prefcontrol' );
1426 $htmlForm->setSubmitCallback( function ( array $formData, PreferencesForm
$form ) {
1427 return $this->submitForm( $formData, $form );
1434 * @param IContextSource $context
1437 protected function getTimezoneOptions( IContextSource
$context ) {
1440 $localTZoffset = $this->config
->get( 'LocalTZoffset' );
1441 $timeZoneList = $this->getTimeZoneList( $context->getLanguage() );
1443 $timestamp = MWTimestamp
::getLocalInstance();
1444 // Check that the LocalTZoffset is the same as the local time zone offset
1445 if ( $localTZoffset == $timestamp->format( 'Z' ) / 60 ) {
1446 $timezoneName = $timestamp->getTimezone()->getName();
1447 // Localize timezone
1448 if ( isset( $timeZoneList[$timezoneName] ) ) {
1449 $timezoneName = $timeZoneList[$timezoneName]['name'];
1451 $server_tz_msg = $context->msg(
1452 'timezoneuseserverdefault',
1456 $tzstring = sprintf(
1458 floor( $localTZoffset / 60 ),
1459 abs( $localTZoffset ) %
60
1461 $server_tz_msg = $context->msg( 'timezoneuseserverdefault', $tzstring )->text();
1463 $opt[$server_tz_msg] = "System|$localTZoffset";
1464 $opt[$context->msg( 'timezoneuseoffset' )->text()] = 'other';
1465 $opt[$context->msg( 'guesstimezone' )->text()] = 'guess';
1467 foreach ( $timeZoneList as $timeZoneInfo ) {
1468 $region = $timeZoneInfo['region'];
1469 if ( !isset( $opt[$region] ) ) {
1472 $opt[$region][$timeZoneInfo['name']] = $timeZoneInfo['timecorrection'];
1479 * @param array $alldata
1482 protected function filterTimezoneInput( $tz, array $alldata ) {
1483 $data = explode( '|', $tz, 3 );
1484 switch ( $data[0] ) {
1488 if ( count( $data ) === 3 ) {
1489 // Make sure this timezone exists
1491 new DateTimeZone( $data[2] );
1492 // If the constructor didn't throw, we know it's valid
1494 } catch ( Exception
$e ) {
1495 // Not a valid timezone
1500 // If the supplied timezone doesn't exist, fall back to the encoded offset
1501 return 'Offset|' . intval( $tz[1] );
1507 $data = explode( ':', $tz, 2 );
1508 if ( count( $data ) == 2 ) {
1509 $data[0] = intval( $data[0] );
1510 $data[1] = intval( $data[1] );
1511 $minDiff = abs( $data[0] ) * 60 +
$data[1];
1512 if ( $data[0] < 0 ) {
1513 $minDiff = - $minDiff;
1516 $minDiff = intval( $data[0] ) * 60;
1519 # Max is +14:00 and min is -12:00, see:
1520 # https://en.wikipedia.org/wiki/Timezone
1521 $minDiff = min( $minDiff, 840 ); # 14:00
1522 $minDiff = max( $minDiff, -720 ); # -12:00
1523 return 'Offset|' . $minDiff;
1528 * Handle the form submission if everything validated properly
1530 * @param array $formData
1531 * @param PreferencesForm $form
1532 * @return bool|Status|string
1534 protected function saveFormData( $formData, PreferencesForm
$form ) {
1535 $user = $form->getModifiedUser();
1536 $hiddenPrefs = $this->config
->get( 'HiddenPrefs' );
1539 if ( !$user->isAllowedAny( 'editmyprivateinfo', 'editmyoptions' ) ) {
1540 return Status
::newFatal( 'mypreferencesprotected' );
1544 foreach ( array_keys( $formData ) as $name ) {
1545 $filters = $this->getSaveFilters();
1546 if ( isset( $filters[$name] ) ) {
1547 $formData[$name] = call_user_func( $filters[$name], $formData[$name], $formData );
1551 // Fortunately, the realname field is MUCH simpler
1552 // (not really "private", but still shouldn't be edited without permission)
1554 if ( !in_array( 'realname', $hiddenPrefs )
1555 && $user->isAllowed( 'editmyprivateinfo' )
1556 && array_key_exists( 'realname', $formData )
1558 $realName = $formData['realname'];
1559 $user->setRealName( $realName );
1562 if ( $user->isAllowed( 'editmyoptions' ) ) {
1563 $oldUserOptions = $user->getOptions();
1565 foreach ( $this->getSaveBlacklist() as $b ) {
1566 unset( $formData[$b] );
1569 # If users have saved a value for a preference which has subsequently been disabled
1570 # via $wgHiddenPrefs, we don't want to destroy that setting in case the preference
1571 # is subsequently re-enabled
1572 foreach ( $hiddenPrefs as $pref ) {
1573 # If the user has not set a non-default value here, the default will be returned
1574 # and subsequently discarded
1575 $formData[$pref] = $user->getOption( $pref, null, true );
1578 // If the user changed the rclimit preference, also change the rcfilters-rclimit preference
1580 isset( $formData['rclimit'] ) &&
1581 intval( $formData[ 'rclimit' ] ) !== $user->getIntOption( 'rclimit' )
1583 $formData['rcfilters-limit'] = $formData['rclimit'];
1586 // Keep old preferences from interfering due to back-compat code, etc.
1587 $user->resetOptions( 'unused', $form->getContext() );
1589 foreach ( $formData as $key => $value ) {
1590 $user->setOption( $key, $value );
1594 'PreferencesFormPreSave',
1595 [ $formData, $form, $user, &$result, $oldUserOptions ]
1599 AuthManager
::callLegacyAuthPlugin( 'updateExternalDB', [ $user ] );
1600 $user->saveSettings();
1606 * DO NOT USE. Temporary function to punch hole for the Preferences class.
1608 * @deprecated since 1.31, its inception
1610 * @param array $formData
1611 * @param PreferencesForm $form
1612 * @return bool|Status|string
1614 protected function legacySaveFormData( $formData, PreferencesForm
$form ) {
1615 return $this->saveFormData( $formData, $form );
1619 * Save the form data and reload the page
1621 * @param array $formData
1622 * @param PreferencesForm $form
1625 protected function submitForm( array $formData, PreferencesForm
$form ) {
1626 $res = $this->saveFormData( $formData, $form );
1631 if ( $res === 'eauth' ) {
1632 $urlOptions['eauth'] = 1;
1635 $urlOptions +
= $form->getExtraSuccessRedirectParameters();
1637 $url = $form->getTitle()->getFullURL( $urlOptions );
1639 $context = $form->getContext();
1640 // Set session data for the success message
1641 $context->getRequest()->getSession()->set( 'specialPreferencesSaveSuccess', 1 );
1643 $context->getOutput()->redirect( $url );
1646 return Status
::newGood();
1650 * DO NOT USE. Temporary function to punch hole for the Preferences class.
1652 * @deprecated since 1.31, its inception
1654 * @param array $formData
1655 * @param PreferencesForm $form
1658 public function legacySubmitForm( array $formData, PreferencesForm
$form ) {
1659 return $this->submitForm( $formData, $form );
1663 * Get a list of all time zones
1664 * @param Language $language Language used for the localized names
1665 * @return array A list of all time zones. The system name of the time zone is used as key and
1666 * the value is an array which contains localized name, the timecorrection value used for
1667 * preferences and the region
1670 protected function getTimeZoneList( Language
$language ) {
1671 $identifiers = DateTimeZone
::listIdentifiers();
1672 if ( $identifiers === false ) {
1675 sort( $identifiers );
1678 'Africa' => wfMessage( 'timezoneregion-africa' )->inLanguage( $language )->text(),
1679 'America' => wfMessage( 'timezoneregion-america' )->inLanguage( $language )->text(),
1680 'Antarctica' => wfMessage( 'timezoneregion-antarctica' )->inLanguage( $language )->text(),
1681 'Arctic' => wfMessage( 'timezoneregion-arctic' )->inLanguage( $language )->text(),
1682 'Asia' => wfMessage( 'timezoneregion-asia' )->inLanguage( $language )->text(),
1683 'Atlantic' => wfMessage( 'timezoneregion-atlantic' )->inLanguage( $language )->text(),
1684 'Australia' => wfMessage( 'timezoneregion-australia' )->inLanguage( $language )->text(),
1685 'Europe' => wfMessage( 'timezoneregion-europe' )->inLanguage( $language )->text(),
1686 'Indian' => wfMessage( 'timezoneregion-indian' )->inLanguage( $language )->text(),
1687 'Pacific' => wfMessage( 'timezoneregion-pacific' )->inLanguage( $language )->text(),
1689 asort( $tzRegions );
1693 $now = new DateTime();
1695 foreach ( $identifiers as $identifier ) {
1696 $parts = explode( '/', $identifier, 2 );
1698 // DateTimeZone::listIdentifiers() returns a number of
1699 // backwards-compatibility entries. This filters them out of the
1700 // list presented to the user.
1701 if ( count( $parts ) !== 2 ||
!array_key_exists( $parts[0], $tzRegions ) ) {
1706 $parts[0] = $tzRegions[$parts[0]];
1708 $dateTimeZone = new DateTimeZone( $identifier );
1709 $minDiff = floor( $dateTimeZone->getOffset( $now ) / 60 );
1711 $display = str_replace( '_', ' ', $parts[0] . '/' . $parts[1] );
1712 $value = "ZoneInfo|$minDiff|$identifier";
1714 $timeZoneList[$identifier] = [
1716 'timecorrection' => $value,
1717 'region' => $parts[0],
1721 return $timeZoneList;