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
;
34 use LanguageConverter
;
35 use MediaWiki\Auth\AuthManager
;
36 use MediaWiki\Auth\PasswordAuthenticationRequest
;
37 use MediaWiki\Linker\LinkRenderer
;
38 use MediaWiki\MediaWikiServices
;
46 use PreferencesFormLegacy
;
47 use Psr\Log\LoggerAwareTrait
;
48 use Psr\Log\NullLogger
;
53 use UnexpectedValueException
;
55 use UserGroupMembership
;
59 * This is the default implementation of PreferencesFactory.
61 class DefaultPreferencesFactory
implements PreferencesFactory
{
67 /** @var Language The wiki's content language. */
70 /** @var AuthManager */
71 protected $authManager;
73 /** @var LinkRenderer */
74 protected $linkRenderer;
77 * @param Config $config
78 * @param Language $contLang
79 * @param AuthManager $authManager
80 * @param LinkRenderer $linkRenderer
82 public function __construct(
85 AuthManager
$authManager,
86 LinkRenderer
$linkRenderer
88 $this->config
= $config;
89 $this->contLang
= $contLang;
90 $this->authManager
= $authManager;
91 $this->linkRenderer
= $linkRenderer;
92 $this->logger
= new NullLogger();
98 public function getSaveBlacklist() {
106 * @throws MWException
108 * @param IContextSource $context
111 public function getFormDescriptor( User
$user, IContextSource
$context ) {
114 OutputPage
::setupOOUI(
115 strtolower( $context->getSkin()->getSkinName() ),
116 $context->getLanguage()->getDir()
119 $canIPUseHTTPS = wfCanIPUseHTTPS( $context->getRequest()->getIP() );
120 $this->profilePreferences( $user, $context, $preferences, $canIPUseHTTPS );
121 $this->skinPreferences( $user, $context, $preferences );
122 $this->datetimePreferences( $user, $context, $preferences );
123 $this->filesPreferences( $context, $preferences );
124 $this->renderingPreferences( $user, $context, $preferences );
125 $this->editingPreferences( $user, $context, $preferences );
126 $this->rcPreferences( $user, $context, $preferences );
127 $this->watchlistPreferences( $user, $context, $preferences );
128 $this->searchPreferences( $preferences );
130 Hooks
::run( 'GetPreferences', [ $user, &$preferences ] );
132 $this->loadPreferenceValues( $user, $context, $preferences );
133 $this->logger
->debug( "Created form descriptor for user '{$user->getName()}'" );
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 $userOptions = $user->getOptions();
162 $this->applyFilters( $userOptions, $defaultPreferences, 'filterForForm' );
163 # # Prod in defaults from the user
164 foreach ( $defaultPreferences as $name => &$info ) {
165 $prefFromUser = $this->getOptionFromUser( $name, $info, $userOptions );
166 if ( $disable && !in_array( $name, $this->getSaveBlacklist() ) ) {
167 $info['disabled'] = 'disabled';
169 $field = HTMLForm
::loadInputFromParameters( $name, $info, $dummyForm ); // For validation
170 $globalDefault = $defaultOptions[$name] ??
null;
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
194 * @param array $userOptions
195 * @return array|string
197 protected function getOptionFromUser( $name, $info, array $userOptions ) {
198 $val = $userOptions[$name] ??
null;
200 // Handling for multiselect preferences
201 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
202 ( isset( $info['class'] ) && $info['class'] == \HTMLMultiSelectField
::class ) ) {
203 $options = HTMLFormField
::flattenOptions( $info['options'] );
204 $prefix = $info['prefix'] ??
$name;
207 foreach ( $options as $value ) {
208 if ( $userOptions["$prefix$value"] ??
false ) {
214 // Handling for checkmatrix preferences
215 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
216 ( isset( $info['class'] ) && $info['class'] == \HTMLCheckMatrix
::class ) ) {
217 $columns = HTMLFormField
::flattenOptions( $info['columns'] );
218 $rows = HTMLFormField
::flattenOptions( $info['rows'] );
219 $prefix = $info['prefix'] ??
$name;
222 foreach ( $columns as $column ) {
223 foreach ( $rows as $row ) {
224 if ( $userOptions["$prefix$column-$row"] ??
false ) {
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 $groupStringOrObject = $userGroupMemberships[$ueg] ??
$ueg;
272 $userG = UserGroupMembership
::getLink( $groupStringOrObject, $context, 'html' );
273 $userM = UserGroupMembership
::getLink( $groupStringOrObject, $context, 'html',
276 // Store expiring groups separately, so we can place them before non-expiring
277 // groups in the list. This is to avoid the ambiguity of something like
278 // "administrator, bureaucrat (until X date)" -- users might wonder whether the
279 // expiry date applies to both groups, or just the last one
280 if ( $groupStringOrObject instanceof UserGroupMembership
&&
281 $groupStringOrObject->getExpiry()
283 $userTempGroups[] = $userG;
284 $userTempMembers[] = $userM;
286 $userGroups[] = $userG;
287 $userMembers[] = $userM;
291 sort( $userMembers );
292 sort( $userTempGroups );
293 sort( $userTempMembers );
294 $userGroups = array_merge( $userTempGroups, $userGroups );
295 $userMembers = array_merge( $userTempMembers, $userMembers );
297 $defaultPreferences['usergroups'] = [
299 'label' => $context->msg( 'prefs-memberingroups' )->numParams(
300 count( $userGroups ) )->params( $userName )->parse(),
301 'default' => $context->msg( 'prefs-memberingroups-type' )
302 ->rawParams( $lang->commaList( $userGroups ), $lang->commaList( $userMembers ) )
305 'section' => 'personal/info',
308 $contribTitle = SpecialPage
::getTitleFor( "Contributions", $userName );
309 $formattedEditCount = $lang->formatNum( $user->getEditCount() );
310 $editCount = $this->linkRenderer
->makeLink( $contribTitle, $formattedEditCount );
312 $defaultPreferences['editcount'] = [
315 'label-message' => 'prefs-edits',
316 'default' => $editCount,
317 'section' => 'personal/info',
320 if ( $user->getRegistration() ) {
321 $displayUser = $context->getUser();
322 $userRegistration = $user->getRegistration();
323 $defaultPreferences['registrationdate'] = [
325 'label-message' => 'prefs-registration',
326 'default' => $context->msg(
327 'prefs-registration-date-time',
328 $lang->userTimeAndDate( $userRegistration, $displayUser ),
329 $lang->userDate( $userRegistration, $displayUser ),
330 $lang->userTime( $userRegistration, $displayUser )
332 'section' => 'personal/info',
336 $canViewPrivateInfo = $user->isAllowed( 'viewmyprivateinfo' );
337 $canEditPrivateInfo = $user->isAllowed( 'editmyprivateinfo' );
339 // Actually changeable stuff
340 $defaultPreferences['realname'] = [
341 // (not really "private", but still shouldn't be edited without permission)
342 'type' => $canEditPrivateInfo && $this->authManager
->allowsPropertyChange( 'realname' )
344 'default' => $user->getRealName(),
345 'section' => 'personal/info',
346 'label-message' => 'yourrealname',
347 'help-message' => 'prefs-help-realname',
350 if ( $canEditPrivateInfo && $this->authManager
->allowsAuthenticationDataChange(
351 new PasswordAuthenticationRequest(), false )->isGood()
353 $defaultPreferences['password'] = [
356 'default' => (string)new \OOUI\
ButtonWidget( [
357 'href' => SpecialPage
::getTitleFor( 'ChangePassword' )->getLinkURL( [
358 'returnto' => SpecialPage
::getTitleFor( 'Preferences' )->getPrefixedText()
360 'label' => $context->msg( 'prefs-resetpass' )->text(),
362 'label-message' => 'yourpassword',
363 'section' => 'personal/info',
366 // Only show prefershttps if secure login is turned on
367 if ( $this->config
->get( 'SecureLogin' ) && $canIPUseHTTPS ) {
368 $defaultPreferences['prefershttps'] = [
370 'label-message' => 'tog-prefershttps',
371 'help-message' => 'prefs-help-prefershttps',
372 'section' => 'personal/info'
376 $languages = Language
::fetchLanguageNames( null, 'mwfile' );
377 $languageCode = $this->config
->get( 'LanguageCode' );
378 if ( !array_key_exists( $languageCode, $languages ) ) {
379 $languages[$languageCode] = $languageCode;
380 // Sort the array again
385 foreach ( $languages as $code => $name ) {
386 $display = LanguageCode
::bcp47( $code ) . ' - ' . $name;
387 $options[$display] = $code;
389 $defaultPreferences['language'] = [
391 'section' => 'personal/i18n',
392 'options' => $options,
393 'label-message' => 'yourlanguage',
396 $defaultPreferences['gender'] = [
398 'section' => 'personal/i18n',
400 $context->msg( 'parentheses' )
401 ->params( $context->msg( 'gender-unknown' )->plain() )
402 ->escaped() => 'unknown',
403 $context->msg( 'gender-female' )->escaped() => 'female',
404 $context->msg( 'gender-male' )->escaped() => 'male',
406 'label-message' => 'yourgender',
407 'help-message' => 'prefs-help-gender',
410 // see if there are multiple language variants to choose from
411 if ( !$this->config
->get( 'DisableLangConversion' ) ) {
412 foreach ( LanguageConverter
::$languagesWithVariants as $langCode ) {
413 if ( $langCode == $this->contLang
->getCode() ) {
414 if ( !$this->contLang
->hasVariants() ) {
418 $variants = $this->contLang
->getVariants();
420 foreach ( $variants as $v ) {
421 $v = str_replace( '_', '-', strtolower( $v ) );
422 $variantArray[$v] = $lang->getVariantname( $v, false );
426 foreach ( $variantArray as $code => $name ) {
427 $display = LanguageCode
::bcp47( $code ) . ' - ' . $name;
428 $options[$display] = $code;
431 $defaultPreferences['variant'] = [
432 'label-message' => 'yourvariant',
434 'options' => $options,
435 'section' => 'personal/i18n',
436 'help-message' => 'prefs-help-variant',
439 $defaultPreferences["variant-$langCode"] = [
446 // Stuff from Language::getExtraUserToggles()
447 // FIXME is this dead code? $extraUserToggles doesn't seem to be defined for any language
448 $toggles = $this->contLang
->getExtraUserToggles();
450 foreach ( $toggles as $toggle ) {
451 $defaultPreferences[$toggle] = [
453 'section' => 'personal/i18n',
454 'label-message' => "tog-$toggle",
458 // show a preview of the old signature first
459 $oldsigWikiText = MediaWikiServices
::getInstance()->getParser()->preSaveTransform(
461 $context->getTitle(),
463 ParserOptions
::newFromContext( $context )
465 $oldsigHTML = Parser
::stripOuterParagraph(
466 $context->getOutput()->parseAsContent( $oldsigWikiText )
468 $defaultPreferences['oldsig'] = [
471 'label-message' => 'tog-oldsig',
472 'default' => $oldsigHTML,
473 'section' => 'personal/signature',
475 $defaultPreferences['nickname'] = [
476 'type' => $this->authManager
->allowsPropertyChange( 'nickname' ) ?
'text' : 'info',
477 'maxlength' => $this->config
->get( 'MaxSigChars' ),
478 'label-message' => 'yournick',
479 'validation-callback' => function ( $signature, $alldata, HTMLForm
$form ) {
480 return $this->validateSignature( $signature, $alldata, $form );
482 'section' => 'personal/signature',
483 'filter-callback' => function ( $signature, array $alldata, HTMLForm
$form ) {
484 return $this->cleanSignature( $signature, $alldata, $form );
487 $defaultPreferences['fancysig'] = [
489 'label-message' => 'tog-fancysig',
490 // show general help about signature at the bottom of the section
491 'help-message' => 'prefs-help-signature',
492 'section' => 'personal/signature'
497 if ( $this->config
->get( 'EnableEmail' ) ) {
498 if ( $canViewPrivateInfo ) {
499 $helpMessages[] = $this->config
->get( 'EmailConfirmToEdit' )
500 ?
'prefs-help-email-required'
501 : 'prefs-help-email';
503 if ( $this->config
->get( 'EnableUserEmail' ) ) {
504 // additional messages when users can send email to each other
505 $helpMessages[] = 'prefs-help-email-others';
508 $emailAddress = $user->getEmail() ?
htmlspecialchars( $user->getEmail() ) : '';
509 if ( $canEditPrivateInfo && $this->authManager
->allowsPropertyChange( 'emailaddress' ) ) {
510 $button = new \OOUI\
ButtonWidget( [
511 'href' => SpecialPage
::getTitleFor( 'ChangeEmail' )->getLinkURL( [
512 'returnto' => SpecialPage
::getTitleFor( 'Preferences' )->getPrefixedText()
515 $context->msg( $user->getEmail() ?
'prefs-changeemail' : 'prefs-setemail' )->text(),
518 $emailAddress .= $emailAddress == '' ?
$button : ( '<br />' . $button );
521 $defaultPreferences['emailaddress'] = [
524 'default' => $emailAddress,
525 'label-message' => 'youremail',
526 'section' => 'personal/email',
527 'help-messages' => $helpMessages,
528 # 'cssclass' chosen below
532 $disableEmailPrefs = false;
534 if ( $this->config
->get( 'EmailAuthentication' ) ) {
535 $emailauthenticationclass = 'mw-email-not-authenticated';
536 if ( $user->getEmail() ) {
537 if ( $user->getEmailAuthenticationTimestamp() ) {
538 // date and time are separate parameters to facilitate localisation.
539 // $time is kept for backward compat reasons.
540 // 'emailauthenticated' is also used in SpecialConfirmemail.php
541 $displayUser = $context->getUser();
542 $emailTimestamp = $user->getEmailAuthenticationTimestamp();
543 $time = $lang->userTimeAndDate( $emailTimestamp, $displayUser );
544 $d = $lang->userDate( $emailTimestamp, $displayUser );
545 $t = $lang->userTime( $emailTimestamp, $displayUser );
546 $emailauthenticated = $context->msg( 'emailauthenticated',
547 $time, $d, $t )->parse() . '<br />';
548 $disableEmailPrefs = false;
549 $emailauthenticationclass = 'mw-email-authenticated';
551 $disableEmailPrefs = true;
552 $emailauthenticated = $context->msg( 'emailnotauthenticated' )->parse() . '<br />' .
553 new \OOUI\
ButtonWidget( [
554 'href' => SpecialPage
::getTitleFor( 'Confirmemail' )->getLinkURL(),
555 'label' => $context->msg( 'emailconfirmlink' )->text(),
557 $emailauthenticationclass = "mw-email-not-authenticated";
560 $disableEmailPrefs = true;
561 $emailauthenticated = $context->msg( 'noemailprefs' )->escaped();
562 $emailauthenticationclass = 'mw-email-none';
565 if ( $canViewPrivateInfo ) {
566 $defaultPreferences['emailauthentication'] = [
569 'section' => 'personal/email',
570 'label-message' => 'prefs-emailconfirm-label',
571 'default' => $emailauthenticated,
572 # Apply the same CSS class used on the input to the message:
573 'cssclass' => $emailauthenticationclass,
578 if ( $this->config
->get( 'EnableUserEmail' ) && $user->isAllowed( 'sendemail' ) ) {
579 $defaultPreferences['disablemail'] = [
580 'id' => 'wpAllowEmail',
583 'section' => 'personal/email',
584 'label-message' => 'allowemail',
585 'disabled' => $disableEmailPrefs,
588 $defaultPreferences['email-allow-new-users'] = [
589 'id' => 'wpAllowEmailFromNewUsers',
591 'section' => 'personal/email',
592 'label-message' => 'email-allow-new-users-label',
593 'disabled' => $disableEmailPrefs,
596 $defaultPreferences['ccmeonemails'] = [
598 'section' => 'personal/email',
599 'label-message' => 'tog-ccmeonemails',
600 'disabled' => $disableEmailPrefs,
603 if ( $this->config
->get( 'EnableUserEmailBlacklist' ) ) {
604 $defaultPreferences['email-blacklist'] = [
605 'type' => 'usersmultiselect',
606 'label-message' => 'email-blacklist-label',
607 'section' => 'personal/email',
608 'disabled' => $disableEmailPrefs,
609 'filter' => MultiUsernameFilter
::class,
614 if ( $this->config
->get( 'EnotifWatchlist' ) ) {
615 $defaultPreferences['enotifwatchlistpages'] = [
617 'section' => 'personal/email',
618 'label-message' => 'tog-enotifwatchlistpages',
619 'disabled' => $disableEmailPrefs,
622 if ( $this->config
->get( 'EnotifUserTalk' ) ) {
623 $defaultPreferences['enotifusertalkpages'] = [
625 'section' => 'personal/email',
626 'label-message' => 'tog-enotifusertalkpages',
627 'disabled' => $disableEmailPrefs,
630 if ( $this->config
->get( 'EnotifUserTalk' ) ||
$this->config
->get( 'EnotifWatchlist' ) ) {
631 if ( $this->config
->get( 'EnotifMinorEdits' ) ) {
632 $defaultPreferences['enotifminoredits'] = [
634 'section' => 'personal/email',
635 'label-message' => 'tog-enotifminoredits',
636 'disabled' => $disableEmailPrefs,
640 if ( $this->config
->get( 'EnotifRevealEditorAddress' ) ) {
641 $defaultPreferences['enotifrevealaddr'] = [
643 'section' => 'personal/email',
644 'label-message' => 'tog-enotifrevealaddr',
645 'disabled' => $disableEmailPrefs,
654 * @param IContextSource $context
655 * @param array &$defaultPreferences
658 protected function skinPreferences( User
$user, IContextSource
$context, &$defaultPreferences ) {
659 # # Skin #####################################
661 // Skin selector, if there is at least one valid skin
662 $skinOptions = $this->generateSkinOptions( $user, $context );
663 if ( $skinOptions ) {
664 $defaultPreferences['skin'] = [
666 'options' => $skinOptions,
667 'section' => 'rendering/skin',
671 $allowUserCss = $this->config
->get( 'AllowUserCss' );
672 $allowUserJs = $this->config
->get( 'AllowUserJs' );
673 # Create links to user CSS/JS pages for all skins
674 # This code is basically copied from generateSkinOptions(). It'd
675 # be nice to somehow merge this back in there to avoid redundancy.
676 if ( $allowUserCss ||
$allowUserJs ) {
678 $userName = $user->getName();
680 if ( $allowUserCss ) {
681 $cssPage = Title
::makeTitleSafe( NS_USER
, $userName . '/common.css' );
682 $cssLinkText = $context->msg( 'prefs-custom-css' )->text();
683 $linkTools[] = $this->linkRenderer
->makeLink( $cssPage, $cssLinkText );
686 if ( $allowUserJs ) {
687 $jsPage = Title
::makeTitleSafe( NS_USER
, $userName . '/common.js' );
688 $jsLinkText = $context->msg( 'prefs-custom-js' )->text();
689 $linkTools[] = $this->linkRenderer
->makeLink( $jsPage, $jsLinkText );
692 $defaultPreferences['commoncssjs'] = [
695 'default' => $context->getLanguage()->pipeList( $linkTools ),
696 'label-message' => 'prefs-common-config',
697 'section' => 'rendering/skin',
703 * @param IContextSource $context
704 * @param array &$defaultPreferences
706 protected function filesPreferences( IContextSource
$context, &$defaultPreferences ) {
707 # # Files #####################################
708 $defaultPreferences['imagesize'] = [
710 'options' => $this->getImageSizes( $context ),
711 'label-message' => 'imagemaxsize',
712 'section' => 'rendering/files',
714 $defaultPreferences['thumbsize'] = [
716 'options' => $this->getThumbSizes( $context ),
717 'label-message' => 'thumbsize',
718 'section' => 'rendering/files',
724 * @param IContextSource $context
725 * @param array &$defaultPreferences
728 protected function datetimePreferences( $user, IContextSource
$context, &$defaultPreferences ) {
729 # # Date and time #####################################
730 $dateOptions = $this->getDateOptions( $context );
731 if ( $dateOptions ) {
732 $defaultPreferences['date'] = [
734 'options' => $dateOptions,
735 'section' => 'rendering/dateformat',
740 $now = wfTimestampNow();
741 $lang = $context->getLanguage();
742 $nowlocal = Xml
::element( 'span', [ 'id' => 'wpLocalTime' ],
743 $lang->userTime( $now, $user ) );
744 $nowserver = $lang->userTime( $now, $user,
745 [ 'format' => false, 'timecorrection' => false ] ) .
746 Html
::hidden( 'wpServerTime', (int)substr( $now, 8, 2 ) * 60 +
(int)substr( $now, 10, 2 ) );
748 $defaultPreferences['nowserver'] = [
751 'label-message' => 'servertime',
752 'default' => $nowserver,
753 'section' => 'rendering/timeoffset',
756 $defaultPreferences['nowlocal'] = [
759 'label-message' => 'localtime',
760 'default' => $nowlocal,
761 'section' => 'rendering/timeoffset',
764 // Grab existing pref.
765 $tzOffset = $user->getOption( 'timecorrection' );
766 $tz = explode( '|', $tzOffset, 3 );
768 $tzOptions = $this->getTimezoneOptions( $context );
770 $tzSetting = $tzOffset;
771 if ( count( $tz ) > 1 && $tz[0] == 'ZoneInfo' &&
772 !in_array( $tzOffset, HTMLFormField
::flattenOptions( $tzOptions ) )
774 // Timezone offset can vary with DST
776 $userTZ = new DateTimeZone( $tz[2] );
777 $minDiff = floor( $userTZ->getOffset( new DateTime( 'now' ) ) / 60 );
778 $tzSetting = "ZoneInfo|$minDiff|{$tz[2]}";
779 } catch ( Exception
$e ) {
780 // User has an invalid time zone set. Fall back to just using the offset
784 if ( count( $tz ) > 1 && $tz[0] == 'Offset' ) {
786 $tzSetting = sprintf( '%+03d:%02d', floor( $minDiff / 60 ), abs( $minDiff ) %
60 );
789 $defaultPreferences['timecorrection'] = [
790 'class' => \HTMLSelectOrOtherField
::class,
791 'label-message' => 'timezonelegend',
792 'options' => $tzOptions,
793 'default' => $tzSetting,
795 'section' => 'rendering/timeoffset',
796 'id' => 'wpTimeCorrection',
797 'filter' => TimezoneFilter
::class,
798 'placeholder-message' => 'timezone-useoffset-placeholder',
804 * @param MessageLocalizer $l10n
805 * @param array &$defaultPreferences
807 protected function renderingPreferences(
809 MessageLocalizer
$l10n,
812 # # Diffs ####################################
813 $defaultPreferences['diffonly'] = [
815 'section' => 'rendering/diffs',
816 'label-message' => 'tog-diffonly',
818 $defaultPreferences['norollbackdiff'] = [
820 'section' => 'rendering/diffs',
821 'label-message' => 'tog-norollbackdiff',
824 # # Page Rendering ##############################
825 if ( $this->config
->get( 'AllowUserCssPrefs' ) ) {
826 $defaultPreferences['underline'] = [
829 $l10n->msg( 'underline-never' )->text() => 0,
830 $l10n->msg( 'underline-always' )->text() => 1,
831 $l10n->msg( 'underline-default' )->text() => 2,
833 'label-message' => 'tog-underline',
834 'section' => 'rendering/advancedrendering',
838 $stubThresholdValues = [ 50, 100, 500, 1000, 2000, 5000, 10000 ];
839 $stubThresholdOptions = [ $l10n->msg( 'stub-threshold-disabled' )->text() => 0 ];
840 foreach ( $stubThresholdValues as $value ) {
841 $stubThresholdOptions[$l10n->msg( 'size-bytes', $value )->text()] = $value;
844 $defaultPreferences['stubthreshold'] = [
846 'section' => 'rendering/advancedrendering',
847 'options' => $stubThresholdOptions,
848 // This is not a raw HTML message; label-raw is needed for the manual <a></a>
849 'label-raw' => $l10n->msg( 'stub-threshold' )->rawParams(
851 $l10n->msg( 'stub-threshold-sample-link' )->parse() .
855 $defaultPreferences['showhiddencats'] = [
857 'section' => 'rendering/advancedrendering',
858 'label-message' => 'tog-showhiddencats'
861 $defaultPreferences['numberheadings'] = [
863 'section' => 'rendering/advancedrendering',
864 'label-message' => 'tog-numberheadings',
867 if ( $user->isAllowed( 'rollback' ) ) {
868 $defaultPreferences['showrollbackconfirmation'] = [
870 'section' => 'rendering/advancedrendering',
871 'label-message' => 'tog-showrollbackconfirmation',
876 * Remove temporary help text and references to DisableRollbackConfirmationFeature
877 * after release of rollback feature. See T199534
879 if ( MediaWikiServices
::getInstance()
880 ->getMainConfig()->get( 'DisableRollbackConfirmationFeature' ) ) {
881 $defaultPreferences['showrollbackconfirmation']
882 ['help-message'] = 'tog-showrollbackconfirmation-prerelease-warning';
889 * @param MessageLocalizer $l10n
890 * @param array &$defaultPreferences
892 protected function editingPreferences( User
$user, MessageLocalizer
$l10n, &$defaultPreferences ) {
893 # # Editing #####################################
894 $defaultPreferences['editsectiononrightclick'] = [
896 'section' => 'editing/advancedediting',
897 'label-message' => 'tog-editsectiononrightclick',
899 $defaultPreferences['editondblclick'] = [
901 'section' => 'editing/advancedediting',
902 'label-message' => 'tog-editondblclick',
905 if ( $this->config
->get( 'AllowUserCssPrefs' ) ) {
906 $defaultPreferences['editfont'] = [
908 'section' => 'editing/editor',
909 'label-message' => 'editfont-style',
911 $l10n->msg( 'editfont-monospace' )->text() => 'monospace',
912 $l10n->msg( 'editfont-sansserif' )->text() => 'sans-serif',
913 $l10n->msg( 'editfont-serif' )->text() => 'serif',
918 if ( $user->isAllowed( 'minoredit' ) ) {
919 $defaultPreferences['minordefault'] = [
921 'section' => 'editing/editor',
922 'label-message' => 'tog-minordefault',
926 $defaultPreferences['forceeditsummary'] = [
928 'section' => 'editing/editor',
929 'label-message' => 'tog-forceeditsummary',
931 $defaultPreferences['useeditwarning'] = [
933 'section' => 'editing/editor',
934 'label-message' => 'tog-useeditwarning',
937 $defaultPreferences['previewonfirst'] = [
939 'section' => 'editing/preview',
940 'label-message' => 'tog-previewonfirst',
942 $defaultPreferences['previewontop'] = [
944 'section' => 'editing/preview',
945 'label-message' => 'tog-previewontop',
947 $defaultPreferences['uselivepreview'] = [
949 'section' => 'editing/preview',
950 'label-message' => 'tog-uselivepreview',
956 * @param MessageLocalizer $l10n
957 * @param array &$defaultPreferences
959 protected function rcPreferences( User
$user, MessageLocalizer
$l10n, &$defaultPreferences ) {
960 $rcMaxAge = $this->config
->get( 'RCMaxAge' );
961 # # RecentChanges #####################################
962 $defaultPreferences['rcdays'] = [
964 'label-message' => 'recentchangesdays',
965 'section' => 'rc/displayrc',
967 'max' => ceil( $rcMaxAge / ( 3600 * 24 ) ),
968 'help' => $l10n->msg( 'recentchangesdays-max' )->numParams(
969 ceil( $rcMaxAge / ( 3600 * 24 ) ) )->escaped()
971 $defaultPreferences['rclimit'] = [
975 'label-message' => 'recentchangescount',
976 'help-message' => 'prefs-help-recentchangescount',
977 'section' => 'rc/displayrc',
978 'filter' => IntvalFilter
::class,
980 $defaultPreferences['usenewrc'] = [
982 'label-message' => 'tog-usenewrc',
983 'section' => 'rc/advancedrc',
985 $defaultPreferences['hideminor'] = [
987 'label-message' => 'tog-hideminor',
988 'section' => 'rc/changesrc',
990 $defaultPreferences['rcfilters-rc-collapsed'] = [
993 $defaultPreferences['rcfilters-wl-collapsed'] = [
996 $defaultPreferences['rcfilters-saved-queries'] = [
999 $defaultPreferences['rcfilters-wl-saved-queries'] = [
1002 // Override RCFilters preferences for RecentChanges 'limit'
1003 $defaultPreferences['rcfilters-limit'] = [
1006 $defaultPreferences['rcfilters-saved-queries-versionbackup'] = [
1009 $defaultPreferences['rcfilters-wl-saved-queries-versionbackup'] = [
1013 if ( $this->config
->get( 'RCWatchCategoryMembership' ) ) {
1014 $defaultPreferences['hidecategorization'] = [
1016 'label-message' => 'tog-hidecategorization',
1017 'section' => 'rc/changesrc',
1021 if ( $user->useRCPatrol() ) {
1022 $defaultPreferences['hidepatrolled'] = [
1024 'section' => 'rc/changesrc',
1025 'label-message' => 'tog-hidepatrolled',
1029 if ( $user->useNPPatrol() ) {
1030 $defaultPreferences['newpageshidepatrolled'] = [
1032 'section' => 'rc/changesrc',
1033 'label-message' => 'tog-newpageshidepatrolled',
1037 if ( $this->config
->get( 'RCShowWatchingUsers' ) ) {
1038 $defaultPreferences['shownumberswatching'] = [
1040 'section' => 'rc/advancedrc',
1041 'label-message' => 'tog-shownumberswatching',
1045 $defaultPreferences['rcenhancedfilters-disable'] = [
1047 'section' => 'rc/advancedrc',
1048 'label-message' => 'rcfilters-preference-label',
1049 'help-message' => 'rcfilters-preference-help',
1055 * @param IContextSource $context
1056 * @param array &$defaultPreferences
1058 protected function watchlistPreferences(
1059 User
$user, IContextSource
$context, &$defaultPreferences
1061 $watchlistdaysMax = ceil( $this->config
->get( 'RCMaxAge' ) / ( 3600 * 24 ) );
1063 # # Watchlist #####################################
1064 if ( $user->isAllowed( 'editmywatchlist' ) ) {
1065 $editWatchlistLinks = '';
1066 $editWatchlistLinksOld = [];
1067 $editWatchlistModes = [
1068 'edit' => [ 'subpage' => false, 'flags' => [] ],
1069 'raw' => [ 'subpage' => 'raw', 'flags' => [] ],
1070 'clear' => [ 'subpage' => 'clear', 'flags' => [ 'destructive' ] ],
1072 foreach ( $editWatchlistModes as $mode => $options ) {
1073 // Messages: prefs-editwatchlist-edit, prefs-editwatchlist-raw, prefs-editwatchlist-clear
1074 $editWatchlistLinks .=
1075 new \OOUI\
ButtonWidget( [
1076 'href' => SpecialPage
::getTitleFor( 'EditWatchlist', $options['subpage'] )->getLinkURL(),
1077 'flags' => $options[ 'flags' ],
1078 'label' => new \OOUI\
HtmlSnippet(
1079 $context->msg( "prefs-editwatchlist-{$mode}" )->parse()
1084 $defaultPreferences['editwatchlist'] = [
1087 'default' => $editWatchlistLinks,
1088 'label-message' => 'prefs-editwatchlist-label',
1089 'section' => 'watchlist/editwatchlist',
1093 $defaultPreferences['watchlistdays'] = [
1096 'max' => $watchlistdaysMax,
1097 'section' => 'watchlist/displaywatchlist',
1098 'help' => $context->msg( 'prefs-watchlist-days-max' )->numParams(
1099 $watchlistdaysMax )->escaped(),
1100 'label-message' => 'prefs-watchlist-days',
1102 $defaultPreferences['wllimit'] = [
1106 'label-message' => 'prefs-watchlist-edits',
1107 'help' => $context->msg( 'prefs-watchlist-edits-max' )->escaped(),
1108 'section' => 'watchlist/displaywatchlist',
1109 'filter' => IntvalFilter
::class,
1111 $defaultPreferences['extendwatchlist'] = [
1113 'section' => 'watchlist/advancedwatchlist',
1114 'label-message' => 'tog-extendwatchlist',
1116 $defaultPreferences['watchlisthideminor'] = [
1118 'section' => 'watchlist/changeswatchlist',
1119 'label-message' => 'tog-watchlisthideminor',
1121 $defaultPreferences['watchlisthidebots'] = [
1123 'section' => 'watchlist/changeswatchlist',
1124 'label-message' => 'tog-watchlisthidebots',
1126 $defaultPreferences['watchlisthideown'] = [
1128 'section' => 'watchlist/changeswatchlist',
1129 'label-message' => 'tog-watchlisthideown',
1131 $defaultPreferences['watchlisthideanons'] = [
1133 'section' => 'watchlist/changeswatchlist',
1134 'label-message' => 'tog-watchlisthideanons',
1136 $defaultPreferences['watchlisthideliu'] = [
1138 'section' => 'watchlist/changeswatchlist',
1139 'label-message' => 'tog-watchlisthideliu',
1142 if ( !\SpecialWatchlist
::checkStructuredFilterUiEnabled(
1146 $defaultPreferences['watchlistreloadautomatically'] = [
1148 'section' => 'watchlist/advancedwatchlist',
1149 'label-message' => 'tog-watchlistreloadautomatically',
1153 $defaultPreferences['watchlistunwatchlinks'] = [
1155 'section' => 'watchlist/advancedwatchlist',
1156 'label-message' => 'tog-watchlistunwatchlinks',
1159 if ( $this->config
->get( 'RCWatchCategoryMembership' ) ) {
1160 $defaultPreferences['watchlisthidecategorization'] = [
1162 'section' => 'watchlist/changeswatchlist',
1163 'label-message' => 'tog-watchlisthidecategorization',
1167 if ( $user->useRCPatrol() ) {
1168 $defaultPreferences['watchlisthidepatrolled'] = [
1170 'section' => 'watchlist/changeswatchlist',
1171 'label-message' => 'tog-watchlisthidepatrolled',
1176 'edit' => 'watchdefault',
1177 'move' => 'watchmoves',
1178 'delete' => 'watchdeletion'
1182 if ( $user->isAllowed( 'createpage' ) ||
$user->isAllowed( 'createtalk' ) ) {
1183 $watchTypes['read'] = 'watchcreations';
1186 if ( $user->isAllowed( 'rollback' ) ) {
1187 $watchTypes['rollback'] = 'watchrollback';
1190 if ( $user->isAllowed( 'upload' ) ) {
1191 $watchTypes['upload'] = 'watchuploads';
1194 foreach ( $watchTypes as $action => $pref ) {
1195 if ( $user->isAllowed( $action ) ) {
1197 // tog-watchdefault, tog-watchmoves, tog-watchdeletion, tog-watchcreations, tog-watchuploads
1198 // tog-watchrollback
1199 $defaultPreferences[$pref] = [
1201 'section' => 'watchlist/pageswatchlist',
1202 'label-message' => "tog-$pref",
1207 $defaultPreferences['watchlisttoken'] = [
1211 $tokenButton = new \OOUI\
ButtonWidget( [
1212 'href' => SpecialPage
::getTitleFor( 'ResetTokens' )->getLinkURL( [
1213 'returnto' => SpecialPage
::getTitleFor( 'Preferences' )->getPrefixedText()
1215 'label' => $context->msg( 'prefs-watchlist-managetokens' )->text(),
1217 $defaultPreferences['watchlisttoken-info'] = [
1219 'section' => 'watchlist/tokenwatchlist',
1220 'label-message' => 'prefs-watchlist-token',
1221 'help-message' => 'prefs-help-tokenmanagement',
1223 'default' => (string)$tokenButton,
1226 $defaultPreferences['wlenhancedfilters-disable'] = [
1228 'section' => 'watchlist/advancedwatchlist',
1229 'label-message' => 'rcfilters-watchlist-preference-label',
1230 'help-message' => 'rcfilters-watchlist-preference-help',
1235 * @param array &$defaultPreferences
1237 protected function searchPreferences( &$defaultPreferences ) {
1238 foreach ( MWNamespace
::getValidNamespaces() as $n ) {
1239 $defaultPreferences['searchNs' . $n] = [
1246 * @param User $user The User object
1247 * @param IContextSource $context
1248 * @return array Text/links to display as key; $skinkey as value
1250 protected function generateSkinOptions( User
$user, IContextSource
$context ) {
1253 $mptitle = Title
::newMainPage();
1254 $previewtext = $context->msg( 'skin-preview' )->escaped();
1256 # Only show skins that aren't disabled in $wgSkipSkins
1257 $validSkinNames = Skin
::getAllowedSkins();
1259 foreach ( $validSkinNames as $skinkey => &$skinname ) {
1260 $msg = $context->msg( "skinname-{$skinkey}" );
1261 if ( $msg->exists() ) {
1262 $skinname = htmlspecialchars( $msg->text() );
1266 $defaultSkin = $this->config
->get( 'DefaultSkin' );
1267 $allowUserCss = $this->config
->get( 'AllowUserCss' );
1268 $allowUserJs = $this->config
->get( 'AllowUserJs' );
1270 # Sort by the internal name, so that the ordering is the same for each display language,
1271 # especially if some skin names are translated to use a different alphabet and some are not.
1272 uksort( $validSkinNames, function ( $a, $b ) use ( $defaultSkin ) {
1273 # Display the default first in the list by comparing it as lesser than any other.
1274 if ( strcasecmp( $a, $defaultSkin ) === 0 ) {
1277 if ( strcasecmp( $b, $defaultSkin ) === 0 ) {
1280 return strcasecmp( $a, $b );
1283 $foundDefault = false;
1284 foreach ( $validSkinNames as $skinkey => $sn ) {
1287 # Mark the default skin
1288 if ( strcasecmp( $skinkey, $defaultSkin ) === 0 ) {
1289 $linkTools[] = $context->msg( 'default' )->escaped();
1290 $foundDefault = true;
1293 # Create preview link
1294 $mplink = htmlspecialchars( $mptitle->getLocalURL( [ 'useskin' => $skinkey ] ) );
1295 $linkTools[] = "<a target='_blank' href=\"$mplink\">$previewtext</a>";
1297 # Create links to user CSS/JS pages
1298 if ( $allowUserCss ) {
1299 $cssPage = Title
::makeTitleSafe( NS_USER
, $user->getName() . '/' . $skinkey . '.css' );
1300 $cssLinkText = $context->msg( 'prefs-custom-css' )->text();
1301 $linkTools[] = $this->linkRenderer
->makeLink( $cssPage, $cssLinkText );
1304 if ( $allowUserJs ) {
1305 $jsPage = Title
::makeTitleSafe( NS_USER
, $user->getName() . '/' . $skinkey . '.js' );
1306 $jsLinkText = $context->msg( 'prefs-custom-js' )->text();
1307 $linkTools[] = $this->linkRenderer
->makeLink( $jsPage, $jsLinkText );
1310 $display = $sn . ' ' . $context->msg( 'parentheses' )
1311 ->rawParams( $context->getLanguage()->pipeList( $linkTools ) )
1313 $ret[$display] = $skinkey;
1316 if ( !$foundDefault ) {
1317 // If the default skin is not available, things are going to break horribly because the
1318 // default value for skin selector will not be a valid value. Let's just not show it then.
1326 * @param IContextSource $context
1329 protected function getDateOptions( IContextSource
$context ) {
1330 $lang = $context->getLanguage();
1331 $dateopts = $lang->getDatePreferences();
1336 if ( !in_array( 'default', $dateopts ) ) {
1337 $dateopts[] = 'default'; // Make sure default is always valid T21237
1340 // FIXME KLUGE: site default might not be valid for user language
1341 global $wgDefaultUserOptions;
1342 if ( !in_array( $wgDefaultUserOptions['date'], $dateopts ) ) {
1343 $wgDefaultUserOptions['date'] = 'default';
1346 $epoch = wfTimestampNow();
1347 foreach ( $dateopts as $key ) {
1348 if ( $key == 'default' ) {
1349 $formatted = $context->msg( 'datedefault' )->escaped();
1351 $formatted = htmlspecialchars( $lang->timeanddate( $epoch, false, $key ) );
1353 $ret[$formatted] = $key;
1360 * @param MessageLocalizer $l10n
1363 protected function getImageSizes( MessageLocalizer
$l10n ) {
1365 $pixels = $l10n->msg( 'unit-pixel' )->text();
1367 foreach ( $this->config
->get( 'ImageLimits' ) as $index => $limits ) {
1368 // Note: A left-to-right marker (U+200E) is inserted, see T144386
1369 $display = "{$limits[0]}\u{200E}×{$limits[1]}$pixels";
1370 $ret[$display] = $index;
1377 * @param MessageLocalizer $l10n
1380 protected function getThumbSizes( MessageLocalizer
$l10n ) {
1382 $pixels = $l10n->msg( 'unit-pixel' )->text();
1384 foreach ( $this->config
->get( 'ThumbLimits' ) as $index => $size ) {
1385 $display = $size . $pixels;
1386 $ret[$display] = $index;
1393 * @param string $signature
1394 * @param array $alldata
1395 * @param HTMLForm $form
1396 * @return bool|string
1398 protected function validateSignature( $signature, $alldata, HTMLForm
$form ) {
1399 $maxSigChars = $this->config
->get( 'MaxSigChars' );
1400 if ( mb_strlen( $signature ) > $maxSigChars ) {
1401 return Xml
::element( 'span', [ 'class' => 'error' ],
1402 $form->msg( 'badsiglength' )->numParams( $maxSigChars )->text() );
1403 } elseif ( isset( $alldata['fancysig'] ) &&
1404 $alldata['fancysig'] &&
1405 MediaWikiServices
::getInstance()->getParser()->validateSig( $signature ) === false
1407 return Xml
::element(
1409 [ 'class' => 'error' ],
1410 $form->msg( 'badsig' )->text()
1418 * @param string $signature
1419 * @param array $alldata
1420 * @param HTMLForm $form
1423 protected function cleanSignature( $signature, $alldata, HTMLForm
$form ) {
1424 $parser = MediaWikiServices
::getInstance()->getParser();
1425 if ( isset( $alldata['fancysig'] ) && $alldata['fancysig'] ) {
1426 $signature = $parser->cleanSig( $signature );
1428 // When no fancy sig used, make sure ~{3,5} get removed.
1429 $signature = Parser
::cleanSigInSig( $signature );
1437 * @param IContextSource $context
1438 * @param string $formClass
1439 * @param array $remove Array of items to remove
1442 public function getForm(
1444 IContextSource
$context,
1445 $formClass = PreferencesFormLegacy
::class,
1448 // We use ButtonWidgets in some of the getPreferences() functions
1449 $context->getOutput()->enableOOUI();
1451 $formDescriptor = $this->getFormDescriptor( $user, $context );
1452 if ( count( $remove ) ) {
1453 $removeKeys = array_flip( $remove );
1454 $formDescriptor = array_diff_key( $formDescriptor, $removeKeys );
1457 // Remove type=api preferences. They are not intended for rendering in the form.
1458 foreach ( $formDescriptor as $name => $info ) {
1459 if ( isset( $info['type'] ) && $info['type'] === 'api' ) {
1460 unset( $formDescriptor[$name] );
1465 * @var $htmlForm HTMLForm
1467 $htmlForm = new $formClass( $formDescriptor, $context, 'prefs' );
1469 $htmlForm->setModifiedUser( $user );
1470 $htmlForm->setId( 'mw-prefs-form' );
1471 $htmlForm->setAutocomplete( 'off' );
1472 $htmlForm->setSubmitText( $context->msg( 'saveprefs' )->text() );
1473 # Used message keys: 'accesskey-preferences-save', 'tooltip-preferences-save'
1474 $htmlForm->setSubmitTooltip( 'preferences-save' );
1475 $htmlForm->setSubmitID( 'prefcontrol' );
1476 $htmlForm->setSubmitCallback(
1477 function ( array $formData, HTMLForm
$form ) use ( $formDescriptor ) {
1478 return $this->submitForm( $formData, $form, $formDescriptor );
1486 * @param IContextSource $context
1489 protected function getTimezoneOptions( IContextSource
$context ) {
1492 $localTZoffset = $this->config
->get( 'LocalTZoffset' );
1493 $timeZoneList = $this->getTimeZoneList( $context->getLanguage() );
1495 $timestamp = MWTimestamp
::getLocalInstance();
1496 // Check that the LocalTZoffset is the same as the local time zone offset
1497 if ( $localTZoffset == $timestamp->format( 'Z' ) / 60 ) {
1498 $timezoneName = $timestamp->getTimezone()->getName();
1499 // Localize timezone
1500 if ( isset( $timeZoneList[$timezoneName] ) ) {
1501 $timezoneName = $timeZoneList[$timezoneName]['name'];
1503 $server_tz_msg = $context->msg(
1504 'timezoneuseserverdefault',
1508 $tzstring = sprintf(
1510 floor( $localTZoffset / 60 ),
1511 abs( $localTZoffset ) %
60
1513 $server_tz_msg = $context->msg( 'timezoneuseserverdefault', $tzstring )->text();
1515 $opt[$server_tz_msg] = "System|$localTZoffset";
1516 $opt[$context->msg( 'timezoneuseoffset' )->text()] = 'other';
1517 $opt[$context->msg( 'guesstimezone' )->text()] = 'guess';
1519 foreach ( $timeZoneList as $timeZoneInfo ) {
1520 $region = $timeZoneInfo['region'];
1521 if ( !isset( $opt[$region] ) ) {
1524 $opt[$region][$timeZoneInfo['name']] = $timeZoneInfo['timecorrection'];
1530 * Handle the form submission if everything validated properly
1532 * @param array $formData
1533 * @param HTMLForm $form
1534 * @param array[] $formDescriptor
1535 * @return bool|Status|string
1537 protected function saveFormData( $formData, HTMLForm
$form, array $formDescriptor ) {
1538 /** @var \User $user */
1539 $user = $form->getModifiedUser();
1540 $hiddenPrefs = $this->config
->get( 'HiddenPrefs' );
1543 if ( !$user->isAllowedAny( 'editmyprivateinfo', 'editmyoptions' ) ) {
1544 return Status
::newFatal( 'mypreferencesprotected' );
1548 $this->applyFilters( $formData, $formDescriptor, 'filterFromForm' );
1550 // Fortunately, the realname field is MUCH simpler
1551 // (not really "private", but still shouldn't be edited without permission)
1553 if ( !in_array( 'realname', $hiddenPrefs )
1554 && $user->isAllowed( 'editmyprivateinfo' )
1555 && array_key_exists( 'realname', $formData )
1557 $realName = $formData['realname'];
1558 $user->setRealName( $realName );
1561 if ( $user->isAllowed( 'editmyoptions' ) ) {
1562 $oldUserOptions = $user->getOptions();
1564 foreach ( $this->getSaveBlacklist() as $b ) {
1565 unset( $formData[$b] );
1568 # If users have saved a value for a preference which has subsequently been disabled
1569 # via $wgHiddenPrefs, we don't want to destroy that setting in case the preference
1570 # is subsequently re-enabled
1571 foreach ( $hiddenPrefs as $pref ) {
1572 # If the user has not set a non-default value here, the default will be returned
1573 # and subsequently discarded
1574 $formData[$pref] = $user->getOption( $pref, null, true );
1577 // If the user changed the rclimit preference, also change the rcfilters-rclimit preference
1579 isset( $formData['rclimit'] ) &&
1580 intval( $formData[ 'rclimit' ] ) !== $user->getIntOption( 'rclimit' )
1582 $formData['rcfilters-limit'] = $formData['rclimit'];
1585 // Keep old preferences from interfering due to back-compat code, etc.
1586 $user->resetOptions( 'unused', $form->getContext() );
1588 foreach ( $formData as $key => $value ) {
1589 $user->setOption( $key, $value );
1593 'PreferencesFormPreSave',
1594 [ $formData, $form, $user, &$result, $oldUserOptions ]
1598 $user->saveSettings();
1604 * Applies filters to preferences either before or after form usage
1606 * @param array &$preferences
1607 * @param array $formDescriptor
1608 * @param string $verb Name of the filter method to call, either 'filterFromForm' or
1611 protected function applyFilters( array &$preferences, array $formDescriptor, $verb ) {
1612 foreach ( $formDescriptor as $preference => $desc ) {
1613 if ( !isset( $desc['filter'] ) ||
!isset( $preferences[$preference] ) ) {
1616 $filterDesc = $desc['filter'];
1617 if ( $filterDesc instanceof Filter
) {
1618 $filter = $filterDesc;
1619 } elseif ( class_exists( $filterDesc ) ) {
1620 $filter = new $filterDesc();
1621 } elseif ( is_callable( $filterDesc ) ) {
1622 $filter = $filterDesc();
1624 throw new UnexpectedValueException(
1625 "Unrecognized filter type for preference '$preference'"
1628 $preferences[$preference] = $filter->$verb( $preferences[$preference] );
1633 * Save the form data and reload the page
1635 * @param array $formData
1636 * @param HTMLForm $form
1637 * @param array $formDescriptor
1640 protected function submitForm( array $formData, HTMLForm
$form, array $formDescriptor ) {
1641 $res = $this->saveFormData( $formData, $form, $formDescriptor );
1643 if ( $res === true ) {
1644 $context = $form->getContext();
1647 if ( $res === 'eauth' ) {
1648 $urlOptions['eauth'] = 1;
1651 $urlOptions +
= $form->getExtraSuccessRedirectParameters();
1653 $url = $form->getTitle()->getFullURL( $urlOptions );
1655 // Set session data for the success message
1656 $context->getRequest()->getSession()->set( 'specialPreferencesSaveSuccess', 1 );
1658 $context->getOutput()->redirect( $url );
1661 return ( $res === true ? Status
::newGood() : $res );
1665 * Get a list of all time zones
1666 * @param Language $language Language used for the localized names
1667 * @return array A list of all time zones. The system name of the time zone is used as key and
1668 * the value is an array which contains localized name, the timecorrection value used for
1669 * preferences and the region
1672 protected function getTimeZoneList( Language
$language ) {
1673 $identifiers = DateTimeZone
::listIdentifiers();
1674 if ( $identifiers === false ) {
1677 sort( $identifiers );
1680 'Africa' => wfMessage( 'timezoneregion-africa' )->inLanguage( $language )->text(),
1681 'America' => wfMessage( 'timezoneregion-america' )->inLanguage( $language )->text(),
1682 'Antarctica' => wfMessage( 'timezoneregion-antarctica' )->inLanguage( $language )->text(),
1683 'Arctic' => wfMessage( 'timezoneregion-arctic' )->inLanguage( $language )->text(),
1684 'Asia' => wfMessage( 'timezoneregion-asia' )->inLanguage( $language )->text(),
1685 'Atlantic' => wfMessage( 'timezoneregion-atlantic' )->inLanguage( $language )->text(),
1686 'Australia' => wfMessage( 'timezoneregion-australia' )->inLanguage( $language )->text(),
1687 'Europe' => wfMessage( 'timezoneregion-europe' )->inLanguage( $language )->text(),
1688 'Indian' => wfMessage( 'timezoneregion-indian' )->inLanguage( $language )->text(),
1689 'Pacific' => wfMessage( 'timezoneregion-pacific' )->inLanguage( $language )->text(),
1691 asort( $tzRegions );
1695 $now = new DateTime();
1697 foreach ( $identifiers as $identifier ) {
1698 $parts = explode( '/', $identifier, 2 );
1700 // DateTimeZone::listIdentifiers() returns a number of
1701 // backwards-compatibility entries. This filters them out of the
1702 // list presented to the user.
1703 if ( count( $parts ) !== 2 ||
!array_key_exists( $parts[0], $tzRegions ) ) {
1708 $parts[0] = $tzRegions[$parts[0]];
1710 $dateTimeZone = new DateTimeZone( $identifier );
1711 $minDiff = floor( $dateTimeZone->getOffset( $now ) / 60 );
1713 $display = str_replace( '_', ' ', $parts[0] . '/' . $parts[1] );
1714 $value = "ZoneInfo|$minDiff|$identifier";
1716 $timeZoneList[$identifier] = [
1718 'timecorrection' => $value,
1719 'region' => $parts[0],
1723 return $timeZoneList;