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',
878 * @param MessageLocalizer $l10n
879 * @param array &$defaultPreferences
881 protected function editingPreferences( User
$user, MessageLocalizer
$l10n, &$defaultPreferences ) {
882 # # Editing #####################################
883 $defaultPreferences['editsectiononrightclick'] = [
885 'section' => 'editing/advancedediting',
886 'label-message' => 'tog-editsectiononrightclick',
888 $defaultPreferences['editondblclick'] = [
890 'section' => 'editing/advancedediting',
891 'label-message' => 'tog-editondblclick',
894 if ( $this->config
->get( 'AllowUserCssPrefs' ) ) {
895 $defaultPreferences['editfont'] = [
897 'section' => 'editing/editor',
898 'label-message' => 'editfont-style',
900 $l10n->msg( 'editfont-monospace' )->text() => 'monospace',
901 $l10n->msg( 'editfont-sansserif' )->text() => 'sans-serif',
902 $l10n->msg( 'editfont-serif' )->text() => 'serif',
907 if ( $user->isAllowed( 'minoredit' ) ) {
908 $defaultPreferences['minordefault'] = [
910 'section' => 'editing/editor',
911 'label-message' => 'tog-minordefault',
915 $defaultPreferences['forceeditsummary'] = [
917 'section' => 'editing/editor',
918 'label-message' => 'tog-forceeditsummary',
920 $defaultPreferences['useeditwarning'] = [
922 'section' => 'editing/editor',
923 'label-message' => 'tog-useeditwarning',
926 $defaultPreferences['previewonfirst'] = [
928 'section' => 'editing/preview',
929 'label-message' => 'tog-previewonfirst',
931 $defaultPreferences['previewontop'] = [
933 'section' => 'editing/preview',
934 'label-message' => 'tog-previewontop',
936 $defaultPreferences['uselivepreview'] = [
938 'section' => 'editing/preview',
939 'label-message' => 'tog-uselivepreview',
945 * @param MessageLocalizer $l10n
946 * @param array &$defaultPreferences
948 protected function rcPreferences( User
$user, MessageLocalizer
$l10n, &$defaultPreferences ) {
949 $rcMaxAge = $this->config
->get( 'RCMaxAge' );
950 # # RecentChanges #####################################
951 $defaultPreferences['rcdays'] = [
953 'label-message' => 'recentchangesdays',
954 'section' => 'rc/displayrc',
956 'max' => ceil( $rcMaxAge / ( 3600 * 24 ) ),
957 'help' => $l10n->msg( 'recentchangesdays-max' )->numParams(
958 ceil( $rcMaxAge / ( 3600 * 24 ) ) )->escaped()
960 $defaultPreferences['rclimit'] = [
964 'label-message' => 'recentchangescount',
965 'help-message' => 'prefs-help-recentchangescount',
966 'section' => 'rc/displayrc',
967 'filter' => IntvalFilter
::class,
969 $defaultPreferences['usenewrc'] = [
971 'label-message' => 'tog-usenewrc',
972 'section' => 'rc/advancedrc',
974 $defaultPreferences['hideminor'] = [
976 'label-message' => 'tog-hideminor',
977 'section' => 'rc/changesrc',
979 $defaultPreferences['rcfilters-rc-collapsed'] = [
982 $defaultPreferences['rcfilters-wl-collapsed'] = [
985 $defaultPreferences['rcfilters-saved-queries'] = [
988 $defaultPreferences['rcfilters-wl-saved-queries'] = [
991 // Override RCFilters preferences for RecentChanges 'limit'
992 $defaultPreferences['rcfilters-limit'] = [
995 $defaultPreferences['rcfilters-saved-queries-versionbackup'] = [
998 $defaultPreferences['rcfilters-wl-saved-queries-versionbackup'] = [
1002 if ( $this->config
->get( 'RCWatchCategoryMembership' ) ) {
1003 $defaultPreferences['hidecategorization'] = [
1005 'label-message' => 'tog-hidecategorization',
1006 'section' => 'rc/changesrc',
1010 if ( $user->useRCPatrol() ) {
1011 $defaultPreferences['hidepatrolled'] = [
1013 'section' => 'rc/changesrc',
1014 'label-message' => 'tog-hidepatrolled',
1018 if ( $user->useNPPatrol() ) {
1019 $defaultPreferences['newpageshidepatrolled'] = [
1021 'section' => 'rc/changesrc',
1022 'label-message' => 'tog-newpageshidepatrolled',
1026 if ( $this->config
->get( 'RCShowWatchingUsers' ) ) {
1027 $defaultPreferences['shownumberswatching'] = [
1029 'section' => 'rc/advancedrc',
1030 'label-message' => 'tog-shownumberswatching',
1034 $defaultPreferences['rcenhancedfilters-disable'] = [
1036 'section' => 'rc/advancedrc',
1037 'label-message' => 'rcfilters-preference-label',
1038 'help-message' => 'rcfilters-preference-help',
1044 * @param IContextSource $context
1045 * @param array &$defaultPreferences
1047 protected function watchlistPreferences(
1048 User
$user, IContextSource
$context, &$defaultPreferences
1050 $watchlistdaysMax = ceil( $this->config
->get( 'RCMaxAge' ) / ( 3600 * 24 ) );
1052 # # Watchlist #####################################
1053 if ( $user->isAllowed( 'editmywatchlist' ) ) {
1054 $editWatchlistLinks = '';
1055 $editWatchlistLinksOld = [];
1056 $editWatchlistModes = [
1057 'edit' => [ 'subpage' => false, 'flags' => [] ],
1058 'raw' => [ 'subpage' => 'raw', 'flags' => [] ],
1059 'clear' => [ 'subpage' => 'clear', 'flags' => [ 'destructive' ] ],
1061 foreach ( $editWatchlistModes as $mode => $options ) {
1062 // Messages: prefs-editwatchlist-edit, prefs-editwatchlist-raw, prefs-editwatchlist-clear
1063 $editWatchlistLinks .=
1064 new \OOUI\
ButtonWidget( [
1065 'href' => SpecialPage
::getTitleFor( 'EditWatchlist', $options['subpage'] )->getLinkURL(),
1066 'flags' => $options[ 'flags' ],
1067 'label' => new \OOUI\
HtmlSnippet(
1068 $context->msg( "prefs-editwatchlist-{$mode}" )->parse()
1073 $defaultPreferences['editwatchlist'] = [
1076 'default' => $editWatchlistLinks,
1077 'label-message' => 'prefs-editwatchlist-label',
1078 'section' => 'watchlist/editwatchlist',
1082 $defaultPreferences['watchlistdays'] = [
1085 'max' => $watchlistdaysMax,
1086 'section' => 'watchlist/displaywatchlist',
1087 'help' => $context->msg( 'prefs-watchlist-days-max' )->numParams(
1088 $watchlistdaysMax )->escaped(),
1089 'label-message' => 'prefs-watchlist-days',
1091 $defaultPreferences['wllimit'] = [
1095 'label-message' => 'prefs-watchlist-edits',
1096 'help' => $context->msg( 'prefs-watchlist-edits-max' )->escaped(),
1097 'section' => 'watchlist/displaywatchlist',
1098 'filter' => IntvalFilter
::class,
1100 $defaultPreferences['extendwatchlist'] = [
1102 'section' => 'watchlist/advancedwatchlist',
1103 'label-message' => 'tog-extendwatchlist',
1105 $defaultPreferences['watchlisthideminor'] = [
1107 'section' => 'watchlist/changeswatchlist',
1108 'label-message' => 'tog-watchlisthideminor',
1110 $defaultPreferences['watchlisthidebots'] = [
1112 'section' => 'watchlist/changeswatchlist',
1113 'label-message' => 'tog-watchlisthidebots',
1115 $defaultPreferences['watchlisthideown'] = [
1117 'section' => 'watchlist/changeswatchlist',
1118 'label-message' => 'tog-watchlisthideown',
1120 $defaultPreferences['watchlisthideanons'] = [
1122 'section' => 'watchlist/changeswatchlist',
1123 'label-message' => 'tog-watchlisthideanons',
1125 $defaultPreferences['watchlisthideliu'] = [
1127 'section' => 'watchlist/changeswatchlist',
1128 'label-message' => 'tog-watchlisthideliu',
1131 if ( !\SpecialWatchlist
::checkStructuredFilterUiEnabled(
1135 $defaultPreferences['watchlistreloadautomatically'] = [
1137 'section' => 'watchlist/advancedwatchlist',
1138 'label-message' => 'tog-watchlistreloadautomatically',
1142 $defaultPreferences['watchlistunwatchlinks'] = [
1144 'section' => 'watchlist/advancedwatchlist',
1145 'label-message' => 'tog-watchlistunwatchlinks',
1148 if ( $this->config
->get( 'RCWatchCategoryMembership' ) ) {
1149 $defaultPreferences['watchlisthidecategorization'] = [
1151 'section' => 'watchlist/changeswatchlist',
1152 'label-message' => 'tog-watchlisthidecategorization',
1156 if ( $user->useRCPatrol() ) {
1157 $defaultPreferences['watchlisthidepatrolled'] = [
1159 'section' => 'watchlist/changeswatchlist',
1160 'label-message' => 'tog-watchlisthidepatrolled',
1165 'edit' => 'watchdefault',
1166 'move' => 'watchmoves',
1167 'delete' => 'watchdeletion'
1171 if ( $user->isAllowed( 'createpage' ) ||
$user->isAllowed( 'createtalk' ) ) {
1172 $watchTypes['read'] = 'watchcreations';
1175 if ( $user->isAllowed( 'rollback' ) ) {
1176 $watchTypes['rollback'] = 'watchrollback';
1179 if ( $user->isAllowed( 'upload' ) ) {
1180 $watchTypes['upload'] = 'watchuploads';
1183 foreach ( $watchTypes as $action => $pref ) {
1184 if ( $user->isAllowed( $action ) ) {
1186 // tog-watchdefault, tog-watchmoves, tog-watchdeletion, tog-watchcreations, tog-watchuploads
1187 // tog-watchrollback
1188 $defaultPreferences[$pref] = [
1190 'section' => 'watchlist/pageswatchlist',
1191 'label-message' => "tog-$pref",
1196 $defaultPreferences['watchlisttoken'] = [
1200 $tokenButton = new \OOUI\
ButtonWidget( [
1201 'href' => SpecialPage
::getTitleFor( 'ResetTokens' )->getLinkURL( [
1202 'returnto' => SpecialPage
::getTitleFor( 'Preferences' )->getPrefixedText()
1204 'label' => $context->msg( 'prefs-watchlist-managetokens' )->text(),
1206 $defaultPreferences['watchlisttoken-info'] = [
1208 'section' => 'watchlist/tokenwatchlist',
1209 'label-message' => 'prefs-watchlist-token',
1210 'help-message' => 'prefs-help-tokenmanagement',
1212 'default' => (string)$tokenButton,
1215 $defaultPreferences['wlenhancedfilters-disable'] = [
1217 'section' => 'watchlist/advancedwatchlist',
1218 'label-message' => 'rcfilters-watchlist-preference-label',
1219 'help-message' => 'rcfilters-watchlist-preference-help',
1224 * @param array &$defaultPreferences
1226 protected function searchPreferences( &$defaultPreferences ) {
1227 foreach ( MWNamespace
::getValidNamespaces() as $n ) {
1228 $defaultPreferences['searchNs' . $n] = [
1235 * @param User $user The User object
1236 * @param IContextSource $context
1237 * @return array Text/links to display as key; $skinkey as value
1239 protected function generateSkinOptions( User
$user, IContextSource
$context ) {
1242 $mptitle = Title
::newMainPage();
1243 $previewtext = $context->msg( 'skin-preview' )->escaped();
1245 # Only show skins that aren't disabled in $wgSkipSkins
1246 $validSkinNames = Skin
::getAllowedSkins();
1248 foreach ( $validSkinNames as $skinkey => &$skinname ) {
1249 $msg = $context->msg( "skinname-{$skinkey}" );
1250 if ( $msg->exists() ) {
1251 $skinname = htmlspecialchars( $msg->text() );
1255 $defaultSkin = $this->config
->get( 'DefaultSkin' );
1256 $allowUserCss = $this->config
->get( 'AllowUserCss' );
1257 $allowUserJs = $this->config
->get( 'AllowUserJs' );
1259 # Sort by the internal name, so that the ordering is the same for each display language,
1260 # especially if some skin names are translated to use a different alphabet and some are not.
1261 uksort( $validSkinNames, function ( $a, $b ) use ( $defaultSkin ) {
1262 # Display the default first in the list by comparing it as lesser than any other.
1263 if ( strcasecmp( $a, $defaultSkin ) === 0 ) {
1266 if ( strcasecmp( $b, $defaultSkin ) === 0 ) {
1269 return strcasecmp( $a, $b );
1272 $foundDefault = false;
1273 foreach ( $validSkinNames as $skinkey => $sn ) {
1276 # Mark the default skin
1277 if ( strcasecmp( $skinkey, $defaultSkin ) === 0 ) {
1278 $linkTools[] = $context->msg( 'default' )->escaped();
1279 $foundDefault = true;
1282 # Create preview link
1283 $mplink = htmlspecialchars( $mptitle->getLocalURL( [ 'useskin' => $skinkey ] ) );
1284 $linkTools[] = "<a target='_blank' href=\"$mplink\">$previewtext</a>";
1286 # Create links to user CSS/JS pages
1287 if ( $allowUserCss ) {
1288 $cssPage = Title
::makeTitleSafe( NS_USER
, $user->getName() . '/' . $skinkey . '.css' );
1289 $cssLinkText = $context->msg( 'prefs-custom-css' )->text();
1290 $linkTools[] = $this->linkRenderer
->makeLink( $cssPage, $cssLinkText );
1293 if ( $allowUserJs ) {
1294 $jsPage = Title
::makeTitleSafe( NS_USER
, $user->getName() . '/' . $skinkey . '.js' );
1295 $jsLinkText = $context->msg( 'prefs-custom-js' )->text();
1296 $linkTools[] = $this->linkRenderer
->makeLink( $jsPage, $jsLinkText );
1299 $display = $sn . ' ' . $context->msg( 'parentheses' )
1300 ->rawParams( $context->getLanguage()->pipeList( $linkTools ) )
1302 $ret[$display] = $skinkey;
1305 if ( !$foundDefault ) {
1306 // If the default skin is not available, things are going to break horribly because the
1307 // default value for skin selector will not be a valid value. Let's just not show it then.
1315 * @param IContextSource $context
1318 protected function getDateOptions( IContextSource
$context ) {
1319 $lang = $context->getLanguage();
1320 $dateopts = $lang->getDatePreferences();
1325 if ( !in_array( 'default', $dateopts ) ) {
1326 $dateopts[] = 'default'; // Make sure default is always valid T21237
1329 // FIXME KLUGE: site default might not be valid for user language
1330 global $wgDefaultUserOptions;
1331 if ( !in_array( $wgDefaultUserOptions['date'], $dateopts ) ) {
1332 $wgDefaultUserOptions['date'] = 'default';
1335 $epoch = wfTimestampNow();
1336 foreach ( $dateopts as $key ) {
1337 if ( $key == 'default' ) {
1338 $formatted = $context->msg( 'datedefault' )->escaped();
1340 $formatted = htmlspecialchars( $lang->timeanddate( $epoch, false, $key ) );
1342 $ret[$formatted] = $key;
1349 * @param MessageLocalizer $l10n
1352 protected function getImageSizes( MessageLocalizer
$l10n ) {
1354 $pixels = $l10n->msg( 'unit-pixel' )->text();
1356 foreach ( $this->config
->get( 'ImageLimits' ) as $index => $limits ) {
1357 // Note: A left-to-right marker (U+200E) is inserted, see T144386
1358 $display = "{$limits[0]}\u{200E}×{$limits[1]}$pixels";
1359 $ret[$display] = $index;
1366 * @param MessageLocalizer $l10n
1369 protected function getThumbSizes( MessageLocalizer
$l10n ) {
1371 $pixels = $l10n->msg( 'unit-pixel' )->text();
1373 foreach ( $this->config
->get( 'ThumbLimits' ) as $index => $size ) {
1374 $display = $size . $pixels;
1375 $ret[$display] = $index;
1382 * @param string $signature
1383 * @param array $alldata
1384 * @param HTMLForm $form
1385 * @return bool|string
1387 protected function validateSignature( $signature, $alldata, HTMLForm
$form ) {
1388 $maxSigChars = $this->config
->get( 'MaxSigChars' );
1389 if ( mb_strlen( $signature ) > $maxSigChars ) {
1390 return Xml
::element( 'span', [ 'class' => 'error' ],
1391 $form->msg( 'badsiglength' )->numParams( $maxSigChars )->text() );
1392 } elseif ( isset( $alldata['fancysig'] ) &&
1393 $alldata['fancysig'] &&
1394 MediaWikiServices
::getInstance()->getParser()->validateSig( $signature ) === false
1396 return Xml
::element(
1398 [ 'class' => 'error' ],
1399 $form->msg( 'badsig' )->text()
1407 * @param string $signature
1408 * @param array $alldata
1409 * @param HTMLForm $form
1412 protected function cleanSignature( $signature, $alldata, HTMLForm
$form ) {
1413 $parser = MediaWikiServices
::getInstance()->getParser();
1414 if ( isset( $alldata['fancysig'] ) && $alldata['fancysig'] ) {
1415 $signature = $parser->cleanSig( $signature );
1417 // When no fancy sig used, make sure ~{3,5} get removed.
1418 $signature = Parser
::cleanSigInSig( $signature );
1426 * @param IContextSource $context
1427 * @param string $formClass
1428 * @param array $remove Array of items to remove
1431 public function getForm(
1433 IContextSource
$context,
1434 $formClass = PreferencesFormLegacy
::class,
1437 // We use ButtonWidgets in some of the getPreferences() functions
1438 $context->getOutput()->enableOOUI();
1440 $formDescriptor = $this->getFormDescriptor( $user, $context );
1441 if ( count( $remove ) ) {
1442 $removeKeys = array_flip( $remove );
1443 $formDescriptor = array_diff_key( $formDescriptor, $removeKeys );
1446 // Remove type=api preferences. They are not intended for rendering in the form.
1447 foreach ( $formDescriptor as $name => $info ) {
1448 if ( isset( $info['type'] ) && $info['type'] === 'api' ) {
1449 unset( $formDescriptor[$name] );
1454 * @var $htmlForm HTMLForm
1456 $htmlForm = new $formClass( $formDescriptor, $context, 'prefs' );
1458 $htmlForm->setModifiedUser( $user );
1459 $htmlForm->setId( 'mw-prefs-form' );
1460 $htmlForm->setAutocomplete( 'off' );
1461 $htmlForm->setSubmitText( $context->msg( 'saveprefs' )->text() );
1462 # Used message keys: 'accesskey-preferences-save', 'tooltip-preferences-save'
1463 $htmlForm->setSubmitTooltip( 'preferences-save' );
1464 $htmlForm->setSubmitID( 'prefcontrol' );
1465 $htmlForm->setSubmitCallback(
1466 function ( array $formData, HTMLForm
$form ) use ( $formDescriptor ) {
1467 return $this->submitForm( $formData, $form, $formDescriptor );
1475 * @param IContextSource $context
1478 protected function getTimezoneOptions( IContextSource
$context ) {
1481 $localTZoffset = $this->config
->get( 'LocalTZoffset' );
1482 $timeZoneList = $this->getTimeZoneList( $context->getLanguage() );
1484 $timestamp = MWTimestamp
::getLocalInstance();
1485 // Check that the LocalTZoffset is the same as the local time zone offset
1486 if ( $localTZoffset == $timestamp->format( 'Z' ) / 60 ) {
1487 $timezoneName = $timestamp->getTimezone()->getName();
1488 // Localize timezone
1489 if ( isset( $timeZoneList[$timezoneName] ) ) {
1490 $timezoneName = $timeZoneList[$timezoneName]['name'];
1492 $server_tz_msg = $context->msg(
1493 'timezoneuseserverdefault',
1497 $tzstring = sprintf(
1499 floor( $localTZoffset / 60 ),
1500 abs( $localTZoffset ) %
60
1502 $server_tz_msg = $context->msg( 'timezoneuseserverdefault', $tzstring )->text();
1504 $opt[$server_tz_msg] = "System|$localTZoffset";
1505 $opt[$context->msg( 'timezoneuseoffset' )->text()] = 'other';
1506 $opt[$context->msg( 'guesstimezone' )->text()] = 'guess';
1508 foreach ( $timeZoneList as $timeZoneInfo ) {
1509 $region = $timeZoneInfo['region'];
1510 if ( !isset( $opt[$region] ) ) {
1513 $opt[$region][$timeZoneInfo['name']] = $timeZoneInfo['timecorrection'];
1519 * Handle the form submission if everything validated properly
1521 * @param array $formData
1522 * @param HTMLForm $form
1523 * @param array[] $formDescriptor
1524 * @return bool|Status|string
1526 protected function saveFormData( $formData, HTMLForm
$form, array $formDescriptor ) {
1527 /** @var \User $user */
1528 $user = $form->getModifiedUser();
1529 $hiddenPrefs = $this->config
->get( 'HiddenPrefs' );
1532 if ( !$user->isAllowedAny( 'editmyprivateinfo', 'editmyoptions' ) ) {
1533 return Status
::newFatal( 'mypreferencesprotected' );
1537 $this->applyFilters( $formData, $formDescriptor, 'filterFromForm' );
1539 // Fortunately, the realname field is MUCH simpler
1540 // (not really "private", but still shouldn't be edited without permission)
1542 if ( !in_array( 'realname', $hiddenPrefs )
1543 && $user->isAllowed( 'editmyprivateinfo' )
1544 && array_key_exists( 'realname', $formData )
1546 $realName = $formData['realname'];
1547 $user->setRealName( $realName );
1550 if ( $user->isAllowed( 'editmyoptions' ) ) {
1551 $oldUserOptions = $user->getOptions();
1553 foreach ( $this->getSaveBlacklist() as $b ) {
1554 unset( $formData[$b] );
1557 # If users have saved a value for a preference which has subsequently been disabled
1558 # via $wgHiddenPrefs, we don't want to destroy that setting in case the preference
1559 # is subsequently re-enabled
1560 foreach ( $hiddenPrefs as $pref ) {
1561 # If the user has not set a non-default value here, the default will be returned
1562 # and subsequently discarded
1563 $formData[$pref] = $user->getOption( $pref, null, true );
1566 // If the user changed the rclimit preference, also change the rcfilters-rclimit preference
1568 isset( $formData['rclimit'] ) &&
1569 intval( $formData[ 'rclimit' ] ) !== $user->getIntOption( 'rclimit' )
1571 $formData['rcfilters-limit'] = $formData['rclimit'];
1574 // Keep old preferences from interfering due to back-compat code, etc.
1575 $user->resetOptions( 'unused', $form->getContext() );
1577 foreach ( $formData as $key => $value ) {
1578 $user->setOption( $key, $value );
1582 'PreferencesFormPreSave',
1583 [ $formData, $form, $user, &$result, $oldUserOptions ]
1587 $user->saveSettings();
1593 * Applies filters to preferences either before or after form usage
1595 * @param array &$preferences
1596 * @param array $formDescriptor
1597 * @param string $verb Name of the filter method to call, either 'filterFromForm' or
1600 protected function applyFilters( array &$preferences, array $formDescriptor, $verb ) {
1601 foreach ( $formDescriptor as $preference => $desc ) {
1602 if ( !isset( $desc['filter'] ) ||
!isset( $preferences[$preference] ) ) {
1605 $filterDesc = $desc['filter'];
1606 if ( $filterDesc instanceof Filter
) {
1607 $filter = $filterDesc;
1608 } elseif ( class_exists( $filterDesc ) ) {
1609 $filter = new $filterDesc();
1610 } elseif ( is_callable( $filterDesc ) ) {
1611 $filter = $filterDesc();
1613 throw new UnexpectedValueException(
1614 "Unrecognized filter type for preference '$preference'"
1617 $preferences[$preference] = $filter->$verb( $preferences[$preference] );
1622 * Save the form data and reload the page
1624 * @param array $formData
1625 * @param HTMLForm $form
1626 * @param array $formDescriptor
1629 protected function submitForm( array $formData, HTMLForm
$form, array $formDescriptor ) {
1630 $res = $this->saveFormData( $formData, $form, $formDescriptor );
1632 if ( $res === true ) {
1633 $context = $form->getContext();
1636 if ( $res === 'eauth' ) {
1637 $urlOptions['eauth'] = 1;
1640 $urlOptions +
= $form->getExtraSuccessRedirectParameters();
1642 $url = $form->getTitle()->getFullURL( $urlOptions );
1644 // Set session data for the success message
1645 $context->getRequest()->getSession()->set( 'specialPreferencesSaveSuccess', 1 );
1647 $context->getOutput()->redirect( $url );
1650 return ( $res === true ? Status
::newGood() : $res );
1654 * Get a list of all time zones
1655 * @param Language $language Language used for the localized names
1656 * @return array A list of all time zones. The system name of the time zone is used as key and
1657 * the value is an array which contains localized name, the timecorrection value used for
1658 * preferences and the region
1661 protected function getTimeZoneList( Language
$language ) {
1662 $identifiers = DateTimeZone
::listIdentifiers();
1663 if ( $identifiers === false ) {
1666 sort( $identifiers );
1669 'Africa' => wfMessage( 'timezoneregion-africa' )->inLanguage( $language )->text(),
1670 'America' => wfMessage( 'timezoneregion-america' )->inLanguage( $language )->text(),
1671 'Antarctica' => wfMessage( 'timezoneregion-antarctica' )->inLanguage( $language )->text(),
1672 'Arctic' => wfMessage( 'timezoneregion-arctic' )->inLanguage( $language )->text(),
1673 'Asia' => wfMessage( 'timezoneregion-asia' )->inLanguage( $language )->text(),
1674 'Atlantic' => wfMessage( 'timezoneregion-atlantic' )->inLanguage( $language )->text(),
1675 'Australia' => wfMessage( 'timezoneregion-australia' )->inLanguage( $language )->text(),
1676 'Europe' => wfMessage( 'timezoneregion-europe' )->inLanguage( $language )->text(),
1677 'Indian' => wfMessage( 'timezoneregion-indian' )->inLanguage( $language )->text(),
1678 'Pacific' => wfMessage( 'timezoneregion-pacific' )->inLanguage( $language )->text(),
1680 asort( $tzRegions );
1684 $now = new DateTime();
1686 foreach ( $identifiers as $identifier ) {
1687 $parts = explode( '/', $identifier, 2 );
1689 // DateTimeZone::listIdentifiers() returns a number of
1690 // backwards-compatibility entries. This filters them out of the
1691 // list presented to the user.
1692 if ( count( $parts ) !== 2 ||
!array_key_exists( $parts[0], $tzRegions ) ) {
1697 $parts[0] = $tzRegions[$parts[0]];
1699 $dateTimeZone = new DateTimeZone( $identifier );
1700 $minDiff = floor( $dateTimeZone->getOffset( $now ) / 60 );
1702 $display = str_replace( '_', ' ', $parts[0] . '/' . $parts[1] );
1703 $value = "ZoneInfo|$minDiff|$identifier";
1705 $timeZoneList[$identifier] = [
1707 'timecorrection' => $value,
1708 'region' => $parts[0],
1712 return $timeZoneList;