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;
74 * @param Config $config
75 * @param Language $contLang
76 * @param AuthManager $authManager
77 * @param LinkRenderer $linkRenderer
79 public function __construct(
82 AuthManager
$authManager,
83 LinkRenderer
$linkRenderer
85 $this->config
= $config;
86 $this->contLang
= $contLang;
87 $this->authManager
= $authManager;
88 $this->linkRenderer
= $linkRenderer;
94 protected function getSaveFilters() {
95 // Wrap intval() so that we can pass it multiple parameters and treat all filters the same.
96 $intvalFilter = function ( $value, $alldata ) {
97 return intval( $value );
100 'timecorrection' => [ $this, 'filterTimezoneInput' ],
101 'rclimit' => $intvalFilter,
102 'wllimit' => $intvalFilter,
103 'searchlimit' => $intvalFilter,
110 public function getSaveBlacklist() {
118 * @throws MWException
120 * @param IContextSource $context
123 public function getFormDescriptor( User
$user, IContextSource
$context ) {
126 $canIPUseHTTPS = wfCanIPUseHTTPS( $context->getRequest()->getIP() );
127 $this->profilePreferences( $user, $context, $preferences, $canIPUseHTTPS );
128 $this->skinPreferences( $user, $context, $preferences );
129 $this->datetimePreferences( $user, $context, $preferences );
130 $this->filesPreferences( $context, $preferences );
131 $this->renderingPreferences( $context, $preferences );
132 $this->editingPreferences( $user, $context, $preferences );
133 $this->rcPreferences( $user, $context, $preferences );
134 $this->watchlistPreferences( $user, $context, $preferences );
135 $this->searchPreferences( $preferences );
137 Hooks
::run( 'GetPreferences', [ $user, &$preferences ] );
139 $this->loadPreferenceValues( $user, $context, $preferences );
144 * Loads existing values for a given array of preferences
145 * @throws MWException
147 * @param IContextSource $context
148 * @param array &$defaultPreferences Array to load values for
151 private function loadPreferenceValues(
152 User
$user, IContextSource
$context, &$defaultPreferences
154 # # Remove preferences that wikis don't want to use
155 foreach ( $this->config
->get( 'HiddenPrefs' ) as $pref ) {
156 if ( isset( $defaultPreferences[$pref] ) ) {
157 unset( $defaultPreferences[$pref] );
161 # # Make sure that form fields have their parent set. See T43337.
162 $dummyForm = new HTMLForm( [], $context );
164 $disable = !$user->isAllowed( 'editmyoptions' );
166 $defaultOptions = User
::getDefaultOptions();
167 # # Prod in defaults from the user
168 foreach ( $defaultPreferences as $name => &$info ) {
169 $prefFromUser = $this->getOptionFromUser( $name, $info, $user );
170 if ( $disable && !in_array( $name, $this->getSaveBlacklist() ) ) {
171 $info['disabled'] = 'disabled';
173 $field = HTMLForm
::loadInputFromParameters( $name, $info, $dummyForm ); // For validation
174 $globalDefault = isset( $defaultOptions[$name] )
175 ?
$defaultOptions[$name]
178 // If it validates, set it as the default
179 if ( isset( $info['default'] ) ) {
180 // Already set, no problem
182 } elseif ( !is_null( $prefFromUser ) && // Make sure we're not just pulling nothing
183 $field->validate( $prefFromUser, $user->getOptions() ) === true ) {
184 $info['default'] = $prefFromUser;
185 } elseif ( $field->validate( $globalDefault, $user->getOptions() ) === true ) {
186 $info['default'] = $globalDefault;
188 throw new MWException( "Global default '$globalDefault' is invalid for field $name" );
192 return $defaultPreferences;
196 * Pull option from a user account. Handles stuff like array-type preferences.
198 * @param string $name
201 * @return array|string
203 protected function getOptionFromUser( $name, $info, User
$user ) {
204 $val = $user->getOption( $name );
206 // Handling for multiselect preferences
207 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
208 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
209 $options = HTMLFormField
::flattenOptions( $info['options'] );
210 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
213 foreach ( $options as $value ) {
214 if ( $user->getOption( "$prefix$value" ) ) {
220 // Handling for checkmatrix preferences
221 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
222 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
223 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
224 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
225 $prefix = isset( $info['prefix'] ) ?
$info['prefix'] : $name;
228 foreach ( $columns as $column ) {
229 foreach ( $rows as $row ) {
230 if ( $user->getOption( "$prefix$column-$row" ) ) {
231 $val[] = "$column-$row";
241 * @todo Inject user Language instead of using context.
243 * @param IContextSource $context
244 * @param array &$defaultPreferences
245 * @param bool $canIPUseHTTPS Whether the user's IP is likely to be able to access the wiki
249 protected function profilePreferences(
250 User
$user, IContextSource
$context, &$defaultPreferences, $canIPUseHTTPS
252 // retrieving user name for GENDER and misc.
253 $userName = $user->getName();
255 # # User info #####################################
257 $defaultPreferences['username'] = [
259 'label-message' => [ 'username', $userName ],
260 'default' => $userName,
261 'section' => 'personal/info',
264 $lang = $context->getLanguage();
266 # Get groups to which the user belongs
267 $userEffectiveGroups = $user->getEffectiveGroups();
268 $userGroupMemberships = $user->getGroupMemberships();
269 $userGroups = $userMembers = $userTempGroups = $userTempMembers = [];
270 foreach ( $userEffectiveGroups as $ueg ) {
272 // Skip the default * group, seems useless here
276 if ( isset( $userGroupMemberships[$ueg] ) ) {
277 $groupStringOrObject = $userGroupMemberships[$ueg];
279 $groupStringOrObject = $ueg;
282 $userG = UserGroupMembership
::getLink( $groupStringOrObject, $context, 'html' );
283 $userM = UserGroupMembership
::getLink( $groupStringOrObject, $context, 'html',
286 // Store expiring groups separately, so we can place them before non-expiring
287 // groups in the list. This is to avoid the ambiguity of something like
288 // "administrator, bureaucrat (until X date)" -- users might wonder whether the
289 // expiry date applies to both groups, or just the last one
290 if ( $groupStringOrObject instanceof UserGroupMembership
&&
291 $groupStringOrObject->getExpiry()
293 $userTempGroups[] = $userG;
294 $userTempMembers[] = $userM;
296 $userGroups[] = $userG;
297 $userMembers[] = $userM;
301 sort( $userMembers );
302 sort( $userTempGroups );
303 sort( $userTempMembers );
304 $userGroups = array_merge( $userTempGroups, $userGroups );
305 $userMembers = array_merge( $userTempMembers, $userMembers );
307 $defaultPreferences['usergroups'] = [
309 'label' => $context->msg( 'prefs-memberingroups' )->numParams(
310 count( $userGroups ) )->params( $userName )->parse(),
311 'default' => $context->msg( 'prefs-memberingroups-type' )
312 ->rawParams( $lang->commaList( $userGroups ), $lang->commaList( $userMembers ) )
315 'section' => 'personal/info',
318 $contribTitle = SpecialPage
::getTitleFor( "Contributions", $userName );
319 $formattedEditCount = $lang->formatNum( $user->getEditCount() );
320 $editCount = $this->linkRenderer
->makeLink( $contribTitle, $formattedEditCount );
322 $defaultPreferences['editcount'] = [
325 'label-message' => 'prefs-edits',
326 'default' => $editCount,
327 'section' => 'personal/info',
330 if ( $user->getRegistration() ) {
331 $displayUser = $context->getUser();
332 $userRegistration = $user->getRegistration();
333 $defaultPreferences['registrationdate'] = [
335 'label-message' => 'prefs-registration',
336 'default' => $context->msg(
337 'prefs-registration-date-time',
338 $lang->userTimeAndDate( $userRegistration, $displayUser ),
339 $lang->userDate( $userRegistration, $displayUser ),
340 $lang->userTime( $userRegistration, $displayUser )
342 'section' => 'personal/info',
346 $canViewPrivateInfo = $user->isAllowed( 'viewmyprivateinfo' );
347 $canEditPrivateInfo = $user->isAllowed( 'editmyprivateinfo' );
349 // Actually changeable stuff
350 $defaultPreferences['realname'] = [
351 // (not really "private", but still shouldn't be edited without permission)
352 'type' => $canEditPrivateInfo && $this->authManager
->allowsPropertyChange( 'realname' )
354 'default' => $user->getRealName(),
355 'section' => 'personal/info',
356 'label-message' => 'yourrealname',
357 'help-message' => 'prefs-help-realname',
360 if ( $canEditPrivateInfo && $this->authManager
->allowsAuthenticationDataChange(
361 new PasswordAuthenticationRequest(), false )->isGood()
363 $link = $this->linkRenderer
->makeLink( SpecialPage
::getTitleFor( 'ChangePassword' ),
364 $context->msg( 'prefs-resetpass' )->text(), [],
365 [ 'returnto' => SpecialPage
::getTitleFor( 'Preferences' )->getPrefixedText() ] );
366 $defaultPreferences['password'] = [
370 'label-message' => 'yourpassword',
371 'section' => 'personal/info',
374 // Only show prefershttps if secure login is turned on
375 if ( $this->config
->get( 'SecureLogin' ) && $canIPUseHTTPS ) {
376 $defaultPreferences['prefershttps'] = [
378 'label-message' => 'tog-prefershttps',
379 'help-message' => 'prefs-help-prefershttps',
380 'section' => 'personal/info'
385 $languages = Language
::fetchLanguageNames( null, 'mw' );
386 $languageCode = $this->config
->get( 'LanguageCode' );
387 if ( !array_key_exists( $languageCode, $languages ) ) {
388 $languages[$languageCode] = $languageCode;
393 foreach ( $languages as $code => $name ) {
394 $display = LanguageCode
::bcp47( $code ) . ' - ' . $name;
395 $options[$display] = $code;
397 $defaultPreferences['language'] = [
399 'section' => 'personal/i18n',
400 'options' => $options,
401 'label-message' => 'yourlanguage',
404 $defaultPreferences['gender'] = [
406 'section' => 'personal/i18n',
408 $context->msg( 'parentheses' )
409 ->params( $context->msg( 'gender-unknown' )->plain() )
410 ->escaped() => 'unknown',
411 $context->msg( 'gender-female' )->escaped() => 'female',
412 $context->msg( 'gender-male' )->escaped() => 'male',
414 'label-message' => 'yourgender',
415 'help-message' => 'prefs-help-gender',
418 // see if there are multiple language variants to choose from
419 if ( !$this->config
->get( 'DisableLangConversion' ) ) {
420 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
421 if ( $langCode == $this->contLang
->getCode() ) {
422 $variants = $this->contLang
->getVariants();
424 if ( count( $variants ) <= 1 ) {
429 foreach ( $variants as $v ) {
430 $v = str_replace( '_', '-', strtolower( $v ) );
431 $variantArray[$v] = $lang->getVariantname( $v, false );
435 foreach ( $variantArray as $code => $name ) {
436 $display = LanguageCode
::bcp47( $code ) . ' - ' . $name;
437 $options[$display] = $code;
440 $defaultPreferences['variant'] = [
441 'label-message' => 'yourvariant',
443 'options' => $options,
444 'section' => 'personal/i18n',
445 'help-message' => 'prefs-help-variant',
448 $defaultPreferences["variant-$langCode"] = [
455 // Stuff from Language::getExtraUserToggles()
456 // FIXME is this dead code? $extraUserToggles doesn't seem to be defined for any language
457 $toggles = $this->contLang
->getExtraUserToggles();
459 foreach ( $toggles as $toggle ) {
460 $defaultPreferences[$toggle] = [
462 'section' => 'personal/i18n',
463 'label-message' => "tog-$toggle",
467 // show a preview of the old signature first
468 $oldsigWikiText = MediaWikiServices
::getInstance()->getParser()->preSaveTransform(
470 $context->getTitle(),
472 ParserOptions
::newFromContext( $context )
474 $oldsigHTML = $context->getOutput()->parseInline( $oldsigWikiText, true, true );
475 $defaultPreferences['oldsig'] = [
478 'label-message' => 'tog-oldsig',
479 'default' => $oldsigHTML,
480 'section' => 'personal/signature',
482 $defaultPreferences['nickname'] = [
483 'type' => $this->authManager
->allowsPropertyChange( 'nickname' ) ?
'text' : 'info',
484 'maxlength' => $this->config
->get( 'MaxSigChars' ),
485 'label-message' => 'yournick',
486 'validation-callback' => function ( $signature, $alldata, HTMLForm
$form ) {
487 return $this->validateSignature( $signature, $alldata, $form );
489 'section' => 'personal/signature',
490 'filter-callback' => function ( $signature, array $alldata, HTMLForm
$form ) {
491 return $this->cleanSignature( $signature, $alldata, $form );
494 $defaultPreferences['fancysig'] = [
496 'label-message' => 'tog-fancysig',
497 // show general help about signature at the bottom of the section
498 'help-message' => 'prefs-help-signature',
499 'section' => 'personal/signature'
504 if ( $this->config
->get( 'EnableEmail' ) ) {
505 if ( $canViewPrivateInfo ) {
506 $helpMessages[] = $this->config
->get( 'EmailConfirmToEdit' )
507 ?
'prefs-help-email-required'
508 : 'prefs-help-email';
510 if ( $this->config
->get( 'EnableUserEmail' ) ) {
511 // additional messages when users can send email to each other
512 $helpMessages[] = 'prefs-help-email-others';
515 $emailAddress = $user->getEmail() ?
htmlspecialchars( $user->getEmail() ) : '';
516 if ( $canEditPrivateInfo && $this->authManager
->allowsPropertyChange( 'emailaddress' ) ) {
517 $link = $this->linkRenderer
->makeLink(
518 SpecialPage
::getTitleFor( 'ChangeEmail' ),
519 $context->msg( $user->getEmail() ?
'prefs-changeemail' : 'prefs-setemail' )->text(),
521 [ 'returnto' => SpecialPage
::getTitleFor( 'Preferences' )->getPrefixedText() ] );
523 $emailAddress .= $emailAddress == '' ?
$link : (
524 $context->msg( 'word-separator' )->escaped()
525 . $context->msg( 'parentheses' )->rawParams( $link )->escaped()
529 $defaultPreferences['emailaddress'] = [
532 'default' => $emailAddress,
533 'label-message' => 'youremail',
534 'section' => 'personal/email',
535 'help-messages' => $helpMessages,
536 # 'cssclass' chosen below
540 $disableEmailPrefs = false;
542 if ( $this->config
->get( 'EmailAuthentication' ) ) {
543 $emailauthenticationclass = 'mw-email-not-authenticated';
544 if ( $user->getEmail() ) {
545 if ( $user->getEmailAuthenticationTimestamp() ) {
546 // date and time are separate parameters to facilitate localisation.
547 // $time is kept for backward compat reasons.
548 // 'emailauthenticated' is also used in SpecialConfirmemail.php
549 $displayUser = $context->getUser();
550 $emailTimestamp = $user->getEmailAuthenticationTimestamp();
551 $time = $lang->userTimeAndDate( $emailTimestamp, $displayUser );
552 $d = $lang->userDate( $emailTimestamp, $displayUser );
553 $t = $lang->userTime( $emailTimestamp, $displayUser );
554 $emailauthenticated = $context->msg( 'emailauthenticated',
555 $time, $d, $t )->parse() . '<br />';
556 $disableEmailPrefs = false;
557 $emailauthenticationclass = 'mw-email-authenticated';
559 $disableEmailPrefs = true;
560 $emailauthenticated = $context->msg( 'emailnotauthenticated' )->parse() . '<br />' .
561 $this->linkRenderer
->makeKnownLink(
562 SpecialPage
::getTitleFor( 'Confirmemail' ),
563 $context->msg( 'emailconfirmlink' )->text()
565 $emailauthenticationclass = "mw-email-not-authenticated";
568 $disableEmailPrefs = true;
569 $emailauthenticated = $context->msg( 'noemailprefs' )->escaped();
570 $emailauthenticationclass = 'mw-email-none';
573 if ( $canViewPrivateInfo ) {
574 $defaultPreferences['emailauthentication'] = [
577 'section' => 'personal/email',
578 'label-message' => 'prefs-emailconfirm-label',
579 'default' => $emailauthenticated,
580 # Apply the same CSS class used on the input to the message:
581 'cssclass' => $emailauthenticationclass,
586 if ( $this->config
->get( 'EnableUserEmail' ) && $user->isAllowed( 'sendemail' ) ) {
587 $defaultPreferences['disablemail'] = [
588 'id' => 'wpAllowEmail',
591 'section' => 'personal/email',
592 'label-message' => 'allowemail',
593 'disabled' => $disableEmailPrefs,
596 $defaultPreferences['email-allow-new-users'] = [
597 'id' => 'wpAllowEmailFromNewUsers',
599 'section' => 'personal/email',
600 'label-message' => 'email-allow-new-users-label',
601 'disabled' => $disableEmailPrefs,
604 $defaultPreferences['ccmeonemails'] = [
606 'section' => 'personal/email',
607 'label-message' => 'tog-ccmeonemails',
608 'disabled' => $disableEmailPrefs,
611 if ( $this->config
->get( 'EnableUserEmailBlacklist' ) ) {
612 $lookup = CentralIdLookup
::factory();
613 $ids = $user->getOption( 'email-blacklist', [] );
614 $names = $ids ?
$lookup->namesFromCentralIds( $ids, $user ) : [];
616 $defaultPreferences['email-blacklist'] = [
617 'type' => 'usersmultiselect',
618 'label-message' => 'email-blacklist-label',
619 'section' => 'personal/email',
620 'default' => implode( "\n", $names ),
621 'disabled' => $disableEmailPrefs,
626 if ( $this->config
->get( 'EnotifWatchlist' ) ) {
627 $defaultPreferences['enotifwatchlistpages'] = [
629 'section' => 'personal/email',
630 'label-message' => 'tog-enotifwatchlistpages',
631 'disabled' => $disableEmailPrefs,
634 if ( $this->config
->get( 'EnotifUserTalk' ) ) {
635 $defaultPreferences['enotifusertalkpages'] = [
637 'section' => 'personal/email',
638 'label-message' => 'tog-enotifusertalkpages',
639 'disabled' => $disableEmailPrefs,
642 if ( $this->config
->get( 'EnotifUserTalk' ) ||
$this->config
->get( 'EnotifWatchlist' ) ) {
643 if ( $this->config
->get( 'EnotifMinorEdits' ) ) {
644 $defaultPreferences['enotifminoredits'] = [
646 'section' => 'personal/email',
647 'label-message' => 'tog-enotifminoredits',
648 'disabled' => $disableEmailPrefs,
652 if ( $this->config
->get( 'EnotifRevealEditorAddress' ) ) {
653 $defaultPreferences['enotifrevealaddr'] = [
655 'section' => 'personal/email',
656 'label-message' => 'tog-enotifrevealaddr',
657 'disabled' => $disableEmailPrefs,
666 * @param IContextSource $context
667 * @param array &$defaultPreferences
670 protected function skinPreferences( User
$user, IContextSource
$context, &$defaultPreferences ) {
671 # # Skin #####################################
673 // Skin selector, if there is at least one valid skin
674 $skinOptions = $this->generateSkinOptions( $user, $context );
675 if ( $skinOptions ) {
676 $defaultPreferences['skin'] = [
678 'options' => $skinOptions,
679 'section' => 'rendering/skin',
683 $allowUserCss = $this->config
->get( 'AllowUserCss' );
684 $allowUserJs = $this->config
->get( 'AllowUserJs' );
685 # Create links to user CSS/JS pages for all skins
686 # This code is basically copied from generateSkinOptions(). It'd
687 # be nice to somehow merge this back in there to avoid redundancy.
688 if ( $allowUserCss ||
$allowUserJs ) {
690 $userName = $user->getName();
692 if ( $allowUserCss ) {
693 $cssPage = Title
::makeTitleSafe( NS_USER
, $userName . '/common.css' );
694 $cssLinkText = $context->msg( 'prefs-custom-css' )->text();
695 $linkTools[] = $this->linkRenderer
->makeLink( $cssPage, $cssLinkText );
698 if ( $allowUserJs ) {
699 $jsPage = Title
::makeTitleSafe( NS_USER
, $userName . '/common.js' );
700 $jsLinkText = $context->msg( 'prefs-custom-js' )->text();
701 $linkTools[] = $this->linkRenderer
->makeLink( $jsPage, $jsLinkText );
704 $defaultPreferences['commoncssjs'] = [
707 'default' => $context->getLanguage()->pipeList( $linkTools ),
708 'label-message' => 'prefs-common-css-js',
709 'section' => 'rendering/skin',
715 * @param IContextSource $context
716 * @param array &$defaultPreferences
718 protected function filesPreferences( IContextSource
$context, &$defaultPreferences ) {
719 # # Files #####################################
720 $defaultPreferences['imagesize'] = [
722 'options' => $this->getImageSizes( $context ),
723 'label-message' => 'imagemaxsize',
724 'section' => 'rendering/files',
726 $defaultPreferences['thumbsize'] = [
728 'options' => $this->getThumbSizes( $context ),
729 'label-message' => 'thumbsize',
730 'section' => 'rendering/files',
736 * @param IContextSource $context
737 * @param array &$defaultPreferences
740 protected function datetimePreferences( $user, IContextSource
$context, &$defaultPreferences ) {
741 # # Date and time #####################################
742 $dateOptions = $this->getDateOptions( $context );
743 if ( $dateOptions ) {
744 $defaultPreferences['date'] = [
746 'options' => $dateOptions,
747 'section' => 'rendering/dateformat',
752 $now = wfTimestampNow();
753 $lang = $context->getLanguage();
754 $nowlocal = Xml
::element( 'span', [ 'id' => 'wpLocalTime' ],
755 $lang->userTime( $now, $user ) );
756 $nowserver = $lang->userTime( $now, $user,
757 [ 'format' => false, 'timecorrection' => false ] ) .
758 Html
::hidden( 'wpServerTime', (int)substr( $now, 8, 2 ) * 60 +
(int)substr( $now, 10, 2 ) );
760 $defaultPreferences['nowserver'] = [
763 'label-message' => 'servertime',
764 'default' => $nowserver,
765 'section' => 'rendering/timeoffset',
768 $defaultPreferences['nowlocal'] = [
771 'label-message' => 'localtime',
772 'default' => $nowlocal,
773 'section' => 'rendering/timeoffset',
776 // Grab existing pref.
777 $tzOffset = $user->getOption( 'timecorrection' );
778 $tz = explode( '|', $tzOffset, 3 );
780 $tzOptions = $this->getTimezoneOptions( $context );
782 $tzSetting = $tzOffset;
783 if ( count( $tz ) > 1 && $tz[0] == 'ZoneInfo' &&
784 !in_array( $tzOffset, HTMLFormField
::flattenOptions( $tzOptions ) )
786 // Timezone offset can vary with DST
788 $userTZ = new DateTimeZone( $tz[2] );
789 $minDiff = floor( $userTZ->getOffset( new DateTime( 'now' ) ) / 60 );
790 $tzSetting = "ZoneInfo|$minDiff|{$tz[2]}";
791 } catch ( Exception
$e ) {
792 // User has an invalid time zone set. Fall back to just using the offset
796 if ( count( $tz ) > 1 && $tz[0] == 'Offset' ) {
798 $tzSetting = sprintf( '%+03d:%02d', floor( $minDiff / 60 ), abs( $minDiff ) %
60 );
801 $defaultPreferences['timecorrection'] = [
802 'class' => 'HTMLSelectOrOtherField',
803 'label-message' => 'timezonelegend',
804 'options' => $tzOptions,
805 'default' => $tzSetting,
807 'section' => 'rendering/timeoffset',
812 * @param MessageLocalizer $l10n
813 * @param array &$defaultPreferences
815 protected function renderingPreferences( MessageLocalizer
$l10n, &$defaultPreferences ) {
816 # # Diffs ####################################
817 $defaultPreferences['diffonly'] = [
819 'section' => 'rendering/diffs',
820 'label-message' => 'tog-diffonly',
822 $defaultPreferences['norollbackdiff'] = [
824 'section' => 'rendering/diffs',
825 'label-message' => 'tog-norollbackdiff',
828 # # Page Rendering ##############################
829 if ( $this->config
->get( 'AllowUserCssPrefs' ) ) {
830 $defaultPreferences['underline'] = [
833 $l10n->msg( 'underline-never' )->text() => 0,
834 $l10n->msg( 'underline-always' )->text() => 1,
835 $l10n->msg( 'underline-default' )->text() => 2,
837 'label-message' => 'tog-underline',
838 'section' => 'rendering/advancedrendering',
842 $stubThresholdValues = [ 50, 100, 500, 1000, 2000, 5000, 10000 ];
843 $stubThresholdOptions = [ $l10n->msg( 'stub-threshold-disabled' )->text() => 0 ];
844 foreach ( $stubThresholdValues as $value ) {
845 $stubThresholdOptions[$l10n->msg( 'size-bytes', $value )->text()] = $value;
848 $defaultPreferences['stubthreshold'] = [
850 'section' => 'rendering/advancedrendering',
851 'options' => $stubThresholdOptions,
852 // This is not a raw HTML message; label-raw is needed for the manual <a></a>
853 'label-raw' => $l10n->msg( 'stub-threshold' )->rawParams(
854 '<a href="#" class="stub">' .
855 $l10n->msg( 'stub-threshold-sample-link' )->parse() .
859 $defaultPreferences['showhiddencats'] = [
861 'section' => 'rendering/advancedrendering',
862 'label-message' => 'tog-showhiddencats'
865 $defaultPreferences['numberheadings'] = [
867 'section' => 'rendering/advancedrendering',
868 'label-message' => 'tog-numberheadings',
874 * @param MessageLocalizer $l10n
875 * @param array &$defaultPreferences
877 protected function editingPreferences( User
$user, MessageLocalizer
$l10n, &$defaultPreferences ) {
878 # # Editing #####################################
879 $defaultPreferences['editsectiononrightclick'] = [
881 'section' => 'editing/advancedediting',
882 'label-message' => 'tog-editsectiononrightclick',
884 $defaultPreferences['editondblclick'] = [
886 'section' => 'editing/advancedediting',
887 'label-message' => 'tog-editondblclick',
890 if ( $this->config
->get( 'AllowUserCssPrefs' ) ) {
891 $defaultPreferences['editfont'] = [
893 'section' => 'editing/editor',
894 'label-message' => 'editfont-style',
896 $l10n->msg( 'editfont-monospace' )->text() => 'monospace',
897 $l10n->msg( 'editfont-sansserif' )->text() => 'sans-serif',
898 $l10n->msg( 'editfont-serif' )->text() => 'serif',
903 if ( $user->isAllowed( 'minoredit' ) ) {
904 $defaultPreferences['minordefault'] = [
906 'section' => 'editing/editor',
907 'label-message' => 'tog-minordefault',
911 $defaultPreferences['forceeditsummary'] = [
913 'section' => 'editing/editor',
914 'label-message' => 'tog-forceeditsummary',
916 $defaultPreferences['useeditwarning'] = [
918 'section' => 'editing/editor',
919 'label-message' => 'tog-useeditwarning',
921 $defaultPreferences['showtoolbar'] = [
923 'section' => 'editing/editor',
924 'label-message' => 'tog-showtoolbar',
927 $defaultPreferences['previewonfirst'] = [
929 'section' => 'editing/preview',
930 'label-message' => 'tog-previewonfirst',
932 $defaultPreferences['previewontop'] = [
934 'section' => 'editing/preview',
935 'label-message' => 'tog-previewontop',
937 $defaultPreferences['uselivepreview'] = [
939 'section' => 'editing/preview',
940 'label-message' => 'tog-uselivepreview',
946 * @param MessageLocalizer $l10n
947 * @param array &$defaultPreferences
949 protected function rcPreferences( User
$user, MessageLocalizer
$l10n, &$defaultPreferences ) {
950 $rcMaxAge = $this->config
->get( 'RCMaxAge' );
951 # # RecentChanges #####################################
952 $defaultPreferences['rcdays'] = [
954 'label-message' => 'recentchangesdays',
955 'section' => 'rc/displayrc',
957 'max' => ceil( $rcMaxAge / ( 3600 * 24 ) ),
958 'help' => $l10n->msg( 'recentchangesdays-max' )->numParams(
959 ceil( $rcMaxAge / ( 3600 * 24 ) ) )->escaped()
961 $defaultPreferences['rclimit'] = [
965 'label-message' => 'recentchangescount',
966 'help-message' => 'prefs-help-recentchangescount',
967 'section' => 'rc/displayrc',
969 $defaultPreferences['usenewrc'] = [
971 'label-message' => 'tog-usenewrc',
972 'section' => 'rc/advancedrc',
974 $defaultPreferences['hideminor'] = [
976 'label-message' => 'tog-hideminor',
977 'section' => 'rc/advancedrc',
979 $defaultPreferences['rcfilters-saved-queries'] = [
982 $defaultPreferences['rcfilters-wl-saved-queries'] = [
985 // Override RCFilters preferences for RecentChanges 'limit'
986 $defaultPreferences['rcfilters-limit'] = [
989 $defaultPreferences['rcfilters-saved-queries-versionbackup'] = [
992 $defaultPreferences['rcfilters-wl-saved-queries-versionbackup'] = [
996 if ( $this->config
->get( 'RCWatchCategoryMembership' ) ) {
997 $defaultPreferences['hidecategorization'] = [
999 'label-message' => 'tog-hidecategorization',
1000 'section' => 'rc/advancedrc',
1004 if ( $user->useRCPatrol() ) {
1005 $defaultPreferences['hidepatrolled'] = [
1007 'section' => 'rc/advancedrc',
1008 'label-message' => 'tog-hidepatrolled',
1012 if ( $user->useNPPatrol() ) {
1013 $defaultPreferences['newpageshidepatrolled'] = [
1015 'section' => 'rc/advancedrc',
1016 'label-message' => 'tog-newpageshidepatrolled',
1020 if ( $this->config
->get( 'RCShowWatchingUsers' ) ) {
1021 $defaultPreferences['shownumberswatching'] = [
1023 'section' => 'rc/advancedrc',
1024 'label-message' => 'tog-shownumberswatching',
1028 if ( $this->config
->get( 'StructuredChangeFiltersShowPreference' ) ) {
1029 $defaultPreferences['rcenhancedfilters-disable'] = [
1031 'section' => 'rc/opt-out',
1032 'label-message' => 'rcfilters-preference-label',
1033 'help-message' => 'rcfilters-preference-help',
1040 * @param IContextSource $context
1041 * @param array &$defaultPreferences
1043 protected function watchlistPreferences(
1044 User
$user, IContextSource
$context, &$defaultPreferences
1046 $watchlistdaysMax = ceil( $this->config
->get( 'RCMaxAge' ) / ( 3600 * 24 ) );
1048 # # Watchlist #####################################
1049 if ( $user->isAllowed( 'editmywatchlist' ) ) {
1050 $editWatchlistLinks = [];
1051 $editWatchlistModes = [
1052 'edit' => [ 'EditWatchlist', false ],
1053 'raw' => [ 'EditWatchlist', 'raw' ],
1054 'clear' => [ 'EditWatchlist', 'clear' ],
1056 foreach ( $editWatchlistModes as $editWatchlistMode => $mode ) {
1057 // Messages: prefs-editwatchlist-edit, prefs-editwatchlist-raw, prefs-editwatchlist-clear
1058 $editWatchlistLinks[] = $this->linkRenderer
->makeKnownLink(
1059 SpecialPage
::getTitleFor( $mode[0], $mode[1] ),
1060 new HtmlArmor( $context->msg( "prefs-editwatchlist-{$editWatchlistMode}" )->parse() )
1064 $defaultPreferences['editwatchlist'] = [
1067 'default' => $context->getLanguage()->pipeList( $editWatchlistLinks ),
1068 'label-message' => 'prefs-editwatchlist-label',
1069 'section' => 'watchlist/editwatchlist',
1073 $defaultPreferences['watchlistdays'] = [
1076 'max' => $watchlistdaysMax,
1077 'section' => 'watchlist/displaywatchlist',
1078 'help' => $context->msg( 'prefs-watchlist-days-max' )->numParams(
1079 $watchlistdaysMax )->escaped(),
1080 'label-message' => 'prefs-watchlist-days',
1082 $defaultPreferences['wllimit'] = [
1086 'label-message' => 'prefs-watchlist-edits',
1087 'help' => $context->msg( 'prefs-watchlist-edits-max' )->escaped(),
1088 'section' => 'watchlist/displaywatchlist',
1090 $defaultPreferences['extendwatchlist'] = [
1092 'section' => 'watchlist/advancedwatchlist',
1093 'label-message' => 'tog-extendwatchlist',
1095 $defaultPreferences['watchlisthideminor'] = [
1097 'section' => 'watchlist/advancedwatchlist',
1098 'label-message' => 'tog-watchlisthideminor',
1100 $defaultPreferences['watchlisthidebots'] = [
1102 'section' => 'watchlist/advancedwatchlist',
1103 'label-message' => 'tog-watchlisthidebots',
1105 $defaultPreferences['watchlisthideown'] = [
1107 'section' => 'watchlist/advancedwatchlist',
1108 'label-message' => 'tog-watchlisthideown',
1110 $defaultPreferences['watchlisthideanons'] = [
1112 'section' => 'watchlist/advancedwatchlist',
1113 'label-message' => 'tog-watchlisthideanons',
1115 $defaultPreferences['watchlisthideliu'] = [
1117 'section' => 'watchlist/advancedwatchlist',
1118 'label-message' => 'tog-watchlisthideliu',
1120 $defaultPreferences['watchlistreloadautomatically'] = [
1122 'section' => 'watchlist/advancedwatchlist',
1123 'label-message' => 'tog-watchlistreloadautomatically',
1125 $defaultPreferences['watchlistunwatchlinks'] = [
1127 'section' => 'watchlist/advancedwatchlist',
1128 'label-message' => 'tog-watchlistunwatchlinks',
1131 if ( $this->config
->get( 'RCWatchCategoryMembership' ) ) {
1132 $defaultPreferences['watchlisthidecategorization'] = [
1134 'section' => 'watchlist/advancedwatchlist',
1135 'label-message' => 'tog-watchlisthidecategorization',
1139 if ( $user->useRCPatrol() ) {
1140 $defaultPreferences['watchlisthidepatrolled'] = [
1142 'section' => 'watchlist/advancedwatchlist',
1143 'label-message' => 'tog-watchlisthidepatrolled',
1148 'edit' => 'watchdefault',
1149 'move' => 'watchmoves',
1150 'delete' => 'watchdeletion'
1154 if ( $user->isAllowed( 'createpage' ) ||
$user->isAllowed( 'createtalk' ) ) {
1155 $watchTypes['read'] = 'watchcreations';
1158 if ( $user->isAllowed( 'rollback' ) ) {
1159 $watchTypes['rollback'] = 'watchrollback';
1162 if ( $user->isAllowed( 'upload' ) ) {
1163 $watchTypes['upload'] = 'watchuploads';
1166 foreach ( $watchTypes as $action => $pref ) {
1167 if ( $user->isAllowed( $action ) ) {
1169 // tog-watchdefault, tog-watchmoves, tog-watchdeletion, tog-watchcreations, tog-watchuploads
1170 // tog-watchrollback
1171 $defaultPreferences[$pref] = [
1173 'section' => 'watchlist/advancedwatchlist',
1174 'label-message' => "tog-$pref",
1179 if ( $this->config
->get( 'EnableAPI' ) ) {
1180 $defaultPreferences['watchlisttoken'] = [
1183 $defaultPreferences['watchlisttoken-info'] = [
1185 'section' => 'watchlist/tokenwatchlist',
1186 'label-message' => 'prefs-watchlist-token',
1187 'default' => $user->getTokenFromOption( 'watchlisttoken' ),
1188 'help-message' => 'prefs-help-watchlist-token2',
1194 * @param array &$defaultPreferences
1196 protected function searchPreferences( &$defaultPreferences ) {
1197 foreach ( MWNamespace
::getValidNamespaces() as $n ) {
1198 $defaultPreferences['searchNs' . $n] = [
1205 * @param User $user The User object
1206 * @param IContextSource $context
1207 * @return array Text/links to display as key; $skinkey as value
1209 protected function generateSkinOptions( User
$user, IContextSource
$context ) {
1212 $mptitle = Title
::newMainPage();
1213 $previewtext = $context->msg( 'skin-preview' )->escaped();
1215 # Only show skins that aren't disabled in $wgSkipSkins
1216 $validSkinNames = Skin
::getAllowedSkins();
1218 foreach ( $validSkinNames as $skinkey => &$skinname ) {
1219 $msg = $context->msg( "skinname-{$skinkey}" );
1220 if ( $msg->exists() ) {
1221 $skinname = htmlspecialchars( $msg->text() );
1225 $defaultSkin = $this->config
->get( 'DefaultSkin' );
1226 $allowUserCss = $this->config
->get( 'AllowUserCss' );
1227 $allowUserJs = $this->config
->get( 'AllowUserJs' );
1229 # Sort by the internal name, so that the ordering is the same for each display language,
1230 # especially if some skin names are translated to use a different alphabet and some are not.
1231 uksort( $validSkinNames, function ( $a, $b ) use ( $defaultSkin ) {
1232 # Display the default first in the list by comparing it as lesser than any other.
1233 if ( strcasecmp( $a, $defaultSkin ) === 0 ) {
1236 if ( strcasecmp( $b, $defaultSkin ) === 0 ) {
1239 return strcasecmp( $a, $b );
1242 $foundDefault = false;
1243 foreach ( $validSkinNames as $skinkey => $sn ) {
1246 # Mark the default skin
1247 if ( strcasecmp( $skinkey, $defaultSkin ) === 0 ) {
1248 $linkTools[] = $context->msg( 'default' )->escaped();
1249 $foundDefault = true;
1252 # Create preview link
1253 $mplink = htmlspecialchars( $mptitle->getLocalURL( [ 'useskin' => $skinkey ] ) );
1254 $linkTools[] = "<a target='_blank' href=\"$mplink\">$previewtext</a>";
1256 # Create links to user CSS/JS pages
1257 if ( $allowUserCss ) {
1258 $cssPage = Title
::makeTitleSafe( NS_USER
, $user->getName() . '/' . $skinkey . '.css' );
1259 $cssLinkText = $context->msg( 'prefs-custom-css' )->text();
1260 $linkTools[] = $this->linkRenderer
->makeLink( $cssPage, $cssLinkText );
1263 if ( $allowUserJs ) {
1264 $jsPage = Title
::makeTitleSafe( NS_USER
, $user->getName() . '/' . $skinkey . '.js' );
1265 $jsLinkText = $context->msg( 'prefs-custom-js' )->text();
1266 $linkTools[] = $this->linkRenderer
->makeLink( $jsPage, $jsLinkText );
1269 $display = $sn . ' ' . $context->msg( 'parentheses' )
1270 ->rawParams( $context->getLanguage()->pipeList( $linkTools ) )
1272 $ret[$display] = $skinkey;
1275 if ( !$foundDefault ) {
1276 // If the default skin is not available, things are going to break horribly because the
1277 // default value for skin selector will not be a valid value. Let's just not show it then.
1285 * @param IContextSource $context
1288 protected function getDateOptions( IContextSource
$context ) {
1289 $lang = $context->getLanguage();
1290 $dateopts = $lang->getDatePreferences();
1295 if ( !in_array( 'default', $dateopts ) ) {
1296 $dateopts[] = 'default'; // Make sure default is always valid T21237
1299 // FIXME KLUGE: site default might not be valid for user language
1300 global $wgDefaultUserOptions;
1301 if ( !in_array( $wgDefaultUserOptions['date'], $dateopts ) ) {
1302 $wgDefaultUserOptions['date'] = 'default';
1305 $epoch = wfTimestampNow();
1306 foreach ( $dateopts as $key ) {
1307 if ( $key == 'default' ) {
1308 $formatted = $context->msg( 'datedefault' )->escaped();
1310 $formatted = htmlspecialchars( $lang->timeanddate( $epoch, false, $key ) );
1312 $ret[$formatted] = $key;
1319 * @param MessageLocalizer $l10n
1322 protected function getImageSizes( MessageLocalizer
$l10n ) {
1324 $pixels = $l10n->msg( 'unit-pixel' )->text();
1326 foreach ( $this->config
->get( 'ImageLimits' ) as $index => $limits ) {
1327 // Note: A left-to-right marker (\u200e) is inserted, see T144386
1328 $display = "{$limits[0]}" . json_decode( '"\u200e"' ) . "×{$limits[1]}" . $pixels;
1329 $ret[$display] = $index;
1336 * @param MessageLocalizer $l10n
1339 protected function getThumbSizes( MessageLocalizer
$l10n ) {
1341 $pixels = $l10n->msg( 'unit-pixel' )->text();
1343 foreach ( $this->config
->get( 'ThumbLimits' ) as $index => $size ) {
1344 $display = $size . $pixels;
1345 $ret[$display] = $index;
1352 * @param string $signature
1353 * @param array $alldata
1354 * @param HTMLForm $form
1355 * @return bool|string
1357 protected function validateSignature( $signature, $alldata, HTMLForm
$form ) {
1358 $maxSigChars = $this->config
->get( 'MaxSigChars' );
1359 if ( mb_strlen( $signature ) > $maxSigChars ) {
1360 return Xml
::element( 'span', [ 'class' => 'error' ],
1361 $form->msg( 'badsiglength' )->numParams( $maxSigChars )->text() );
1362 } elseif ( isset( $alldata['fancysig'] ) &&
1363 $alldata['fancysig'] &&
1364 MediaWikiServices
::getInstance()->getParser()->validateSig( $signature ) === false
1366 return Xml
::element(
1368 [ 'class' => 'error' ],
1369 $form->msg( 'badsig' )->text()
1377 * @param string $signature
1378 * @param array $alldata
1379 * @param HTMLForm $form
1382 protected function cleanSignature( $signature, $alldata, HTMLForm
$form ) {
1383 $parser = MediaWikiServices
::getInstance()->getParser();
1384 if ( isset( $alldata['fancysig'] ) && $alldata['fancysig'] ) {
1385 $signature = $parser->cleanSig( $signature );
1387 // When no fancy sig used, make sure ~{3,5} get removed.
1388 $signature = Parser
::cleanSigInSig( $signature );
1396 * @param IContextSource $context
1397 * @param string $formClass
1398 * @param array $remove Array of items to remove
1399 * @return PreferencesForm|HTMLForm
1401 public function getForm(
1403 IContextSource
$context,
1404 $formClass = 'PreferencesForm',
1407 $formDescriptor = $this->getFormDescriptor( $user, $context );
1408 if ( count( $remove ) ) {
1409 $removeKeys = array_flip( $remove );
1410 $formDescriptor = array_diff_key( $formDescriptor, $removeKeys );
1413 // Remove type=api preferences. They are not intended for rendering in the form.
1414 foreach ( $formDescriptor as $name => $info ) {
1415 if ( isset( $info['type'] ) && $info['type'] === 'api' ) {
1416 unset( $formDescriptor[$name] );
1421 * @var $htmlForm PreferencesForm
1423 $htmlForm = new $formClass( $formDescriptor, $context, 'prefs' );
1425 $htmlForm->setModifiedUser( $user );
1426 $htmlForm->setId( 'mw-prefs-form' );
1427 $htmlForm->setAutocomplete( 'off' );
1428 $htmlForm->setSubmitText( $context->msg( 'saveprefs' )->text() );
1429 # Used message keys: 'accesskey-preferences-save', 'tooltip-preferences-save'
1430 $htmlForm->setSubmitTooltip( 'preferences-save' );
1431 $htmlForm->setSubmitID( 'prefcontrol' );
1432 $htmlForm->setSubmitCallback( function ( array $formData, PreferencesForm
$form ) {
1433 return $this->submitForm( $formData, $form );
1440 * @param IContextSource $context
1443 protected function getTimezoneOptions( IContextSource
$context ) {
1446 $localTZoffset = $this->config
->get( 'LocalTZoffset' );
1447 $timeZoneList = $this->getTimeZoneList( $context->getLanguage() );
1449 $timestamp = MWTimestamp
::getLocalInstance();
1450 // Check that the LocalTZoffset is the same as the local time zone offset
1451 if ( $localTZoffset == $timestamp->format( 'Z' ) / 60 ) {
1452 $timezoneName = $timestamp->getTimezone()->getName();
1453 // Localize timezone
1454 if ( isset( $timeZoneList[$timezoneName] ) ) {
1455 $timezoneName = $timeZoneList[$timezoneName]['name'];
1457 $server_tz_msg = $context->msg(
1458 'timezoneuseserverdefault',
1462 $tzstring = sprintf(
1464 floor( $localTZoffset / 60 ),
1465 abs( $localTZoffset ) %
60
1467 $server_tz_msg = $context->msg( 'timezoneuseserverdefault', $tzstring )->text();
1469 $opt[$server_tz_msg] = "System|$localTZoffset";
1470 $opt[$context->msg( 'timezoneuseoffset' )->text()] = 'other';
1471 $opt[$context->msg( 'guesstimezone' )->text()] = 'guess';
1473 foreach ( $timeZoneList as $timeZoneInfo ) {
1474 $region = $timeZoneInfo['region'];
1475 if ( !isset( $opt[$region] ) ) {
1478 $opt[$region][$timeZoneInfo['name']] = $timeZoneInfo['timecorrection'];
1485 * @param array $alldata
1488 protected function filterTimezoneInput( $tz, array $alldata ) {
1489 $data = explode( '|', $tz, 3 );
1490 switch ( $data[0] ) {
1494 if ( count( $data ) === 3 ) {
1495 // Make sure this timezone exists
1497 new DateTimeZone( $data[2] );
1498 // If the constructor didn't throw, we know it's valid
1500 } catch ( Exception
$e ) {
1501 // Not a valid timezone
1506 // If the supplied timezone doesn't exist, fall back to the encoded offset
1507 return 'Offset|' . intval( $tz[1] );
1513 $data = explode( ':', $tz, 2 );
1514 if ( count( $data ) == 2 ) {
1515 $data[0] = intval( $data[0] );
1516 $data[1] = intval( $data[1] );
1517 $minDiff = abs( $data[0] ) * 60 +
$data[1];
1518 if ( $data[0] < 0 ) {
1519 $minDiff = - $minDiff;
1522 $minDiff = intval( $data[0] ) * 60;
1525 # Max is +14:00 and min is -12:00, see:
1526 # https://en.wikipedia.org/wiki/Timezone
1527 $minDiff = min( $minDiff, 840 ); # 14:00
1528 $minDiff = max( $minDiff, -720 ); # -12:00
1529 return 'Offset|' . $minDiff;
1534 * Handle the form submission if everything validated properly
1536 * @param array $formData
1537 * @param PreferencesForm $form
1538 * @return bool|Status|string
1540 protected function saveFormData( $formData, PreferencesForm
$form ) {
1541 $user = $form->getModifiedUser();
1542 $hiddenPrefs = $this->config
->get( 'HiddenPrefs' );
1545 if ( !$user->isAllowedAny( 'editmyprivateinfo', 'editmyoptions' ) ) {
1546 return Status
::newFatal( 'mypreferencesprotected' );
1550 foreach ( array_keys( $formData ) as $name ) {
1551 $filters = $this->getSaveFilters();
1552 if ( isset( $filters[$name] ) ) {
1553 $formData[$name] = call_user_func( $filters[$name], $formData[$name], $formData );
1557 // Fortunately, the realname field is MUCH simpler
1558 // (not really "private", but still shouldn't be edited without permission)
1560 if ( !in_array( 'realname', $hiddenPrefs )
1561 && $user->isAllowed( 'editmyprivateinfo' )
1562 && array_key_exists( 'realname', $formData )
1564 $realName = $formData['realname'];
1565 $user->setRealName( $realName );
1568 if ( $user->isAllowed( 'editmyoptions' ) ) {
1569 $oldUserOptions = $user->getOptions();
1571 foreach ( $this->getSaveBlacklist() as $b ) {
1572 unset( $formData[$b] );
1575 # If users have saved a value for a preference which has subsequently been disabled
1576 # via $wgHiddenPrefs, we don't want to destroy that setting in case the preference
1577 # is subsequently re-enabled
1578 foreach ( $hiddenPrefs as $pref ) {
1579 # If the user has not set a non-default value here, the default will be returned
1580 # and subsequently discarded
1581 $formData[$pref] = $user->getOption( $pref, null, true );
1584 // If the user changed the rclimit preference, also change the rcfilters-rclimit preference
1586 isset( $formData['rclimit'] ) &&
1587 intval( $formData[ 'rclimit' ] ) !== $user->getIntOption( 'rclimit' )
1589 $formData['rcfilters-limit'] = $formData['rclimit'];
1592 // Keep old preferences from interfering due to back-compat code, etc.
1593 $user->resetOptions( 'unused', $form->getContext() );
1595 foreach ( $formData as $key => $value ) {
1596 $user->setOption( $key, $value );
1600 'PreferencesFormPreSave',
1601 [ $formData, $form, $user, &$result, $oldUserOptions ]
1605 AuthManager
::callLegacyAuthPlugin( 'updateExternalDB', [ $user ] );
1606 $user->saveSettings();
1612 * DO NOT USE. Temporary function to punch hole for the Preferences class.
1614 * @deprecated since 1.31, its inception
1616 * @param array $formData
1617 * @param PreferencesForm $form
1618 * @return bool|Status|string
1620 protected function legacySaveFormData( $formData, PreferencesForm
$form ) {
1621 return $this->saveFormData( $formData, $form );
1625 * Save the form data and reload the page
1627 * @param array $formData
1628 * @param PreferencesForm $form
1631 protected function submitForm( array $formData, PreferencesForm
$form ) {
1632 $res = $this->saveFormData( $formData, $form );
1637 if ( $res === 'eauth' ) {
1638 $urlOptions['eauth'] = 1;
1641 $urlOptions +
= $form->getExtraSuccessRedirectParameters();
1643 $url = $form->getTitle()->getFullURL( $urlOptions );
1645 $context = $form->getContext();
1646 // Set session data for the success message
1647 $context->getRequest()->getSession()->set( 'specialPreferencesSaveSuccess', 1 );
1649 $context->getOutput()->redirect( $url );
1652 return Status
::newGood();
1656 * DO NOT USE. Temporary function to punch hole for the Preferences class.
1658 * @deprecated since 1.31, its inception
1660 * @param array $formData
1661 * @param PreferencesForm $form
1664 public function legacySubmitForm( array $formData, PreferencesForm
$form ) {
1665 return $this->submitForm( $formData, $form );
1669 * Get a list of all time zones
1670 * @param Language $language Language used for the localized names
1671 * @return array A list of all time zones. The system name of the time zone is used as key and
1672 * the value is an array which contains localized name, the timecorrection value used for
1673 * preferences and the region
1676 protected function getTimeZoneList( Language
$language ) {
1677 $identifiers = DateTimeZone
::listIdentifiers();
1678 if ( $identifiers === false ) {
1681 sort( $identifiers );
1684 'Africa' => wfMessage( 'timezoneregion-africa' )->inLanguage( $language )->text(),
1685 'America' => wfMessage( 'timezoneregion-america' )->inLanguage( $language )->text(),
1686 'Antarctica' => wfMessage( 'timezoneregion-antarctica' )->inLanguage( $language )->text(),
1687 'Arctic' => wfMessage( 'timezoneregion-arctic' )->inLanguage( $language )->text(),
1688 'Asia' => wfMessage( 'timezoneregion-asia' )->inLanguage( $language )->text(),
1689 'Atlantic' => wfMessage( 'timezoneregion-atlantic' )->inLanguage( $language )->text(),
1690 'Australia' => wfMessage( 'timezoneregion-australia' )->inLanguage( $language )->text(),
1691 'Europe' => wfMessage( 'timezoneregion-europe' )->inLanguage( $language )->text(),
1692 'Indian' => wfMessage( 'timezoneregion-indian' )->inLanguage( $language )->text(),
1693 'Pacific' => wfMessage( 'timezoneregion-pacific' )->inLanguage( $language )->text(),
1695 asort( $tzRegions );
1699 $now = new DateTime();
1701 foreach ( $identifiers as $identifier ) {
1702 $parts = explode( '/', $identifier, 2 );
1704 // DateTimeZone::listIdentifiers() returns a number of
1705 // backwards-compatibility entries. This filters them out of the
1706 // list presented to the user.
1707 if ( count( $parts ) !== 2 ||
!array_key_exists( $parts[0], $tzRegions ) ) {
1712 $parts[0] = $tzRegions[$parts[0]];
1714 $dateTimeZone = new DateTimeZone( $identifier );
1715 $minDiff = floor( $dateTimeZone->getOffset( $now ) / 60 );
1717 $display = str_replace( '_', ' ', $parts[0] . '/' . $parts[1] );
1718 $value = "ZoneInfo|$minDiff|$identifier";
1720 $timeZoneList[$identifier] = [
1722 'timecorrection' => $value,
1723 'region' => $parts[0],
1727 return $timeZoneList;